Datasets:
Download src/mcr/cache.py from Lux1997/eMCR: direct link, hf CLI and curl.
- Browser
- Download file 2.44 kB
-
https://huggingface.co/datasets/Lux1997/eMCR/resolve/main/src/mcr/cache.py
- Command line
-
hf download hf://datasets/Lux1997/eMCR/src/mcr/cache.py
-
curl -L -o cache.py https://huggingface.co/datasets/Lux1997/eMCR/resolve/main/src/mcr/cache.py
2.44 kB
| """On-disk embedding cache. | |
| All four upstream projects re-implemented "encode once, save to disk, skip on | |
| re-run". This centralises it. Embeddings are stored as ``.npy`` next to a | |
| ``.ids.json`` so a cached matrix can be validated against the ids it was built | |
| for (a mismatch means the corpus changed and we must re-encode). | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| from typing import Callable, List, Sequence | |
| import numpy as np | |
| def _slug(s: str) -> str: | |
| return re.sub(r"[^0-9A-Za-z._-]+", "_", s)[:120] | |
| class EmbeddingCache: | |
| def __init__(self, root: str, enabled: bool = True): | |
| self.root = root | |
| self.enabled = enabled | |
| def _paths(self, model_tag: str, task_name: str, split: str): | |
| d = os.path.join(self.root, _slug(model_tag), _slug(task_name)) | |
| base = os.path.join(d, _slug(split)) | |
| return d, base + ".npy", base + ".ids.json" | |
| def get_or_encode( | |
| self, | |
| model_tag: str, | |
| task_name: str, | |
| split: str, | |
| ids: Sequence[str], | |
| encode_fn: Callable[[], np.ndarray], | |
| ) -> np.ndarray: | |
| """Return cached embeddings if present and ids match, else encode + save. | |
| ``encode_fn`` is a zero-arg closure so encoding only happens on a miss. | |
| """ | |
| ids = [str(i) for i in ids] | |
| if not self.enabled: | |
| return encode_fn().astype("float32") | |
| d, emb_path, ids_path = self._paths(model_tag, task_name, split) | |
| if os.path.exists(emb_path) and os.path.exists(ids_path): | |
| with open(ids_path, "r", encoding="utf-8") as f: | |
| cached_ids = json.load(f) | |
| if _ids_match(cached_ids, ids): | |
| return np.load(emb_path).astype("float32") | |
| emb = encode_fn().astype("float32") | |
| os.makedirs(d, exist_ok=True) | |
| np.save(emb_path, emb) | |
| with open(ids_path, "w", encoding="utf-8") as f: | |
| json.dump({"n": len(ids), "hash": _ids_hash(ids)}, f) | |
| return emb | |
| def _ids_hash(ids: List[str]) -> str: | |
| h = hashlib.sha1() | |
| for i in ids: | |
| h.update(i.encode("utf-8")) | |
| h.update(b"\x00") | |
| return h.hexdigest() | |
| def _ids_match(cached, ids: List[str]) -> bool: | |
| if isinstance(cached, dict): # compact form {n, hash} | |
| return cached.get("n") == len(ids) and cached.get("hash") == _ids_hash(ids) | |
| return list(cached) == ids # legacy full-list form | |