Ears for coding agents: let AI hear, review and make sound. CPU-only, open source.
Local model folders load again; narrow custom-model downloads; Gemini rubric judges synthesis by intent
Leonxlnxd1671ad81856
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea58918..256823e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,15 @@ Two fixes from a careful outside review (thanks, @markblundeberg).- `earshot doctor` reports, per model, the pinned revision, what the cache holds (cached / legacy / incomplete /missing), the folder that loads and the offline flag; `--load` adds the revision and weights file that loaded.The first download is ~1.1 GB (the docs said 1.4 GB).+ - `EARSHOT_CLAP` / `EARSHOT_AST` may still name a local model folder (`config.json` plus `model.safetensors`, or an+ older checkpoint's `pytorch_model.bin`): it loads from disk as it is, with no network and no revision, has its own+ embedding caches, and earshot never downloads into it (an incomplete folder is an error naming what is missing).+ - A custom Hub model downloads its top-level config, tokenizer and safetensors files by name; the old `*.json` /+ `*.safetensors` globs also matched every subfolder and weight variant of a repo.+- **The optional Gemini critique no longer treats synthesized sound as a defect by itself** (#1). Its rubric set+ "real recorded foley" as the bar and scored "obviously cheap or synthetic"; it now judges each sound by whether it+ fits the film and is well made, counts synthesis as a flaw only where a sound should read as recorded, and+ `earshot llm --synth-intended` (MCP `synth_intended`) tells the model that synthesized sound is the point.### Addeddiff --git a/README.md b/README.mdindex 8a637ee..8114e1c 100644--- a/README.md+++ b/README.md@@ -213,8 +213,11 @@ doctor` says so; `earshot doctor --fetch` downloads the pinned safetensors (776Settings (environment variables): `EARSHOT_THREADS` (torch CPU threads, default min(4, cores/2)), `EARSHOT_HOME`(cache root), `EARSHOT_PRECISION` (`bf16` by default, used only on CPUs with native bf16 such as AVX512-BF16 / AMX,-fp32 everywhere else; `fp32` forces fp32), `EARSHOT_OFFLINE=1` (above), `EARSHOT_CLAP` / `EARSHOT_AST` (other model-ids) and `EARSHOT_CLAP_REVISION` / `EARSHOT_AST_REVISION` (another Hub revision; safetensors weights only).+fp32 everywhere else; `fp32` forces fp32), `EARSHOT_OFFLINE=1` (above), `EARSHOT_CLAP` / `EARSHOT_AST` (another+Hub model id, or a local model folder with `config.json` and `model.safetensors`, which loads from disk as it is with+no network and is never downloaded into) and `EARSHOT_CLAP_REVISION` / `EARSHOT_AST_REVISION` (another Hub revision;+safetensors weights only). A custom Hub model downloads its top-level config, tokenizer and safetensors files by name,+never a repo's subfolders or weight variants.`earshot doctor` reports the revisions and what the cache holds; `--load` also what loads (revision, weights,precision).diff --git a/earshot/config.py b/earshot/config.pyindex f3294be..38dcb27 100644--- a/earshot/config.py+++ b/earshot/config.py@@ -3,8 +3,9 @@EARSHOT_HOME cache root (models, embeddings, decoded audio). Default: <repo>/.cache in a source checkout,else ~/.cache/earshot.EARSHOT_THREADS torch CPU threads per process (default: min(4, cores // 2)); earshot never uses a GPU.-EARSHOT_CLAP CLAP model id (default laion/larger_clap_general)-EARSHOT_AST AudioSet tagger id (default MIT/ast-finetuned-audioset-10-10-0.4593)+EARSHOT_CLAP CLAP model: a Hub id (default laion/larger_clap_general) or a local model folder (config.json plus+ model.safetensors), loaded from disk as it is, never downloaded into+EARSHOT_AST AudioSet tagger: a Hub id (default MIT/ast-finetuned-audioset-10-10-0.4593) or a local model folderEARSHOT_CLAP_REVISION, EARSHOT_AST_REVISIONHub revision (commit sha, branch or tag) to use instead of the pinned one (PINS below); a custommodel id without a revision uses 'main'diff --git a/earshot/doctor.py b/earshot/doctor.pyindex 469c51e..e71d4db 100644--- a/earshot/doctor.py+++ b/earshot/doctor.py@@ -31,7 +31,8 @@ def _models():def models():- """per model id: the revision earshot wants, what the cache holds and the folder that loads. Filesystem only"""+ """per model id: the revision earshot wants ('local' for a local model folder), what the cache holds and the+ folder that loads. Filesystem only"""from .models import hubout = {}for mid, rev in _models():@@ -49,7 +50,7 @@ def fetch():for mid, rev in _models():s = hub.resolve(mid, rev)if s.state == 'cached':- out[mid] = 'already cached'+ out[mid] = 'already cached' if not s.folder else 'a local folder (nothing to download)'continuetry:out[mid] = 'downloaded ' + hub.fetch(s).sha[:7]@@ -114,7 +115,11 @@ def check(load=False, fetch_missing=False):problems += [f'data file earshot/data/{f} missing' for f, ok in data.items() if not ok]failed = [m for m, v in r.get('fetched', {}).items() if v.startswith('failed')]problems += [f"{m}: {r['fetched'][m]}" for m in failed]- notes, todo = [], [m for m, ok in r['models_cached'].items() if not ok and m not in failed]+ folders = {m for m, v in r['models'].items() if v['revision'] == 'local'}+ problems += [f"{m}: the local model folder lacks {' and '.join(r['models'][m]['missing'])} (earshot never "+ 'downloads into a folder)' for m in r['models']+ if m in folders and not r['models_cached'][m] and m not in failed]+ notes, todo = [], [m for m, ok in r['models_cached'].items() if not ok and m not in failed and m not in folders]if todo and r['offline']:problems.append(f"{' and '.join(todo)} not in the cache ({config.HF_CACHE}) and {r['offline']} is set, so "'earshot will not download them: run `earshot doctor --fetch` once without it, or copy a 'diff --git a/earshot/forge/critic.py b/earshot/forge/critic.pyindex 857ea9f..bf9c963 100644--- a/earshot/forge/critic.py+++ b/earshot/forge/critic.py@@ -216,11 +216,13 @@ _HOLD = {}def holdout_key(mono):- """cache key of one sound for Critic.holdout: sha1 of its mono float32 samples + the AudioSet model id"""+ """cache key of one sound for Critic.holdout: sha1 of its mono float32 samples + the AudioSet model's cache name+ (org--name for the pinned model, so existing caches stay valid; a revision or a local folder gets its own)"""import hashlibfrom .. import config+ from ..models import hubm = np.ascontiguousarray(mono, np.float32)- return config.AST_MODEL.replace('/', '--') + '/' + hashlib.sha1(m.tobytes()).hexdigest()+ return hub.cache_name(config.AST_MODEL, config.AST_REVISION) + '/' + hashlib.sha1(m.tobytes()).hexdigest()def _holdout_dir():diff --git a/earshot/llm.py b/earshot/llm.pyindex 17c5761..1a39991 100644--- a/earshot/llm.py+++ b/earshot/llm.py@@ -45,32 +45,40 @@ RETRY_WAIT = (4, 12)KEY_URL = 'https://aistudio.google.com/apikey'RUBRIC = """You are a senior re-recording mixer and sound supervisor reviewing the soundtrack of a short product launch-film (or one stem of it). The bar is a premium launch film from a top studio: real recorded foley and ambience, music-that is produced and mixed, sounds that land exactly on picture events, a clean, controlled master that is loud but-not crushed. Listen to the whole clip. Be specific and blunt; praise only what is genuinely good.+film (or one stem of it). The bar is a premium launch film from a top studio: every sound crafted and intentional,+music that is produced and mixed, sounds that land exactly on picture events, a clean, controlled master that is loud+but not crushed. Effects may be recorded foley or designed / synthesized on purpose: judge each by whether it fits the+film and is well made, not by how it was made. Listen to the whole clip. Be specific and blunt; praise only what is+genuinely good.Judge:1. sync: do hits, whooshes and accents land where they seem to belong? You cannot see the picture: use the picturecut / cue times in the context if given, otherwise judge rhythmic tightness and whether sounds feel late, early orsmeared. Use null for the sync score when there is nothing to judge it against.-2. realism: which sounds are real recordings and which sound code-synthesized, stock-cheesy or generic (pure sine+2. realism: which sounds read as real recordings and which as code-synthesized, stock-cheesy or generic (pure sinebeeps, plain filtered-noise whooshes, chiptune blips, preset risers, the identical sample machine-gunned)?+ Synthesis is a flaw only where a sound is meant to read as recorded. If the context or the editor's question says+ the film uses synthesized or procedural sound on purpose, judge those sounds as designed sound (clean, crafted,+ fitting the picture) and do not count synthesis itself as a flaw.3. mix balance: music vs effects vs ambience, masking, elements too loud or buried, low-end mud, harsh 2-5 kHz(the clip is a mono reduction: do not judge stereo width).4. loudness and dynamics: use the measured numbers in the context, never guess numbers; squashed, too quiet, peaky,pumping, clipped?5. what is cheap: the moments that would make a professional wince.-6. concrete fixes, each tied to a time range and saying exactly what to change (for example: replace the beep with a- recorded UI tap, -4 dB on the music under 12.0-15.0, move the hit 80 ms earlier, high-pass the pad at 150 Hz).+6. concrete fixes, each tied to a time range and saying exactly what to change (for example: soften the harsh beep+ or swap it for a gentler tap that suits the film, -4 dB on the music under 12.0-15.0, move the hit 80 ms earlier,+ high-pass the pad at 150 Hz).Scores 1-10: 10 = indistinguishable from the premium reference, 7 = good professional work with small flaws,-5 = competent amateur, 3 = obviously cheap or synthetic, 1 = broken.+5 = competent amateur, 3 = obviously cheap, 1 = broken. realism rates how convincing and well made the sounds are for+what the film intends (recorded, or designed on purpose), not whether they were recorded.Times are seconds from the start of THIS clip, as numbers (12.4, not "0:12"). Reply with ONLY this JSON object:{"overall": {"score": <1-10>, "verdict": "<one sentence>"},"scores": {"sync": <1-10 or null>, "realism": <1-10>, "mix_balance": <1-10>, "loudness": <1-10>,"music": <1-10 or null when there is no music>},"notes": {"sync": "", "realism": "", "mix_balance": "", "loudness": "", "music": ""},- "synthetic_or_cheap": [{"start": <s>, "end": <s>, "what": "<the sound>", "why": "<what gives it away>"}],+ "synthetic_or_cheap": [{"start": <s>, "end": <s>, "what": "<the sound>",+ "why": "<what gives it away: cheap, generic, or synthetic where it should read as recorded>"}],"issues": [{"start": <s>, "end": <s>, "severity": "high|medium|low","category": "sync|realism|mix|loudness|music|noise|edit", "problem": "", "fix": ""}],"strengths": [""],@@ -292,11 +300,17 @@ def context(path, clip, video=None, with_timeline=False, cuts=True):return '\n'.join(lines), notes-def build_prompt(ctx_text, question=None):+SYNTH_INTENT = ('Intent: this film uses synthesized / procedural sound on purpose. Judge those sounds as designed '+ 'sound; list a sound under synthetic_or_cheap only when it is cheap, harsh, generic or badly made, '+ 'never only because it is synthesized.')+++def build_prompt(ctx_text, question=None, synth_intended=False):rubric = RUBRIC % (',\n "answer": "<direct answer to the editor\'s question>"' if question else '')q = (f'\n\nThe editor\'s specific question (answer it in "answer"; still fill the rest):\n{question}'if question else '')- return f'{rubric}\n\nContext:\n{ctx_text}{q}'+ intent = f'\n{SYNTH_INTENT}' if synth_intended else ''+ return f'{rubric}\n\nContext:\n{ctx_text}{intent}{q}'def parse_json(text):@@ -437,8 +451,10 @@ def _off(path, provider, why, steps):def critique(path, prompt=None, provider='gemini', model=None, consent=False, video=None, with_timeline=False,- start=None, end=None, max_seconds=600.0, cuts=True):- """audio-LLM critique of a soundtrack against the film-sound rubric (only with an API key AND consent)"""+ start=None, end=None, max_seconds=600.0, cuts=True, synth_intended=False):+ """audio-LLM critique of a soundtrack against the film-sound rubric (only with an API key AND consent).+ synth_intended=True tells the model that synthesized / procedural sound is the point of this film, so synthesis+ itself is not counted as a flaw (the rubric also says so when the editor's question mentions it)"""if provider not in PROVIDERS:raise ValueError(f'unknown provider {provider!r}; available: {", ".join(PROVIDERS)}')if not os.path.isfile(path):@@ -464,7 +480,7 @@ def critique(path, prompt=None, provider='gemini', model=None, consent=False, vitry:data, mime, clip = encode(path, start, end, max_seconds)ctx_text, notes = context(path, clip, video, with_timeline, cuts)- out = pv.generate(data, mime, build_prompt(ctx_text, prompt), m, key)+ out = pv.generate(data, mime, build_prompt(ctx_text, prompt, synth_intended), m, key)except Exception as e: # noqa: BLE001 - any failure becomes a readable result, never a traceback with the keymsg = _scrub(_msg(e), key)return {'enabled': True, 'ok': False, 'path': path, 'provider': pv.name, 'model': m, 'uploaded': clip,@@ -512,7 +528,10 @@ def add_cli(sub):p.add_argument('--start', type=float, help='send only from here (s)')p.add_argument('--end', type=float, help='send only up to here (s)')p.add_argument('--max-seconds', type=float, default=600.0, help='trim longer audio to this (default 600)')+ p.add_argument('--synth-intended', action='store_true',+ help='the film uses synthesized / procedural sound on purpose: do not count synthesis as a flaw')p.set_defaults(func=lambda a: 0 if emit(critique(a.file, a.prompt, model=a.model, consent=a.yes_upload,video=a.video, with_timeline=a.with_timeline, start=a.start,- end=a.end, max_seconds=a.max_seconds, cuts=not a.no_cuts),+ end=a.end, max_seconds=a.max_seconds, cuts=not a.no_cuts,+ synth_intended=a.synth_intended),a)['ok'] else 1)diff --git a/earshot/mcp_server.py b/earshot/mcp_server.pyindex ca802c8..d30d117 100644--- a/earshot/mcp_server.py+++ b/earshot/mcp_server.py@@ -497,6 +497,10 @@ def tool_llm_critique(path: Path,model: Annotated[str | None, Field(description='Gemini model id (default ''EARSHOT_GEMINI_MODEL or gemini-3.8-flash)')]= None,+ synth_intended: Annotated[bool, Field(description='true when the film uses synthesized or '+ 'procedural sound on purpose: the critique '+ 'then does not count synthesis as a flaw')]+ = False,start: Start = None, end: End = None, full: Full = False) -> str:"""OPTIONAL second opinion from Google Gemini (an audio LLM): rubric critique of sync, realism, mix balance,loudness, cheap / synthetic moments, and concrete fixes with timestamps. Use after timeline / critique when a@@ -507,7 +511,7 @@ def tool_llm_critique(path: Path,from . import llmp = _file(path)kw = dict(path=p, consent=consent, prompt=prompt, video=_opt_file(video, 'video'), with_timeline=with_timeline,- model=model, start=start, end=end)+ model=model, start=start, end=end, synth_intended=synth_intended)return _run('llm_critique', kw, full, llm.critique)diff --git a/earshot/models/ast.py b/earshot/models/ast.pyindex a7098c2..e77cd85 100644--- a/earshot/models/ast.py+++ b/earshot/models/ast.py@@ -19,7 +19,7 @@ import numpy as npfrom .. import audio, configfrom . import hub-from .clap import _load_hf, _set_precision, _slug+from .clap import _load_hf, _set_precisionSR_AST = 16000WIN_S = 10.24@@ -43,8 +43,7 @@ class AST:self.precision = 'bf16' if self.dtype == torch.bfloat16 else 'fp32'self.labels = [self.model.config.id2label[i] for i in range(len(self.model.config.id2label))]self.index = {l: i for i, l in enumerate(self.labels)}- self.dir = os.path.join(config.EMB_CACHE, 'ast',- _slug(self.model_id) + self.spec.cache_tag + '--' + self.precision)+ self.dir = os.path.join(config.EMB_CACHE, 'ast', self.spec.cache_name + '--' + self.precision)os.makedirs(self.dir, exist_ok=True)def _forward(self, segs16, batch=8):diff --git a/earshot/models/clap.py b/earshot/models/clap.pyindex cacdb38..b108b2d 100644--- a/earshot/models/clap.py+++ b/earshot/models/clap.py@@ -30,7 +30,7 @@ _inst = Nonedef _slug(model_id):- return model_id.replace('/', '--')+ return hub.slug(model_id)def _read_npz(path):@@ -56,18 +56,22 @@ def _quiet_transformers():def _load_hf(cls, spec, weights=False):"""a model (weights=True) or its processor from the spec's local snapshot folder (hub.Spec). transformers gets thefolder, not the repo id, so nothing asks the Hub. A failed load is an error that names the folder, never a- silent new download; only a legacy snapshot loads pickle weights (pytorch_model.bin, torch weights_only)"""+ silent new download; only a legacy snapshot or a local model folder loads pickle weights (pytorch_model.bin,+ torch weights_only)"""import warnings_quiet_transformers()kw = dict(local_files_only=True)if weights:- kw['use_safetensors'] = not spec.weights.endswith('.bin')+ kw['use_safetensors'] = spec.weights not in hub.PICKLEwith warnings.catch_warnings():warnings.filterwarnings('ignore', message='.*mel filter.*')warnings.filterwarnings('ignore', category=FutureWarning)try:return cls.from_pretrained(spec.snapshot, **kw)except Exception as e:+ if spec.folder: # the user's own folder: never suggest deleting it+ raise RuntimeError(f'could not load {spec.label} ({cls.__name__}): {type(e).__name__}: {e}. The '+ 'files may be damaged or this transformers version cannot read them') from eraise RuntimeError(f'could not load {spec.label} ({cls.__name__}) from the earshot cache 'f'({spec.snapshot}): {type(e).__name__}: {e}. The files may be damaged or this ''transformers version cannot read them: delete that folder and earshot fetches the '@@ -125,8 +129,7 @@ class Clap:self.proc = _load_hf(ClapProcessor, self.spec)self.dtype = _set_precision(self.model, torch)self.precision = 'bf16' if self.dtype == torch.bfloat16 else 'fp32'- self.dir = os.path.join(config.EMB_CACHE, 'clap',- _slug(self.model_id) + self.spec.cache_tag + '--' + self.precision)+ self.dir = os.path.join(config.EMB_CACHE, 'clap', self.spec.cache_name + '--' + self.precision)os.makedirs(self.dir, exist_ok=True)self._text = {}self._text_path = os.path.join(self.dir, 'text.npz')diff --git a/earshot/models/hub.py b/earshot/models/hub.pyindex 4b8eb2d..5499865 100644--- a/earshot/models/hub.py+++ b/earshot/models/hub.py@@ -9,7 +9,12 @@ gets a folder, never a repo id, so a cached load never asks the Hub, and a damagfolder instead of a silent new download. A model that is not cached is downloaded once at its pinned revision(config.PINS), with safetensors weights, unless an offline flag is set (config.offline()). earshot never sets orclears HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE. Imports nothing heavy: earshot doctor uses it without torch.++EARSHOT_CLAP / EARSHOT_AST may also name a local model folder (config.json plus model.safetensors, or the+pytorch_model.bin of an older checkpoint, as transformers reads it): it loads from that folder as it is, with no+network and no revision, and earshot never downloads into it (an incomplete folder is an error naming what is missing)."""+import hashlibimport osimport refrom dataclasses import dataclass@@ -17,7 +22,16 @@ from dataclasses import dataclassfrom .. import configSAFETENSORS = ('model.safetensors', 'model.safetensors.index.json') # one file, or the index of a sharded checkpoint-CUSTOM_PATTERNS = ('*.json', '*.txt', '*.model', '*.safetensors') # an unpinned model: configs, tokenizer, weights+PICKLE = ('pytorch_model.bin', 'pytorch_model.bin.index.json') # loaded only from a folder the user names+# An unpinned Hub model: its top-level configs, tokenizer files and safetensors weights, by name. snapshot_download+# matches allow_patterns with fnmatch, where '*' also matches '/', so bare '*.json' / '*.safetensors' globs would pull+# every subfolder and weight variant of a repo (onnx/, fp16 copies, other pipelines' components): possibly several GB.+CUSTOM_PATTERNS = ('config.json', 'preprocessor_config.json', 'feature_extractor_config.json', 'processor_config.json',+ 'tokenizer.json', 'tokenizer_config.json', 'special_tokens_map.json', 'added_tokens.json',+ 'vocab.json', 'vocab.txt', 'merges.txt', 'tokenizer.model', 'spiece.model',+ 'sentencepiece.bpe.model', 'model.safetensors', 'model.safetensors.index.json',+ 'model-?????-of-?????.safetensors')+LOCAL = 'local' # Spec.revision of a local model folder_SHA = re.compile(r'[0-9a-f]{40}')@@ -25,12 +39,13 @@ _SHA = re.compile(r'[0-9a-f]{40}')class Spec:"""one model as earshot will load it"""model_id: str- revision: str # the revision earshot wants: its pin, an EARSHOT_*_REVISION override, or 'main'+ revision: str # the revision earshot wants: its pin, an EARSHOT_*_REVISION override, 'main' or 'local'state: str # cached | legacy (a pre-0.2.1 snapshot of the pin stands in) | incomplete | missingsnapshot: str | None # the complete local folder to load from (state cached or legacy), else Noneweights: str # the weights file loaded or to download (pytorch_model.bin only for a legacy snapshot)missing: tuple = () # files of the wanted revision that are not in the cachepinned: bool = False # the wanted revision is earshot's pin+ folder: bool = False # model_id names a local model folder (revision 'local'), not a Hub repo id@propertydef local(self):@@ -38,24 +53,66 @@ class Spec:@propertydef sha(self):- """the commit of the snapshot that loads (None when nothing local can)"""- return os.path.basename(self.snapshot) if self.snapshot else None+ """the commit of the snapshot that loads (None when nothing local can, and for a local model folder)"""+ return os.path.basename(self.snapshot) if self.snapshot and not self.folder else None@propertydef label(self):+ if self.folder:+ return f'the local model folder {self.model_id}'return f'{self.model_id}@{self.revision[:7] if _SHA.fullmatch(self.revision) else self.revision}'@propertydef cache_tag(self):"""suffix for embedding caches: none for the pin and its legacy snapshot (the same tensors), else the commit,- so embeddings of another checkpoint never mix with the pinned model's"""+ so embeddings of another checkpoint never mix with the pinned model's. A local folder: a hash of its path and+ of its weights file's size and time, so new weights in the same folder get a fresh cache"""if self.pinned:return ''+ if self.folder:+ p = _abs(self.model_id)+ try:+ st = os.stat(os.path.join(p, self.weights))+ key = f'{os.path.normcase(p)}|{st.st_size}|{st.st_mtime_ns}'+ except OSError:+ key = os.path.normcase(p)+ return '--local' + hashlib.sha1(key.encode('utf-8')).hexdigest()[:8]return '--' + (self.sha or re.sub(r'[^0-9A-Za-z._-]', '_', self.revision))[:8]+ @property+ def cache_name(self):+ """one path component that names this model's embedding caches: slug + cache_tag. A Hub id keeps its name+ (org--name, unchanged for the default models); a local folder becomes local--<folder name>, never a path (a+ drive letter in it would leave the cache root on Windows)"""+ if self.folder:+ base = re.sub(r'[^0-9A-Za-z._-]', '_', os.path.basename(os.path.normpath(_abs(self.model_id))))[:40]+ return 'local--' + (base or 'model') + self.cache_tag+ return slug(self.model_id) + self.cache_tag+++def _abs(path):+ return os.path.abspath(os.path.expanduser(path))+++def slug(model_id):+ """a Hub repo id as one path component: org/name -> org--name"""+ return model_id.replace('/', '--')+++def is_folder(model_id):+ """True when model_id names an existing local folder rather than a Hub repo id (transformers reads an existing+ folder the same way). earshot's pinned ids always mean the Hub model: a folder of that name in the working+ directory does not replace the pin"""+ return bool(model_id) and model_id not in config.PINS and os.path.isdir(os.path.expanduser(model_id))+++def cache_name(model_id, revision=None):+ """resolve(model_id, revision).cache_name: the embedding-cache component of a model, filesystem only"""+ return resolve(model_id, revision).cache_name+def model_dir(model_id):- return os.path.join(config.HF_CACHE, 'models--' + model_id.replace('/', '--'))+ return os.path.join(config.HF_CACHE, 'models--' + slug(model_id))def snapshot_dir(model_id, revision):@@ -86,10 +143,25 @@ def _found(folder, alts):return next((a for a in alts if folder and os.path.exists(os.path.join(folder, a))), alts[0])+def _resolve_folder(model_id):+ """a local model folder as it is: complete with config.json and weights (safetensors preferred; the+ pytorch_model.bin of an older checkpoint loads as transformers would load it, torch weights_only), else+ incomplete. No revision, never downloaded into"""+ p = _abs(model_id)+ alts = SAFETENSORS + PICKLE+ missing = _missing(p, ('config.json', alts))+ if missing:+ return Spec(model_id, LOCAL, 'incomplete', None, _found(p, alts), missing, folder=True)+ return Spec(model_id, LOCAL, 'cached', p, _found(p, alts), folder=True)++def resolve(model_id, revision=None):"""what the cache holds for model_id at revision. revision None = earshot's pin (config.PINS), or 'main' for amodel without one. Only a pinned model with no explicit revision may fall back to its legacy snapshot, and only- when that snapshot is complete in the cache. Filesystem only, no network"""+ when that snapshot is complete in the cache. A model_id that names a local folder resolves to that folder+ (revision 'local'; a revision means nothing there and is ignored). Filesystem only, no network"""+ if is_folder(model_id):+ return _resolve_folder(model_id)pin = config.PINS.get(model_id)if pin and revision in (None, pin['revision']):rev, files, weights = pin['revision'], tuple(pin['files']), (pin['weights'],)@@ -110,8 +182,13 @@ def resolve(model_id, revision=None):def fetch(spec):"""download the wanted revision of spec.model_id into the earshot cache and return the new, complete Spec. For a- pinned model exactly its files (safetensors weights, never the pickle); for another model its configs, tokenizer- and safetensors weights. Refused while an offline flag is set"""+ pinned model exactly its files (safetensors weights, never the pickle); for another model its top-level configs,+ tokenizer and safetensors weights, by name. Refused while an offline flag is set, and always for a local folder"""+ if spec.folder:+ raise RuntimeError(f'{spec.label} lacks {" and ".join(spec.missing)}: earshot loads a local model folder as '+ 'it is and never downloads into it. Put config.json and model.safetensors (or the '+ 'pytorch_model.bin of an older checkpoint) there, or set EARSHOT_CLAP / EARSHOT_AST to a '+ 'Hub model id.')flag = config.offline()where = (f'incomplete in the earshot cache (missing: {", ".join(spec.missing)})' if spec.state == 'incomplete' elsef'not in the earshot cache ({config.HF_CACHE})')@@ -136,7 +213,7 @@ def fetch(spec):def ensure(model_id, revision=None):- """the Spec to load from: what the cache holds, or the wanted revision downloaded now when nothing local can- load (one download, never while an offline flag is set)"""+ """the Spec to load from: what the cache (or a local model folder) holds, or the wanted revision downloaded now+ when nothing local can load (one download, never while an offline flag is set, never into a local folder)"""spec = resolve(model_id, revision)return spec if spec.local else fetch(spec)diff --git a/earshot/vocab.py b/earshot/vocab.pyindex b478292..f54e3c4 100644--- a/earshot/vocab.py+++ b/earshot/vocab.py@@ -73,10 +73,9 @@ def _clap():def _cache_dir():- from .models import hub # filesystem only: another CLAP revision gets its own cache (Spec.cache_tag)- tag = hub.resolve(config.CLAP_MODEL, config.CLAP_REVISION).cache_tag+ from .models import hub # filesystem only: another CLAP revision or a local folder gets its own cached = os.path.join(config.EMB_CACHE, 'semantics',- config.CLAP_MODEL.replace('/', '--') + tag + '--' + config.PRECISION)+ hub.cache_name(config.CLAP_MODEL, config.CLAP_REVISION) + '--' + config.PRECISION)os.makedirs(d, exist_ok=True)return ddiff --git a/tests/test_interfaces.py b/tests/test_interfaces.pyindex f876b23..e68153b 100644--- a/tests/test_interfaces.py+++ b/tests/test_interfaces.py@@ -456,6 +456,7 @@ def test_agent_text_states_no_preference_as_a_rule():import anyiotexts = {f'tool {t.name}': t.description for t in anyio.run(mcp_server.build().list_tools)}texts['INSTRUCTIONS'] = mcp_server.INSTRUCTIONS+ texts['llm.RUBRIC'] = llm.RUBRIC # the Gemini rubric is fed back to agents through llm_critiquefor pattern in ('README.md', 'docs/*.md', 'skills/**/*.md', 'eval/*/RESULTS.md'):for path in glob.glob(os.path.join(REPO, pattern), recursive=True):with open(path, encoding='utf-8') as f:@@ -472,6 +473,28 @@ def test_agent_text_states_no_preference_as_a_rule():assert "Reject 'likely code-synthesized'" not in skill and 'realness is information, not a gate' in skill+def test_llm_rubric_does_not_count_synthesis_as_a_flaw(keyed, wav, fake):+ """issue #1 leftover (review): the Gemini rubric set 'real recorded foley' as the bar, scored '3 = obviously cheap+ or synthetic' and suggested 'replace the beep with a recorded UI tap', so a film synthesized on purpose got+ 'replace your synthesized sounds' advice. Synthesis is a flaw only where a sound should read as recorded, and+ synth_intended (CLI --synth-intended, MCP synth_intended) says so in the prompt"""+ rubric = ' '.join(llm.RUBRIC.split())+ for gone in ('real recorded foley', 'cheap or synthetic', 'recorded UI tap'):+ assert gone not in rubric, gone+ assert 'do not count synthesis itself as a flaw' in rubric and 'Synthesis is a flaw only where' in rubric+ assert llm.SYNTH_INTENT not in llm.build_prompt('ctx')+ assert llm.SYNTH_INTENT in llm.build_prompt('ctx', synth_intended=True)+ f = fake(_answer(), _answer())+ assert llm.critique(wav(_bursts()), consent=True, synth_intended=True)['ok']+ assert llm.SYNTH_INTENT in f.calls[0][3]['json']['contents'][0]['parts'][1]['text']+ assert cli.main(['llm', wav(_bursts()), '--yes-upload', '--synth-intended', '--json']) == 0+ assert llm.SYNTH_INTENT in f.calls[-1][3]['json']['contents'][0]['parts'][1]['text']+ import anyio+ [tool] = [t for t in anyio.run(mcp_server.build().list_tools) if t.name == 'llm_critique']+ schema = getattr(tool, 'input_schema', None) or tool.inputSchema+ assert 'synth_intended' in schema['properties']++async def _stdio_session(calls, log, *args):"""start `python -m earshot mcp` (or `python -m <args>`) as a subprocess and run calls(session) over stdio"""import anyiodiff --git a/tests/test_models_hub.py b/tests/test_models_hub.pyindex 4afe8c4..37fbe02 100644--- a/tests/test_models_hub.py+++ b/tests/test_models_hub.py@@ -7,6 +7,7 @@ import reimport subprocessimport sys+import numpy as npimport pytestfrom earshot import config, doctor@@ -43,8 +44,10 @@ def downloads(monkeypatch):calls.append(dict(repo_id=repo_id, revision=revision, cache_dir=cache_dir, allow_patterns=allow_patterns, **kw))if fake.fail:raise ConnectionError('no route to the Hub')- files = [f for f in allow_patterns if '*' not in f and f not in fake.skip]- return snap(repo_id, revision, files)+ files = [f for f in allow_patterns if '*' not in f and '?' not in f and f not in fake.skip]+ if re.fullmatch(r'[0-9a-f]{40}', revision or ''):+ return snap(repo_id, revision, files)+ return snap(repo_id, 'c' * 40, files, ref=revision) # a branch: a commit plus refs/<branch>, as the Hub'sfake.fail, fake.skip = False, ()monkeypatch.setattr(huggingface_hub, 'snapshot_download', fake)fake.calls = calls@@ -234,10 +237,131 @@ def test_missing_model_downloads_the_pinned_files_once(cache, downloads):def test_custom_model_download_never_asks_for_pickles(cache, downloads):- with pytest.raises(RuntimeError, match='safetensors weights only'):- hub.ensure('someone/clap-ft') # the fake writes no files for wildcard patterns+ spec = hub.ensure('someone/clap-ft')+ assert (spec.state, spec.weights) == ('cached', 'model.safetensors')[call] = downloads.callsassert call['revision'] == 'main' and not any('.bin' in p or p == '*' for p in call['allow_patterns'])+ downloads.skip = hub.SAFETENSORS # a repo with pickle weights only+ with pytest.raises(RuntimeError, match='safetensors weights only'):+ hub.ensure('someone/other-ft')+++def test_custom_model_download_takes_top_level_files_by_name():+ """review finding: '*.json' / '*.safetensors' matched every subfolder and weight variant of a custom repo+ (fnmatch's '*' also matches '/'), possibly several GB. Only the top-level configs, tokenizer and weights load"""+ from huggingface_hub.utils import filter_repo_objects+ repo = ['config.json', 'preprocessor_config.json', 'tokenizer.json', 'tokenizer_config.json', 'vocab.json',+ 'merges.txt', 'special_tokens_map.json', 'model.safetensors', 'model.safetensors.index.json',+ 'model-00001-of-00002.safetensors', 'model-00002-of-00002.safetensors', 'spiece.model',+ 'model.fp16.safetensors', 'onnx/model.safetensors', 'onnx/config.json', 'unet/config.json',+ 'unet/diffusion_pytorch_model.safetensors', 'tokenizer/vocab.json', 'tokenizer/merges.txt',+ 'pytorch_model.bin', 'flax_model.msgpack', 'README.md', 'training_args.txt', 'eval/results.json',+ 'text_encoder/model.safetensors', 'sub/spiece.model']+ got = set(filter_repo_objects(repo, allow_patterns=list(hub.CUSTOM_PATTERNS)))+ assert got == {'config.json', 'preprocessor_config.json', 'tokenizer.json', 'tokenizer_config.json', 'vocab.json',+ 'merges.txt', 'special_tokens_map.json', 'model.safetensors', 'model.safetensors.index.json',+ 'model-00001-of-00002.safetensors', 'model-00002-of-00002.safetensors', 'spiece.model'}+++# ------------------------------------------------------------------------------------------- local model folder+def model_folder(path, files=('config.json', 'model.safetensors')):+ os.makedirs(path, exist_ok=True)+ for f in files:+ with open(os.path.join(path, f), 'wb') as fh:+ fh.write(b'x')+ return str(path)++[email protected]('flag', [None, *config.OFFLINE_FLAGS])+def test_local_model_folder_loads_from_disk_with_no_network(cache, fake, downloads, monkeypatch, tmp_path, flag):+ """review finding (regression from main): EARSHOT_CLAP / EARSHOT_AST naming a local folder with config.json and+ model.safetensors loaded from disk on main (from_pretrained(folder, local_files_only=True)); it must again, with+ or without an offline flag, and never look in the Hub cache or download"""+ if flag:+ monkeypatch.setenv(flag, '1')+ d = model_folder(tmp_path / 'models' / 'my-clap')+ s = hub.ensure(d)+ assert (s.state, s.revision, s.snapshot, s.weights, s.folder) == ('cached', 'local', d, 'model.safetensors', True)+ assert s.local and not s.pinned and s.sha is None and s.missing == ()+ assert s.label == f'the local model folder {d}'+ clap._load_hf(fake, s, weights=True)+ clap._load_hf(fake, s)+ assert fake.calls == [(d, {'local_files_only': True, 'use_safetensors': True}), (d, {'local_files_only': True})]+ assert downloads.calls == [] and not os.path.exists(config.HF_CACHE)+ monkeypatch.chdir(tmp_path) # a relative folder works too+ assert hub.resolve(os.path.join('models', 'my-clap')).snapshot == d+++def test_local_model_folder_with_pickle_weights_loads_as_transformers_would(cache, fake, downloads, tmp_path):+ d = model_folder(tmp_path / 'old-ast', ('config.json', 'preprocessor_config.json', 'pytorch_model.bin'))+ s = hub.ensure(d)+ assert (s.state, s.weights) == ('cached', 'pytorch_model.bin')+ clap._load_hf(fake, s, weights=True)+ assert fake.calls == [(d, {'local_files_only': True, 'use_safetensors': False})] and downloads.calls == []+ model_folder(d, ('model.safetensors',)) # safetensors win when both are there+ assert hub.resolve(d).weights == 'model.safetensors'+++def test_incomplete_local_model_folder_is_an_error_never_a_download(cache, downloads, tmp_path):+ d = model_folder(tmp_path / 'half', ('config.json',))+ s = hub.resolve(d)+ assert (s.state, s.snapshot, s.missing, s.folder) == ('incomplete', None, ('model.safetensors',), True)+ with pytest.raises(RuntimeError, match='lacks model.safetensors: earshot loads a local model folder as it is'):+ hub.ensure(d)+ assert downloads.calls == []+++def test_failed_local_folder_load_never_suggests_deleting_it(cache, fake, tmp_path):+ d = model_folder(tmp_path / 'mine')+ fake.error = OSError('bad header')+ with pytest.raises(RuntimeError, match='could not load the local model folder') as e:+ clap._load_hf(fake, hub.ensure(d), weights=True)+ assert 'delete' not in str(e.value) and 'bad header' in str(e.value)+++def test_pinned_ids_are_never_read_as_folders(cache, tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ model_folder(tmp_path / 'laion' / 'larger_clap_general') # a stray folder named like the pin+ s = hub.resolve(CLAP_ID)+ assert not s.folder and s.revision == CLAP_PIN['revision'] and s.state == 'missing'+++def test_local_folder_embedding_caches_stay_inside_the_cache_root(cache, tmp_path, monkeypatch):+ """a folder path (with a drive letter on Windows) must become one path component, or os.path.join would leave+ EMB_CACHE; new weights in the same folder get a fresh cache. The pinned models keep their old names"""+ from earshot import vocab+ from earshot.forge import critic+ d = model_folder(tmp_path / 'clap ft')+ s = hub.resolve(d)+ name = s.cache_name+ assert re.fullmatch(r'local--clap_ft--local[0-9a-f]{8}', name), name+ root = os.path.abspath(config.EMB_CACHE)+ assert os.path.abspath(os.path.join(root, 'clap', name)).startswith(root)+ model_folder(d, ())+ with open(os.path.join(d, 'model.safetensors'), 'wb') as fh:+ fh.write(b'other weights')+ assert hub.resolve(d).cache_name != name+ monkeypatch.setattr(config, 'CLAP_MODEL', d)+ assert os.path.abspath(vocab._cache_dir()).startswith(root)+ monkeypatch.setattr(config, 'AST_MODEL', d)+ key = critic.holdout_key(np.zeros(16, np.float32))+ assert key.startswith('local--clap_ft--local') and ':' not in key+ assert hub.cache_name(CLAP_ID) == 'laion--larger_clap_general' and hub.cache_name(AST_ID) == hub.slug(AST_ID)+++def test_doctor_reports_a_local_model_folder(cache, downloads, tmp_path, monkeypatch):+ good = model_folder(tmp_path / 'clap')+ half = model_folder(tmp_path / 'ast', ('config.json',))+ monkeypatch.setattr(config, 'CLAP_MODEL', good)+ monkeypatch.setattr(config, 'AST_MODEL', half)+ r = doctor.check(fetch_missing=True)+ assert r['models'][good]['revision'] == 'local' and r['models'][good]['cached'] == 'cached'+ assert r['models'][good]['snapshot'] == good and r['models_cached'] == {good: True, half: False}+ assert r['fetched'][good] == 'a local folder (nothing to download)'+ assert r['fetched'][half].startswith('failed: the local model folder') and downloads.calls == []+ assert 'Not cached yet' not in r['summary']+ r = doctor.check()+ assert any('local model folder lacks model.safetensors' in p for p in r['problems'])def test_failed_download_is_one_readable_error(cache, downloads):