Skip to content

Ears for coding agents: let AI hear, review and make sound. CPU-only, open source.

Load pinned models from the cache only; respect HF offline flags

Leonxlnxb90e1a1c4270
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8d2ee7f..ea58918 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,31 @@ Two fixes from a careful outside review (thanks, @markblundeberg).
decision to the current user: use it when real or professionally produced sound is wanted, and treat a synthesized
verdict as information when synthesized sound is the point. `critique`'s realness fix is scoped the same way. A
test keeps such phrasing out of tool descriptions, the server instructions, skills and docs.
+- **Model loading respects the user's offline setting, never downloads after a failed load, and pins its weights**
+ (#2). Before, earshot set `HF_HUB_OFFLINE` / `TRANSFORMERS_OFFLINE` once a model's cache folder existed, cleared
+ them and downloaded again after any failed local load (a damaged cache, a transformers mismatch, a typo in
+ `EARSHOT_CLAP`), and fetched whatever each repo's main held, for CLAP a pickle. Now (`earshot/models/hub.py`):
+ - `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` mean the same as `EARSHOT_OFFLINE=1`: no download, a clear error
+ naming the flag when a model is not cached. earshot never sets or clears any of them.
+ - Models load from a complete local snapshot folder only (transformers gets a folder, not a repo id), so a cached
+ load never contacts the Hub (no update checks, no safetensors conversion requests). A failed load is an error
+ that names the folder; the only download is for files that are not in the cache.
+ - Pinned revisions with safetensors weights: CLAP `16c8cc3` (the Hub's safetensors conversion of main `ada0c23`),
+ AST `f826b80`; overrides `EARSHOT_CLAP_REVISION` / `EARSHOT_AST_REVISION`. A cache made before 0.2.1 (CLAP
+ `ada0c23`, `pytorch_model.bin`, the same tensors) keeps working from the cache, without a forced 776 MB download.
+ - `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).
+
+### Added
+
+- `earshot doctor --fetch`: download the pinned model files that are not in the cache (also upgrades a legacy CLAP
+ cache to the pinned safetensors).
+
+### Changed
+
+- A custom model (`EARSHOT_CLAP` / `EARSHOT_AST`) or another revision keeps its embedding caches per commit, so they
+ never mix with the pinned model's; the default models keep their existing caches.
## 0.2.0 - 2026-10-16
diff --git a/README.md b/README.md
index aef7a47..8a637ee 100644
--- a/README.md
+++ b/README.md
@@ -198,13 +198,25 @@ python -m venv .venv
.venv/bin/python -m earshot doctor --load
```
-The first model use downloads two open models (~1.4 GB) into `.cache/hf` inside the repo (or `EARSHOT_HOME`): CLAP
-`laion/larger_clap_general` (text-audio embeddings) and the AudioSet tagger `MIT/ast-finetuned-audioset-10-10-0.4593`.
-After that earshot works offline.
+The first model use downloads two open models (~1.1 GB) into `.cache/hf` inside the repo (or `EARSHOT_HOME`), each at
+a pinned revision with safetensors weights: CLAP `laion/larger_clap_general` @ `16c8cc3` (text-audio embeddings; the
+Hub's safetensors conversion of its main revision) and the AudioSet tagger `MIT/ast-finetuned-audioset-10-10-0.4593`
+@ `f826b80`. `earshot doctor --fetch` downloads them up front. After that earshot loads them from that cache only and
+never contacts the Hub; a damaged cache is an error that names the folder, not a silent new download.
+
+Offline: `EARSHOT_OFFLINE=1`, `HF_HUB_OFFLINE=1` and `TRANSFORMERS_OFFLINE=1` all mean the same to earshot: it never
+downloads, and a model missing from the cache is an error that says so. earshot never sets or clears these variables.
+
+A cache made before 0.2.1 holds CLAP's main revision `ada0c23`, whose only weights are a pickle (`pytorch_model.bin`,
+the same tensors). earshot still loads it from the cache (torch `weights_only`), never downloads it, and `earshot
+doctor` says so; `earshot doctor --fetch` downloads the pinned safetensors (776 MB), used from then on.
Settings (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`. `earshot doctor --load` reports what is in use.
+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).
+`earshot doctor` reports the revisions and what the cache holds; `--load` also what loads (revision, weights,
+precision).
### MCP server for Claude Code
diff --git a/earshot/config.py b/earshot/config.py
index 73b31b7..f3294be 100644
--- a/earshot/config.py
+++ b/earshot/config.py
@@ -5,7 +5,11 @@ EARSHOT_HOME cache root (models, embeddings, decoded audio). Default: <repo>
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_OFFLINE 1 = never touch the network (models must already be in the cache)
+EARSHOT_CLAP_REVISION, EARSHOT_AST_REVISION
+ Hub revision (commit sha, branch or tag) to use instead of the pinned one (PINS below); a custom
+ model id without a revision uses 'main'
+EARSHOT_OFFLINE 1 = never touch the network (models must already be in the cache). HF_HUB_OFFLINE=1 and
+ TRANSFORMERS_OFFLINE=1 mean the same to earshot, which never sets or clears any of the three
EARSHOT_PRECISION bf16 (default; used only on CPUs with native bf16, AVX512-BF16 / AMX, else fp32: on the dev laptop
1.4x faster, embeddings within cosine 0.9993 of fp32, eval/semantics/precision.json) | fp32
"""
@@ -31,9 +35,43 @@ DEC_CACHE = os.path.join(HOME, 'decoded')
CLAP_MODEL = os.environ.get('EARSHOT_CLAP', 'laion/larger_clap_general')
AST_MODEL = os.environ.get('EARSHOT_AST', 'MIT/ast-finetuned-audioset-10-10-0.4593')
-OFFLINE = os.environ.get('EARSHOT_OFFLINE', '0') == '1'
+CLAP_REVISION = os.environ.get('EARSHOT_CLAP_REVISION') or None
+AST_REVISION = os.environ.get('EARSHOT_AST_REVISION') or None
PRECISION = os.environ.get('EARSHOT_PRECISION', 'bf16').lower()
+# Pinned model files (earshot.models.hub downloads exactly these, at exactly this commit, weights as safetensors).
+# - laion/larger_clap_general @ 16c8cc3: the Hub's refs/pr/2, the safetensors conversion bot's commit (2024-05-06) on
+# top of main ada0c23 (2023-10-31). Same files as main plus model.safetensors; main itself has only the pickle
+# pytorch_model.bin. The Hub keeps PR refs, also after a close, and the sha stays valid if the PR is merged
+# (EARSHOT_CLAP_REVISION overrides it). Caches made before earshot 0.2.1 hold ada0c23: that 'legacy' snapshot is
+# still loaded, from the local cache only and never downloaded (the same tensors, so cached embeddings stay valid),
+# until the pinned one is there (earshot doctor --fetch).
+# - MIT/ast-finetuned-audioset-10-10-0.4593 @ f826b80: main (2023-09-06), which already has model.safetensors.
+# 'files' are the config / tokenizer files next to the weights (the legacy snapshot has the same ones).
+PINS = {
+ 'laion/larger_clap_general': {
+ 'revision': '16c8cc3159a3c8a31e8ff5ef1f66b0d9ab3667db', 'weights': 'model.safetensors',
+ 'files': ('config.json', 'preprocessor_config.json', 'merges.txt', 'special_tokens_map.json',
+ 'tokenizer.json', 'tokenizer_config.json', 'vocab.json'),
+ 'legacy': {'revision': 'ada0c23a36c4e8582805bb38fec3905903f18b41', 'weights': 'pytorch_model.bin'}},
+ 'MIT/ast-finetuned-audioset-10-10-0.4593': {
+ 'revision': 'f826b80d28226b62986cc218e5cec390b1096902', 'weights': 'model.safetensors',
+ 'files': ('config.json', 'preprocessor_config.json')},
+}
+OFFLINE_FLAGS = ('EARSHOT_OFFLINE', 'HF_HUB_OFFLINE', 'TRANSFORMERS_OFFLINE')
+
+
+def offline():
+ """the name of the first offline flag that is set (1 / true / yes / on, any case, as huggingface_hub reads
+ them), else None. Read at call time: earshot never downloads while one is set"""
+ for k in OFFLINE_FLAGS:
+ if os.environ.get(k, '').strip().upper() in ('1', 'TRUE', 'YES', 'ON'):
+ return k
+ return None
+
+
+OFFLINE = offline() is not None # the state at import, kept for old callers; earshot itself calls offline()
+
def threads():
if os.environ.get('EARSHOT_THREADS'):
diff --git a/earshot/doctor.py b/earshot/doctor.py
index 5272789..469c51e 100644
--- a/earshot/doctor.py
+++ b/earshot/doctor.py
@@ -1,9 +1,12 @@
"""earshot doctor: check the install (python packages, ffmpeg, model files, CPU settings, optional extras).
- earshot doctor [--load] [--json]
+ earshot doctor [--load] [--fetch] [--json]
-Without --load it imports nothing heavy (a few seconds). --load also loads both models, times one embedding (first
-load can take ~20-40 s) and reports the precision in use (bf16 only on CPUs with native bf16, else fp32).
+Without --load it imports nothing heavy (a few seconds). It reports, per model, the pinned revision, what the cache
+holds (cached / legacy / incomplete / missing) and the folder that loads, and whether an offline flag is set. --load
+also loads both models, times one embedding (first load can take ~20-40 s) and reports the revision, weights file and
+precision in use (bf16 only on CPUs with native bf16, else fp32). --fetch downloads the pinned files that are not in
+the cache yet (~1.1 GB the first time; refused while an offline flag is set).
"""
import importlib
import importlib.metadata
@@ -22,7 +25,63 @@ PACKAGES = [('numpy', 'numpy'), ('scipy', 'scipy'), ('soundfile', 'soundfile'),
('requests', 'requests')]
-def check(load=False):
+def _models():
+ """(model id, revision override or None) for CLAP and AST"""
+ return ((config.CLAP_MODEL, config.CLAP_REVISION), (config.AST_MODEL, config.AST_REVISION))
+
+
+def models():
+ """per model id: the revision earshot wants, what the cache holds and the folder that loads. Filesystem only"""
+ from .models import hub
+ out = {}
+ for mid, rev in _models():
+ s = hub.resolve(mid, rev)
+ out[mid] = {'revision': s.revision, 'cached': s.state, 'loads': s.sha, 'weights': s.weights,
+ 'snapshot': s.snapshot, 'missing': list(s.missing)}
+ return out
+
+
+def fetch():
+ """download the wanted revision of every model whose files are not all in the cache: {model id: what happened}.
+ A model running on a legacy snapshot gets its pinned safetensors. Raises nothing; failures are reported"""
+ from .models import hub
+ out = {}
+ for mid, rev in _models():
+ s = hub.resolve(mid, rev)
+ if s.state == 'cached':
+ out[mid] = 'already cached'
+ continue
+ try:
+ out[mid] = 'downloaded ' + hub.fetch(s).sha[:7]
+ except RuntimeError as e:
+ out[mid] = f'failed: {e}'
+ return out
+
+
+def _load(r):
+ """load both models, time one window each and record what loaded (revision, weights file, precision)"""
+ import numpy as np
+ from .models import ast, clap
+ t = time.time()
+ c = clap.get()
+ r['clap_load_s'] = round(time.time() - t, 1)
+ t = time.time()
+ c.embed_audio([np.zeros(48000, np.float32)])
+ r['clap_one_window_s'] = round(time.time() - t, 2)
+ r['clap_precision'] = c.precision
+ r['clap_revision'], r['clap_weights'] = c.revision, c.weights
+ t = time.time()
+ a = ast.get()
+ r['ast_load_s'] = round(time.time() - t, 1)
+ t = time.time()
+ a.probs([np.zeros(48000, np.float32)])
+ r['ast_one_window_s'] = round(time.time() - t, 2)
+ r['ast_revision'], r['ast_weights'] = a.revision, a.weights
+ import torch
+ r['native_bf16'] = clap.native_bf16(torch)
+
+
+def check(load=False, fetch_missing=False):
r = {'python': sys.version.split()[0], 'earshot_home': config.HOME, 'threads': config.threads(),
'precision': config.PRECISION, 'clap_model': config.CLAP_MODEL, 'ast_model': config.AST_MODEL}
pk = {}
@@ -40,11 +99,11 @@ def check(load=False):
r['ffmpeg'] = shutil.which('ffmpeg') or 'MISSING (install ffmpeg and put it on PATH)'
r['ffprobe'] = shutil.which('ffprobe') or 'MISSING'
r['torch_cuda_used'] = False
-
- def cached(mid):
- d = os.path.join(config.HF_CACHE, 'models--' + mid.replace('/', '--'))
- return os.path.isdir(d)
- r['models_cached'] = {config.CLAP_MODEL: cached(config.CLAP_MODEL), config.AST_MODEL: cached(config.AST_MODEL)}
+ r['offline'] = config.offline() # the flag that keeps earshot off the network, or None
+ if fetch_missing:
+ r['fetched'] = fetch()
+ r['models'] = models()
+ r['models_cached'] = {m: v['snapshot'] is not None for m, v in r['models'].items()}
r['llm_keys_present'] = {k: bool(os.environ.get(k)) for k in ('GEMINI_API_KEY', 'GOOGLE_API_KEY')}
data = {f: os.path.exists(os.path.join(config.DATA_DIR, f)) for f in
('vocab.json', 'vocab_stats.json', 'realness_model.json', 'launch_profile.json')}
@@ -53,28 +112,30 @@ def check(load=False):
if 'MISSING' in str(r['ffmpeg']):
problems.append('ffmpeg missing')
problems += [f'data file earshot/data/{f} missing' for f, ok in data.items() if not ok]
- if load:
- import numpy as np
- from .models import ast, clap
- t = time.time()
- c = clap.get()
- r['clap_load_s'] = round(time.time() - t, 1)
- t = time.time()
- c.embed_audio([np.zeros(48000, np.float32)])
- r['clap_one_window_s'] = round(time.time() - t, 2)
- r['clap_precision'] = c.precision
- t = time.time()
- a = ast.get()
- r['ast_load_s'] = round(time.time() - t, 1)
- t = time.time()
- a.probs([np.zeros(48000, np.float32)])
- r['ast_one_window_s'] = round(time.time() - t, 2)
- import torch
- r['native_bf16'] = clap.native_bf16(torch)
- r['problems'] = problems
- r['summary'] = ('earshot looks healthy.' if not problems else 'Problems: ' + '; '.join(problems)) + (
- '' if all(r['models_cached'].values()) else ' Models are not cached yet: the first call downloads them '
- '(~1.4 GB) into ' + config.HF_CACHE + '.')
+ 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]
+ 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 '
+ 'cache there')
+ elif todo:
+ notes.append(f"Not cached yet: {' and '.join(todo)}. The first call that needs them downloads the pinned "
+ f'files (safetensors; ~1.1 GB for both models) into {config.HF_CACHE}, or run '
+ '`earshot doctor --fetch` now.')
+ for m, v in r['models'].items():
+ if v['cached'] == 'legacy':
+ notes.append(f"{m} loads the pickle weights of a cache made before earshot 0.2.1 ({v['loads'][:7]}, "
+ f"{v['weights']}), from the cache only; `earshot doctor --fetch` downloads the pinned "
+ f"safetensors ({v['revision'][:7]}), used from then on.")
+ if load and not (r['offline'] and not all(r['models_cached'].values())): # (cannot load: a problem says why)
+ try:
+ _load(r)
+ except RuntimeError as e: # a model that cannot load (offline and not cached, a damaged cache): say why
+ problems.append(f'model load failed: {e}')
+ r['problems'], r['notes'] = problems, notes
+ r['summary'] = ' '.join(['earshot looks healthy.' if not problems else
+ 'Problems: ' + '; '.join(p.rstrip('.') for p in problems) + '.'] + notes)
return r
@@ -82,4 +143,6 @@ def add_cli(sub):
from .cli import common
p = common(sub.add_parser('doctor', help='check the install, models and CPU settings'))
p.add_argument('--load', action='store_true', help='also load both models and time one window')
- p.set_defaults(func=lambda a: emit(check(a.load), a) and 0)
+ p.add_argument('--fetch', action='store_true', help='download the pinned model files that are not in the cache '
+ '(~1.1 GB the first time; refused while an offline flag is set)')
+ p.set_defaults(func=lambda a: emit(check(a.load, a.fetch), a) and 0)
diff --git a/earshot/mcp_server.py b/earshot/mcp_server.py
index 38c5ebc..ca802c8 100644
--- a/earshot/mcp_server.py
+++ b/earshot/mcp_server.py
@@ -479,8 +479,9 @@ def tool_critique(path: Path, video: Video = None,
def tool_doctor(load: Annotated[bool, Field(description='also load both models and time one window (~20-60 s)')]
= False, full: Full = False) -> str:
- """Check the earshot install: python packages, ffmpeg, cached models, CPU threads, whether an LLM key is present.
- Use when a tool fails, or once before the first real use."""
+ """Check the earshot install: python packages, ffmpeg, the models (pinned revision, what the cache holds, whether
+ an offline flag is set), CPU threads, whether an LLM key is present. Use when a tool fails, or once before the
+ first real use."""
from . import doctor
return _run('doctor', dict(load=load), full, doctor.check)
diff --git a/earshot/models/ast.py b/earshot/models/ast.py
index d6bcc2d..a7098c2 100644
--- a/earshot/models/ast.py
+++ b/earshot/models/ast.py
@@ -18,7 +18,8 @@ import warnings
import numpy as np
from .. import audio, config
-from .clap import _load_hf, _set_precision, _slug, offline_if_cached
+from . import hub
+from .clap import _load_hf, _set_precision, _slug
SR_AST = 16000
WIN_S = 10.24
@@ -29,19 +30,21 @@ _inst = None
class AST:
def __init__(self, model_id=None):
config.ensure_dirs()
- offline_if_cached(model_id or config.AST_MODEL)
+ self.model_id = model_id or config.AST_MODEL
+ self.spec = hub.ensure(self.model_id, config.AST_REVISION if self.model_id == config.AST_MODEL else None)
+ self.revision, self.weights = self.spec.sha, self.spec.weights
import torch
from transformers import ASTFeatureExtractor, ASTForAudioClassification
torch.set_num_threads(config.threads())
self.torch = torch
- self.model_id = model_id or config.AST_MODEL
- self.model = _load_hf(ASTForAudioClassification, self.model_id).eval()
- self.fe = _load_hf(ASTFeatureExtractor, self.model_id)
+ self.model = _load_hf(ASTForAudioClassification, self.spec, weights=True).eval()
+ self.fe = _load_hf(ASTFeatureExtractor, self.spec)
self.dtype = _set_precision(self.model, torch)
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.precision)
+ self.dir = os.path.join(config.EMB_CACHE, 'ast',
+ _slug(self.model_id) + self.spec.cache_tag + '--' + 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.py
index aa53579..cacdb38 100644
--- a/earshot/models/clap.py
+++ b/earshot/models/clap.py
@@ -6,11 +6,13 @@
t = c.embed_text(['a fast air whoosh']) # (1, 512)
cos = a @ t.T
-Model: laion/larger_clap_general (Apache-2.0) by default. Its mel front end covers 50 Hz - 14 kHz at 48 kHz, so it is
-deaf to "air" above 14 kHz (use earshot.features for bandwidth / lowpass checks). Inputs longer than 10 s are embedded
-as deterministic 10 s windows (hop 5 s) and averaged; the model's own random crop is never used, so results are
-reproducible. Short sounds are repeat-padded to 10 s like in CLAP's training (pad='repeatpad'); pad='zero' pads with
-silence instead (better for judging a single hit's character in isolation).
+Model: laion/larger_clap_general (Apache-2.0) by default, at a pinned revision with safetensors weights, loaded from
+earshot's cache only (earshot.models.hub: fetched once when missing, never while an offline flag is set). Its mel
+front end covers 50 Hz - 14 kHz at 48 kHz, so it is deaf to "air" above 14 kHz (use earshot.features for bandwidth /
+lowpass checks). Inputs longer than 10 s are embedded as deterministic 10 s windows (hop 5 s) and averaged; the
+model's own random crop is never used, so results are reproducible. Short sounds are repeat-padded to 10 s like in
+CLAP's training (pad='repeatpad'); pad='zero' pads with silence instead (better for judging a single hit's character
+in isolation).
"""
import hashlib
import os
@@ -19,6 +21,7 @@ import threading
import numpy as np
from .. import audio, config
+from . import hub
WIN_S = 10.0
HOP_S = 5.0
@@ -41,15 +44,6 @@ def _read_npz(path):
return {}
-def offline_if_cached(*model_ids):
- """when every model is already in the cache, keep huggingface_hub / transformers fully offline (no update checks)"""
- ok = all(os.path.isdir(os.path.join(config.HF_CACHE, 'models--' + _slug(m))) for m in model_ids)
- if ok or config.OFFLINE:
- os.environ.setdefault('HF_HUB_OFFLINE', '1')
- os.environ.setdefault('TRANSFORMERS_OFFLINE', '1')
- return ok
-
-
def _quiet_transformers():
try:
from transformers.utils import logging as tlog
@@ -59,21 +53,25 @@ def _quiet_transformers():
pass
-def _load_hf(cls, model_id):
+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 the
+ folder, 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)"""
import warnings
_quiet_transformers()
- kw = dict(cache_dir=config.HF_CACHE)
+ kw = dict(local_files_only=True)
+ if weights:
+ kw['use_safetensors'] = not spec.weights.endswith('.bin')
with warnings.catch_warnings():
warnings.filterwarnings('ignore', message='.*mel filter.*')
warnings.filterwarnings('ignore', category=FutureWarning)
try:
- return cls.from_pretrained(model_id, local_files_only=True, **kw)
- except Exception:
- if config.OFFLINE:
- raise
- os.environ.pop('HF_HUB_OFFLINE', None)
- os.environ.pop('TRANSFORMERS_OFFLINE', None)
- return cls.from_pretrained(model_id, **kw)
+ return cls.from_pretrained(spec.snapshot, **kw)
+ except Exception as e:
+ raise 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 '
+ 'pinned files again, or run earshot doctor') from e
def native_bf16(torch):
@@ -116,17 +114,19 @@ def _set_precision(model, torch):
class Clap:
def __init__(self, model_id=None):
config.ensure_dirs()
- offline_if_cached(model_id or config.CLAP_MODEL)
+ self.model_id = model_id or config.CLAP_MODEL
+ self.spec = hub.ensure(self.model_id, config.CLAP_REVISION if self.model_id == config.CLAP_MODEL else None)
+ self.revision, self.weights = self.spec.sha, self.spec.weights # what actually loads (doctor reports it)
import torch
from transformers import ClapModel, ClapProcessor
torch.set_num_threads(config.threads())
self.torch = torch
- self.model_id = model_id or config.CLAP_MODEL
- self.model = _load_hf(ClapModel, self.model_id).eval()
- self.proc = _load_hf(ClapProcessor, self.model_id)
+ self.model = _load_hf(ClapModel, self.spec, weights=True).eval()
+ 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.precision)
+ self.dir = os.path.join(config.EMB_CACHE, 'clap',
+ _slug(self.model_id) + self.spec.cache_tag + '--' + 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.py
new file mode 100644
index 0000000..4b8eb2d
--- /dev/null
+++ b/earshot/models/hub.py
@@ -0,0 +1,142 @@
+"""The model files earshot loads: pinned revisions in earshot's own Hugging Face cache, never fetched behind your back.
+
+ from earshot.models import hub
+ s = hub.resolve('laion/larger_clap_general') # filesystem only; s.state: cached / legacy / incomplete / missing
+ s = hub.ensure('laion/larger_clap_general') # the same, plus one download of the pinned files if none can load
+
+The models load only from a complete snapshot folder (EARSHOT_HOME/hf/models--org--name/snapshots/<sha>): transformers
+gets a folder, never a repo id, so a cached load never asks the Hub, and a damaged cache is an error that names the
+folder 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 or
+clears HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE. Imports nothing heavy: earshot doctor uses it without torch.
+"""
+import os
+import re
+from dataclasses import dataclass
+
+from .. import config
+
+SAFETENSORS = ('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
+_SHA = re.compile(r'[0-9a-f]{40}')
+
+
+@dataclass(frozen=True)
+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'
+ state: str # cached | legacy (a pre-0.2.1 snapshot of the pin stands in) | incomplete | missing
+ snapshot: str | None # the complete local folder to load from (state cached or legacy), else None
+ weights: 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 cache
+ pinned: bool = False # the wanted revision is earshot's pin
+
+ @property
+ def local(self):
+ return self.snapshot is not None
+
+ @property
+ def 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
+
+ @property
+ def label(self):
+ return f'{self.model_id}@{self.revision[:7] if _SHA.fullmatch(self.revision) else self.revision}'
+
+ @property
+ def 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"""
+ if self.pinned:
+ return ''
+ return '--' + (self.sha or re.sub(r'[^0-9A-Za-z._-]', '_', self.revision))[:8]
+
+
+def model_dir(model_id):
+ return os.path.join(config.HF_CACHE, 'models--' + model_id.replace('/', '--'))
+
+
+def snapshot_dir(model_id, revision):
+ """the cache folder of a revision: a 40-hex sha directly, a branch / tag / PR ref through the cache's refs file;
+ None when the cache has never resolved that name"""
+ if _SHA.fullmatch(revision):
+ return os.path.join(model_dir(model_id), 'snapshots', revision)
+ try:
+ with open(os.path.join(model_dir(model_id), 'refs', *revision.split('/')), encoding='utf-8') as f:
+ sha = f.read().strip()
+ except OSError:
+ return None
+ return os.path.join(model_dir(model_id), 'snapshots', sha) if _SHA.fullmatch(sha) else None
+
+
+def _missing(folder, names):
+ """the names not present in folder; a tuple entry lists alternatives (any one will do). os.path.exists follows
+ the cache's symlinks, so a dangling link (a download that never finished) counts as missing"""
+ out = []
+ for n in names:
+ alts = n if isinstance(n, tuple) else (n,)
+ if not folder or not any(os.path.exists(os.path.join(folder, a)) for a in alts):
+ out.append(alts[0])
+ return tuple(out)
+
+
+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(model_id, revision=None):
+ """what the cache holds for model_id at revision. revision None = earshot's pin (config.PINS), or 'main' for a
+ model 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"""
+ pin = config.PINS.get(model_id)
+ if pin and revision in (None, pin['revision']):
+ rev, files, weights = pin['revision'], tuple(pin['files']), (pin['weights'],)
+ legacy = pin.get('legacy') if revision is None else None
+ else:
+ rev, files, weights, legacy, pin = revision or 'main', ('config.json',), SAFETENSORS, None, None
+ folder = snapshot_dir(model_id, rev)
+ missing = _missing(folder, files + (weights,))
+ if not missing:
+ return Spec(model_id, rev, 'cached', folder, _found(folder, weights), pinned=bool(pin))
+ if legacy:
+ old = snapshot_dir(model_id, legacy['revision'])
+ if not _missing(old, files + (legacy['weights'],)):
+ return Spec(model_id, rev, 'legacy', old, legacy['weights'], missing, pinned=True)
+ state = 'incomplete' if folder and os.path.isdir(folder) else 'missing'
+ return Spec(model_id, rev, state, None, weights[0], missing, pinned=bool(pin))
+
+
+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"""
+ flag = config.offline()
+ where = (f'incomplete in the earshot cache (missing: {", ".join(spec.missing)})' if spec.state == 'incomplete' else
+ f'not in the earshot cache ({config.HF_CACHE})')
+ if flag:
+ raise RuntimeError(f'{spec.label} is {where} and {flag} is set, so earshot will not download it. Run once '
+ f'without {flag} (`earshot doctor --fetch` downloads the models, ~1.1 GB), copy a cache '
+ 'there, or point EARSHOT_HOME at one.')
+ from huggingface_hub import snapshot_download # a dependency of transformers
+ pin = config.PINS.get(spec.model_id) if spec.pinned else None
+ patterns = [*pin['files'], pin['weights']] if pin else list(CUSTOM_PATTERNS)
+ config.ensure_dirs()
+ try:
+ snapshot_download(spec.model_id, revision=spec.revision, cache_dir=config.HF_CACHE, allow_patterns=patterns)
+ except Exception as e: # noqa: BLE001 (network, auth, unknown repo or revision: one readable error)
+ raise RuntimeError(f'could not download {spec.label} into {config.HF_CACHE}: {type(e).__name__}: {e}') from e
+ new = resolve(spec.model_id, spec.revision)
+ if new.state != 'cached':
+ hint = '' if pin else ': earshot loads safetensors weights only'
+ raise RuntimeError(f'downloaded {spec.label}, but the cache still lacks {", ".join(new.missing)} '
+ f'({model_dir(spec.model_id)}){hint}')
+ return new
+
+
+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)"""
+ spec = resolve(model_id, revision)
+ return spec if spec.local else fetch(spec)
diff --git a/earshot/vocab.py b/earshot/vocab.py
index 08ed471..b478292 100644
--- a/earshot/vocab.py
+++ b/earshot/vocab.py
@@ -73,7 +73,10 @@ def _clap():
def _cache_dir():
- d = os.path.join(config.EMB_CACHE, 'semantics', config.CLAP_MODEL.replace('/', '--') + '--' + config.PRECISION)
+ 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
+ d = os.path.join(config.EMB_CACHE, 'semantics',
+ config.CLAP_MODEL.replace('/', '--') + tag + '--' + config.PRECISION)
os.makedirs(d, exist_ok=True)
return d
diff --git a/skills/earshot/SKILL.md b/skills/earshot/SKILL.md
index f658a92..054d582 100644
--- a/skills/earshot/SKILL.md
+++ b/skills/earshot/SKILL.md
@@ -15,7 +15,7 @@ handful of calls, use MCP or a short script (`from earshot import api; api.find(
## Setup (once)
```
pip install -e "/path/to/earshot[mcp,llm]" # or the repo venv: /path/to/earshot/.venv/bin/python -m earshot ...
-earshot doctor # packages, ffmpeg, cached models; --load also times the models
+earshot doctor # packages, ffmpeg, models (pinned revision, cache state); --load times them
```
Two ways in, same functions:
- **CLI**: `earshot <command> ... [--json] [--out result.json]`. Text output starts with a plain summary; times are
diff --git a/tests/test_models_hub.py b/tests/test_models_hub.py
new file mode 100644
index 0000000..4afe8c4
--- /dev/null
+++ b/tests/test_models_hub.py
@@ -0,0 +1,324 @@
+"""model files (issue #2): pinned revisions, local-only loads, offline flags respected, no download behind the user's
+back. A fake cache tree and fake transformers classes: no network, no model load (the real load is a slow test)."""
+import glob
+import json
+import os
+import re
+import subprocess
+import sys
+
+import pytest
+
+from earshot import config, doctor
+from earshot.models import clap, hub
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+CLAP_ID, AST_ID = 'laion/larger_clap_general', 'MIT/ast-finetuned-audioset-10-10-0.4593'
+CLAP_PIN, AST_PIN = config.PINS[CLAP_ID], config.PINS[AST_ID]
+LEGACY = CLAP_PIN['legacy']
+
+
+def cache(tmp_path, monkeypatch):
+ """an empty earshot model cache, default model ids, no revision override and no offline flag"""
+ monkeypatch.setattr(config, 'HF_CACHE', str(tmp_path / 'hf'))
+ monkeypatch.setattr(config, 'HOME', str(tmp_path))
+ monkeypatch.setattr(config, 'EMB_CACHE', str(tmp_path / 'emb'))
+ monkeypatch.setattr(config, 'DEC_CACHE', str(tmp_path / 'decoded'))
+ for k, v in (('CLAP_MODEL', CLAP_ID), ('AST_MODEL', AST_ID), ('CLAP_REVISION', None), ('AST_REVISION', None)):
+ monkeypatch.setattr(config, k, v)
+ for k in config.OFFLINE_FLAGS:
+ monkeypatch.delenv(k, raising=False)
+ return tmp_path / 'hf'
+
+
+def downloads(monkeypatch):
+ """replace huggingface_hub.snapshot_download: record each call, and write the requested files (minus `skip`)
+ into the cache like the real one does"""
+ import huggingface_hub
+ calls = []
+
+ def fake(repo_id, revision=None, cache_dir=None, allow_patterns=None, **kw):
+ 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)
+ fake.fail, fake.skip = False, ()
+ monkeypatch.setattr(huggingface_hub, 'snapshot_download', fake)
+ fake.calls = calls
+ return fake
+
+
+def snap(model_id, sha, files, ref=None):
+ """write a snapshot folder into the (patched) cache, plus refs/<ref> -> sha"""
+ d = os.path.join(hub.model_dir(model_id), 'snapshots', sha)
+ os.makedirs(d, exist_ok=True)
+ for f in files:
+ with open(os.path.join(d, f), 'wb') as fh:
+ fh.write(b'x')
+ if ref:
+ os.makedirs(os.path.join(hub.model_dir(model_id), 'refs'), exist_ok=True)
+ with open(os.path.join(hub.model_dir(model_id), 'refs', ref), 'w') as fh:
+ fh.write(sha)
+ return d
+
+
+def pinned(model_id):
+ p = config.PINS[model_id]
+ return snap(model_id, p['revision'], [*p['files'], p['weights']])
+
+
+def legacy_clap():
+ return snap(CLAP_ID, LEGACY['revision'], [*CLAP_PIN['files'], LEGACY['weights']], ref='main')
+
+
+class Fake:
+ """stands in for a transformers class: records from_pretrained calls, or raises `error`"""
+ calls, error = [], None
+
+ @classmethod
+ def from_pretrained(cls, path, **kw):
+ cls.calls.append((path, kw))
+ if cls.error:
+ raise cls.error
+ return cls()
+
+
+def fake():
+ Fake.calls, Fake.error = [], None
+ return Fake
+
+
+# ------------------------------------------------------------------------------------------------------- pins
+def test_pins_are_full_shas_with_safetensors_weights():
+ assert set(config.PINS) == {CLAP_ID, AST_ID}
+ assert CLAP_PIN['revision'] == '16c8cc3159a3c8a31e8ff5ef1f66b0d9ab3667db'
+ assert AST_PIN['revision'] == 'f826b80d28226b62986cc218e5cec390b1096902'
+ assert LEGACY == {'revision': 'ada0c23a36c4e8582805bb38fec3905903f18b41', 'weights': 'pytorch_model.bin'}
+ for p in config.PINS.values():
+ assert re.fullmatch(r'[0-9a-f]{40}', p['revision']) and p['weights'] == 'model.safetensors'
+ assert 'config.json' in p['files'] and not any(f.endswith('.bin') for f in p['files'])
+
+
[email protected]('flag', config.OFFLINE_FLAGS)
[email protected]('value, on', [('1', True), ('true', True), ('YES', True), ('on', True), ('0', False),
+ ('', False), ('false', False)])
+def test_offline_reads_every_flag_at_call_time(monkeypatch, flag, value, on):
+ for k in config.OFFLINE_FLAGS:
+ monkeypatch.delenv(k, raising=False)
+ assert config.offline() is None
+ monkeypatch.setenv(flag, value)
+ assert config.offline() == (flag if on else None)
+
+
+def test_no_code_sets_or_clears_the_hf_offline_flags():
+ """earshot once set HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE when a cache folder existed and removed them to
+ download after any failed load; both are the user's settings"""
+ writes = re.compile(r"environ(?:\.pop|\.setdefault|\.update|\[)\W*(?:HF_HUB_OFFLINE|TRANSFORMERS_OFFLINE)")
+ hits = []
+ for path in glob.glob(os.path.join(REPO, 'earshot', '**', '*.py'), recursive=True):
+ with open(path, encoding='utf-8') as f:
+ hits += [f'{os.path.relpath(path, REPO)}: {m.group(0)}' for m in writes.finditer(f.read())]
+ assert not hits, hits
+ assert not hasattr(clap, 'offline_if_cached')
+
+
+# ----------------------------------------------------------------------------------------------------- resolve
+def test_resolve_pinned_snapshot(cache):
+ d = pinned(CLAP_ID)
+ s = hub.resolve(CLAP_ID)
+ assert (s.state, s.snapshot, s.weights, s.revision, s.sha) == ('cached', d, 'model.safetensors',
+ CLAP_PIN['revision'], CLAP_PIN['revision'])
+ assert s.local and s.pinned and s.missing == () and s.cache_tag == ''
+ assert s.label == f'{CLAP_ID}@16c8cc3'
+
+
+def test_resolve_empty_cache(cache):
+ s = hub.resolve(AST_ID)
+ assert (s.state, s.snapshot, s.local, s.sha) == ('missing', None, False, None)
+ assert set(s.missing) == {*AST_PIN['files'], 'model.safetensors'}
+
+
+def test_resolve_incomplete_download(cache):
+ """an interrupted download leaves the folder without its weights: not loadable, reported as incomplete"""
+ snap(AST_ID, AST_PIN['revision'], AST_PIN['files'])
+ s = hub.resolve(AST_ID)
+ assert (s.state, s.snapshot, s.missing) == ('incomplete', None, ('model.safetensors',))
+
+
+def test_legacy_snapshot_stands_in_for_the_pin(cache):
+ """a cache made before 0.2.1 (main ada0c23, pickle weights only) still loads, without a download"""
+ d = legacy_clap()
+ s = hub.resolve(CLAP_ID)
+ assert (s.state, s.snapshot, s.weights, s.revision) == ('legacy', d, 'pytorch_model.bin', CLAP_PIN['revision'])
+ assert s.sha == LEGACY['revision'] and s.pinned and s.cache_tag == '' # same tensors: same embedding cache
+ assert 'model.safetensors' in s.missing
+ pinned(CLAP_ID) # once the pinned files are there, they win
+ assert hub.resolve(CLAP_ID).state == 'cached'
+
+
+def test_legacy_needs_a_complete_snapshot_and_no_explicit_revision(cache):
+ d = legacy_clap()
+ assert hub.resolve(CLAP_ID, CLAP_PIN['revision']).state == 'missing' # asked for the pin itself
+ assert hub.resolve(CLAP_ID, LEGACY['revision']).state == 'incomplete' # an override must be safetensors
+ os.remove(os.path.join(d, 'tokenizer.json'))
+ assert hub.resolve(CLAP_ID).state == 'missing'
+
+
+def test_custom_model_resolves_through_refs(cache):
+ sha = 'a' * 40
+ d = snap('someone/clap-ft', sha, ['config.json', 'model.safetensors.index.json'], ref='main')
+ s = hub.resolve('someone/clap-ft')
+ assert (s.state, s.snapshot, s.revision, s.weights) == ('cached', d, 'main', 'model.safetensors.index.json')
+ assert not s.pinned and s.cache_tag == '--aaaaaaaa' # another checkpoint: its own embedding cache
+ snap('someone/clap-ft', 'b' * 40, ['config.json', 'pytorch_model.bin'], ref='v2')
+ assert hub.resolve('someone/clap-ft', 'v2').state == 'incomplete' # pickle weights only: not loadable
+ assert hub.resolve('someone/clap-ft', 'v3').state == 'missing'
+
+
+# -------------------------------------------------------------------------------------------------------- load
+def test_cached_load_reads_the_snapshot_folder_only(cache, fake):
+ d = pinned(CLAP_ID)
+ spec = hub.ensure(CLAP_ID)
+ clap._load_hf(fake, spec, weights=True)
+ clap._load_hf(fake, spec)
+ assert fake.calls == [(d, {'local_files_only': True, 'use_safetensors': True}),
+ (d, {'local_files_only': True})]
+ assert not any(k in os.environ for k in config.OFFLINE_FLAGS) # nothing set behind the user's back
+
+
+def test_legacy_load_uses_the_pickle_from_the_cache(cache, fake, downloads):
+ d = legacy_clap()
+ clap._load_hf(fake, hub.ensure(CLAP_ID), weights=True)
+ assert fake.calls == [(d, {'local_files_only': True, 'use_safetensors': False})] and downloads.calls == []
+
+
+def test_failed_cached_load_is_an_error_not_a_download(cache, fake, downloads):
+ d = pinned(AST_ID)
+ fake.error = OSError('unexpected end of file')
+ with pytest.raises(RuntimeError, match='could not load') as e:
+ clap._load_hf(fake, hub.ensure(AST_ID), weights=True)
+ assert d in str(e.value) and 'unexpected end of file' in str(e.value)
+ assert len(fake.calls) == 1 and downloads.calls == []
+
+
[email protected]('flag', config.OFFLINE_FLAGS)
+def test_offline_flag_refuses_a_download(cache, downloads, monkeypatch, flag):
+ monkeypatch.setenv(flag, '1')
+ with pytest.raises(RuntimeError, match=f'{flag} is set, so earshot will not download'):
+ hub.ensure(CLAP_ID)
+ snap(AST_ID, AST_PIN['revision'], AST_PIN['files'])
+ with pytest.raises(RuntimeError, match='incomplete in the earshot cache \\(missing: model.safetensors\\)'):
+ hub.ensure(AST_ID)
+ assert downloads.calls == [] and os.environ[flag] == '1' # refused, and the user's flag left alone
+
+
+def test_offline_flag_still_loads_what_is_cached(cache, downloads, monkeypatch):
+ monkeypatch.setenv('HF_HUB_OFFLINE', '1')
+ d = pinned(AST_ID)
+ assert hub.ensure(AST_ID).snapshot == d and downloads.calls == []
+
+
+def test_missing_model_downloads_the_pinned_files_once(cache, downloads):
+ spec = hub.ensure(CLAP_ID)
+ assert spec.state == 'cached' and spec.sha == CLAP_PIN['revision']
+ [call] = downloads.calls
+ assert call['repo_id'] == CLAP_ID and call['revision'] == CLAP_PIN['revision']
+ assert call['cache_dir'] == config.HF_CACHE
+ assert sorted(call['allow_patterns']) == sorted([*CLAP_PIN['files'], 'model.safetensors'])
+ hub.ensure(CLAP_ID)
+ assert len(downloads.calls) == 1 # cached now: no second download
+
+
+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
+ [call] = downloads.calls
+ assert call['revision'] == 'main' and not any('.bin' in p or p == '*' for p in call['allow_patterns'])
+
+
+def test_failed_download_is_one_readable_error(cache, downloads):
+ downloads.fail = True
+ with pytest.raises(RuntimeError, match='could not download .*ConnectionError: no route to the Hub'):
+ hub.ensure(AST_ID)
+ downloads.fail, downloads.skip = False, ('model.safetensors',)
+ with pytest.raises(RuntimeError, match='still lacks model.safetensors'):
+ hub.ensure(AST_ID)
+
+
+# ------------------------------------------------------------------------------------------------------ doctor
+def test_doctor_reports_revisions_and_cache_state(cache):
+ legacy_clap()
+ pinned(AST_ID)
+ r = doctor.check()
+ c, a = r['models'][CLAP_ID], r['models'][AST_ID]
+ assert c == {'revision': CLAP_PIN['revision'], 'cached': 'legacy', 'loads': LEGACY['revision'],
+ 'weights': 'pytorch_model.bin', 'snapshot': hub.resolve(CLAP_ID).snapshot,
+ 'missing': [*CLAP_PIN['files'], 'model.safetensors']}
+ assert (a['cached'], a['loads'], a['weights']) == ('cached', AST_PIN['revision'], 'model.safetensors')
+ assert r['models_cached'] == {CLAP_ID: True, AST_ID: True} and r['offline'] is None
+ assert 'earshot doctor --fetch' in r['summary'] and 'pickle weights' in r['summary']
+
+
+def test_doctor_names_the_offline_flag_when_models_are_missing(cache, monkeypatch):
+ monkeypatch.setenv('TRANSFORMERS_OFFLINE', '1')
+ r = doctor.check()
+ assert r['offline'] == 'TRANSFORMERS_OFFLINE' and r['models_cached'] == {CLAP_ID: False, AST_ID: False}
+ assert any('TRANSFORMERS_OFFLINE is set' in p for p in r['problems'])
+
+
+def test_doctor_load_reports_instead_of_failing(cache, monkeypatch):
+ monkeypatch.setenv('EARSHOT_OFFLINE', '1')
+ monkeypatch.setattr(doctor, '_load', lambda r: pytest.fail('loaded a model that is not cached while offline'))
+ r = doctor.check(load=True)
+ assert 'EARSHOT_OFFLINE is set' in r['summary'] and 'load failed' not in r['summary']
+ pinned(CLAP_ID)
+ pinned(AST_ID)
+
+ def broken(r):
+ raise RuntimeError('could not load the model (damaged).')
+ monkeypatch.setattr(doctor, '_load', broken)
+ r = doctor.check(load=True)
+ assert r['problems'][-1] == 'model load failed: could not load the model (damaged).'
+ assert r['summary'].endswith('(damaged).') # one full stop, not two
+
+
+def test_doctor_fetch_downloads_only_what_is_missing(cache, downloads):
+ legacy_clap()
+ pinned(AST_ID)
+ r = doctor.check(fetch_missing=True)
+ assert r['fetched'] == {CLAP_ID: 'downloaded 16c8cc3', AST_ID: 'already cached'}
+ assert [c['repo_id'] for c in downloads.calls] == [CLAP_ID]
+ assert r['models'][CLAP_ID]['cached'] == 'cached' and 'pickle' not in r['summary']
+
+
+def test_doctor_cli_takes_fetch(cache, downloads, capsys, monkeypatch):
+ monkeypatch.setenv('EARSHOT_OFFLINE', '1')
+ from earshot import cli
+ assert cli.main(['doctor', '--fetch', '--json']) == 0
+ r = json.loads(capsys.readouterr().out)
+ assert r['fetched'][CLAP_ID].startswith('failed: ') and 'EARSHOT_OFFLINE is set' in r['fetched'][CLAP_ID]
+ assert downloads.calls == []
+
+
+# --------------------------------------------------------------------------------------------------- real load
+def test_cached_models_load_without_network(tmp_path):
+ """the real models from the real cache, with the Hub unreachable and no offline flag: a cached load must not try
+ the network (earshot used to call the Hub for update checks and safetensors conversion)"""
+ s = [hub.resolve(m) for m in (CLAP_ID, AST_ID)]
+ if not all(x.local for x in s):
+ pytest.skip('the models are not in the earshot cache')
+ env = {k: v for k, v in os.environ.items() if k not in config.OFFLINE_FLAGS}
+ env.update(HF_ENDPOINT='http://127.0.0.1:9', EARSHOT_THREADS='2', EARSHOT_HOME=config.HOME,
+ PYTHONIOENCODING='utf-8')
+ p = subprocess.run([sys.executable, '-m', 'earshot', 'doctor', '--load', '--json'], cwd=REPO, env=env,
+ capture_output=True, text=True, encoding='utf-8', timeout=900)
+ assert p.returncode == 0, p.stderr
+ r = json.loads(p.stdout)
+ assert not any('load failed' in x for x in r['problems']), r['problems']
+ assert (r['clap_revision'], r['ast_revision']) == (s[0].sha, s[1].sha)
+ assert (r['clap_weights'], r['ast_weights']) == (s[0].weights, s[1].weights)