Skip to content

Commit 955cd88

Browse files
dkackmanclaude
andcommitted
refactor(dsp): #1118 - looped-bed self-correlation measured in dsp via scipy, vectorized
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 226b339 commit 955cd88

3 files changed

Lines changed: 38 additions & 25 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ one to open.
141141
| Output comparison | `dw/media_compare.py`: `compare`, `psnr`, `ssim`, `mean_abs_diff`, `check_request`, `crop_box` | Metrics always compare the same pixels: one shared crop is the measured region, and per-output crops are display only, leaving metrics on the full frame. An output whose size differs from the baseline's, or a moment past its end, gets null metrics with a reason; nothing is resized to force a number. SSIM is on Rec. 601 luma (SSIM's convention, not `image_ops.luma`). It runs in the server process and decodes through `dw/media.py` and `open_bounded`. | `tests/test_compare_route.py::test_a_shared_crop_is_the_region_measured`, `tests/test_compare_route.py::test_per_output_crops_are_display_only`, `tests/test_compare_route.py::test_a_size_mismatch_gets_no_numbers_and_says_why`, `tests/test_compare_route.py::test_a_moment_past_the_shorter_clip_is_a_blank_cell` |
142142
| Signal processing | `dw/dsp.py` | It measures and transforms waveforms, decides nothing, and imports nothing from `dw`. | `tests/test_media_layering.py::test_dsp_imports_nothing_from_dw` |
143143
| Assessment probes | `dw/tasks/assess.py`, `dw/assessment_rules.py` | Exactly three registered commands are assessment probes. Each measures a finished file, and every rule names a real probe field. | `tests/test_assessment_rules.py::TestRuleProbesAreRealCommands::test_assessment_is_exactly_the_three_probes`, `tests/test_assessment_rules.py::TestRuleProbesAreRealCommands::test_every_rule_names_a_registered_json_command` |
144-
| Script check | `dw/tasks/script_check.py`: `check`; `dw/tasks/script_take.py`: `guard_words`, `word_level`, `shot_spans`; `dw/script_lines.py`: `parse_lines`, `parse_shots`, `shot_names_error` | `check_script` aligns a take's heard words to its expected lines and guards out words heard over silence and repetition loops (Whisper's hallucination over music). It builds its findings with `assessment_rules.finding()` and reads the guard's floor and window (`DEAD_AIR_FLOOR_DBFS`, `DEAD_AIR_WINDOW`) rather than copying them; the loudest-window measure is `dsp.loudest_window_dbfs` (`script_take.word_level` wraps it; the guard, the transcription levelling, the floor-gated `audible_runs` and the shot placement (with `clamp_to_shot`, a line's timing kept inside its shot) are `dw/tasks/script_take.py`, which `script_check` reads one way - nothing there reads the rule tables), which `transcribe_audio`'s `suspect: "silent"` mark reads with the same floor and window; the repetition-loop detector (`script_lines.looped_texts`, `REPEAT_RUN_MIN`, `REPEAT_MAX_PERIOD`) lives in `dw/script_lines.py` and backs both `check_script`'s `repetition` discard and `transcribe_audio`'s `suspect: "repetition"`, and `script_lines.suspect_runs`/`SUSPECT_LEFT_OUT` are what `plan_cuts` groups and leaves out suspect chunks by - so neither task imports the other. It is not an assessment probe and adds nothing to `RULES`. Its literal `lines` is refused at validation through `task_problems` (`script_lines_errors`), which calls the same `parse_lines` the task runs, and a literal `shots` through the same `parse_shots` and `shot_names_error`; the parsers live in `dw/script_lines.py`, not the task, so that `task_problems` reaches them without importing `script_check` (the `import_cycles` ratchet in `scripts/arch_metrics.py`). A line's `shot` may be the short `@name` of the one recorded shot that carries it (`script_lines.matching_shot_names`, `with_full_shot_names`, shared by the task and the literal-`shots` check); which member key a recorded name carries comes from `references.member_keys`, beside `MEMBER_SEPARATOR` and `for_each.member_name`, never a re-derived pattern: a key ends at the first character outside `references.VARIABLE_NAME_CHARACTERS`, the set `security.validate_variable_name` (which checks a for_each entry's name) builds its pattern from. With `audio` an `output:`/`asset:`/path whose run manifest records shots, `dw/shot_span_preflight.py: script_shot_name_errors` (the `script_shot_names` error check) runs `shot_names_error` at validation, reading the map through `runs.shots_beside`. Its shot map comes from `assess.resolve_shots`, the one the probes use, never a copy; it places each shot on the soundtrack with `assess.sample_span`, decides repeated shot names with `shots.duplicate_shot_names`, and asks `locations.is_http_url` whether the take is a URL. | `tests/test_script_check.py::TestRegistration::test_registered_as_json_command_without_assessment_flag`, `tests/test_script_check.py::TestEmptyLines::test_words_only_over_silence_are_discarded_not_found`, `tests/test_script_check.py::TestLinesErrors::test_literal_with_a_colon_is_not_a_reference`, `tests/test_script_check.py::TestShotValidation::test_a_short_member_name_matches_the_one_shot_carrying_it`, `tests/test_script_check.py::TestShotValidation::test_a_valid_variable_name_comes_back_whole_as_a_member_key`, `tests/test_shot_span_preflight.py::TestScriptShotNames::test_a_wrong_shot_name_is_an_error_at_validate_time` |
144+
| Script check | `dw/tasks/script_check.py`: `check`; `dw/tasks/script_take.py`: `guard_words`, `word_level`, `shot_spans`; `dw/script_lines.py`: `parse_lines`, `parse_shots`, `shot_names_error` | `check_script` aligns a take's heard words to its expected lines and guards out words heard over silence and repetition loops (Whisper's hallucination over music). It builds its findings with `assessment_rules.finding()` and reads the guard's floor and window (`DEAD_AIR_FLOOR_DBFS`, `DEAD_AIR_WINDOW`) rather than copying them; the loudest-window measure is `dsp.loudest_window_dbfs` and the looped-bed self-correlation `dsp.repeat_correlation` (`script_check.is_looped_bed` only decides on it) (`script_take.word_level` wraps it; the guard, the transcription levelling, the floor-gated `audible_runs` and the shot placement (with `clamp_to_shot`, a line's timing kept inside its shot) are `dw/tasks/script_take.py`, which `script_check` reads one way - nothing there reads the rule tables), which `transcribe_audio`'s `suspect: "silent"` mark reads with the same floor and window; the repetition-loop detector (`script_lines.looped_texts`, `REPEAT_RUN_MIN`, `REPEAT_MAX_PERIOD`) lives in `dw/script_lines.py` and backs both `check_script`'s `repetition` discard and `transcribe_audio`'s `suspect: "repetition"`, and `script_lines.suspect_runs`/`SUSPECT_LEFT_OUT` are what `plan_cuts` groups and leaves out suspect chunks by - so neither task imports the other. It is not an assessment probe and adds nothing to `RULES`. Its literal `lines` is refused at validation through `task_problems` (`script_lines_errors`), which calls the same `parse_lines` the task runs, and a literal `shots` through the same `parse_shots` and `shot_names_error`; the parsers live in `dw/script_lines.py`, not the task, so that `task_problems` reaches them without importing `script_check` (the `import_cycles` ratchet in `scripts/arch_metrics.py`). A line's `shot` may be the short `@name` of the one recorded shot that carries it (`script_lines.matching_shot_names`, `with_full_shot_names`, shared by the task and the literal-`shots` check); which member key a recorded name carries comes from `references.member_keys`, beside `MEMBER_SEPARATOR` and `for_each.member_name`, never a re-derived pattern: a key ends at the first character outside `references.VARIABLE_NAME_CHARACTERS`, the set `security.validate_variable_name` (which checks a for_each entry's name) builds its pattern from. With `audio` an `output:`/`asset:`/path whose run manifest records shots, `dw/shot_span_preflight.py: script_shot_name_errors` (the `script_shot_names` error check) runs `shot_names_error` at validation, reading the map through `runs.shots_beside`. Its shot map comes from `assess.resolve_shots`, the one the probes use, never a copy; it places each shot on the soundtrack with `assess.sample_span`, decides repeated shot names with `shots.duplicate_shot_names`, and asks `locations.is_http_url` whether the take is a URL. | `tests/test_script_check.py::TestRegistration::test_registered_as_json_command_without_assessment_flag`, `tests/test_script_check.py::TestEmptyLines::test_words_only_over_silence_are_discarded_not_found`, `tests/test_script_check.py::TestLinesErrors::test_literal_with_a_colon_is_not_a_reference`, `tests/test_script_check.py::TestShotValidation::test_a_short_member_name_matches_the_one_shot_carrying_it`, `tests/test_script_check.py::TestShotValidation::test_a_valid_variable_name_comes_back_whole_as_a_member_key`, `tests/test_shot_span_preflight.py::TestScriptShotNames::test_a_wrong_shot_name_is_an_error_at_validate_time` |
145145
| Audio sync against a source slice | `dw/tasks/measure_sync.py`: `measure_sync`; `dw/dsp.py`: `envelope_lag` | `measure_sync` cross-correlates the onset envelopes of a shot's audio and its source slice and answers the lag and a 0-1 confidence. A positive lag means the audio is LATE (its events fall after the reference's), negative early; `lag_seconds` is None for a silent or flat track. It builds its findings (`sync_unmeasurable`, `sync_low_confidence`, `audio_out_of_sync`) with `assessment_rules.finding()` over module-local rule dicts and adds nothing to `RULES`; it reads the silence floor from `beats.SILENT_DBFS`. `envelope_lag` imports nothing from `dw`. | `tests/test_measure_sync.py::TestLag::test_late_audio_is_a_positive_lag`, `tests/test_measure_sync.py::TestLag::test_early_audio_is_a_negative_lag`, `tests/test_measure_sync.py::TestUnmeasurable::test_a_silent_reference_has_no_lag` |
146146
| Sung phrases from voiced energy | `dw/tasks/phrases.py`: `analyze_phrases`, `voiced_power`, `voiced_runs`; `dw/task_problems.py`: `phrases_problems`, `phrases_errors` | `analyze_phrases` times a song's sung phrases with no model: a stereo file's centre-weighted band power (max(0, P_mid - P_side), 250-3500 Hz, 20 ms frames) or, for mono, `centre: false` or identical channels, the downmix's band power (`method` `band`). The voiced floor is `voice_attribution.voiced_floor_dbfs`, the rule `attribute_voices` uses, unless `floor_db` is given. It answers a dict - `{phrases, duration_seconds, method, warnings}` - so a step saves one JSON artifact. Its ranges are the registration's domains; `phrases_problems` (a real boolean `centre`) runs at validate and at run time. | `tests/test_analyze_phrases.py::TestCentre::test_centred_bursts_under_hard_panned_noise_are_found`, `tests/test_analyze_phrases.py::TestCentre::test_bursts_panned_hard_to_one_side_are_not_centre`, `tests/test_analyze_phrases.py::TestRefusals::test_validate_refuses_a_missing_audio_and_a_negative_gap` |
147147

