Skip to content

Research-grounded bark classification with peak-frequency pitch - #58

Merged
RobbieTheWagner merged 6 commits into
masterfrom
bark-classifier-multidimensional
Jul 12, 2026
Merged

RobbieTheWagner merged 6 commits into
masterfrom
bark-classifier-multidimensional

Conversation

@RobbieTheWagner

@RobbieTheWagner RobbieTheWagner commented Jun 13, 2026 •

Copy link
Copy Markdown
Owner

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)

  • determineBarkPitch now uses the peak (loudest) frequency bin, with the low/high split placed in the empty gap between observed alert and play peaks.
  • Adds rhythm (inter-bark interval) and bark count as scoring features.
  • Adds spectralFlatness/determineBarkTonality but 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.
  • translateBark returns a BarkTranslation (verdict + pitch/rhythm/arousal + confidence); the result sheet shows trait chips and a confidence label.

Testing

  • New labelled-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 (asserted as a QUnit todo) because an excited greeting bark can peak as low as a guard bark — indistinguishable at this resolution.
  • scripts/audio-to-fixture.mjs converts 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)

  1. Greeting ≈ alert (the open todo).
  2. Revive tonality at finer fftSize (1024–2048) — highest-leverage fix; unlocks greeting + distress.
  3. Distress is unvalidated — needs a real whimper/yelp clip.
  4. Pitch-band overfitting risk — a high-pitched small-dog alarm would currently read as playful; add small-dog alert clips.
  5. Grow the labelled set.

Test plan

  • pnpm test — 43 pass, 1 todo (greeting gap), 0 fail
  • pnpm lint — clean
  • pnpm lint:types — clean

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features
    • Bark results now include richer translations: confidence text, pitch/tonality insights, rhythm pattern chips, and arousal assessment.
    • The bark result sheet can now render optional trait chips and confidence alongside the verdict.
  • Tests
    • Added an end-to-end “labeled barks” integration suite with new audio fixtures and analysis helper.
    • Expanded unit coverage for pitch/tonality/rhythm segmentation, translation scoring, and arousal logic (including known gaps).
  • Documentation
    • Updated architecture guidance to reflect the full decode→analyze→classify pipeline and its limitations.

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>
@coderabbitai

coderabbitai Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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.

Changes

Bark Translation Feature Expansion

Layer / File(s) Summary
Feature extraction and event analysis
app/utils/barks.ts
Adds pitch, tonality, event segmentation, and rhythm analysis using peak frequency bins, spectral flatness, modal event features, and inter-event gaps.
Translation scoring and verdict construction
app/utils/barks.ts
Adds BarkTranslation, scores bark types from pitch/rhythm/count, derives confidence and arousal, and routes determineBarkType through translateBark.
Audio analyzer integration
app/services/audio-analyzer.ts
Tracks per-chunk tonalities, stores the translated verdict, derives barkType and outcome, and resets the new state between analyses.
Result display and template wiring
app/components/bark-result-sheet.gts, app/templates/microphone.gts, app/templates/upload.gts
Displays confidence and pitch/rhythm traits and passes audioAnalyzer.translation into the result sheet.

Fixture-Driven Validation

Layer / File(s) Summary
Fixture generation and labeled dataset
scripts/audio-to-fixture.mjs, tests/fixtures/*
Adds a CLI for generating TypeScript audio data-URI modules and registers labeled alert, greeting, and playful bark fixtures.
End-to-end audio classification
tests/helpers/analyze-audio-blob.ts, tests/integration/labeled-barks-test.ts
Decodes and offline-renders fixture audio, translates the collected features, and asserts expected types while treating marked known gaps as QUnit todos.
Unit coverage and project guidance
tests/unit/utils/barks-test.ts, CLAUDE.md, .gitignore
Tests feature extraction and translation edge cases, documents the pipeline and classifier limitations, and ignores scratch bark candidates.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: a research-backed bark classifier using peak-frequency pitch analysis.
Docstring Coverage ✅ Passed Docstring coverage is 92.86% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bark-classifier-multidimensional

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c0f25c8 and f16e233.

📒 Files selected for processing (18)
  • .gitignore
  • CLAUDE.md
  • app/components/bark-result-sheet.gts
  • app/services/audio-analyzer.ts
  • app/templates/microphone.gts
  • app/templates/upload.gts
  • app/utils/barks.ts
  • scripts/audio-to-fixture.mjs
  • tests/fixtures/alert-door-aggressive.ts
  • tests/fixtures/alert-measured-bark.ts
  • tests/fixtures/alert-rapid-bark.ts
  • tests/fixtures/greeting-spinning-bark.ts
  • tests/fixtures/labeled-barks.ts
  • tests/fixtures/playful-dogs-playing-2.ts
  • tests/fixtures/playful-dogs-playing.ts
  • tests/helpers/analyze-audio-blob.ts
  • tests/integration/labeled-barks-test.ts
  • tests/unit/utils/barks-test.ts

Comment thread app/utils/barks.ts
Comment on lines +316 to +321
function determineArousal(rhythm: Rhythm, tonality?: Tonality): Arousal {
if (rhythm === 'rapid') {
return 'intense';
}
if (rhythm === 'measured' || tonality === 'harsh') {
return 'moderate';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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

Comment thread CLAUDE.md
Comment on lines 39 to +42
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment thread tests/helpers/analyze-audio-blob.ts Resolved
Comment thread tests/helpers/analyze-audio-blob.ts Resolved
Comment thread tests/helpers/analyze-audio-blob.ts Resolved
RobbieTheWagner and others added 5 commits June 16, 2026 10:46
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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between f16e233 and c46314d.

📒 Files selected for processing (6)
  • CLAUDE.md
  • app/components/bark-result-sheet.gts
  • app/services/audio-analyzer.ts
  • app/utils/barks.ts
  • tests/helpers/analyze-audio-blob.ts
  • tests/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

Comment thread CLAUDE.md
Comment on lines +47 to +49
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)).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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

@RobbieTheWagner
RobbieTheWagner merged commit 64928e8 into master Jul 12, 2026
6 checks passed
@RobbieTheWagner
RobbieTheWagner deleted the bark-classifier-multidimensional branch July 12, 2026 19:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant