From 6104e8f0f90790e93e20998c63df54434fcc93cb Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:46:17 +0800 Subject: [PATCH 01/23] fix: preserve selected audio track levels and stereo image --- earshot/audio.py | 27 +++++++------- earshot/timeline.py | 4 +-- tests/test_audio_multitrack.py | 66 ++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 17 deletions(-) create mode 100644 tests/test_audio_multitrack.py diff --git a/earshot/audio.py b/earshot/audio.py index f406725..11b4f8e 100644 --- a/earshot/audio.py +++ b/earshot/audio.py @@ -8,6 +8,9 @@ m = load('kick.ogg', mono=True) # (n,) seg = load('long.wav', start=1.2, end=1.8, mono=True) +Track selection stays with ffmpeg (including default-track preferences); probe() reports the first audio track, +which may not be the selected track in a multi-track file. + Levels: the stereo decode keeps true sample levels (a mono file is duplicated to both channels at unity gain), so measure peaks and loudness on it (features.measure does). mono=True is ffmpeg's downmix, which sums a stereo source at -3 dB per channel: correlated stereo reads up to +3 dB hotter than mean(L, R). It is the models' input convention @@ -33,7 +36,7 @@ class AudioError(RuntimeError): pass -DECODE_VERSION = 2 # bump when decoded samples change (derived caches may key on it) +DECODE_VERSION = 3 # bump when decoded samples change (derived caches may key on it) def _sample_hash(path, size, blocks=16, block=4096): @@ -76,15 +79,6 @@ def replace_quietly(tmp, dst, tries=5): return False -def _src_channels(path): - try: - out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', - '-of', 'csv=p=0', path], capture_output=True, text=True, timeout=60).stdout.strip() - return int(out.splitlines()[0]) if out else 0 - except Exception: # noqa: BLE001 - return 0 - - def file_id(path): """stable id of a file's content state (path + size + mtime + sampled content); used as a cache key by the models""" return hashlib.sha1(_state(path).encode()).hexdigest()[:20] @@ -104,9 +98,14 @@ def _ffmpeg_reason(err): def _decode(path, sr, ch): - up = ch == 2 and _src_channels(path) == 1 # ffmpeg would upmix mono at -3 dB; duplicate at unity instead - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', '-acodec', 'pcm_f32le', - '-ac', '1' if up else str(ch), '-ar', str(sr), '-'], capture_output=True) + cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn'] + if ch == 2: + # Inspect the actually selected input layout, not the first audio stream: ffmpeg may select a later track. + # Keep mono at unity; stereo and surround retain ffmpeg's usual stereo downmix. + cmd += ['-af', "aformat=channel_layouts=mono|stereo," + "aeval=exprs='val(0)|val(if(eq(nb_in_channels,1),0,1))':channel_layout=stereo"] + cmd += ['-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', str(ch), '-ar', str(sr), '-'] + p = subprocess.run(cmd, capture_output=True) err = p.stderr.decode(errors='replace') if p.returncode != 0 or not p.stdout: pr = probe(path) @@ -116,8 +115,6 @@ def _decode(path, sr, ch): raise AudioError(f'{path}: no audio stream') raise AudioError(f'cannot decode {path}: {_ffmpeg_reason(err)}') x = np.frombuffer(p.stdout, np.float32).copy() - if up: - return np.repeat(x[:, None], 2, axis=1) return x.reshape(-1, ch) if ch > 1 else x diff --git a/earshot/timeline.py b/earshot/timeline.py index 90377b1..d2a4fa2 100644 --- a/earshot/timeline.py +++ b/earshot/timeline.py @@ -784,8 +784,8 @@ def _cached(model, fid, spans, kind, compute, reuse=True): def span_id(path): - """file id for the per-span model cache; mono sources decode at unity gain since core decode v2""" - return audio.file_id(path) + ('|mono2' if audio.probe(path).get('channels') == 1 else '') + """per-span models consume the stereo decode averaged to mono, so follow its decode version""" + return audio.file_id(path) + f'|decode{audio.DECODE_VERSION}' def _seg(x, a, b): diff --git a/tests/test_audio_multitrack.py b/tests/test_audio_multitrack.py new file mode 100644 index 0000000..c1c1002 --- /dev/null +++ b/tests/test_audio_multitrack.py @@ -0,0 +1,66 @@ +"""Real synthetic media: preserve FFmpeg's selected track, stereo image and mono unity gain.""" +import hashlib +import subprocess + +import numpy as np +import pytest +import soundfile as sf + +from earshot import audio, timeline + + +def _wav(tmp_path, channels, sr=48000): + t = np.arange(sr) / sr + x = np.column_stack([0.1 * np.sin(2 * np.pi * (220 + i * 110) * t) for i in range(channels)]) + p = tmp_path / f'{channels}_{sr}.wav' + sf.write(p, x, sr, subtype='FLOAT') + return str(p) + + +def _reference(path, channels, sr=48000): + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', + '-acodec', 'pcm_f32le', '-ac', str(channels), '-ar', str(sr), '-'], + capture_output=True, check=True) + x = np.frombuffer(p.stdout, np.float32) + return x if channels == 1 else x.reshape(-1, channels) + + +@pytest.mark.parametrize('first_channels,second_channels,default', [ + (1, 2, None), (1, 2, 0), (1, 2, 1), (2, 1, 1), (2, 1, None), (1, 2, 'both'), +]) +def test_multitrack_stereo_and_mono(tmp_path, first_channels, second_channels, default): + sources = [_wav(tmp_path, first_channels), _wav(tmp_path, second_channels)] + path = str(tmp_path / 'tracks.mkv') + subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', sources[0], '-i', sources[1], + '-map', '0:a', '-map', '1:a', '-c:a', 'pcm_f32le', + '-disposition:a:0', 'default' if default in (0, 'both') else '0', + '-disposition:a:1', 'default' if default in (1, 'both') else '0', path], check=True) + # With these populated streams, FFmpeg prioritizes default, then channel count. + selected = default if isinstance(default, int) else (0 if first_channels > second_channels else 1) + count = [first_channels, second_channels][selected] + expected = _reference(sources[selected], 1 if count == 1 else 2) + if count == 1: + expected = np.repeat(expected[:, None], 2, axis=1) + actual = audio.load(path, cache=False) + np.testing.assert_allclose(actual, expected, atol=1e-7) + # Model input convention must remain byte-for-byte the original FFmpeg mono downmix. + np.testing.assert_array_equal(audio.load(path, mono=True, cache=False), _reference(path, 1)) + + +@pytest.mark.parametrize('channels', [1, 2, 6]) +@pytest.mark.parametrize('sr', [44100, 48000]) +def test_single_track_and_resampling(tmp_path, channels, sr): + path = _wav(tmp_path, channels, sr) + expected = _reference(path, 1 if channels == 1 else 2) + if channels == 1: + expected = np.repeat(expected[:, None], 2, axis=1) + np.testing.assert_allclose(audio.load(path, cache=False), expected, atol=1e-7) + np.testing.assert_array_equal(audio.load(path, mono=True, cache=False), _reference(path, 1)) + + +def test_decode_and_span_keys_cannot_reuse_v2_samples(tmp_path): + path = _wav(tmp_path, 1) + old_decode = hashlib.sha1(f'{audio._state(path)}|48000|2|v2'.encode()).hexdigest()[:20] + assert audio._key(path, 48000, 2) != old_decode + assert timeline.span_id(path) != audio.file_id(path) + '|mono2' + assert timeline.span_id(path).endswith(f'|decode{audio.DECODE_VERSION}') From a07211a6a7d32f714016b2b191b6637824472c3e Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:36:21 +0800 Subject: [PATCH 02/23] fix: preserve requested sample peak after bank resampling --- earshot/forge/bank.py | 16 +++++++++---- tests/test_resampled_level.py | 44 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 5 deletions(-) create mode 100644 tests/test_resampled_level.py diff --git a/earshot/forge/bank.py b/earshot/forge/bank.py index ce0e9d4..99cad02 100644 --- a/earshot/forge/bank.py +++ b/earshot/forge/bank.py @@ -313,6 +313,7 @@ def render(sound_id, seed=None, dur=None, apex=None, pitch=None, peak_db=PEAK_DB final); dur / apex (s), pitch ('E5' or Hz) aim it through the recipe's own parameters (earshot.forge.knobs); peak_db = its sample peak (0 dBFS or less); weight scales that by 6 dB per doubling (1 = peak_db, 0.5 = 6 dB down; a level over 0 dBFS is refused: level()). sr (one of SRS) != 48000 resamples the finished take (soxr). + The sample peak is set after conversion. Loudness and the audit use a 48 kHz analysis copy. checks=False skips the model-free audit (meta['checks'] None).""" lv = level(peak_db, weight) sr = check_sr(sr) @@ -330,14 +331,19 @@ def render(sound_id, seed=None, dur=None, apex=None, pitch=None, peak_db=PEAK_DB y = normalize(x, level_db).astype(np.float32) meta = {'id': sid, 'seed': int(e['seed'] if seed is None else seed), 'sr': int(sr), **measure(y), 'edits': edits, 'checks': None} + if int(sr) != SR: + import soxr + from .polish import lufs_max + # The final sample rate can introduce new peaks; set the requested level after conversion. + y = normalize(soxr.resample(y, SR, int(sr)), level_db).astype(np.float32) + meta.update(times(y, sr)) + meta['peak_db'] = round(float(20 * np.log10(np.abs(y).max() + 1e-12)), 2) + # Loudness and the artifact audit use a 48 kHz analysis copy, not a mislabelled final array. + meta['lufs_m_max'] = round(float(lufs_max(soxr.resample(y.astype(np.float64), sr, SR))), 2) if checks: from . import sfx - meta['checks'] = sfx.check(y, category=e.get('category'), sound=sid) + meta['checks'] = sfx.check(y, sr=sr, category=e.get('category'), sound=sid) add_warning(meta['checks'], knobs.pitch_warning(edits)) - if int(sr) != SR: - import soxr - y = np.asarray(soxr.resample(y, SR, int(sr)), np.float32) - meta['dur_s'] = round(len(y) / int(sr), 4) return y, meta diff --git a/tests/test_resampled_level.py b/tests/test_resampled_level.py new file mode 100644 index 0000000..76e549d --- /dev/null +++ b/tests/test_resampled_level.py @@ -0,0 +1,44 @@ +import numpy as np +import pytest +import soundfile as sf +import soxr +from earshot.forge import bank, sfx +from earshot.forge.polish import lufs_max + +@pytest.mark.parametrize('sr', bank.SRS) +@pytest.mark.parametrize('peak_db,weight', [(0, None), (-1, None), (-1, 0.5)]) +def test_final_sample_peak_and_metadata(sr, peak_db, weight): + y, meta = bank.render('click/tink', sr=sr, peak_db=peak_db, weight=weight, checks=False) + target = bank.level(peak_db, weight) + assert y.dtype == np.float32 and y.ndim == 2 and y.shape[1] == 2 + assert float(np.max(np.abs(y))) == pytest.approx(10 ** (target / 20), abs=1e-7) + assert np.max(np.abs(y)) <= 1 + assert meta['peak_db'] == round(target, 2) + assert all(meta[k] == v for k, v in bank.times(y, sr).items()) + analysis = y.astype(np.float64) if sr == bank.SR else soxr.resample(y.astype(np.float64), sr, bank.SR) + assert meta['lufs_m_max'] == round(float(lufs_max(analysis)), 2) + assert meta['checks'] is None + +@pytest.mark.parametrize('sr', [44100, 88200, 96000]) +def test_official_pcm24_writer_preserves_the_take_within_quantization(tmp_path, sr): + y, meta = bank.render('click/tink', sr=sr, peak_db=0) + result = sfx.sfx_render('click/tink', out=str(tmp_path / 'take.wav'), sr=sr, peak_db=0) + saved, read_sr = sf.read(result['file'], dtype='float32') + assert read_sr == sr and sf.info(result['file']).subtype == 'PCM_24' + np.testing.assert_allclose(saved, y, atol=2**-23, rtol=0) + assert meta == result['meta'] + assert meta['checks'] == sfx.check(y, sr=sr, category='click', sound='click/tink') + +@pytest.mark.parametrize('sound,options', [ + ('tap/finger', {'dur': 0.12}), + ('whoosh_fast/crisp', {'dur': 0.4, 'apex': 0.2}), + ('pluck/kalimba', {'pitch': 'E5', 'dur': 0.3}), +]) +def test_other_shapes_and_knobs_keep_output_level(sound, options): + native, _ = bank.render(sound, checks=False, **options) + y, meta = bank.render(sound, sr=44100, peak_db=-1, checks=False, **options) + assert y.ndim == native.ndim and y.shape[1:] == native.shape[1:] + assert abs(len(y) - round(len(native) * 44100 / 48000)) <= 1 + assert np.max(np.abs(y)) == pytest.approx(10 ** (-1 / 20), abs=1e-7) + assert all(meta[k] == v for k, v in bank.times(y, 44100).items()) + assert all(k in meta['edits'] for k in options) From ec876bcfd921ffda75eb108fce1a952b10ad975d Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:46:17 +0800 Subject: [PATCH 03/23] fix: isolate named theme axes from preset state --- earshot/sounds/theme.py | 2 +- tests/test_theme_isolation.py | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/test_theme_isolation.py diff --git a/earshot/sounds/theme.py b/earshot/sounds/theme.py index a18eab8..be8b068 100644 --- a/earshot/sounds/theme.py +++ b/earshot/sounds/theme.py @@ -47,7 +47,7 @@ def get(theme=None): if isinstance(theme, str): if theme not in THEMES: raise ValueError(f'unknown theme {theme!r}: one of {", ".join(THEMES)}') - return dict(THEMES[theme], name=theme) + return dict(THEMES[theme], name=theme, axes=dict(THEMES[theme]['axes'])) t = dict(theme) base = t.pop('base', None) if base is not None and base not in THEMES: diff --git a/tests/test_theme_isolation.py b/tests/test_theme_isolation.py new file mode 100644 index 0000000..9fc5ff2 --- /dev/null +++ b/tests/test_theme_isolation.py @@ -0,0 +1,45 @@ +"""Theme edits must not change presets or other rendering requests.""" +from copy import deepcopy + +from earshot.sounds import theme + + +def test_named_theme_axes_do_not_alias_presets_or_other_requests(): + for name in theme.THEMES: + saved = deepcopy(theme.THEMES[name]) + try: + edited = theme.get(name) + other = theme.get(name) + edited['axes']['bright'] = 0.99 + assert other['axes'] == saved['axes'], name + assert theme.get(name)['axes'] == saved['axes'], name + assert theme.THEMES[name] == saved, name + assert edited['axes']['bright'] == 0.99 + finally: + # Keep the suite isolated even when run against the broken baseline. + theme.THEMES[name] = saved + + +def test_named_theme_axes_can_be_cleared_without_resetting_the_preset(): + for name in theme.THEMES: + saved = deepcopy(theme.THEMES[name]) + try: + edited = theme.get(name) + edited['axes'].clear() + assert theme.get(name)['axes'] == saved['axes'], name + assert theme.THEMES[name] == saved, name + finally: + theme.THEMES[name] = saved + + +def test_dict_theme_overrides_are_independent_and_preserve_values(): + override = {'base': 'wood', 'key': 'D', 'axes': {'hard': 0.2}} + saved = deepcopy(override) + result = theme.get(override) + assert result['axes'] == {'bright': -0.1, 'ring': -0.2, 'hard': 0.2} + assert result['key'] == 'D' + assert result['voice'] == 'marimba' + result['axes']['hard'] = -0.8 + assert override == saved + assert theme.get(None) is None + assert theme.get({'key': 'E'}) == {'key': 'E', 'axes': {}} From 2eb7dc040fa4a166933a084202f757a8a8d3a962 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:26:34 +0800 Subject: [PATCH 04/23] fix: retain the search index backing cached positions --- earshot/brief.py | 8 +++--- tests/test_brief_index_lifetime.py | 43 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 tests/test_brief_index_lifetime.py diff --git a/earshot/brief.py b/earshot/brief.py index c48d96e..dc231e2 100644 --- a/earshot/brief.py +++ b/earshot/brief.py @@ -1124,8 +1124,8 @@ def _twin(sid, out, idx): None""" if not idx: return None - if _cache.get('pos_key') != id(idx): - _cache['pos_key'], _cache['pos'] = id(idx), {r['id']: k for k, r in enumerate(idx[0])} + if _cache.get('pos_idx') is not idx: + _cache['pos_idx'], _cache['pos'] = idx, {r['id']: k for k, r in enumerate(idx[0])} pos, terms = _cache['pos'], idx[1] fam, name, jobs = sid.split('/')[0], _name_words(sid), terms[pos[sid]]['family'] for r in out: @@ -1146,8 +1146,8 @@ def _preferred(b, sid, out, idx): if not idx or any(modifier(w) for w in sid.split('/')[1].split('_')): return None rows, terms = idx[0], idx[1] - if _cache.get('pos_key') != id(idx): - _cache['pos_key'], _cache['pos'] = id(idx), {r['id']: k for k, r in enumerate(rows)} + if _cache.get('pos_idx') is not idx: + _cache['pos_idx'], _cache['pos'] = idx, {r['id']: k for k, r in enumerate(rows)} pos = _cache['pos'] fam, prior = sid.split('/')[0], rows[pos[sid]].get('prior', 1.0) if 'real' in rows[pos[sid]].get('tags', ()): diff --git a/tests/test_brief_index_lifetime.py b/tests/test_brief_index_lifetime.py new file mode 100644 index 0000000..b0fa1ae --- /dev/null +++ b/tests/test_brief_index_lifetime.py @@ -0,0 +1,43 @@ +from earshot import brief + + +def _rows(family): + return [dict(id=family + '/pop', uses=[family], says=['a ' + family + ' pop'], + tags=[], kind='pop', prior=1.0), + dict(id=family + '/wine', uses=[family], says=['a ' + family + ' with a hollow pop'], + tags=['real'], kind='pop', prior=1.0)] + + +def test_position_cache_retains_the_index_it_describes(): + previous = dict(brief._cache) + try: + brief._cache.clear() + idx = brief.index(_rows('cork')) + brief.rank(brief.read('a cork pop'), idx=idx) + assert brief._cache.get('pos_idx') is idx + other = brief.index(list(reversed(_rows('bottle')))) + brief.rank(brief.read('a bottle pop'), idx=other) + assert brief._cache.get('pos_idx') is other + assert brief._cache['pos'] == {r['id']: i for i, r in enumerate(other[0])} + finally: + brief._cache.clear() + brief._cache.update(previous) + + +def test_temporary_catalogues_match_cold_rankings(): + previous = dict(brief._cache) + try: + catalogues = [_rows('cork'), list(reversed(_rows('bottle')))] + queries = [brief.read('a cork pop'), brief.read('a bottle pop')] + for semantic in (None, {'cork/pop': 0.3, 'cork/wine': 0.6, 'bottle/pop': 0.3, 'bottle/wine': 0.6}): + cold = [] + for query, rows in zip(queries, catalogues): + brief._cache.clear() + cold.append(brief.rank(query, rows=rows, semantic=semantic)) + brief._cache.clear() + for i in range(100): + k = i % 2 + assert brief.rank(queries[k], rows=catalogues[k], semantic=semantic) == cold[k] + finally: + brief._cache.clear() + brief._cache.update(previous) From 8d5487926284f03c3536f6daf9eeb3ee56725fb8 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:26:06 +0800 Subject: [PATCH 05/23] fix: reject duplicate expanded set take names before rendering --- earshot/make.py | 19 +++++++-- tests/test_make_set_names.py | 81 ++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 tests/test_make_set_names.py diff --git a/earshot/make.py b/earshot/make.py index 7701f47..cb45d87 100644 --- a/earshot/make.py +++ b/earshot/make.py @@ -317,6 +317,9 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, "lufs": -18, "sprite": "sprite.webm", "sounds": [{"name": "tap", "want": "a soft tap for buttons"}, {"name": "success", "want": "a happy two-note success chime", "dur": 0.5, "axes": {"bright": 0.2}}]} + Expanded take names must be unique ("tap" with n=2 would conflict with "tap_1"); conflicts are refused + before any take is rendered or written. Names also identify manifest rows, so directory prefixes do not + distinguish two takes with the same basename. "set" starts from a ready-made list; "sounds" adds to it, or changes the sound of the same name. Each sound takes name (the file name) and want (words) and / or sound (a design id), plus pitch, dur, voice, material, seed, n, axes, lufs. Every sound shares the theme (one voice, key and room). The sounds are levelled against @@ -357,17 +360,27 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, fmts = _formats(fmt or spec.get('format') or 'wav') mono = spec.get('mono', False) if mono is None else mono top = lufs if lufs is not None else spec.get('lufs', -16.0) - rows, lines, ys, alts, missed, first, played = [], [], [], {}, {}, {}, {} + # Expanded names identify both manifest rows and sprite entries; validate before writing any take. + planned, paths = [], set() for it in items: b, cands = choose(it.get('want'), it.get('sound'), pitch=it.get('pitch'), dur=it.get('dur'), voice=it.get('voice'), material=it.get('material'), axes=it.get('axes')) if not cands: raise ValueError(f'{it["name"]}: no sound in the catalogue answers {it.get("want")!r}') d = registry.get(cands[0]['id']) - level = it.get('lufs', top + WEIGHT.get(d.kind, -4.0)) k = int(it.get('n') or b['n'] or 1) + takes = _paths(os.path.join(out, f'{it["name"]}.{fmts[0]}'), k, fmts[0]) + for p in takes: + key = os.path.normcase(os.path.splitext(os.path.basename(p))[0]) + if key in paths: + raise ValueError(f'take name {os.path.basename(p)!r} is used more than once: rename a sound of the set') + paths.add(key) + planned.append((it, b, cands, d, takes)) + rows, lines, ys, alts, missed, first, played = [], [], [], {}, {}, {}, {} + for it, b, cands, d, takes in planned: + level = it.get('lufs', top + WEIGHT.get(d.kind, -4.0)) mine = {} # the recordings this name played: {n: meta['member']} - for p in _paths(os.path.join(out, f'{it["name"]}.{fmts[0]}'), k, fmts[0]): + for p in takes: y, meta = take(d.id, int(it.get('seed', seed)) + len(rows), _request(b, theme), lufs=level) stem = os.path.splitext(p)[0] loop = bool(meta.get('loop', False)) diff --git a/tests/test_make_set_names.py b/tests/test_make_set_names.py new file mode 100644 index 0000000..d30afb7 --- /dev/null +++ b/tests/test_make_set_names.py @@ -0,0 +1,81 @@ +"""Expanded set names must not overwrite another take or duplicate manifest identities.""" +import json + +import numpy as np +import pytest +import soundfile as sf + +from earshot.make import make_set +from earshot.sounds import registry + + +@pytest.fixture +def tone_catalogue(monkeypatch): + # A controlled catalogue; the real renderer, mastering, audit and file writer still run. + monkeypatch.setattr(registry, '_designs', {}) + monkeypatch.setattr(registry, '_loaded', True) + + @registry.design('test/tone', kind='note', says=('a test tone', 'a short note'), dur=0.2, pitch='A4') + def tone(c, r): + t = np.arange(round(c.seconds() * 48000)) / 48000 + return np.sin(2 * np.pi * 440 * t) * np.sin(np.linspace(0, np.pi, len(t))) ** 2 + + +@pytest.mark.parametrize('reverse', [False, True]) +@pytest.mark.parametrize('fmt', ['wav', ['wav', 'flac']]) +@pytest.mark.parametrize('count', [{'n': 2}, {'want': 'two variations of a note'}]) +def test_expanded_take_names_are_rejected_before_writes(tmp_path, tone_catalogue, reverse, fmt, count): + items = [{'name': 'tap', 'sound': 'test/tone', 'dur': 0.2, **count}, + {'name': 'tap_1', 'sound': 'test/tone', 'dur': 0.4}] + if reverse: + items.reverse() + # Existing output must survive, including its manifest and the colliding filename. + sentinel = tmp_path / 'tap_1.wav' + sentinel.write_bytes(b'existing take') + manifest = tmp_path / 'manifest.json' + manifest.write_text('{"existing": true}', encoding='utf-8') + before = {p.name: p.read_bytes() for p in tmp_path.iterdir()} + with pytest.raises(ValueError, match='take name'): + make_set({'sounds': items, 'format': fmt}, out=str(tmp_path)) + assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before + + +def test_duplicate_manifest_basenames_are_rejected(tmp_path, tone_catalogue): + items = [{'name': 'first/tap', 'sound': 'test/tone'}, + {'name': 'second/tap', 'sound': 'test/tone'}] + with pytest.raises(ValueError, match='take name'): + make_set({'sounds': items}, out=str(tmp_path)) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('fmt', ['wav', ['wav', 'flac']]) +def test_distinct_expanded_names_keep_files_and_metadata(tmp_path, tone_catalogue, fmt): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'n': 2, 'dur': 0.2}, + {'name': 'other', 'sound': 'test/tone', 'dur': 0.4}], + 'format': fmt}, out=str(tmp_path)) + assert [r['name'] for r in result['sounds']] == ['tap_1', 'tap_2', 'other'] + assert len(set(result['files'])) == len(result['files']) + assert json.loads((tmp_path / 'manifest.json').read_text())['sounds'] == result['sounds'] + for row in result['sounds']: + for path in row['files']: + data, sr = sf.read(tmp_path / path) + assert len(data) / sr == pytest.approx(row['dur_s'], abs=0.002) + assert np.isfinite(data).all() and np.max(np.abs(data)) > 0 + + +def test_explicit_take_count_overrides_words(tmp_path, tone_catalogue): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'want': 'two variations of a note', 'n': 1}, + {'name': 'tap_1', 'sound': 'test/tone'}]}, out=str(tmp_path)) + assert [r['name'] for r in result['sounds']] == ['tap', 'tap_1'] + assert len(set(result['files'])) == 2 + + +def test_loop_format_replacement_is_unchanged(tmp_path, tone_catalogue): + d = registry.get('test/tone') + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(d.fn) + result = make_set({'sounds': [{'name': 'loop', 'sound': 'test/loop', 'n': 2}], + 'format': ['mp3', 'flac']}, out=str(tmp_path)) + assert [r['files'] for r in result['sounds']] == [['loop_1.flac'], ['loop_2.flac']] + assert all(r['loop'] for r in result['sounds']) + assert sorted(p.name for p in tmp_path.iterdir()) == ['loop_1.flac', 'loop_2.flac', 'manifest.json'] From 69f3ae554f918fc4a973d9cffd429a0ddff78fc5 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:35:12 +0800 Subject: [PATCH 06/23] fix: reserve sprite destinations before rendering sets --- earshot/make.py | 26 +++++++++++---- tests/test_make_set_names.py | 64 ++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/earshot/make.py b/earshot/make.py index cb45d87..c208e70 100644 --- a/earshot/make.py +++ b/earshot/make.py @@ -319,7 +319,8 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, {"name": "success", "want": "a happy two-note success chime", "dur": 0.5, "axes": {"bright": 0.2}}]} Expanded take names must be unique ("tap" with n=2 would conflict with "tap_1"); conflicts are refused before any take is rendered or written. Names also identify manifest rows, so directory prefixes do not - distinguish two takes with the same basename. + distinguish two takes with the same basename. Sprite audio and map paths must not overwrite takes or + manifest.json; these collisions are also refused before rendering. "set" starts from a ready-made list; "sounds" adds to it, or changes the sound of the same name. Each sound takes name (the file name) and want (words) and / or sound (a design id), plus pitch, dur, voice, material, seed, n, axes, lufs. Every sound shares the theme (one voice, key and room). The sounds are levelled against @@ -376,6 +377,23 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, raise ValueError(f'take name {os.path.basename(p)!r} is used more than once: rename a sound of the set') paths.add(key) planned.append((it, b, cands, d, takes)) + sprite = sprite or spec.get('sprite') + outs = [] + if sprite: + stem, ext = os.path.splitext(os.path.join(out, os.path.basename(sprite))) + ext = ext.lower().lstrip('.') + outs = [f'{stem}.{f}' for f in fmts] if not ext or ext in fmts else [f'{stem}.{ext}'] + destinations = {os.path.normcase(os.path.abspath(os.path.join(out, 'manifest.json')))} + for it, b, cands, d, takes in planned: + own = _loop_formats(fmts) if d.loop and b.get('loop') is not False else fmts + for p in takes: + stem = os.path.splitext(p)[0] + destinations.update(os.path.normcase(os.path.abspath(f'{stem}.{f}')) for f in own) + for p in outs + [os.path.splitext(outs[0])[0] + '.json']: + key = os.path.normcase(os.path.abspath(p)) + if key in destinations: + raise ValueError(f'sprite output {p!r} would overwrite a set file: rename the sprite') + destinations.add(key) rows, lines, ys, alts, missed, first, played = [], [], [], {}, {}, {}, {} for it, b, cands, d, takes in planned: level = it.get('lufs', top + WEIGHT.get(d.kind, -4.0)) @@ -433,12 +451,8 @@ def make_set(spec, out=None, theme=None, fmt=None, seed=0, mono=None, lufs=None, head = f'{len(rows)} sounds in {out} ({", ".join(fmts)}), manifest.json' res = {'files': [os.path.join(out, f) for r in rows for f in r['files']], 'manifest': man, 'sounds': rows, 'also': alts, 'not_in_sound': missed} - sprite = sprite or spec.get('sprite') - if sprite: + if outs: from .pack import pack - stem, ext = os.path.splitext(os.path.join(out, os.path.basename(sprite))) - ext = ext.lower().lstrip('.') - outs = [f'{stem}.{f}' for f in fmts] if not ext or ext in fmts else [f'{stem}.{ext}'] sp = pack([os.path.join(out, r['file']) for r in rows], outs, mono=mono, loops=[r['name'] for r in rows if r['loop']], ys=ys) lines.append(sp['summary']) diff --git a/tests/test_make_set_names.py b/tests/test_make_set_names.py index d30afb7..934b585 100644 --- a/tests/test_make_set_names.py +++ b/tests/test_make_set_names.py @@ -1,5 +1,7 @@ """Expanded set names must not overwrite another take or duplicate manifest identities.""" import json +import shutil +from pathlib import Path import numpy as np import pytest @@ -79,3 +81,65 @@ def test_loop_format_replacement_is_unchanged(tmp_path, tone_catalogue): assert [r['files'] for r in result['sounds']] == [['loop_1.flac'], ['loop_2.flac']] assert all(r['loop'] for r in result['sounds']) assert sorted(p.name for p in tmp_path.iterdir()) == ['loop_1.flac', 'loop_2.flac', 'manifest.json'] + + +@pytest.mark.parametrize('sprite,fmt', [ + ('tap.wav', 'wav'), ('tap', 'wav'), ('tap.flac', ['wav', 'flac']), + ('nested/tap.wav', 'wav'), ('manifest.wav', 'wav'), ('manifest', ['wav', 'flac']), +]) +@pytest.mark.parametrize('argument', [False, True]) +def test_sprite_destinations_cannot_overwrite_set_files(tmp_path, tone_catalogue, sprite, fmt, argument): + items = [{'name': 'tap', 'sound': 'test/tone'}, {'name': 'other', 'sound': 'test/tone'}] + spec = {'sounds': items, 'format': fmt} + kwargs = {'sprite': sprite} if argument else {} + if not argument: + spec['sprite'] = sprite + (tmp_path / 'tap.wav').write_bytes(b'existing take') + (tmp_path / 'manifest.json').write_bytes(b'existing manifest') + before = {p.name: p.read_bytes() for p in tmp_path.iterdir()} + with pytest.raises(ValueError, match='sprite output'): + make_set(spec, out=str(tmp_path), **kwargs) + assert {p.name: p.read_bytes() for p in tmp_path.iterdir()} == before + + +def test_sprite_checks_the_loop_replacement_format(tmp_path, tone_catalogue): + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(registry.get('test/tone').fn) + with pytest.raises(ValueError, match='sprite output'): + make_set({'sounds': [{'name': 'tap', 'sound': 'test/loop'}], 'format': 'mp3', + 'sprite': 'tap.flac'}, out=str(tmp_path)) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('sprite,fmt', [('sprite', ['wav', 'flac']), ('tap.flac', 'wav')]) +def test_nonconflicting_sprite_keeps_takes_manifest_and_map(tmp_path, tone_catalogue, sprite, fmt): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone', 'dur': 0.2}, + {'name': 'other', 'sound': 'test/tone', 'dur': 0.4}], + 'format': fmt, 'sprite': sprite}, out=str(tmp_path)) + assert json.loads((tmp_path / 'manifest.json').read_text())['sounds'] == result['sounds'] + for row in result['sounds']: + assert sf.info(tmp_path / row['file']).duration == pytest.approx(row['dur_s'], abs=0.002) + sprite_path = result['sprite'] + doc = json.loads(Path(sprite_path).with_suffix('.json').read_text()) + assert set(doc['sprite']) == {'tap', 'other'} + assert doc['src'] == [Path(p).name for p in result['sprites']] + for p in result['sprites']: + assert sf.info(p).duration > 0.8 + + +def test_sprite_override_takes_precedence_over_spec(tmp_path, tone_catalogue): + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/tone'}], 'sprite': 'manifest.wav'}, + out=str(tmp_path), sprite='safe.wav') + assert result['sprite'] == str(tmp_path / 'safe.wav') + assert 'sounds' in json.loads((tmp_path / 'manifest.json').read_text()) + + +@pytest.mark.skipif(shutil.which('ffmpeg') is None, reason='mp3 writing needs ffmpeg') +def test_loop_rendered_once_reserves_its_requested_format(tmp_path, tone_catalogue): + registry.design('test/loop', kind='note', says=('a looping tone', 'a sustained note'), dur=0.2, + pitch='A4', loop=True)(registry.get('test/tone').fn) + result = make_set({'sounds': [{'name': 'tap', 'sound': 'test/loop', 'want': 'one-shot'}], + 'format': 'mp3', 'sprite': 'tap.flac'}, out=str(tmp_path)) + assert result['sounds'][0]['loop'] is False + assert result['sounds'][0]['files'] == ['tap.mp3'] + assert (tmp_path / 'tap.mp3').is_file() and (tmp_path / 'tap.flac').is_file() From 811fbf5573b67262aa5aa2bba6b72a63035da024 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:24:17 +0800 Subject: [PATCH 07/23] fix: reject sprite names count mismatches before audio I/O --- earshot/pack.py | 2 ++ tests/test_pack_names.py | 66 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 tests/test_pack_names.py diff --git a/earshot/pack.py b/earshot/pack.py index 5b2414b..2f41563 100644 --- a/earshot/pack.py +++ b/earshot/pack.py @@ -56,6 +56,8 @@ def pack(files, out, gap=GAP_S, mono=False, names=None, loops=(), ys=None): if not files: raise ValueError('nothing to pack: no audio files') names = list(names) if names else [os.path.splitext(os.path.basename(f))[0] for f in files] + if len(names) != len(files): + raise ValueError('a sprite needs one name per audio file') if len(set(names)) != len(names): raise ValueError('two sounds of a sprite share a name') parts, sprite, t = [], {}, 0.0 diff --git a/tests/test_pack_names.py b/tests/test_pack_names.py new file mode 100644 index 0000000..c13f3d4 --- /dev/null +++ b/tests/test_pack_names.py @@ -0,0 +1,66 @@ +"""Names must not silently truncate an audio sprite's inputs.""" +import json + +import numpy as np +import pytest +import soundfile as sf + +from earshot.pack import pack +from earshot.synth import master + + +@pytest.fixture +def inputs(tmp_path): + paths = [] + for name, frequency in [('first', 440), ('second', 880)]: + path = tmp_path / f'{name}.wav' + t = np.arange(4800) / master.SR + sf.write(path, .2 * np.sin(2 * np.pi * frequency * t), master.SR) + paths.append(str(path)) + return paths + + +@pytest.mark.parametrize('names', [['only'], ['a', 'b', 'c']]) +@pytest.mark.parametrize('source', ['paths', 'folder', 'arrays']) +def test_mismatched_names_leave_existing_outputs_untouched(tmp_path, inputs, names, source): + out = tmp_path / 'sprite.wav' + mapping = tmp_path / 'sprite.json' + out.write_bytes(b'existing audio') + mapping.write_bytes(b'existing map') + files = str(tmp_path) if source == 'folder' else inputs + kwargs = {'ys': [np.zeros(4800), np.ones(4800) * .1]} if source == 'arrays' else {} + with pytest.raises(ValueError, match='one name per audio file'): + pack(files, str(out), names=names, **kwargs) + assert out.read_bytes() == b'existing audio' + assert mapping.read_bytes() == b'existing map' + + +@pytest.mark.parametrize('names', [['only'], ['a', 'b', 'c'], iter(())]) +def test_count_checked_before_loading_missing_inputs(tmp_path, names): + out = tmp_path / 'sprite.wav' + with pytest.raises(ValueError, match='one name per audio file'): + pack(['missing-a.wav', 'missing-b.wav'], str(out), names=names) + assert not out.exists() + assert not out.with_suffix('.json').exists() + + +@pytest.mark.parametrize('kind', ['list', 'tuple', 'generator', 'default', 'empty']) +def test_matching_and_default_names_keep_all_audio(tmp_path, inputs, kind): + names = {'list': ['first', 'second'], 'tuple': ('first', 'second'), + 'generator': iter(['first', 'second']), 'default': None, 'empty': []}[kind] + out = tmp_path / 'sprite.wav' + result = pack(inputs, str(out), names=names, gap=.05) + assert list(result['sprite']) == ['first', 'second'] + assert result['sprite'] == {'first': [0, 100], 'second': [150, 100]} + assert result['summary'].startswith('2 sounds in ') + assert sf.info(out).frames == 12000 + doc = json.loads(out.with_suffix('.json').read_text()) + assert doc['sprite'] == result['sprite'] + control = tmp_path / 'control.wav' + pack(inputs, str(control), gap=.05) + assert out.read_bytes() == control.read_bytes() + + +def test_duplicate_names_still_rejected(tmp_path, inputs): + with pytest.raises(ValueError, match='share a name'): + pack(inputs, str(tmp_path / 'sprite.wav'), names=['same', 'same']) From 1685b0795488e982154e99ed0d5decf1641f5d08 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:10:39 +0800 Subject: [PATCH 08/23] fix: keep media analysis usable when optional caches cannot be written --- earshot/audio.py | 27 +++++- earshot/timeline.py | 13 ++- earshot/video.py | 27 ++---- tests/test_optional_media_cache.py | 133 +++++++++++++++++++++++++++++ 4 files changed, 166 insertions(+), 34 deletions(-) create mode 100644 tests/test_optional_media_cache.py diff --git a/earshot/audio.py b/earshot/audio.py index f406725..07a99a4 100644 --- a/earshot/audio.py +++ b/earshot/audio.py @@ -85,6 +85,28 @@ def _src_channels(path): return 0 +def write_cache(path, write): + """Best-effort cache write; only filesystem errors are optional, not errors in the producer.""" + import tempfile + tmp = None + try: + folder = os.path.dirname(path) or '.' + os.makedirs(folder, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=folder, prefix=os.path.basename(path) + '.', + suffix=os.path.splitext(path)[1], delete=False) as fh: + tmp = fh.name + write(tmp) + return replace_quietly(tmp, path) + except OSError: + return False + finally: + if tmp is not None: + try: + os.remove(tmp) + except OSError: + pass + + def file_id(path): """stable id of a file's content state (path + size + mtime + sampled content); used as a cache key by the models""" return hashlib.sha1(_state(path).encode()).hexdigest()[:20] @@ -129,7 +151,6 @@ def load(path, sr=SR, mono=False, start=None, end=None, cache=True): x = None npy = None if cache: - config.ensure_dirs() npy = os.path.join(config.DEC_CACHE, _key(path, sr, ch) + '.npy') if os.path.exists(npy): try: @@ -139,9 +160,7 @@ def load(path, sr=SR, mono=False, start=None, end=None, cache=True): if x is None: x = _decode(path, sr, ch) if npy: - tmp = f'{npy}.{os.getpid()}.tmp.npy' - np.save(tmp, x) - replace_quietly(tmp, npy) + write_cache(npy, lambda tmp: np.save(tmp, x)) bad = ~np.isfinite(x) if bad.any(): # one NaN / Inf sample breaks every analysis downstream (#12) bad = bad.any(axis=-1) if x.ndim == 2 else bad diff --git a/earshot/timeline.py b/earshot/timeline.py index 7f9bc6d..7ec8361 100644 --- a/earshot/timeline.py +++ b/earshot/timeline.py @@ -777,9 +777,7 @@ def _cached(model, fid, spans, kind, compute, reuse=True): res = compute([spans[i] for i in todo]) for i, v in zip(todo, res): out[i] = v - tmp = f'{files[i]}.{os.getpid()}.tmp.npy' - np.save(tmp, v) - audio.replace_quietly(tmp, files[i]) + audio.write_cache(files[i], lambda tmp: np.save(tmp, v)) return np.stack(out) if out else None @@ -1222,11 +1220,10 @@ def timeline(path, video=None, cues=None, start=None, end=None, detail='normal', r['summary'] = _summary(r) r['text'] = transcript(r) if cache or fresh: - os.makedirs(os.path.dirname(cfile), exist_ok=True) - tmp = f'{cfile}.{os.getpid()}.tmp' - with open(tmp, 'w', encoding='utf-8') as fh: - fh.write(to_json(r)) - audio.replace_quietly(tmp, cfile) + def save(tmp): + with open(tmp, 'w', encoding='utf-8') as fh: + fh.write(to_json(r)) + audio.write_cache(cfile, save) return dict(r, cached=False) diff --git a/earshot/video.py b/earshot/video.py index 2f4e9c0..5d5c6b4 100644 --- a/earshot/video.py +++ b/earshot/video.py @@ -15,7 +15,6 @@ import os import re import subprocess -import tempfile import numpy as np @@ -36,10 +35,7 @@ def info(path): def _cache(name): - config.ensure_dirs() - d = os.path.join(config.EMB_CACHE, 'video') - os.makedirs(d, exist_ok=True) - return os.path.join(d, name) + return os.path.join(config.EMB_CACHE, 'video', name) def frame_diff(path, cache=True): @@ -57,9 +53,7 @@ def frame_diff(path, cache=True): if p.returncode != 0 or not p.stdout: raise audio.AudioError(f'cannot decode the picture of {path}: {p.stderr.decode(errors="replace")[:200]}') d = _frame_differences(p.stdout) - tmp = f + f'.{os.getpid()}.tmp.npz' - np.savez(tmp, fps=fps, d=d) - audio.replace_quietly(tmp, f) + audio.write_cache(f, lambda tmp: np.savez(tmp, fps=fps, d=d)) return float(fps), d @@ -119,21 +113,10 @@ def cuts(path, method='diff', threshold=0.3, min_gap=0.2, cache=True): for t in ts: if not out or t - out[-1] >= min_gap: out.append(round(t, 3)) - tmp = None - try: - with tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(f), - prefix=os.path.basename(f) + '.', suffix='.tmp', delete=False) as saved: - tmp = saved.name + def save(tmp): + with open(tmp, 'w') as saved: json.dump(out, saved) - audio.replace_quietly(tmp, f) - except OSError: - pass # caching is optional; the scan itself succeeded - finally: - if tmp is not None: - try: - os.remove(tmp) - except OSError: - pass + audio.write_cache(f, save) return out diff --git a/tests/test_optional_media_cache.py b/tests/test_optional_media_cache.py new file mode 100644 index 0000000..c84da17 --- /dev/null +++ b/tests/test_optional_media_cache.py @@ -0,0 +1,133 @@ +"""Cache filesystem failures must not turn successful media work into failed calls.""" +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace +import os +import subprocess +import wave + +import numpy as np +import pytest + +from earshot import audio, config, video +from earshot import timeline as tl + + +@pytest.fixture +def media(tmp_path, monkeypatch): + home = tmp_path / 'cache' + for key, value in [('HOME', home), ('HF_CACHE', home/'hf'), ('EMB_CACHE', home/'emb'), + ('DEC_CACHE', home/'decoded')]: + monkeypatch.setattr(config, key, str(value)) + sound = tmp_path / 'silence.wav' + with wave.open(str(sound), 'wb') as f: + f.setnchannels(2) + f.setsampwidth(2) + f.setframerate(audio.SR) + f.writeframes(bytes(2 * audio.SR * 4)) + film = tmp_path / 'film.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=black:s=96x54:r=25:d=1', + '-f', 'lavfi', '-i', 'color=c=white:s=96x54:r=25:d=1', '-filter_complex', + '[0:v][1:v]concat=n=2:v=1:a=0[v]', '-map', '[v]', '-c:v', 'mpeg4', str(film)], + check=True, capture_output=True) + return home, str(sound), str(film) + + +@contextmanager +def readonly(home): + folders = [home] + [p for p in home.rglob('*') if p.is_dir()] + modes = [(p, p.stat().st_mode & 0o777) for p in folders] + try: + for p, _ in modes: + p.chmod(0o555) + if os.access(home, os.W_OK): + pytest.skip('host does not enforce directory write permissions for this user') + yield + finally: + for p, mode in modes: + p.chmod(mode) + + +def run(action, sound, film): + if action == 'audio': + assert audio.load(sound).shape == (2 * audio.SR, 2) + elif action in ('diff', 'scene'): + assert video.cuts(film, method=action) == [1.0] + else: + r = tl.timeline(sound if action == 'timeline_audio' else film) + assert r['duration'] == 2 and r['loudness']['digital_silence'] + assert all(v == 0 for v in r['model_calls'].values()) + + +@pytest.mark.parametrize('existing', [False, True]) +@pytest.mark.parametrize('action', ['audio', 'diff', 'scene', 'timeline_audio', 'timeline_video']) +def test_readonly_cache_does_not_fail_media(media, existing, action): + home, sound, film = media + home.mkdir() + if existing: + config.ensure_dirs() + (home/'emb'/'video').mkdir() + (home/'emb'/'timeline').mkdir() + with readonly(home): + run(action, sound, film) + assert not [p for p in home.rglob('*') if p.is_file()] + + +@pytest.mark.parametrize('action', ['audio', 'diff', 'scene', 'timeline_audio', 'timeline_video']) +def test_readonly_populated_cache_is_still_reused(media, monkeypatch, action): + home, sound, film = media + run(action, sound, film) + assert any(p.is_file() for p in home.rglob('*')) + def unexpected(*args, **kwargs): + raise AssertionError('cache hit must not recompute') + if action == 'audio': + monkeypatch.setattr(audio, '_decode', unexpected) + elif action in ('diff', 'scene'): + monkeypatch.setattr(subprocess, 'run', unexpected) + else: + monkeypatch.setattr(tl, '_analyse', unexpected) + with readonly(home): + run(action, sound, film) + + +def test_span_cache_write_is_optional(tmp_path): + model = SimpleNamespace(dir=str(tmp_path)) + with readonly(tmp_path): + result = tl._cached(model, 'test', [(0., 1.)], 'test', lambda spans: [np.array([1., 2.])]) + np.testing.assert_array_equal(result, [[1., 2.]]) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize('error', [OSError('disk full'), ValueError('invalid value')]) +def test_partial_cache_write_preserves_old_cache_and_cleans_up(tmp_path, error): + path = tmp_path/'cached.npy' + path.write_bytes(b'previous cache') + def fail(tmp): + Path(tmp).write_bytes(b'partial') + raise error + if isinstance(error, OSError): + assert audio.write_cache(str(path), fail) is False + else: + with pytest.raises(ValueError, match='invalid value'): + audio.write_cache(str(path), fail) + assert path.read_bytes() == b'previous cache' + assert list(tmp_path.iterdir()) == [path] + + +def test_cache_writer_keeps_numpy_extension_and_replaces_atomically(tmp_path): + path = tmp_path/'new'/'cached.npz' + assert audio.write_cache(str(path), lambda tmp: np.savez(tmp, values=[1, 2])) is True + with np.load(path) as data: + np.testing.assert_array_equal(data['values'], [1, 2]) + assert list(path.parent.iterdir()) == [path] + + +def test_decode_failure_is_not_hidden_by_readonly_cache(media): + home, _, film = media + home.mkdir() + Path(film).write_bytes(b'not media') + with readonly(home): + with pytest.raises(audio.AudioError): + audio.load(film) + with pytest.raises(audio.AudioError): + video.cuts(film) From e2df66d05bbba351cd7ac95e7ce702052cd702b1 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:48:22 +0800 Subject: [PATCH 09/23] refactor: isolate optional cache helper from selected-track changes --- earshot/audio.py | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/earshot/audio.py b/earshot/audio.py index 07a99a4..3f258dc 100644 --- a/earshot/audio.py +++ b/earshot/audio.py @@ -85,28 +85,6 @@ def _src_channels(path): return 0 -def write_cache(path, write): - """Best-effort cache write; only filesystem errors are optional, not errors in the producer.""" - import tempfile - tmp = None - try: - folder = os.path.dirname(path) or '.' - os.makedirs(folder, exist_ok=True) - with tempfile.NamedTemporaryFile(dir=folder, prefix=os.path.basename(path) + '.', - suffix=os.path.splitext(path)[1], delete=False) as fh: - tmp = fh.name - write(tmp) - return replace_quietly(tmp, path) - except OSError: - return False - finally: - if tmp is not None: - try: - os.remove(tmp) - except OSError: - pass - - def file_id(path): """stable id of a file's content state (path + size + mtime + sampled content); used as a cache key by the models""" return hashlib.sha1(_state(path).encode()).hexdigest()[:20] @@ -270,3 +248,26 @@ def check_paths(paths, what='paths'): def db(v, floor=1e-12): return float(20 * np.log10(max(float(v), floor))) + + +def write_cache(path, write): + """Best-effort cache write; only filesystem errors are optional, not errors in the producer.""" + import tempfile + tmp = None + try: + folder = os.path.dirname(path) or '.' + os.makedirs(folder, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=folder, prefix=os.path.basename(path) + '.', + suffix=os.path.splitext(path)[1], delete=False) as fh: + tmp = fh.name + write(tmp) + return replace_quietly(tmp, path) + except OSError: + return False + finally: + if tmp is not None: + try: + os.remove(tmp) + except OSError: + pass + From 800ccc7284ffe3fcfabd70b70dd92a9c38275491 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:51:05 +0800 Subject: [PATCH 10/23] fix: key timeline caches by the parsed cue snapshot --- earshot/timeline.py | 4 +- tests/test_timeline_cue_cache.py | 69 ++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 tests/test_timeline_cue_cache.py diff --git a/earshot/timeline.py b/earshot/timeline.py index 7f9bc6d..b41f10a 100644 --- a/earshot/timeline.py +++ b/earshot/timeline.py @@ -1208,7 +1208,9 @@ def timeline(path, video=None, cues=None, start=None, end=None, detail='normal', if not pr.get('codec') and not video: raise ValueError(f'{os.path.basename(path)} has no audio stream') cue_list, cue_fps = read_cues(cues) - key = hashlib.sha1(f'{audio.file_id(path)}|{audio.file_id(video) if video else None}|{_cue_key(cues)}|{start}|' + # Key the same cue snapshot that is analysed, not the raw spelling or a second read of its file. + cue_key = _cue_key({'events': cue_list, 'fps': cue_fps}) + key = hashlib.sha1(f'{audio.file_id(path)}|{audio.file_id(video) if video else None}|{cue_key}|{start}|' f'{end}|{detail}|{CODE_ID}|{CORE_ID}'.encode()).hexdigest()[:24] cfile = os.path.join(config.EMB_CACHE, 'timeline', f'{key}.json') if cache and not fresh and os.path.exists(cfile): diff --git a/tests/test_timeline_cue_cache.py b/tests/test_timeline_cue_cache.py new file mode 100644 index 0000000..71715eb --- /dev/null +++ b/tests/test_timeline_cue_cache.py @@ -0,0 +1,69 @@ +"""Timeline cache identity follows parsed cues, not a second file observation.""" +import json +import numpy as np +import soundfile as sf +import pytest +from earshot import timeline as tl, config + +@pytest.fixture +def setup(tmp_path, monkeypatch): + monkeypatch.setattr(config, 'EMB_CACHE', str(tmp_path / 'emb')) + p = tmp_path / 'silent.wav' + sf.write(p, np.zeros(96000), 48000) + cues = tmp_path / 'cues.json' + cues.write_text('[0.5]') + return (str(p), cues) + +def times(r): + return [v['t'] for v in r['sync']['cues']['items']] + +def test_whitespace_path_edit(setup): + p, cues = setup + arg = ' ' + str(cues) + ' ' + assert times(tl.timeline(p, cues=arg)) == [0.5] + cues.write_text('[1.5]') + r = tl.timeline(p, cues=arg) + assert not r['cached'] and times(r) == [1.5] + assert tl.timeline(p, cues=arg)['cached'] + +def test_snapshot_read_before_change(setup, monkeypatch): + p, cues = setup + original = tl.read_cues + + def changing(arg): + result = original(arg) + cues.write_text('[1.5]') + return result + with monkeypatch.context() as m: + m.setattr(tl, 'read_cues', changing) + assert times(tl.timeline(p, cues=str(cues))) == [0.5] + r = tl.timeline(p, cues=str(cues)) + assert not r['cached'] and times(r) == [1.5] + +def test_equivalent_inputs(setup): + p, cues = setup + first = tl.timeline(p, cues=str(cues)) + for value in ([0.5], '[0.5]', '0.5', {'events': [{'time': 0.5}]}): + r = tl.timeline(p, cues=value) + assert r['cached'] and times(r) == times(first) + +def test_fps_is_part_of_effective_input(setup): + p, _ = setup + first = tl.timeline(p, cues={'fps': 30, 'events': [{'f': 30}]}) + r = tl.timeline(p, cues={'fps': 60, 'events': [{'f': 30}]}) + assert not r['cached'] and times(first) == [1] and (times(r) == [0.5]) + +def test_invalid_file_never_hidden_by_cache(setup): + p, cues = setup + tl.timeline(p, cues=str(cues)) + cues.write_text('broken') + with pytest.raises(json.JSONDecodeError): + tl.timeline(p, cues=str(cues)) + +def test_same_time_different_fps_preserves_tolerance(setup): + p, _ = setup + first = tl.timeline(p, cues={'fps': 30, 'events': [{'t': 1}]}) + second = tl.timeline(p, cues={'fps': 60, 'events': [{'t': 1}]}) + assert times(first) == times(second) == [1] + assert not second['cached'] + assert first['sync']['cues']['stats']['frame_ms'] != second['sync']['cues']['stats']['frame_ms'] From 63e2939c2be8e83c1866582a03ba5659e694fd7d Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:51:51 +0800 Subject: [PATCH 11/23] fix: bound timeline audio ranges by decoded samples --- earshot/timeline.py | 9 ++- tests/test_timeline_decoded_range.py | 105 +++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 4 deletions(-) create mode 100644 tests/test_timeline_decoded_range.py diff --git a/earshot/timeline.py b/earshot/timeline.py index 7f9bc6d..5a3d011 100644 --- a/earshot/timeline.py +++ b/earshot/timeline.py @@ -1241,20 +1241,21 @@ def _load_range(path, pr, start, end, reuse=True): raise ValueError(f"nothing to analyse between {t0:g} s and {'the end' if end is None else f'{end:g} s'}: " f'{name} is {fdur:.2f} s long') return np.zeros((int(round(fdur * SR)), 2), np.float32), 0.0, t0, t1, fdur + # The container can outlast its selected audio stream. load already decodes the + # whole track before slicing, so use those samples to bound every audio window. + x = audio.load(path, cache=reuse) + fdur = len(x) / SR if start is None and end is None: - x = audio.load(path, cache=reuse) - fdur = len(x) / SR if fdur < 0.1: raise ValueError(f'{name} is {fdur:.2f} s long: too short for a timeline (>= 0.1 s); for a one-shot use ' 'earshot measure / describe') return x, 0.0, 0.0, fdur, fdur - fdur = float(pr.get('duration') or 0) or len(audio.load(path, mono=True, cache=reuse)) / SR t0, t1 = max(0.0, float(start or 0)), min(fdur, float(end)) if end is not None else fdur if t1 - t0 < 0.1: raise ValueError(f"nothing to analyse between {t0:g} s and {'the end' if end is None else f'{end:g} s'}: " f'{name} is {fdur:.2f} s long') c0, c1 = max(0.0, t0 - CONTEXT_S), min(fdur, t1 + CONTEXT_S) - return audio.load(path, start=c0, end=c1, cache=reuse), c0, t0, t1, fdur + return x[int(round(c0 * SR)):int(round(c1 * SR))], c0, t0, t1, fdur def _analyse(path, pr, video, cue_list, cue_fps, start, end, cfg, reuse): diff --git a/tests/test_timeline_decoded_range.py b/tests/test_timeline_decoded_range.py new file mode 100644 index 0000000..b7fdaef --- /dev/null +++ b/tests/test_timeline_decoded_range.py @@ -0,0 +1,105 @@ +"""Audio ranges follow decoded duration, not a longer container's duration.""" +import subprocess +import tempfile +import unittest +import wave +from pathlib import Path + +import numpy as np +from earshot import audio, config +from earshot.timeline import timeline, _load_range + + +class DecodedRangeTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.old = (config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE) + config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE = ( + str(self.root / s) for s in ('cache', 'cache/hf', 'cache/emb', 'cache/decoded')) + self.wav = str(self.root / 'audio.wav') + with wave.open(self.wav, 'wb') as f: + f.setparams((2, 2, 48000, 0, 'NONE', 'not compressed')) + f.writeframes(bytes(48000 * 4)) + self.media = str(self.root / 'long-picture.mkv') + subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-f', 'lavfi', '-i', + 'color=c=black:s=32x32:r=10:d=3', '-i', self.wav, + '-c:v', 'ffv1', '-c:a', 'copy', self.media], check=True, capture_output=True) + self.assertEqual(audio.probe(self.media)['duration'], 3) + + def tearDown(self): + config.HOME, config.HF_CACHE, config.EMB_CACHE, config.DEC_CACHE = self.old + self.tmp.cleanup() + + def test_past_audio_end_rejected_not_cached(self): + for bounds in ({'start': 2, 'end': 3}, {'start': 1}, {'start': 1, 'end': 2}): + with self.subTest(bounds=bounds): + for _ in range(2): + with self.assertRaisesRegex(ValueError, 'nothing to analyse'): + timeline(self.media, detail='low', **bounds) + self.assertFalse(list(Path(config.EMB_CACHE).rglob('*.json'))) + + def test_actual_short_window_rejected(self): + for bounds in ({'start': .95, 'end': 2}, {'start': .95}, {'start': .95, 'end': 1}): + with self.subTest(bounds=bounds): + with self.assertRaisesRegex(ValueError, 'nothing to analyse'): + timeline(self.media, cache=False, detail='low', **bounds) + + def test_valid_window_matches_full_duration_and_cache(self): + full = timeline(self.media, cache=False, detail='low') + for bounds, expected in (({'start': 0, 'end': 3}, (0, 1)), + ({'start': .5, 'end': 3}, (.5, 1)), + ({'start': -.5, 'end': .5}, (0, .5)), + ({'start': .5}, (.5, 1))): + with self.subTest(bounds=bounds): + first = timeline(self.media, detail='low', **bounds) + second = timeline(self.media, detail='low', **bounds) + self.assertEqual((first['start'], first['end']), expected) + self.assertEqual(first['file_duration'], full['file_duration']) + self.assertEqual(first['file_duration'], 1) + self.assertEqual(first['duration'], expected[1] - expected[0]) + self.assertFalse(first['cached']) + self.assertTrue(second['cached']) + self.assertEqual(second['context'], first['context']) + self.assertTrue(all(v == 0 for v in first['model_calls'].values())) + + def test_unknown_or_underreported_probe_duration_uses_samples(self): + for duration in (0, .5, 3): + with self.subTest(duration=duration): + pr = dict(audio.probe(self.wav), duration=duration) + x, c0, t0, t1, fdur = _load_range(self.wav, pr, .5, 2, reuse=False) + self.assertEqual((len(x), c0, t0, t1, fdur), (48000, 0, .5, 1, 1)) + + def test_context_slice_matches_public_audio_load(self): + # Nonzero stereo data proves sample equality, not only zero-array shape. + long_path = str(self.root / 'long.wav') + n = 65 * audio.SR + samples = np.zeros((n, 2), dtype=' Date: Tue, 17 Nov 2026 11:59:50 +0800 Subject: [PATCH 12/23] fix: time picture differences at the selected decoder frame rate --- earshot/video.py | 143 +++++++++++++++++++++++-- tests/test_video_selected_rate.py | 166 ++++++++++++++++++++++++++++++ 2 files changed, 301 insertions(+), 8 deletions(-) create mode 100644 tests/test_video_selected_rate.py diff --git a/earshot/video.py b/earshot/video.py index 2f4e9c0..42d8fcd 100644 --- a/earshot/video.py +++ b/earshot/video.py @@ -11,11 +11,13 @@ missed or found late; treat the result as "big visual change" markers, not an edit decision list. """ import hashlib +from fractions import Fraction import json import os import re import subprocess import tempfile +import threading import numpy as np @@ -43,26 +45,151 @@ def _cache(name): def frame_diff(path, cache=True): - """(fps, d): mean absolute difference (0..1) between consecutive 96x54 grey frames (d[0] = 0), cached""" - f = _cache('diff_' + hashlib.sha1(f'{audio.file_id(path)}|{FRAME_W}x{FRAME_H}|v1'.encode()).hexdigest()[:20] + '.npz') + """(decoded fps, d): consecutive 96x54 grey-frame differences (d[0] = 0), cached. + + The rate belongs to FFmpeg's selected decode, not necessarily probe()'s first stream. + """ + f = _cache('diff_' + hashlib.sha1(f'{audio.file_id(path)}|{FRAME_W}x{FRAME_H}|v2'.encode()).hexdigest()[:20] + '.npz') if cache and os.path.exists(f): try: with np.load(f, allow_pickle=False) as z: return float(z['fps']), np.array(z['d']) except Exception: pass - fps = (audio.probe(path).get('video') or {}).get('fps') or 30.0 - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-an', '-vf', - f'scale={FRAME_W}:{FRAME_H}:flags=area,format=gray', '-f', 'rawvideo', '-'], capture_output=True) - if p.returncode != 0 or not p.stdout: - raise audio.AudioError(f'cannot decode the picture of {path}: {p.stderr.decode(errors="replace")[:200]}') - d = _frame_differences(p.stdout) + raw, log, returncode = _decode_picture(path) + if returncode != 0 or not raw: + reason = audio._ffmpeg_reason(log.tail.decode(errors='replace')) + raise audio.AudioError(f'cannot decode the picture of {path}: {reason}') + fps = log.rate(path) + d = _frame_differences(raw) tmp = f + f'.{os.getpid()}.tmp.npz' np.savez(tmp, fps=fps, d=d) audio.replace_quietly(tmp, f) return float(fps), d +class _PictureLog: + """Drain verbose FFmpeg output without retaining per-frame logs or long metadata.""" + LIMIT = 4096 + + def __init__(self): + self.tail = self.pending = b'' + self.dropping = self.invalid = False + self.fps = None + + @staticmethod + def _is_config(line): + return re.match(rb'^\[showinfo@earshot_rate @ [^\]]+\] config in ', line) is not None + + def _line(self, line): + if not self._is_config(line): + return + try: + fps = _decoded_rate(line, 'FFmpeg output') + if self.fps is not None and self.fps != fps: + self.invalid = True + self.fps = fps + except audio.AudioError: + self.invalid = True + + def feed(self, chunk): + self.tail = (self.tail + chunk)[-self.LIMIT:] + if self.dropping: + end = chunk.find(b'\n') + if end < 0: + return + chunk = chunk[end + 1:] + self.dropping = False + data = self.pending + chunk + lines = data.split(b'\n') + for line in lines[:-1]: + if len(line) <= self.LIMIT: + self._line(line) + elif self._is_config(line): + self.invalid = True + self.pending = lines[-1] + if len(self.pending) > self.LIMIT: + if self._is_config(self.pending): + self.invalid = True + self.pending = b'' + self.dropping = True + + def finish(self): + if self.pending: + self._line(self.pending) + self.pending = b'' + + def rate(self, path): + if self.invalid or self.fps is None: + raise audio.AudioError(f'cannot determine decoded picture frame rate of {path}') + return float(self.fps) + + +def _decode_picture(path): + """The original raw-frame decode, with a bounded concurrent stderr consumer.""" + args = ['ffmpeg', '-hide_banner', '-v', 'info', '-nostats', '-nostdin', '-i', path, '-an', '-vf', + f'scale={FRAME_W}:{FRAME_H}:flags=area,format=gray,showinfo@earshot_rate=checksum=0', + '-f', 'rawvideo', '-'] + log = _PictureLog() + with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: + def drain(): + try: + while True: + chunk = proc.stderr.read(8192) + if not chunk: + break + log.feed(chunk) + log.finish() + except Exception: + log.invalid = True + proc.stderr.close() + + reader = threading.Thread(target=drain) + reader.start() + try: + raw = proc.stdout.read() + returncode = proc.wait() + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + proc.stdout.close() + reader.join() + return raw, log, returncode + + +def _decoded_fps(stderr, path): + return float(_decoded_rate(stderr, path)) + + +def _decoded_rate(stderr, path): + """Read the rate of the actual selected decode, not ffprobe's first picture stream. + + showinfo observes the existing filter graph without changing its frames or + FFmpeg's automatic stream selection / output synchronization. + """ + entries = re.findall(rb'^\[showinfo@earshot_rate @ [^\]]+\] config in (.*)$', + stderr, re.MULTILINE) + try: + rates = set() + for entry in entries: + match = re.fullmatch(rb'time_base: (\d+)/(\d+), frame_rate: (\d+)/(\d+)', entry.strip()) + if match is None: + raise ValueError('malformed rate configuration') + tn, td, n, d = map(int, match.groups()) + if Fraction(tn, td) <= 0 or Fraction(n, d) <= 0: + raise ValueError('nonpositive timing') + rates.add(Fraction(n, d)) + if len(rates) != 1: + raise ValueError('missing or changing rate') + rate = rates.pop() + if not np.isfinite(float(rate)) or float(rate) <= 0: + raise ValueError('invalid rate') + except (ValueError, ZeroDivisionError, OverflowError) as exc: + raise audio.AudioError(f'cannot determine decoded picture frame rate of {path}') from exc + return rate + + def _frame_differences(raw): """Mean differences of complete raw grey frames, with bounded float32 intermediates.""" fr = np.frombuffer(raw, np.uint8) diff --git a/tests/test_video_selected_rate.py b/tests/test_video_selected_rate.py new file mode 100644 index 0000000..b8ffa77 --- /dev/null +++ b/tests/test_video_selected_rate.py @@ -0,0 +1,166 @@ +"""Selected-track timing uses the decoder's rate. Synthetic media only; no models.""" +import hashlib +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import numpy as np +from earshot import audio, config, video + + +@unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg required') +class SelectedVideoRateTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.old = tuple(getattr(config, k) for k in ('HOME', 'HF_CACHE', 'EMB_CACHE', 'DEC_CACHE')) + for k, sub in zip(('HOME', 'HF_CACHE', 'EMB_CACHE', 'DEC_CACHE'), ('cache', 'cache/hf', 'cache/emb', 'cache/decoded')): + setattr(config, k, str(self.root / sub)) + + def tearDown(self): + for k, value in zip(('HOME', 'HF_CACHE', 'EMB_CACHE', 'DEC_CACHE'), self.old): + setattr(config, k, value) + self.tmp.cleanup() + + def make(self, first=10, second=25, default='second', has_audio=False): + path = str(self.root / f'{first}-{second}-{default}-{has_audio}.mkv') + args = ['ffmpeg', '-nostdin', '-y', '-v', 'error', '-f', 'lavfi', '-i', + f'color=black:s=32x32:r={first}:d=3', '-f', 'lavfi', '-i', + f'color=black:s=64x64:r={second}:d=3'] + if has_audio: + args += ['-f', 'lavfi', '-i', 'anullsrc=r=48000:cl=stereo:d=3'] + args += ['-map', '0:v', '-map', '1:v'] + if has_audio: + args += ['-map', '2:a', '-c:a', 'pcm_s16le'] + for i in (0, 1): + args += [f'-filter:v:{i}', "drawbox=color=white:t=fill:enable='between(t,1,1.99)'"] + args += [f'-disposition:v:{i}', 'default' if default == ('first', 'second')[i] else '0'] + subprocess.run(args + ['-c:v', 'ffv1', path], check=True, capture_output=True) + return path + + def test_multitrack_order_defaults_and_audio(self): + for first, second in ((10, 25), (25, 10)): + for default in ('first', 'second', 'none'): + for has_audio in (False, True): + with self.subTest(first=first, second=second, default=default, has_audio=has_audio): + path = self.make(first, second, default, has_audio) + expected = first if default == 'first' else second + fps, d = video.frame_diff(path, cache=False) + self.assertEqual(fps, expected) + self.assertEqual(len(d), 3 * expected) + self.assertEqual(video.cuts(path, cache=False), [1, 2]) + + def test_decoded_pixels_unchanged(self): + path = self.make() + original = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-an', '-vf', + 'scale=96:54:flags=area,format=gray', '-f', 'rawvideo', '-'], + check=True, capture_output=True).stdout + fps, d = video.frame_diff(path, cache=False) + self.assertEqual(fps, 25) + np.testing.assert_array_equal(d, video._frame_differences(original)) + + def test_legacy_metadata_cache_is_not_reused(self): + path = self.make() + folder = self.root / 'cache/emb/video' + folder.mkdir(parents=True) + key = hashlib.sha1(f'{audio.file_id(path)}|96x54|v1'.encode()).hexdigest()[:20] + np.savez(folder / f'diff_{key}.npz', fps=10, d=np.zeros(30)) + self.assertEqual(video.cuts(path), [1, 2]) + self.assertEqual(len(list(folder.glob('diff_*.npz'))), 2) + + def test_cache_hit_and_bypass(self): + path = self.make() + fps, d = video.frame_diff(path) + with patch.object(video, '_decode_picture', side_effect=AssertionError('cache missed')): + got_fps, got_d = video.frame_diff(path) + self.assertEqual(got_fps, fps) + np.testing.assert_array_equal(got_d, d) + cached = next((self.root / 'cache/emb/video').glob('diff_*.npz')) + np.savez(cached, fps=fps, d=np.zeros_like(d)) + self.assertEqual(video.cuts(path), []) + self.assertEqual(video.cuts(path, cache=False), [1, 2]) + cached.write_bytes(b'truncated') + self.assertEqual(video.cuts(path), [1, 2]) + + def test_failed_decode_has_no_result_cache(self): + path = self.root / 'bad.mkv' + path.write_bytes(b'not media') + with self.assertRaises(audio.AudioError): + video.frame_diff(str(path)) + self.assertFalse(list((self.root / 'cache/emb/video').glob('diff_*.npz'))) + + def test_missing_rate_has_no_result_cache(self): + path = self.make() + reply = (bytes(96 * 54), video._PictureLog(), 0) + with patch.object(video, '_decode_picture', return_value=reply): + with self.assertRaisesRegex(audio.AudioError, 'frame rate'): + video.frame_diff(path) + self.assertFalse(list((self.root / 'cache/emb/video').glob('diff_*.npz'))) + + +class RateParsingTests(unittest.TestCase): + @staticmethod + def line(rate, name='showinfo@earshot_rate'): + return f'[{name} @ 0x123] config in time_base: 1/1000, frame_rate: {rate}\n'.encode() + + def test_exact_rational_and_equivalent_repeated_config(self): + self.assertEqual(video._decoded_fps(self.line('30000/1001'), 'x'), 30000 / 1001) + self.assertEqual(video._decoded_fps(self.line('25/1') + self.line('50/2'), 'x'), 25) + + def test_unusable_or_changing_metadata_rejected(self): + for raw in (b'', self.line('25/1', 'other'), self.line('0/1'), self.line('1/0'), + self.line('0/0'), self.line('1/' + '9' * 400), self.line('9' * 400 + '/1'), + self.line('25/1') + self.line('30/1')): + with self.subTest(raw=raw): + with self.assertRaises(audio.AudioError): + video._decoded_fps(raw, 'fixture.mkv') + + def test_valid_then_malformed_config_is_rejected(self): + for bad in ('-1/1', 'N/A', 'nan', '25/1 garbage', '0/0', '0/1'): + with self.subTest(bad=bad): + with self.assertRaises(audio.AudioError): + video._decoded_fps(self.line('25/1') + self.line(bad), 'fixture.mkv') + + + +class BoundedLogTests(unittest.TestCase): + def test_chunked_configs_and_diagnostics_are_bounded(self): + line = RateParsingTests.line('30000/1001') + for size in (1, 3, 29, 8192): + log = video._PictureLog() + data = b'metadata: ' + b'x' * 20000 + b'\n' + line + b'n: ordinary frame\n' * 10000 + for start in range(0, len(data), size): + log.feed(data[start:start + size]) + self.assertLessEqual(len(log.pending), log.LIMIT) + self.assertLessEqual(len(log.tail), log.LIMIT) + log.finish() + self.assertEqual(log.rate('x'), 30000 / 1001) + self.assertEqual(log.pending, b'') + + def test_bad_or_changing_config_remains_invalid_after_good_line(self): + for bad in ('N/A', '-1/1', '30/1', '0/0', '25/1 garbage'): + log = video._PictureLog() + log.feed(RateParsingTests.line('25/1') + RateParsingTests.line(bad) + RateParsingTests.line('25/1')) + log.finish() + with self.assertRaises(audio.AudioError): + log.rate('x') + + def test_long_config_rejected_and_unterminated_config_handled(self): + log = video._PictureLog() + line = RateParsingTests.line('25/1').rstrip(b'\n') + log.feed(line) + log.finish() + self.assertEqual(log.rate('x'), 25) + log = video._PictureLog() + log.feed(line + b'x' * 10000 + b'\n') + log.feed(RateParsingTests.line('25/1')) + log.finish() + with self.assertRaises(audio.AudioError): + log.rate('x') + + +if __name__ == '__main__': + unittest.main() From 2900a6b88f2af1456f4477df07fd2f9a078e0d75 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:26:48 +0800 Subject: [PATCH 13/23] test: patch the shared tempfile writer after cache refactor --- tests/test_video_scene_cache.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_video_scene_cache.py b/tests/test_video_scene_cache.py index 23762f5..5c1a117 100644 --- a/tests/test_video_scene_cache.py +++ b/tests/test_video_scene_cache.py @@ -2,6 +2,7 @@ import builtins import json import subprocess +import tempfile from pathlib import Path import pytest @@ -78,7 +79,7 @@ def test_failed_scene_cache_write_keeps_successful_scan(film, monkeypatch): def unavailable(**kwargs): raise PermissionError('cache unavailable') - monkeypatch.setattr(video.tempfile, 'NamedTemporaryFile', unavailable) + monkeypatch.setattr(tempfile, 'NamedTemporaryFile', unavailable) assert video.cuts(path, method='scene', cache=False) == [1.5] assert json.loads(cached.read_text()) == [] assert not list(cached.parent.glob('*.tmp')) From 8598a79ee39ebb4236cf4594f6fd890a35b3c41d Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:54:06 +0800 Subject: [PATCH 14/23] fix: reap picture decoder when stderr thread cannot start --- earshot/video.py | 5 +++-- tests/test_video_selected_rate.py | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/earshot/video.py b/earshot/video.py index 42d8fcd..0b27e14 100644 --- a/earshot/video.py +++ b/earshot/video.py @@ -145,8 +145,8 @@ def drain(): proc.stderr.close() reader = threading.Thread(target=drain) - reader.start() try: + reader.start() raw = proc.stdout.read() returncode = proc.wait() finally: @@ -154,7 +154,8 @@ def drain(): proc.kill() proc.wait() proc.stdout.close() - reader.join() + if reader.ident is not None: + reader.join() return raw, log, returncode diff --git a/tests/test_video_selected_rate.py b/tests/test_video_selected_rate.py index b8ffa77..8344b99 100644 --- a/tests/test_video_selected_rate.py +++ b/tests/test_video_selected_rate.py @@ -2,6 +2,7 @@ import hashlib import shutil import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -162,5 +163,28 @@ def test_long_config_rejected_and_unterminated_config_handled(self): log.rate('x') +class DecoderCleanupTests(unittest.TestCase): + def test_thread_start_failure_kills_and_reaps_child(self): + # A real child makes context-manager waiting distinguishable from cleanup. + # Use Python rather than FFmpeg so this exceptional path is codec-independent. + popen = subprocess.Popen + children = [] + + def child(*args, **kwargs): + proc = popen([sys.executable, '-c', 'import time; time.sleep(2)'], **kwargs) + children.append(proc) + return proc + + with patch.object(video.subprocess, 'Popen', side_effect=child), \ + patch.object(video.threading.Thread, 'start', side_effect=RuntimeError('cannot start new thread')): + with self.assertRaisesRegex(RuntimeError, 'cannot start new thread'): + video._decode_picture('unused') + self.assertEqual(len(children), 1) + self.assertIsNotNone(children[0].returncode) + self.assertNotEqual(children[0].returncode, 0) + self.assertTrue(children[0].stdout.closed) + self.assertTrue(children[0].stderr.closed) + + if __name__ == '__main__': unittest.main() From 1cc6224e1c4dbeefd5e889800c79fc31e221fa63 Mon Sep 17 00:00:00 2001 From: fcy <3181088318@qq.com> Date: Tue, 17 Nov 2026 14:50:32 +0800 Subject: [PATCH 15/23] cli: read the command word past the value of --threads `earshot [--threads N] ` is the usage line the module documents, and `_hold_blas` already reads a --threads given before the command. The command word itself was the first argument without a leading dash, so in that form it was N: not a command name, so `_register` imported every command module instead of the one asked for, which is the lazy CLI that `--threads=N` keeps (`--threads 2 describe` loaded as much as `-h` does). `measure` imports 5 modules instead of 26, and `doctor` starts in 0.73 s instead of 2.32 s (Windows, Python 3.13, warm cache, min of 3 runs each). Tests: the command word for every documented form, and a fresh process where the two forms import the same number of modules. --- earshot/cli.py | 17 ++++++++++++++++- tests/test_core.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/earshot/cli.py b/earshot/cli.py index 24b2ad4..14de568 100644 --- a/earshot/cli.py +++ b/earshot/cli.py @@ -82,12 +82,27 @@ def _register(sub, modules): return failed +def _command(argv): + """the command word in argv: its first argument that is not a flag, skipping the value of a global option that + takes one, so `--threads 4 describe x.wav` names `describe` (its value `4` is not a command, and reading it as one + registered every module, which is what `--threads=4` avoids)""" + value_next = False + for a in argv: + if value_next: + value_next = False + elif a == '--threads': + value_next = True + elif not a.startswith('-'): + return a + return None + + def main(argv=None): argv = sys.argv[1:] if argv is None else list(argv) _hold_blas(argv) ap = _parser() sub = ap.add_subparsers(dest='command', metavar='') - cmd = next((a for a in argv if not a.startswith('-')), None) + cmd = _command(argv) if cmd in COMMANDS: failed = _register(sub, [COMMANDS[cmd]]) if failed: diff --git a/tests/test_core.py b/tests/test_core.py index c77edfd..56a90fa 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -158,6 +158,40 @@ def test_profile_summary_survives_unmeasured_metrics(): assert 'LRA n.a.' in profile.profile_summary(p) +@pytest.mark.parametrize('argv, want', [ + (['describe', 'x.wav'], 'describe'), + (['--threads', '2', 'describe', 'x.wav'], 'describe'), # the value of the global option is not a command + (['--threads=2', 'describe', 'x.wav'], 'describe'), + (['describe', 'x.wav', '--threads', '2'], 'describe'), + (['--threads', '2'], None), # no command: -h and a bad call read as none + (['-h'], None), +]) +def test_the_command_word_skips_a_global_option_value(argv, want): + assert cli._command(argv) == want + + +# Only a fresh process shows what the command word decided to import: the global --threads takes a value, and reading +# that value as the command registered every command module instead of the one asked for (`measure`: 26 modules and +# `doctor` 2.32 s to start, against 5 modules and 0.73 s in the `--threads=2` / `--threads 2` forms that read as the +# command; Windows, Python 3.13, warm cache) +_LAZY = '''import sys +from earshot import cli +cli.main(sys.argv[1:]) +print(len([m for m in sys.modules if m.startswith('earshot.')])) +''' + + +def test_global_threads_before_the_command_imports_one_command_module(wav, sine): + p = wav(sine) + counted = {} + for args in (['measure', p, '--light'], ['--threads', '2', 'measure', p, '--light']): + r = subprocess.run([sys.executable, '-c', _LAZY, *args], capture_output=True, text=True, cwd=REPO) + assert r.returncode == 0, r.stderr + counted[args[0] == '--threads'] = int(r.stdout.strip().splitlines()[-1]) + assert counted[True] == counted[False], counted + assert counted[True] < len(cli.COMMANDS), counted + + def test_sheet_ticks_at_quarter_seconds_are_exact(): assert sheet._tick_label(0.25, 0.25) == '0:00.25' and sheet._tick_label(0.75, 0.25) == '0:00.75' assert sheet._tick_label(0.5, 0.5) == '0:00.5' and sheet._tick_label(61.0, 1) == '1:01' From c8d8df9d5a6a0299f61af800ae0fc62a79dc527a Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:41:11 +0800 Subject: [PATCH 16/23] fix: disambiguate local media paths for FFmpeg --- earshot/audio.py | 13 +++- earshot/llm.py | 2 +- earshot/synth/master.py | 2 +- earshot/video.py | 6 +- tests/test_local_media_names.py | 99 ++++++++++++++++++++++++++++++ tests/test_local_media_symlinks.py | 50 +++++++++++++++ 6 files changed, 164 insertions(+), 8 deletions(-) create mode 100644 tests/test_local_media_names.py create mode 100644 tests/test_local_media_symlinks.py diff --git a/earshot/audio.py b/earshot/audio.py index f406725..227d950 100644 --- a/earshot/audio.py +++ b/earshot/audio.py @@ -76,10 +76,17 @@ def replace_quietly(tmp, dst, tries=5): return False +def _ffmpeg_input(path): + """Disambiguate existing local files without rewriting URLs or other FFmpeg inputs.""" + path = os.fsdecode(path) + # Do not normalize away symlink/.. components or change native drive-relative paths. + return os.path.join(os.curdir, path) if os.path.exists(path) else path + + def _src_channels(path): try: out = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', - '-of', 'csv=p=0', path], capture_output=True, text=True, timeout=60).stdout.strip() + '-of', 'csv=p=0', _ffmpeg_input(path)], capture_output=True, text=True, timeout=60).stdout.strip() return int(out.splitlines()[0]) if out else 0 except Exception: # noqa: BLE001 return 0 @@ -105,7 +112,7 @@ def _ffmpeg_reason(err): def _decode(path, sr, ch): up = ch == 2 and _src_channels(path) == 1 # ffmpeg would upmix mono at -3 dB; duplicate at unity instead - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-vn', '-f', 'f32le', '-acodec', 'pcm_f32le', + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', _ffmpeg_input(path), '-vn', '-f', 'f32le', '-acodec', 'pcm_f32le', '-ac', '1' if up else str(ch), '-ar', str(sr), '-'], capture_output=True) err = p.stderr.decode(errors='replace') if p.returncode != 0 or not p.stdout: @@ -175,7 +182,7 @@ def probe(path): out = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_type,codec_name,sample_rate,channels,bit_rate,width,height,r_frame_rate:' 'stream_disposition=attached_pic:' - 'format=duration,bit_rate', '-of', 'json', path], + 'format=duration,bit_rate', '-of', 'json', _ffmpeg_input(path)], capture_output=True, text=True, timeout=60).stdout j = json.loads(out or '{}') except Exception as e: # noqa: BLE001 diff --git a/earshot/llm.py b/earshot/llm.py index 1a39991..47ade4a 100644 --- a/earshot/llm.py +++ b/earshot/llm.py @@ -256,7 +256,7 @@ def encode(path, start=None, end=None, max_seconds=600.0, kbps=KBPS): trimmed = b - a > max_seconds if trimmed: b = a + max_seconds - cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{a:.3f}', '-i', path, '-t', f'{b - a:.3f}', '-vn', '-ac', '1', + cmd = ['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{a:.3f}', '-i', audio._ffmpeg_input(path), '-t', f'{b - a:.3f}', '-vn', '-ac', '1', '-ar', '44100', '-c:a', 'libmp3lame', '-b:a', f'{kbps}k', '-f', 'mp3', '-'] p = subprocess.run(cmd, capture_output=True) if p.returncode != 0 or not p.stdout: diff --git a/earshot/synth/master.py b/earshot/synth/master.py index c85b275..7549c2b 100644 --- a/earshot/synth/master.py +++ b/earshot/synth/master.py @@ -208,7 +208,7 @@ def write(path, y, sr=SR, mono=False, bits=24, bitrate=None): cmd = [ff, '-v', 'error', '-y', '-i', tmp, '-c:a', CODEC[ext], '-b:a', bitrate or BITRATE[ext]] if ext == 'webm' and sr not in (8000, 12000, 16000, 24000, 48000): cmd += ['-ar', '48000'] # Opus has no 44.1 kHz - p = subprocess.run(cmd + [path], capture_output=True, text=True) + p = subprocess.run(cmd + [os.path.join(os.curdir, path)], capture_output=True, text=True) if p.returncode != 0: raise RuntimeError(f'ffmpeg could not write {path}: {p.stderr.strip()[:300]}') finally: diff --git a/earshot/video.py b/earshot/video.py index 2f4e9c0..c99c1c5 100644 --- a/earshot/video.py +++ b/earshot/video.py @@ -52,7 +52,7 @@ def frame_diff(path, cache=True): except Exception: pass fps = (audio.probe(path).get('video') or {}).get('fps') or 30.0 - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', path, '-an', '-vf', + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', audio._ffmpeg_input(path), '-an', '-vf', f'scale={FRAME_W}:{FRAME_H}:flags=area,format=gray', '-f', 'rawvideo', '-'], capture_output=True) if p.returncode != 0 or not p.stdout: raise audio.AudioError(f'cannot decode the picture of {path}: {p.stderr.decode(errors="replace")[:200]}') @@ -109,7 +109,7 @@ def cuts(path, method='diff', threshold=0.3, min_gap=0.2, cache=True): return json.load(saved) except (OSError, UnicodeDecodeError, json.JSONDecodeError): pass # a missing, unreadable or interrupted cache is not a failed scan - p = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-i', path, '-an', '-vf', + p = subprocess.run(['ffmpeg', '-hide_banner', '-nostdin', '-i', audio._ffmpeg_input(path), '-an', '-vf', f"scale=320:-2,select='gt(scene,{threshold})',showinfo", '-f', 'null', '-'], capture_output=True, text=True, errors='replace') if p.returncode != 0: @@ -141,7 +141,7 @@ def frame(path, t, width=320): """one frame at time t as a PIL image""" from PIL import Image import io - p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{max(0.0, t):.3f}', '-i', path, '-frames:v', '1', + p = subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-ss', f'{max(0.0, t):.3f}', '-i', audio._ffmpeg_input(path), '-frames:v', '1', '-vf', f'scale={width}:-2', '-f', 'image2pipe', '-vcodec', 'png', '-'], capture_output=True) if p.returncode != 0 or not p.stdout: return None diff --git a/tests/test_local_media_names.py b/tests/test_local_media_names.py new file mode 100644 index 0000000..9cc1198 --- /dev/null +++ b/tests/test_local_media_names.py @@ -0,0 +1,99 @@ +"""Local filename punctuation must not become an FFmpeg protocol or option.""" +import functools +import http.server +import os +from pathlib import Path +import subprocess +import threading + +import numpy as np +import pytest +import soundfile as sf + +from earshot import audio, config, video +from earshot.llm import encode +from earshot.synth import master + + +@pytest.fixture(params=['take:01', '-take', 'ordinary']) +def media(tmp_path, monkeypatch, request): + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(config, 'DEC_CACHE', str(tmp_path / 'decoded')) + monkeypatch.setattr(config, 'EMB_CACHE', str(tmp_path / 'emb')) + wav = tmp_path / f'{request.param}.wav' + # ':' is not a legal native Windows filename. Ordinary names still test URI behavior there. + if os.name == 'nt' and ':' in request.param: + pytest.skip('colon is not a legal Windows filename') + x = (.2 * np.sin(2 * np.pi * 440 * np.arange(48000) / 48000)).astype(np.float32) + sf.write(wav, x, 48000, subtype='FLOAT') + film = wav.with_suffix('.mp4') + subprocess.run(['ffmpeg', '-y', '-v', 'error', '-f', 'lavfi', '-i', + 'color=c=black:s=160x90:r=25:d=1', '-c:v', 'mpeg4', str(film)], + check=True, capture_output=True) + return wav, film, x + + +@pytest.mark.parametrize('spelling', ['bare', 'dot', 'absolute', 'pathlib']) +def test_local_audio_name(media, spelling): + wav, _, x = media + name = {'bare': wav.name, 'dot': './' + wav.name, 'absolute': str(wav), 'pathlib': Path(wav.name)}[spelling] + assert audio.probe(name)['channels'] == 1 + decoded = audio.load(name, cache=False) + np.testing.assert_array_equal(decoded[:, 0], x) + np.testing.assert_array_equal(decoded[:, 1], x) + np.testing.assert_array_equal(audio.load(name), decoded) + np.testing.assert_array_equal(audio.load(name), decoded) + assert audio._key(name, 48000, 2) == audio._key(str(wav), 48000, 2) + encoded, mime, info = encode(name) + assert encoded and mime == 'audio/mp3' and info['seconds'] == 1 + + +@pytest.mark.parametrize('spelling', ['bare', 'dot', 'absolute', 'pathlib']) +def test_local_video_name(media, spelling): + _, film, _ = media + name = {'bare': film.name, 'dot': './' + film.name, 'absolute': str(film), 'pathlib': Path(film.name)}[spelling] + assert audio.probe(name)['has_video'] is True + assert video.cuts(name, cache=False) == [] + assert video.cuts(name, method='scene', cache=False) == [] + assert video.frame(name, .5) is not None + + +@pytest.mark.parametrize('name', ['export:01', '-export', 'ordinary']) +@pytest.mark.parametrize('ext', ['wav', 'flac', 'mp3', 'ogg', 'm4a', 'webm']) +def test_local_export_name(tmp_path, monkeypatch, name, ext): + if os.name == 'nt' and ':' in name: + pytest.skip('colon is not a legal Windows filename') + monkeypatch.chdir(tmp_path) + path = Path(f'{name}.{ext}') + output = master.write(path, np.zeros((4800, 2), np.float32)) + assert output == path and path.is_file() + assert audio.probe(str(path.resolve()))['codec'] + + +def test_existing_file_uri_and_http_inputs(media): + wav, film, _ = media + assert audio.probe('file:' + str(wav))['channels'] == 1 + assert video.frame('file:' + str(film), .5) is not None + handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(wav.parent)) + server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler) + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + from urllib.parse import quote + base = f'http://127.0.0.1:{server.server_port}/' + assert audio.probe(base + quote(wav.name))['channels'] == 1 + assert video.frame(base + quote(film.name), .5) is not None + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_timeline_preserves_public_path_spelling(media): + from earshot.timeline import timeline + _, film, _ = media + first = timeline(film.name) + second = timeline(film.name) + assert first['cached'] is False and second['cached'] is True + for result in (first, second): + assert result['file'] == result['video'] == film.name diff --git a/tests/test_local_media_symlinks.py b/tests/test_local_media_symlinks.py new file mode 100644 index 0000000..958d387 --- /dev/null +++ b/tests/test_local_media_symlinks.py @@ -0,0 +1,50 @@ +"""FFmpeg filename disambiguation must preserve symlink/.. traversal.""" +from pathlib import Path +import subprocess + +import numpy as np +import pytest +import soundfile as sf + +from earshot import audio, video +from earshot.synth import master + + +@pytest.fixture +def linked(tmp_path, monkeypatch): + target = tmp_path / 'target' + nested = target / 'nested' + nested.mkdir(parents=True) + try: + (tmp_path / 'link').symlink_to(nested, target_is_directory=True) + except (OSError, NotImplementedError) as e: + pytest.skip(f'directory symlinks unavailable: {e}') + monkeypatch.chdir(tmp_path) + return tmp_path, target + + +def test_audio_symlink_parent_components(linked): + root, target = linked + for folder, level in [(root, .1), (target, .3)]: + sf.write(folder / 'clip.wav', np.full(4800, level, np.float32), 48000, subtype='FLOAT') + expected = audio.load(str(target / 'clip.wav'), cache=False) + np.testing.assert_array_equal(audio.load('link/../clip.wav', cache=False), expected) + + +def test_video_symlink_parent_components(linked): + root, target = linked + for folder, color in [(root, 'white'), (target, 'black')]: + subprocess.run(['ffmpeg', '-y', '-v', 'error', '-f', 'lavfi', '-i', + f'color=c={color}:s=160x90:r=25:d=1', '-c:v', 'mpeg4', str(folder / 'clip.mp4')], + check=True, capture_output=True) + assert np.mean(video.frame('link/../clip.mp4', .5)) < 1 + + +def test_export_symlink_parent_components(linked): + root, target = linked + sentinel = root / 'out.mp3' + sentinel.write_bytes(b'keep the unrelated normalized-path file') + requested = Path('link/../out.mp3') + assert master.write(requested, np.zeros((4800, 2), np.float32)) == requested + assert sentinel.read_bytes() == b'keep the unrelated normalized-path file' + assert audio.probe(str(target / 'out.mp3'))['codec'] == 'mp3' From aaf789daec00074a7d06af90df4e405a1cdd8981 Mon Sep 17 00:00:00 2001 From: dlgon <106804815+liugedragon@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:21:25 +0800 Subject: [PATCH 17/23] fix: use composed space for walking distance tilt --- earshot/sounds/learned.py | 4 +-- tests/test_walk_effective_space.py | 42 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 tests/test_walk_effective_space.py diff --git a/earshot/sounds/learned.py b/earshot/sounds/learned.py index f25fa44..6325b41 100644 --- a/earshot/sounds/learned.py +++ b/earshot/sounds/learned.py @@ -301,8 +301,8 @@ def perform(sid, seed=0, events=None, peak_db=-1.0, lufs=None, check=True, **req pat = e.get('pattern') or {} # a walk is heard from standing height: the pattern's `far` tilts every step (dB per octave around 1 kHz); a # request that asks for a close or dry sound (space under 0) hears the recording's own closeness - near = (request.get('space') or 0.0) < 0 - far = {'bright': float(pat['far'])} if pat.get('name') == 'walk' and pat.get('far') and not near else None + far = ({'bright': float(pat['far'])} + if pat.get('name') == 'walk' and pat.get('far') and c.space >= 0 else None) whole = wholes(e) walk = order(sid) play, p, cut, long = None, {}, None, False diff --git a/tests/test_walk_effective_space.py b/tests/test_walk_effective_space.py new file mode 100644 index 0000000..32e4a1b --- /dev/null +++ b/tests/test_walk_effective_space.py @@ -0,0 +1,42 @@ +"""Walking distance uses the same composed space axis as the rendered room.""" +import unittest + +import numpy as np + +from earshot.sounds import learned, theme + + +class TestWalkEffectiveSpace(unittest.TestCase): + def assert_same_take(self, left, right, **extra): + a, ma = learned.perform('step/pebbles', seed=0, **extra, **left) + b, mb = learned.perform('step/pebbles', seed=0, **extra, **right) + self.assertTrue(np.isfinite(a).all() and np.isfinite(b).all()) + np.testing.assert_array_equal(a, b) + self.assertEqual(ma, mb) + + def test_nonwalk_theme_offset(self): + a, ma = learned.perform('door/knock', seed=0, space=-.5) + b, mb = learned.perform('door/knock', seed=0, theme={'axes': {'space': -.5}}) + np.testing.assert_array_equal(a, b) + self.assertEqual(ma, mb) + + def test_whole_negative_theme_offset(self): + self.assert_same_take({'space': -.5}, {'theme': {'axes': {'space': -.5}}}) + + def test_sequence_negative_theme_offset(self): + self.assert_same_take({'space': -.5}, {'theme': {'axes': {'space': -.5}}}, events=3) + + def test_cancelled_negative_at_zero(self): + self.assert_same_take({'space': 0}, {'space': -.5, 'theme': {'axes': {'space': .5}}}, events=3) + + def test_positive_composition_with_room(self): + self.assert_same_take({'space': .5, 'theme': {'space': 'hall'}}, + {'space': -.5, 'theme': {'space': 'hall', 'axes': {'space': 1}}}, events=3) + + def test_clipped_negative_named_base(self): + self.assert_same_take({'space': -1, 'theme': theme.get('wood')}, + {'space': -.75, 'theme': theme.get({'base': 'wood', 'axes': {'space': -.75}})}) + + +if __name__ == '__main__': + unittest.main() From ecb07dfe3a454d444c3f1cf505c090c1d89f99f5 Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:08:26 +0100 Subject: [PATCH 18/23] make --listen hears the take it wrote, also in ogg, mp3, m4a and webm, not a new single event Found by the Codex review of #51. Co-Authored-By: Claude Opus 5.5 --- earshot/make.py | 21 +++++++++++---------- tests/test_make.py | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/earshot/make.py b/earshot/make.py index 8435488..85de610 100644 --- a/earshot/make.py +++ b/earshot/make.py @@ -758,14 +758,22 @@ def make(want=None, out=None, sound=None, n=1, seed=0, theme=None, listen=False, req['dur'] = round(0.02 + (int(perf[1]) - 1) * float(b['gap']) + ring, 3) n = takes_asked(b, pick['why'], perf, n) paths = _paths(out or pick['id'].replace('/', '_') + '.' + (fmt or 'wav'), n, fmt) - takes = [] + takes, first = [], None for i, p in enumerate(paths): y, meta = take(pick['id'], seed + i, req, lufs, perform=perf) + first = y if first is None else first master.write(p, y, sr=sr, mono=mono, bits=bits) takes.append({**meta, 'file': p}) if listen and heard is None: - heard = _heard(paths[0] if paths[0].lower().endswith(('.wav', '.flac')) else _tmp_wav(pick['id'], seed, req), - ([want] if want else []) + list(registry.get(pick['id']).says)) + # the first take as it was delivered (its performance and level): a wav or flac is heard as written, any + # other format from the same samples in a wav, so that what is heard is what was handed over + queries = ([want] if want else []) + list(registry.get(pick['id']).says) + if paths[0].lower().endswith(('.wav', '.flac')): + heard = _heard(paths[0], queries) + else: + import tempfile + with tempfile.TemporaryDirectory() as tmp: + heard = _heard(master.write(os.path.join(tmp, 'heard.wav'), first, sr=sr, mono=mono), queries) why = brief.shown(b, pick['why']) lines = [_line(t, t['file'], ', '.join(why) if i == 0 else '') for i, t in enumerate(takes)] played = takes[0].get('performance') @@ -818,13 +826,6 @@ def make(want=None, out=None, sound=None, n=1, seed=0, theme=None, listen=False, return res -def _tmp_wav(sound, seed, req): - import tempfile - from .synth import master - y, _ = take(sound, seed, req) - return master.write(os.path.join(tempfile.mkdtemp(), 'heard.wav'), y) - - def found_by(why, sound=None): """the words the catalogue's first design was found by, a phrase ("ph:launch rocket") as its words: when they hold every word of a cookbook thing the catalogue has that sound itself, and its design answers, not the recipe. With diff --git a/tests/test_make.py b/tests/test_make.py index f081f39..682c43a 100644 --- a/tests/test_make.py +++ b/tests/test_make.py @@ -841,3 +841,23 @@ def test_a_length_within_a_tenth_of_a_second_says_nothing(tmp_path): assert _note(t, 8.0) is None t = {'dur_s': 5.0, 'note': '5.00 s, shorter than the 8 s asked: the longest this sound is made'} assert _note(t, 8.0) == '5.00 s, shorter than the 8 s asked' + + +def test_listening_hears_the_take_that_was_written_in_any_format(tmp_path, monkeypatch): + # an ogg is heard from the samples written into it: the walk of eight steps, not a new single step + if not shutil.which('ffmpeg'): + pytest.skip('ogg needs ffmpeg') + from earshot import extras, make as M + heard = [] + + def ear(path, queries): + y, sr = sf.read(path) + heard.append(len(y) / sr) + return {'query': queries[0], 'z': 0.0, 'verdict': 'no match'} + + monkeypatch.setattr(extras, 'need', lambda *a, **k: None) + monkeypatch.setattr(M, 'semantic', lambda want, listen=None: (None, None)) + monkeypatch.setattr(M, '_heard', ear) + r = make('footsteps on gravel', str(tmp_path / 'walk.ogg'), events=8, listen=True) + assert r['takes'][0]['performance']['events'] == 8 + assert heard and heard[0] == pytest.approx(r['takes'][0]['dur_s'], abs=0.01) From 69e3c7a00b8e66401ceaae46c922bcafce783cb7 Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:08:27 +0100 Subject: [PATCH 19/23] a recipe whose events would start after 120 s is refused before any buffer is allocated Found by the Codex review of #51: count 32, gap 1, faster 2 asked for about 1.6 PB. Co-Authored-By: Claude Opus 5.5 --- docs/MAKE.md | 2 +- earshot/recipe.py | 16 ++++++++++++++-- tests/test_recipe.py | 10 ++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/docs/MAKE.md b/docs/MAKE.md index 4dc393b..29211a3 100644 --- a/docs/MAKE.md +++ b/docs/MAKE.md @@ -594,7 +594,7 @@ cookbook recipe (`"recipe": "thunder_far"`, one level deep: a storm can hold a b | `at` | seconds: where the layer starts | | `fade_in`, `fade_out` | seconds: fades at its ends; when not said, an ambience gets 0.1 and 0.3 s and a source 0.01 and 0.02 s | | `swell`, `decay` | seconds: a slow rise from 30 dB down at its start, a slow fall to nothing at its end | -| `events` | `{"count", "gap", "faster", "softer", "loose"}`: the layer 2 to 64 times, each a new take, `gap` seconds apart; each gap `faster` times the one before (under 1: faster and faster); each event `softer` dB against the one before; `loose` 0 to 1 moves each up to half its gap early or late | +| `events` | `{"count", "gap", "faster", "softer", "loose"}`: the layer 2 to 64 times, each a new take, `gap` seconds apart; each gap `faster` times the one before (under 1: faster and faster); each event `softer` dB against the one before; `loose` 0 to 1 moves each up to half its gap early or late; the last event starts within 120 s | | `scatter` | `{"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}`: the layer many times at random moments, `rate` events a second (0.5 to 400) moving to `rate_to` by the end, over `dur` seconds; each event up to `pitch` semitones (0 to 12) higher or lower, up to `gain` dB (0 to 40) softer, up to `pan` (0 to 1) to either side; with `grain` (0.005 to 2 s) each event is a random piece of that length of the take. Every event another take where the design has several recordings. Rain from drops, applause from claps, hail, gravel, a crowd, a swarm | | `level` | `[[time, dB], ...]`: the layer's loudness over time, from its start, straight in dB between the points (-60 to 12) | | `bend` | `[[time, semitones], ...]`: the layer's pitch over the heard time as a tape does it (-24 to 12): a moo bent into a whale's song | diff --git a/earshot/recipe.py b/earshot/recipe.py index 14a182a..22878eb 100644 --- a/earshot/recipe.py +++ b/earshot/recipe.py @@ -49,8 +49,8 @@ events {"count", "gap", "faster", "softer", "loose"}: the layer several times, each a new take: `gap` s from one to the next, each gap `faster` times the one before (under 1: faster and faster), each event `softer` dB against the one before, each up to `loose` (0 .. 1) of half its gap - early or late (drops, crackles, clicks that come as they come) - scatter {"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}: the layer many times at random + early or late (drops, crackles, clicks that come as they come); the last starts within 120 s + scatter {"rate", "rate_to", "dur", "pitch", "gain", "pan", "grain"}: the layer many times at random moments (a Poisson process): `rate` events a second (0.5 .. 400) moving to `rate_to` by the end, over `dur` s; each event up to `pitch` semitones (0 .. 12) higher or lower, up to `gain` dB (0 .. 40) softer and up to `pan` (0 .. 1) to either side; with `grain` (0.005 .. 2 s) each is a @@ -144,6 +144,7 @@ 'hz': (20.0, 150.0, 'a frequency in Hz'), 'to': (20.0, 150.0, 'a frequency in Hz'), **{a: (-1.0, 1.0, 'an amount') for a in AXES}} CUTOFF = (20.0, 20000.0) +LATEST = 120.0 # s: the last event of a layer starts by then, as `at` does (a layer is mixed whole first) EVENT_RANGE = {'count': (2, 64, 'a whole number'), 'gap': (0.02, 30.0, 'a time in seconds'), 'faster': (0.5, 2.0, 'a factor'), 'softer': (-12.0, 12.0, 'a level in dB'), 'loose': (0.0, 1.0, 'an amount')} @@ -381,6 +382,17 @@ def check(recipe): if 'follow' in lay and lay['follow']['layer'] >= len(layers): raise RecipeError(f'layers[{i}].follow.layer is {lay["follow"]["layer"]}, but the recipe has ' f'{len(layers)} layers (0 to {len(layers) - 1})') + if 'events' in lay: # each gap `faster` times the one before: the last start can run far past any sound + ev, last = lay['events'], lay.get('at', 0.0) + gap = ev['gap'] + for _ in range(int(ev['count']) - 1): + last += gap + gap *= ev.get('faster', 1.0) + if last > LATEST: + break + if last > LATEST: + raise RecipeError(f'layers[{i}].events: its last event would start after {LATEST:.0f} s; events ' + f'start within {LATEST:.0f} s (fewer events, a shorter gap or a smaller "faster")') if 'says' in recipe and not (isinstance(recipe['says'], str) and recipe['says'].strip()): raise RecipeError(f'says is what the sound is, in words ("a dragon roaring"), not {recipe["says"]!r}') if 'built' in recipe and not isinstance(recipe['built'], str): diff --git a/tests/test_recipe.py b/tests/test_recipe.py index c5e365f..1e2c8e2 100644 --- a/tests/test_recipe.py +++ b/tests/test_recipe.py @@ -227,6 +227,16 @@ def test_events_repeat_a_layer_faster_and_softer(): assert 0.75 < meta['dur_s'] < 1.6 and meta['source'] == 'recipe' +def test_events_that_would_start_past_two_minutes_are_refused_before_any_buffer(): + # each gap twice the one before: the 32nd event would start about 2 billion seconds in (about 1.6 PB of samples) + with pytest.raises(R.RecipeError, match=r'layers\[0\]\.events: its last event would start after 120 s'): + R.check(rec({**TAP, 'events': {'count': 32, 'gap': 1, 'faster': 2}})) + with pytest.raises(R.RecipeError, match=r'layers\[0\]\.events'): + R.check(rec({**TAP, 'at': 100, 'events': {'count': 3, 'gap': 15}})) + assert R.check(rec({**TAP, 'at': 10, 'events': {'count': 64, 'gap': 1.5, 'faster': 1}})) # the last at 104.5 s + assert R.check(rec({**TAP, 'events': {'count': 64, 'gap': 30, 'faster': 0.5}})) # under a minute + + def test_follow_gives_a_layer_the_loudness_of_another_or_makes_it_give_way(): lead = np.zeros((dsp.n_of(1.0), 2)) lead[dsp.n_of(0.2):dsp.n_of(0.4)] = 0.5 From 6b28d19170f2c495d8f18feee149b86fa0fc3872 Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:08:27 +0100 Subject: [PATCH 20/23] build hears a sound file at its own sample rate Found by the Codex review of #51: a 24 kHz file was measured half as long and twice as high. Co-Authored-By: Claude Opus 5.5 --- earshot/build.py | 5 ++++- tests/test_build.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/earshot/build.py b/earshot/build.py index 1035a7e..d30ed04 100644 --- a/earshot/build.py +++ b/earshot/build.py @@ -1450,8 +1450,11 @@ def hear(recipe, words=None, without=(), seed=SEED, ears=None, near=None, layers y, meta = take[:2] elif isinstance(recipe, str) and os.path.isfile(recipe) and not recipe.lower().endswith('.json'): import soundfile as sf - y, _ = sf.read(recipe, always_2d=True) + y, rate = sf.read(recipe, always_2d=True) y = np.asarray(y, np.float64) + if rate != 48000: # every measure, the audit and the ears read 48 kHz samples + import soxr + y = np.asarray(soxr.resample(y, rate, 48000, quality='HQ'), np.float64) from .sounds import registry from types import SimpleNamespace meta = {'checks': registry.audit(y, SimpleNamespace(kind='object', pitch=None, loop=False, allows=()))} diff --git a/tests/test_build.py b/tests/test_build.py index 9794fdf..34c3af2 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -277,6 +277,21 @@ def test_hear_without_ears_names_fields(tmp_path): assert any('`dur`' in x for x in h['off']) +def test_hear_reads_a_sound_file_at_its_own_rate(tmp_path): + # a file at 24 kHz is the same sound as at 48 kHz: the same length and brightness, not half as long and twice as high + import soundfile as sf + t = np.arange(int(1.0 * 24000)) / 24000 + y = 0.3 * np.sin(2 * np.pi * 1000 * t) * np.exp(-3 * t) + p24, p48 = str(tmp_path / 'tone24.wav'), str(tmp_path / 'tone48.wav') + sf.write(p24, np.stack([y, y], axis=1), 24000) + t = np.arange(int(1.0 * 48000)) / 48000 + y = 0.3 * np.sin(2 * np.pi * 1000 * t) * np.exp(-3 * t) + sf.write(p48, np.stack([y, y], axis=1), 48000) + a, b = B.hear(p24, 'a tone', listen=False), B.hear(p48, 'a tone', listen=False) + assert a['dur'] == pytest.approx(1.0, abs=0.01) and a['dur'] == pytest.approx(b['dur'], abs=0.01) + assert a['bright'] == pytest.approx(b['bright'], rel=0.05) + + def test_the_command_line_builds(tmp_path, capsys): from earshot import cli out = str(tmp_path / 'cli.wav') From 712bd0d6de78210289a412092a8d981a19d1ca1c Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:21:40 +0100 Subject: [PATCH 21/23] the symlink tests of #47 are skipped on Windows, which resolves link/.. by the name Co-Authored-By: Claude Opus 5.5 --- tests/test_local_media_symlinks.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_local_media_symlinks.py b/tests/test_local_media_symlinks.py index 958d387..88abb88 100644 --- a/tests/test_local_media_symlinks.py +++ b/tests/test_local_media_symlinks.py @@ -1,4 +1,5 @@ """FFmpeg filename disambiguation must preserve symlink/.. traversal.""" +import os from pathlib import Path import subprocess @@ -12,6 +13,8 @@ @pytest.fixture def linked(tmp_path, monkeypatch): + if os.name == 'nt': + pytest.skip('Windows resolves "link/.." by the name before it follows the link: there is no such path') target = tmp_path / 'target' nested = target / 'nested' nested.mkdir(parents=True) From 1c6de2b0cf11ffb2fce93a379e7f553429a64668 Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:21:40 +0100 Subject: [PATCH 22/23] 1.1.0, unreleased: the changelog thanks the community fixes, and TESTING.md says torch comes with the listen extra Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/plugin.json | 2 +- CHANGELOG.md | 43 ++++++++++++++++++++++++++++++++++++++ docs/TESTING.md | 4 ++-- earshot/__init__.py | 2 +- pyproject.toml | 2 +- tests/test_core.py | 2 +- 6 files changed, 49 insertions(+), 6 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ed86379..dbe9aeb 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "earshot", - "version": "1.0.0", + "version": "1.1.0", "description": "Make sound effects from a request in words: interface sounds, everyday foley, ambience, game, film and motion sounds and drums, computed when asked (the realistic ones learned from public-domain recordings, no audio shipped), and build what the catalogue lacks from its parts. Listen to sound an agent cannot hear: describe, match, measure and critique it.", "author": { "name": "Leon Lin" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fe5b43..9051aee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,48 @@ # Changelog +## 1.1.0 - unreleased + +Fixes from the community, thanks to @liugedragon and @fcy222fcy, and three found by an automated review of the 1.0 +release. + +### Fixed + +**Making sounds** + +- **`make --listen` hears the take it wrote.** For ogg, mp3, m4a and webm it rendered a new single event to listen + to, so the `heard` line of "footsteps" with `events=8` described one step. It now hears the samples it wrote. +- **A recipe cannot ask for an endless timeline.** Events whose gaps grow (`"faster": 2`) could start billions of + seconds in and allocate far more memory than any machine has before the recipe's length cut them; the last event + of a layer now starts within 120 s, or the recipe is refused with one sentence. +- **`build` hears a sound file at its own sample rate**: a 24 kHz file was measured half as long and twice as high. +- **A set refuses names and sprites that would overwrite each other** (#39): `tap` with two takes and another sound + named `tap_1`, two names with the same file name in different folders, or a sprite named like a take or + `manifest.json` stop with one sentence before anything is written. +- **`pack` refuses a name count that differs from the file count** (#41), before it reads any audio. +- **A bank sound keeps its asked peak after resampling** (#33). +- **A named theme's axes no longer share state with its preset** (#34): changing one no longer changed the other. +- **A walk's distance tilt uses the composed space** (#48). + +**Listening and video** + +- **The selected audio track keeps its level and stereo image** (#28). In a file with several audio tracks, the + stereo decode read the channel count of the first track while ffmpeg decoded another: a stereo track could become + dual mono, a mono track 3 dB too quiet. The decode version is 3, so the decode caches fill again once. +- **Picture cut timing uses the frame rate of the decoded track** (#45), not the first video track's: cuts in a + file with two video tracks of different rates landed at the wrong times. +- **Local media names are unambiguous for ffmpeg** (#47): a file named `take:01.wav` or starting with `-` is read + and written as a file, not as a protocol or an option. +- **A failed write to an optional media cache is no longer an error** (#42): the analysis goes on without the cache. +- **Timeline caches are keyed by the parsed cues** (#43), and **timeline ranges are bounded by the decoded + samples** (#44). +- **The search index stays alive behind its cached positions** (#36). +- **`earshot --threads 2 ` loads only that command** (#46): the value of `--threads` was read as the + command word, so every command module was loaded and the start took about three times as long. + +### Changed + +- `docs/TESTING.md` says that torch and transformers come with the `listen` extra. + ## 1.0.0 - 2026-11-20 earshot now makes sounds as well as listening to them. An agent asks for a sound in words and earshot renders a new diff --git a/docs/TESTING.md b/docs/TESTING.md index a5d97d2..6e4c4c4 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -15,8 +15,8 @@ python3.12 -m venv .venv-fast EARSHOT_OFFLINE=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 MPLBACKEND=Agg OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 .venv-fast/bin/python -m pytest -q -p no:cacheprovider -rs tests ``` -This intentionally leaves out Torch and Transformers, which remain required by -the normal package metadata. It is **not** a full installation or a packaging +This intentionally leaves out Torch and Transformers, which come with the +`listen` extra; the tests that need them skip without them. It is **not** a full installation or a packaging dependency check. Follow the README's installation instructions when running model-dependent features. Do not run `doctor --load` in this reduced environment. diff --git a/earshot/__init__.py b/earshot/__init__.py index fc31dd2..584929c 100644 --- a/earshot/__init__.py +++ b/earshot/__init__.py @@ -15,7 +15,7 @@ """ import importlib -__version__ = '1.0.0' +__version__ = '1.1.0' # modules that are callable as their main function (see _callable.py) _CALLABLE = {'describe', 'match', 'compare', 'realness', 'timeline', 'sheet', 'critique', 'profile'} diff --git a/pyproject.toml b/pyproject.toml index 07ab7fe..9e227c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "earshot" -version = "1.0.0" +version = "1.1.0" description = "Make sound effects for interfaces, motion videos, games and films, everyday foley, drums and ambience from a request in words (computed at request time; the realistic ones from models learned from public-domain recordings, no audio shipped), build what the catalogue lacks from recorded parts named in words, and describe, match, measure and critique sound an agent cannot hear." readme = "README.md" requires-python = ">=3.10" diff --git a/tests/test_core.py b/tests/test_core.py index be8f697..7ca8c8c 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -268,4 +268,4 @@ def test_one_version_everywhere(): top = re.search(r'^## (\S+)', fh.read(), re.M).group(1) with open(os.path.join(root, '.claude-plugin', 'plugin.json'), encoding='utf-8') as fh: plugin = json.load(fh)['version'] - assert earshot.__version__ == pyproject == top == plugin == '1.0.0' + assert earshot.__version__ == pyproject == top == plugin == '1.1.0' From abe09b1647434ba0a18e9d59c2b932e646932bd9 Mon Sep 17 00:00:00 2001 From: Leonxlnx Date: Sun, 22 Nov 2026 01:30:11 +0100 Subject: [PATCH 23/23] three new test files import the timeline module itself, so they collect on Linux without the listen extra Co-Authored-By: Claude Opus 5.5 --- tests/test_audio_multitrack.py | 3 ++- tests/test_optional_media_cache.py | 2 +- tests/test_timeline_cue_cache.py | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test_audio_multitrack.py b/tests/test_audio_multitrack.py index c1c1002..fe8510a 100644 --- a/tests/test_audio_multitrack.py +++ b/tests/test_audio_multitrack.py @@ -6,7 +6,8 @@ import pytest import soundfile as sf -from earshot import audio, timeline +import earshot.timeline as timeline # the module itself: `from earshot import timeline` asks for the listen extra +from earshot import audio def _wav(tmp_path, channels, sr=48000): diff --git a/tests/test_optional_media_cache.py b/tests/test_optional_media_cache.py index c84da17..5d4ac19 100644 --- a/tests/test_optional_media_cache.py +++ b/tests/test_optional_media_cache.py @@ -9,8 +9,8 @@ import numpy as np import pytest +import earshot.timeline as tl # the module itself: `from earshot import timeline` asks for the listen extra from earshot import audio, config, video -from earshot import timeline as tl @pytest.fixture diff --git a/tests/test_timeline_cue_cache.py b/tests/test_timeline_cue_cache.py index 71715eb..176e41b 100644 --- a/tests/test_timeline_cue_cache.py +++ b/tests/test_timeline_cue_cache.py @@ -3,7 +3,8 @@ import numpy as np import soundfile as sf import pytest -from earshot import timeline as tl, config +import earshot.timeline as tl # the module itself: `from earshot import timeline` asks for the listen extra +from earshot import config @pytest.fixture def setup(tmp_path, monkeypatch):