Spaces:
Sleeping
Sleeping
| """ | |
| cache/memo.py — tiny in-memory and file-backed cache | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| import json | |
| import os | |
| _CACHE: dict[str, Any] = {} | |
| _CACHE_DIR = Path(".cache") | |
| _CACHE_DIR.mkdir(exist_ok=True) | |
| def cache_get(key: str) -> Optional[Any]: | |
| if key in _CACHE: | |
| return _CACHE[key] | |
| f = _CACHE_DIR / (key.replace(":", "_") + ".json") | |
| if f.exists(): | |
| try: | |
| with open(f, "r", encoding="utf-8") as fh: | |
| val = json.load(fh) | |
| _CACHE[key] = val | |
| return val | |
| except Exception: | |
| return None | |
| return None | |
| def cache_put(key: str, value: Any) -> None: | |
| _CACHE[key] = value | |
| f = _CACHE_DIR / (key.replace(":", "_") + ".json") | |
| try: | |
| with open(f, "w", encoding="utf-8") as fh: | |
| json.dump(value, fh, ensure_ascii=False, indent=2) | |
| except Exception: | |
| pass |