Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
test: exercise short sound and encoded loop boundaries
Soohong Kim64b6e341f925
diff --git a/sprite_gen/audio/sound.py b/sprite_gen/audio/sound.pyindex b8ff7d9..23950b7 100644--- a/sprite_gen/audio/sound.py+++ b/sprite_gen/audio/sound.py@@ -11,7 +11,7 @@ import shutilimport tempfilefrom sprite_gen.audio import cache, processing, provider-from sprite_gen.audio.manifest import event_name+from sprite_gen.audio.manifest import event_name, load as load_soundfrom sprite_gen.util.cli_kwargs import namespace_from_kwargs@@ -32,10 +32,7 @@ def generate(*, kind, prompt, duration, event, out_dir, cache_dir=None, loop=Nonmanifest = json.loads((out_dir / 'sound.json').read_text()) if (out_dir / 'sound.json').is_file() else {}if manifest.get('recipe') != recipe:raise ValueError('output directory already exists with a different sound; use a new directory')- for file in manifest['files'].values():- path = out_dir / file['path']- if not path.is_file() or cache_hash(path) != file['sha256']:- raise ValueError('published sound is damaged; use a new output directory with the same cache')+ load_sound(out_dir/'sound.json', 50_000_000)return {**manifest, 'cache_hit': True}processing.require_tools()cache_dir = Path(cache_dir).expanduser() if cache_dir else Path(os.environ.get('XDG_CACHE_HOME', Path.home()/'.cache'))/'sprite-gen'/'audio'@@ -61,11 +58,6 @@ def generate(*, kind, prompt, duration, event, out_dir, cache_dir=None, loop=Nonreturn {**manifest, 'cache_hit': hit}-def cache_hash(path):- import hashlib- return hashlib.sha256(path.read_bytes()).hexdigest()--def add_arguments(parser):parser.add_argument('--kind', choices=('sfx', 'bgm'), required=True)prompts = parser.add_mutually_exclusive_group(required=True)diff --git a/tests/audio/test_sound.py b/tests/audio/test_sound.pyindex 005e751..7df9dca 100644--- a/tests/audio/test_sound.py+++ b/tests/audio/test_sound.py@@ -124,3 +124,39 @@ def test_processing_failure_reuses_paid_audio(tmp_path, monkeypatch):assert not kw['out_dir'].exists()monkeypatch.setattr(processing, 'export', original)assert sound.generate(**kw)['cache_hit'] and len(called) == 1++[email protected]('kind,duration,loop', [('sfx', .5, False), ('bgm', 3, True)])+def test_short_effect_and_loop_encoded_playback(tmp_path, monkeypatch, kind, duration, loop):+ monkeypatch.setattr(provider, 'generate', lambda req: (wav_bytes(duration), {}))+ result = sound.generate(kind=kind, prompt='synthetic', duration=duration, event='sample',+ cache_dir=tmp_path/'cache', out_dir=tmp_path/'out')+ assert result['loop'] is loop+ assert abs(result['duration_seconds'] - (duration-result['crossfade_seconds'])) < .001+ if loop:+ for file in result['files'].values():+ decoded = processing.decode(tmp_path/'out'/file['path'])[:round(result['loop_end_seconds']*48000)]+ assert np.max(np.abs(decoded[-1]-decoded[0])) < .025+++def test_preflight_does_not_claim_and_cached_source_works_without_key(tmp_path, monkeypatch):+ db = tmp_path/'cache.sqlite3'+ def no_key(): raise ValueError('missing key')+ with pytest.raises(ValueError, match='missing key'):+ cache.obtain(db, {'request':1}, lambda: pytest.fail('must preflight'), prepare=no_key)+ assert cache.obtain(db, {'request':1}, lambda: (b'audio', {}))[2] is False+ assert cache.obtain(db, {'request':1}, lambda: pytest.fail('cache must suffice'), prepare=no_key)[2] is True+++def test_error_body_and_transport_cannot_disclose_key(monkeypatch, capsys):+ key = 'secret-api-key-should-never-appear'+ monkeypatch.setenv('ELEVENLABS_API_KEY', key)+ def refuse(req, **kwargs):+ raise urllib.error.HTTPError(req.full_url, 422, key, {}, io.BytesIO(json.dumps({'detail':{'message':key,'status':key}}).encode()))+ monkeypatch.setattr(provider, 'urlopen', refuse)+ with pytest.raises(ValueError) as err: provider.generate(provider.request('sfx','impact',1,False))+ assert key not in str(err.value) + capsys.readouterr().err+ def broken(*a, **kw): raise OSError(key)+ monkeypatch.setattr(provider, 'urlopen', broken)+ with pytest.raises(ValueError) as err: provider.generate(provider.request('sfx','impact',1,False))+ assert key not in str(err.value) + capsys.readouterr().err