Repository navigation
Research-grounded bark classification with peak-frequency pitch - #58
Conversation
Rework the bark classifier around canine bioacoustics (Morton's structural-motivational rules; Pongrácz et al.) and validate it against real recordings. Classifier (app/utils/barks.ts): - determineBarkPitch now uses the peak (loudest) frequency bin instead of band averages, which had labelled nearly every bark "low" since low frequencies always carry more energy. The peak bin tracks the actual fundamental: alert/greeting barks peak ~375-690 Hz, excited play barks peak ~1030-1240 Hz, so the low/high split lands in the gap between. - Add rhythm (inter-bark interval) and bark-count as scoring features. - Add spectralFlatness/determineBarkTonality, but deliberately exclude tonality from scoring: at fftSize 128 it saturates (~0.9-0.99 for every clip) and can't separate harsh from clear barks. - translateBark returns a BarkTranslation (verdict + pitch/rhythm/arousal + confidence); the result sheet surfaces trait chips and a confidence label. Testing: - New labeled-bark regression harness runs real clips through the full decode->render->classify pipeline (tests/helpers/analyze-audio-blob.ts, tests/integration/labeled-barks-test.ts). Verdicts: 4/4 alert and 2/2 playful correct; greeting is a documented knownGap (todo) because an excited greeting bark can peak as low as a guard bark. - scripts/audio-to-fixture.mjs converts audio/video into base64 fixtures. Docs: CLAUDE.md documents the pipeline, the tonality limitation, and a prioritized roadmap (revive tonality at finer fftSize; source distress clips; watch pitch-band overfitting; grow the labeled set). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
📝 WalkthroughWalkthroughThis PR expands bark classification with peak-bin pitch, spectral tonality, event segmentation, rhythm, arousal, confidence, and richer translations. The analyzer and result UI consume the translation, while generated audio fixtures, unit tests, integration tests, and workflow documentation cover the updated pipeline. ChangesBark Translation Feature Expansion
Fixture-Driven Validation
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant AudioBlob
participant OfflineAudioContext
participant AudioAnalyzerService
participant translateBark
participant BarkResultSheet
AudioBlob->>OfflineAudioContext: decode and render audio
OfflineAudioContext->>AudioAnalyzerService: per-chunk bark, pitch, and tonality data
AudioAnalyzerService->>translateBark: translate collected features
translateBark-->>AudioAnalyzerService: BarkTranslation
AudioAnalyzerService->>BarkResultSheet: pass translation for display
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/utils/barks.ts`:
- Around line 316-321: The determineArousal function currently elevates arousal
when tonality === 'harsh'; remove any use of tonality from arousal mapping so
arousal is decided solely from rhythm (e.g., return 'intense' for rhythm ===
'rapid', 'moderate' for 'measured', else default). Update the same logic
wherever else tonality is referenced for arousal (the second occurrence noted)
so no code path reads tonality for bark scoring or UI rendering.
In `@CLAUDE.md`:
- Around line 39-42: Edit the sentence that currently states the real audio
pipeline is replaced in tests to clarify it only applies to most/unit/component
tests; update the wording to something like "In most tests (unit/component), the
real audio pipeline is replaced by
tests/helpers/mocked-audio-analyzer-service.ts, while integration/regression
suites such as tests/integration/labeled-barks-test.ts use the full
decode→render→classify pipeline (tests/helpers/analyze-audio-blob.ts) against
fixtures." Ensure the revised text keeps references to
tests/helpers/mocked-audio-analyzer-service.ts,
tests/integration/labeled-barks-test.ts, tests/helpers/analyze-audio-blob.ts and
the workflow for adding fixtures (node scripts/audio-to-fixture.mjs) so
contributors understand which tests are mocked vs real.
In `@tests/helpers/analyze-audio-blob.ts`:
- Around line 43-45: The analyser node is not wired into the rendered chain
causing its data to not update; after bufferSource.connect(analyser) add a
connection from analyser into the ScriptProcessorNode (scp) so the chain becomes
bufferSource -> analyser -> scp -> offline.destination. Locate the bufferSource,
analyser, and scp usage (and the scp.connect(offline.destination) call) and
insert analyser.connect(scp) before scp.connect(offline.destination) so
onaudioprocess receives real analyser frames.
- Around line 64-70: The code currently calls void offline.startRendering() and
relies on bufferSource.onended to resolve, which can drop rendering errors and
leave the promise unresolved; change this to handle the startRendering()
completion and errors explicitly by using the returned Promise from
offline.startRendering() (or await it) and then call
resolve(translateBark(barksOccurred, pitches, tonalities)) on success and
reject/error-log on failure; ensure you still keep or remove
bufferSource.onended as appropriate and reference bufferSource.onended,
offline.startRendering, resolve, reject, and translateBark when updating the
logic.
- Around line 46-57: The code feeds Uint8 byte-domain samples (amplitudeArray)
into determineBarkOccurred, but that function expects float time-domain samples
around 0..1 (threshold ~0.55); replace the Uint8Array path with a Float32Array
and call analyser.getFloatTimeDomainData instead of
analyser.getByteTimeDomainData (or, alternatively, normalize the Uint8 values to
floats) so determineBarkOccurred receives float samples. Update the
amplitudeArray declaration to a Float32Array, change the getByteTimeDomainData
call to getFloatTimeDomainData, and if determineBarkOccurred's signature
requires it, ensure it accepts Float32Array (or perform conversion just before
the push).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 020196c7-cdce-4e6e-aa28-e2121681c3d7
📒 Files selected for processing (18)
.gitignoreCLAUDE.mdapp/components/bark-result-sheet.gtsapp/services/audio-analyzer.tsapp/templates/microphone.gtsapp/templates/upload.gtsapp/utils/barks.tsscripts/audio-to-fixture.mjstests/fixtures/alert-door-aggressive.tstests/fixtures/alert-measured-bark.tstests/fixtures/alert-rapid-bark.tstests/fixtures/greeting-spinning-bark.tstests/fixtures/labeled-barks.tstests/fixtures/playful-dogs-playing-2.tstests/fixtures/playful-dogs-playing.tstests/helpers/analyze-audio-blob.tstests/integration/labeled-barks-test.tstests/unit/utils/barks-test.ts
| function determineArousal(rhythm: Rhythm, tonality?: Tonality): Arousal { | ||
| if (rhythm === 'rapid') { | ||
| return 'intense'; | ||
| } | ||
| if (rhythm === 'measured' || tonality === 'harsh') { | ||
| return 'moderate'; |
There was a problem hiding this comment.
Remove tonality from arousal mapping to avoid biased translation output.
Line 320 currently raises arousal when tonality === 'harsh'. At fftSize 128, tonality is explicitly treated as saturated/unreliable, so this path can inflate arousal classifications.
Suggested fix
-function determineArousal(rhythm: Rhythm, tonality?: Tonality): Arousal {
+function determineArousal(rhythm: Rhythm): Arousal {
if (rhythm === 'rapid') {
return 'intense';
}
- if (rhythm === 'measured' || tonality === 'harsh') {
+ if (rhythm === 'measured') {
return 'moderate';
}
return 'calm';
}
@@
- arousal: determineArousal(rhythm, tonality),
+ arousal: determineArousal(rhythm),As per coding guidelines, “Do not use tonality in bark scoring or UI rendering; tonality computation is deliberately excluded due to FFT saturation at fftSize 128.”
Also applies to: 367-367
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/utils/barks.ts` around lines 316 - 321, The determineArousal function
currently elevates arousal when tonality === 'harsh'; remove any use of tonality
from arousal mapping so arousal is decided solely from rhythm (e.g., return
'intense' for rhythm === 'rapid', 'moderate' for 'measured', else default).
Update the same logic wherever else tonality is referenced for arousal (the
second occurrence noted) so no code path reads tonality for bark scoring or UI
rendering.
Source: Coding guidelines
| In tests, the real audio pipeline is replaced by `tests/helpers/mocked-audio-analyzer-service.ts`, since OfflineAudioContext rendering isn't reliable in CI. | ||
|
|
||
| To regression-test classification against real recordings, `tests/integration/labeled-barks-test.ts` runs each clip in `tests/fixtures/labeled-barks.ts` through the full decode→render→classify pipeline (`tests/helpers/analyze-audio-blob.ts`) and asserts the expected `BarkType`. Add a clip by converting audio (or a video's audio track) to a base64 data-URI module with `node scripts/audio-to-fixture.mjs <input> [out.ts]` and registering it in the manifest. Clips the classifier currently gets wrong are flagged `knownGap: true`, which asserts them as a QUnit `todo` (expected failure) — the suite stays green but flips loudly to a real failure once a calibration change fixes them. Note: there is **no public dataset labeled by emotional bark type** (the Pongrácz context corpus is private; ESC-50/UrbanSound8K/DogSpeak only tag "dog bark"), so each clip's expected type must be human-judged from its context (watching a video helps), not taken from an off-the-shelf label. | ||
|
|
There was a problem hiding this comment.
Clarify the mock-vs-real test split to avoid contradictory guidance.
Line 39 implies all tests mock the audio pipeline, while Lines 41-42 document real OfflineAudioContext regression tests. Please scope Line 39 to “most tests” (e.g., unit/component) so contributors don’t disable the intended integration harness.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~41-~41: Do not mix variants of the same word (‘labeled’ and ‘labelled’) within a single text.
Context: ...hem. Note: there is no public dataset labeled by emotional bark type (the Pongrácz ...
(EN_EXACT_COHERENCY_RULE)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CLAUDE.md` around lines 39 - 42, Edit the sentence that currently states the
real audio pipeline is replaced in tests to clarify it only applies to
most/unit/component tests; update the wording to something like "In most tests
(unit/component), the real audio pipeline is replaced by
tests/helpers/mocked-audio-analyzer-service.ts, while integration/regression
suites such as tests/integration/labeled-barks-test.ts use the full
decode→render→classify pipeline (tests/helpers/analyze-audio-blob.ts) against
fixtures." Ensure the revised text keeps references to
tests/helpers/mocked-audio-analyzer-service.ts,
tests/integration/labeled-barks-test.ts, tests/helpers/analyze-audio-blob.ts and
the workflow for adding fixtures (node scripts/audio-to-fixture.mjs) so
contributors understand which tests are mocked vs real.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
The test helper was reading float time-domain data while the classifier's getTimeDomainMaxMin/determineBarkOccurred expect byte data (0-255, silence at 128, ÷256), so every chunk read "no bark" and the labeled-barks suite failed. Revert the amplitude read to getByteTimeDomainData to match the real service. Also add a dedicated fftSize-2048 tonality analyser to both the service and the test helper. At fftSize 128 spectral flatness saturated (~0.9-0.99 for every clip) and was useless; measured over the dog band at ~21.5 Hz/bin as linear-power Wiener entropy (spectralFlatnessDb), it becomes a real signal. Empirically it does NOT separate the emotional types on the current fixtures (all barks read fairly tonal, 0.02-0.18; the lone greeting clip sits inside the alert cluster), so tonality stays out of type scoring and the UI. It feeds determineArousal only, now that it is a genuine measurement rather than a saturated constant. The greeting knownGap stays a todo. Docs and comments updated; adds a unit test for the harsh->moderate arousal branch (the one path the tonality pass drives). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@CLAUDE.md`:
- Around line 47-49: Standardize the spelling in this section by replacing
“labelled” with “labeled,” matching the existing variant used elsewhere in
CLAUDE.md while preserving the surrounding content.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 85b0eaba-56b1-4819-9720-af770c7cde4a
📒 Files selected for processing (6)
CLAUDE.mdapp/components/bark-result-sheet.gtsapp/services/audio-analyzer.tsapp/utils/barks.tstests/helpers/analyze-audio-blob.tstests/unit/utils/barks-test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- tests/helpers/analyze-audio-blob.ts
- app/services/audio-analyzer.ts
- tests/unit/utils/barks-test.ts
- app/components/bark-result-sheet.gts
| 1. **Greeting ≈ alert (the open `todo`).** An excited greeting bark can peak as low as a guard bark (~470 Hz), so pitch + rhythm can't separate them. We hoped tonality would be the missing cue, but the finer-resolution measurement (see (2)) shows it isn't: our one greeting clip reads as tonal as several alert clips (flatness ~0.025, inside the 0.019–0.15 alert range). Fixing this now needs **more greeting samples** (and likely a different feature than spectral flatness — e.g. pitch contour/harmonicity), not a threshold tweak. This is the failing `knownGap` fixture today. | ||
| 2. **Tonality at finer resolution — DONE, but not discriminative (yet).** A second analysis pass at fftSize 2048 (~21.5 Hz/bin, `spectralFlatnessDb`) replaced the saturated fftSize-128 estimate with a real linear-power Wiener entropy. It feeds `determineArousal` and is exposed on `BarkTranslation`, but it does **not** separate the emotional types across the current fixtures (all barks read fairly tonal, 0.02–0.18; nothing reaches the harsh end), so it's kept out of type scoring and the UI. The next move is **data, not DSP**: add aggressive/harsh and distress clips so the harsh end of the metric is actually exercised, then revisit scoring. | ||
| 3. **Distress is unvalidated.** We have no labeled distress recording, and without clips that exercise the harsh/tonal contrast a fearful yelp looks like an excited yip (both high-pitched). Need a real whimper/yelp clip as a fixture — this is now the gating item for making tonality useful in scoring (see (2)). |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use one spelling variant consistently.
This section uses labelled, while Line 49 uses labeled. Standardize the wording across the document, preferably to the existing labeled variant.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~49-~49: Do not mix variants of the same word (‘labeled’ and ‘labelled’) within a single text.
Context: ...Distress is unvalidated. We have no labeled distress recording, and without clips t...
(EN_EXACT_COHERENCY_RULE)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@CLAUDE.md` around lines 47 - 49, Standardize the spelling in this section by
replacing “labelled” with “labeled,” matching the existing variant used
elsewhere in CLAUDE.md while preserving the surrounding content.
Source: Linters/SAST tools
What & why
Reworks the bark classifier around canine bioacoustics (Morton's structural-motivational rules; Pongrácz et al.) and, crucially, validates it against real recordings instead of intuition.
The old logic compared frequency-band averages for pitch, which labelled nearly every bark "low" (low frequencies always carry more energy) and over-predicted
alert. Dumping the raw spectra across labelled clips showed the real discriminator is the peak frequency: alert/greeting barks peak ~375–690 Hz, excited play barks peak ~1030–1240 Hz.Changes
Classifier (
app/utils/barks.ts)determineBarkPitchnow uses the peak (loudest) frequency bin, with the low/high split placed in the empty gap between observed alert and play peaks.spectralFlatness/determineBarkTonalitybut deliberately excludes tonality from scoring — at fftSize 128 it saturates (~0.9–0.99 for every clip) and can't separate harsh from clear barks.translateBarkreturns aBarkTranslation(verdict + pitch/rhythm/arousal + confidence); the result sheet shows trait chips and a confidence label.Testing
tests/helpers/analyze-audio-blob.ts,tests/integration/labeled-barks-test.ts).knownGap(asserted as a QUnittodo) because an excited greeting bark can peak as low as a guard bark — indistinguishable at this resolution.scripts/audio-to-fixture.mjsconverts audio/video into base64 fixtures.Docs — CLAUDE.md documents the pipeline, the tonality limitation, and a prioritized roadmap.
Known gaps / next steps (in CLAUDE.md)
todo).Test plan
pnpm test— 43 pass, 1 todo (greeting gap), 0 failpnpm lint— cleanpnpm lint:types— clean🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes