Download backend/shared/cache/core.py from VoiceOfML/Search: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/shared/cache/core.py
- Command line
-
hf download hf://spaces/VoiceOfML/Search/backend/shared/cache/core.py
-
curl -L -o core.py https://huggingface.co/spaces/VoiceOfML/Search/resolve/main/backend/shared/cache/core.py
1.37 kB
| """Bounded insertion-ordered response cache shared by API and search.""" | |
| from collections.abc import Callable, Hashable | |
| import json | |
| import time | |
| def cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable, | |
| builder: Callable[[], object], ttl: float, limit: int, *, | |
| max_entry_bytes: int, max_total_bytes: int) -> object: | |
| now = time.monotonic() | |
| cached = store.get(key) | |
| if cached and now - cached[0] < ttl: | |
| store[key] = store.pop(key) | |
| return cached[1] | |
| value = builder() | |
| store.pop(key, None) | |
| for old_key, entry in list(store.items()): | |
| if now - entry[0] >= ttl: | |
| del store[old_key] | |
| size = (len(value) if isinstance(value, bytes) else len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))) + len(str(key).encode("utf-8")) | |
| if size > max_entry_bytes: | |
| return value | |
| total = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values()) | |
| while store and (len(store) >= limit or total + size > max_total_bytes): | |
| oldest_key = next(iter(store)) | |
| entry = store.pop(oldest_key) | |
| total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) | |
| if size <= max_total_bytes: | |
| store[key] = (now, value, size) | |
| return value | |