‎dw/dsp.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,33 @@ def harmonicity(waveform, sample_rate):
416416
return max(scores) if scores else 0.0
417417

418418

419+
def repeat_correlation(mono, sample_rate, min_lag_seconds, min_overlap_seconds):
420+
"""The best overlap-normalized self-correlation of a block with itself at
421+
any lag of min_lag_seconds or more that leaves min_overlap_seconds to
422+
compare, 0.0 when the block is too short or silent. 1.0 means the block
423+
repeats sample for sample, as a looped bed does (#1118)."""
424+
block = numpy.asarray(mono, dtype=numpy.float64)
425+
if block.size == 0:
426+
return 0.0
427+
block = block - block.mean()
428+
shortest = int(min_lag_seconds * sample_rate)
429+
longest = block.size - int(min_overlap_seconds * sample_rate)
430+
if longest < shortest or shortest < 1:
431+
return 0.0
432+
full = scipy.signal.correlate(block, block, mode="full", method="fft")
433+
auto = full[block.size - 1 :]
434+
# Prefix energies give each lag's two overlapping stretches' energy
435+
energy = numpy.concatenate([[0.0], numpy.cumsum(block * block)])
436+
lags = numpy.arange(shortest, longest + 1)
437+
denominator = numpy.sqrt(
438+
energy[block.size - lags] * (energy[block.size] - energy[lags])
439+
)
440+
valid = denominator > 0
441+
if not valid.any():
442+
return 0.0
443+
return float(numpy.max(auto[lags][valid] / denominator[valid]))
444+
445+
419446
def spectral_balance(waveform, sample_rate):
420447
"""A rough low/mid/high energy reading in dBFS, from one FFT of the
421448
channel-averaged track - not a spectrogram, just enough to say whether

‎dw/tasks/script_check.py‎

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,6 @@
4444
import difflib
4545
import logging
4646
import math
47-
48-
import numpy
4947
from types import SimpleNamespace
5048

5149
from .. import dsp
@@ -855,29 +853,17 @@ def _audible_findings(
855853

856854

857855
def is_looped_bed(mono, sample_rate, start, end):
858-
"""True when [start, end] repeats itself sample for sample at some lag of
859-
BED_MIN_PERIOD_SECONDS or more, leaving BED_MIN_OVERLAP_SECONDS to compare
860-
(#1118): a looped room-tone or score bed, which a voice never does."""
856+
"""True when [start, end] repeats itself sample for sample (#1118): a
857+
looped room-tone or score bed, which a voice never does. The measurement
858+
is `dsp.repeat_correlation`; this is the decision."""
861859
first, last = int(round(start * sample_rate)), int(round(end * sample_rate))
862-
block = numpy.asarray(mono[max(0, first) : last], dtype=numpy.float64)
863-
block = block - block.mean() if block.size else block
864-
shortest = int(BED_MIN_PERIOD_SECONDS * sample_rate)
865-
overlap = int(BED_MIN_OVERLAP_SECONDS * sample_rate)
866-
longest = block.size - overlap
867-
if longest < shortest:
868-
return False
869-
size = 1 << int(block.size * 2 - 1).bit_length()
870-
spectrum = numpy.fft.rfft(block, size)
871-
auto = numpy.fft.irfft(spectrum * numpy.conj(spectrum), size)
872-
# Prefix energies give each lag's two overlapping stretches' energy
873-
energy = numpy.concatenate([[0.0], numpy.cumsum(block * block)])
874-
for lag in range(shortest, longest + 1):
875-
head = energy[block.size - lag]
876-
tail = energy[block.size] - energy[lag]
877-
denominator = math.sqrt(head * tail)
878-
if denominator > 0 and auto[lag] / denominator >= BED_CORRELATION:
879-
return True
880-
return False
860+
block = mono[max(0, first) : last]
861+
return (
862+
dsp.repeat_correlation(
863+
block, sample_rate, BED_MIN_PERIOD_SECONDS, BED_MIN_OVERLAP_SECONDS
864+
)
865+
>= BED_CORRELATION
866+
)
881867

882868

883869
def _untranscribed(mono, sample_rate, index, start, end, shot):

0 commit comments

Comments
 (0)