Download cache_.py from ksshan918/mc: direct link, hf CLI and curl.
- Browser
- Download file 9.86 kB
-
https://huggingface.co/spaces/ksshan918/mc/resolve/main/cache_.py
- Command line
-
hf download hf://spaces/ksshan918/mc/cache_.py
-
curl -L -o cache_.py https://huggingface.co/spaces/ksshan918/mc/resolve/main/cache_.py
9.86 kB
| from collections import OrderedDict | |
| from collections.abc import MutableMapping | |
| from threading import RLock, Timer | |
| from typing import Any, Optional, Iterator, Tuple | |
| import time | |
| import threading | |
| import logging | |
| from urllib.parse import urlparse | |
| # ββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="[%(asctime)s] %(levelname)s %(message)s", | |
| datefmt="%H:%M:%S", | |
| ) | |
| log = logging.getLogger("cfb-api") | |
| COOKIE_TTL = 3600 # cookie cache lifetime in seconds (1 hour) | |
| class Logger: | |
| def __init__(self, name: str): | |
| self.name = name | |
| def info(self, msg: str): | |
| print(f"[{self.name}] {msg}") | |
| def warning(self, msg: str): | |
| print(f"[{self.name}] {msg}") | |
| def error(self, msg: str): | |
| print(f"[{self.name}] {msg}") | |
| def exception(self, msg: str): | |
| print(f"[{self.name}] {msg}") | |
| # ββ Cookie Cache ββββββββββββββββββββββββββββββββββββββββββββββ | |
| class CookieCache: | |
| def __init__(self, ttl: int = COOKIE_TTL): | |
| self.ttl = ttl | |
| self._data = {} # domain -> {cookies, stored_at} | |
| self._lock = threading.Lock() | |
| def _domain(self, url: str) -> str: | |
| host = urlparse(url).netloc.lower() | |
| if host.startswith("www."): | |
| host = host[4:] | |
| return host | |
| def get(self, url: str): | |
| domain = self._domain(url) | |
| with self._lock: | |
| entry = self._data.get(domain) | |
| if not entry: | |
| return None | |
| age = time.time() - entry["stored_at"] | |
| if age > self.ttl: | |
| log.info(f"[cache] {domain} expired ({age:.0f}s) β will re-bypass") | |
| del self._data[domain] | |
| return None | |
| log.info(f"[cache] {domain} HIT β age={age:.0f}s cookies={len(entry['cookies'])}") | |
| return entry["cookies"] | |
| def set(self, url: str, cookies: list): | |
| domain = self._domain(url) | |
| with self._lock: | |
| self._data[domain] = {"cookies": cookies, "stored_at": time.time()} | |
| log.info(f"[cache] {domain} stored β {len(cookies)} cookies") | |
| def invalidate(self, url: str): | |
| domain = self._domain(url) | |
| with self._lock: | |
| self._data.pop(domain, None) | |
| log.info(f"[cache] {domain} invalidated") | |
| def clear_all(self): | |
| with self._lock: | |
| self._data.clear() | |
| def stats(self): | |
| now = time.time() | |
| with self._lock: | |
| return [ | |
| { | |
| "domain": d, | |
| "cookies": len(v["cookies"]), | |
| "age_secs": int(now - v["stored_at"]), | |
| "expires_in": max(0, int(self.ttl - (now - v["stored_at"]))), | |
| } | |
| for d, v in self._data.items() | |
| ] | |
| class TTLCache(MutableMapping): | |
| """ | |
| Major improvements for your use case: | |
| - Default: cleanup_interval=0 (no background threads β saves RAM + CPU) | |
| - Added maxsize (caps memory usage automatically) | |
| - Uses OrderedDict β very low overhead + fast FIFO eviction when full | |
| - Aggressive lazy cleanup on every access/write | |
| - Still fully thread-safe and auto-deletes expired entries | |
| - Much lower memory footprint than previous version | |
| """ | |
| def __init__( | |
| self, | |
| default_timeout: float = 7200.0, | |
| cleanup_interval: float = 0.0, # β changed default to 0 (recommended!) | |
| maxsize: Optional[int] = None, # β NEW: set this to limit RAM! | |
| ) -> None: | |
| """ | |
| Args: | |
| default_timeout: TTL in seconds (2 hours by default) | |
| cleanup_interval: Background cleanup seconds (0 = disabled, recommended) | |
| maxsize: Maximum number of entries (None = unlimited). Highly recommended! | |
| """ | |
| self._data: OrderedDict[Any, Tuple[Any, float]] = OrderedDict() | |
| self._default_timeout = default_timeout | |
| self._maxsize = maxsize | |
| self._lock = RLock() | |
| self._cleanup_interval = cleanup_interval | |
| self._timer: Optional[Timer] = None | |
| if cleanup_interval > 0: | |
| self._start_cleanup_timer() | |
| def _start_cleanup_timer(self) -> None: | |
| self._timer = Timer(self._cleanup_interval, self._periodic_cleanup) | |
| self._timer.daemon = True | |
| self._timer.start() | |
| def _periodic_cleanup(self) -> None: | |
| self._remove_expired() | |
| if self._cleanup_interval > 0: | |
| self._start_cleanup_timer() | |
| def _remove_expired(self) -> None: | |
| """Remove expired entries (very fast).""" | |
| now = time.monotonic() | |
| with self._lock: | |
| # Pop expired from front (oldest first) β super efficient with OrderedDict | |
| while self._data: | |
| key, (value, expiry) = next(iter(self._data.items())) | |
| if expiry > now: | |
| break | |
| self._data.popitem(last=False) | |
| def _evict_if_full(self) -> None: | |
| """Evict oldest entry if we exceed maxsize.""" | |
| if self._maxsize is None or len(self._data) <= self._maxsize: | |
| return | |
| with self._lock: | |
| while len(self._data) > self._maxsize: | |
| self._data.popitem(last=False) # remove oldest | |
| def _get_expiry(self, timeout: Optional[float] = None) -> float: | |
| t = timeout if timeout is not None else self._default_timeout | |
| return time.monotonic() + max(0.0, t) | |
| # ==================== Core methods (fast + low memory) ==================== | |
| def __getitem__(self, key: Any) -> Any: | |
| with self._lock: | |
| if key not in self._data: | |
| raise KeyError(key) | |
| value, expiry = self._data[key] | |
| if time.monotonic() > expiry: | |
| self._data.pop(key, None) | |
| raise KeyError(key) | |
| self._data.move_to_end(key) # keep recent at the end | |
| return value | |
| def __setitem__(self, key: Any, value: Any) -> None: | |
| self.set(key, value, self._default_timeout) | |
| def set(self, key: Any, value: Any, timeout: Optional[float] = None) -> None: | |
| expiry = self._get_expiry(timeout) | |
| with self._lock: | |
| self._data[key] = (value, expiry) | |
| self._data.move_to_end(key) | |
| self._evict_if_full() # β keeps RAM under control | |
| def __delitem__(self, key: Any) -> None: | |
| with self._lock: | |
| del self._data[key] | |
| def __contains__(self, key: Any) -> bool: | |
| try: | |
| self[key] | |
| return True | |
| except KeyError: | |
| return False | |
| def get(self, key: Any, default: Any = None) -> Any: | |
| try: | |
| return self[key] | |
| except KeyError: | |
| return default | |
| def pop(self, key: Any, default: Any = None) -> Any: | |
| try: | |
| value = self[key] | |
| del self[key] | |
| return value | |
| except KeyError: | |
| return default | |
| def _clean_snapshot(self) -> OrderedDict: | |
| self._remove_expired() | |
| with self._lock: | |
| return self._data.copy() | |
| def keys(self): | |
| return list(self._clean_snapshot().keys()) | |
| def values(self): | |
| snapshot = self._clean_snapshot() | |
| return [v for v, _ in snapshot.values()] | |
| def items(self): | |
| snapshot = self._clean_snapshot() | |
| return [(k, v) for k, (v, _) in snapshot.items()] | |
| def __len__(self) -> int: | |
| self._remove_expired() | |
| return len(self._data) | |
| def __iter__(self) -> Iterator[Any]: | |
| return iter(self.keys()) | |
| def clear(self) -> None: | |
| with self._lock: | |
| self._data.clear() | |
| def update(self, other: dict) -> None: | |
| if not other: | |
| return | |
| with self._lock: | |
| now = time.monotonic() | |
| timeout = self._default_timeout | |
| for k, v in (other.items() if hasattr(other, "items") else other): | |
| self._data[k] = (v, now + max(0.0, timeout)) | |
| self._data.move_to_end(k) | |
| self._evict_if_full() | |
| def setdefault(self, key: Any, default: Any = None) -> Any: | |
| with self._lock: | |
| if key in self._data: | |
| value, expiry = self._data[key] | |
| if time.monotonic() <= expiry: | |
| self._data.move_to_end(key) | |
| return value | |
| # set default | |
| expiry = self._get_expiry() | |
| self._data[key] = (default, expiry) | |
| self._data.move_to_end(key) | |
| self._evict_if_full() | |
| return default | |
| def get_expiry_time(self, key: Any) -> Optional[float]: | |
| with self._lock: | |
| if key in self._data: | |
| _, exp = self._data[key] | |
| if time.monotonic() <= exp: | |
| return exp | |
| return None | |
| def refresh_key(self, key: Any, timeout: Optional[float] = None) -> bool: | |
| with self._lock: | |
| if key in self._data: | |
| value, _ = self._data[key] | |
| if time.monotonic() <= _: | |
| self._data[key] = (value, self._get_expiry(timeout)) | |
| self._data.move_to_end(key) | |
| return True | |
| return False | |
| def __repr__(self) -> str: | |
| return str(dict(self.items())) | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, exc_type, exc_val, exc_tb): | |
| self.clear() | |
| if self._timer and self._timer.is_alive(): | |
| self._timer.cancel() | |
| def __del__(self): | |
| if self._timer and self._timer.is_alive(): | |
| self._timer.cancel() | |