Download tools/cache.py from worrrrrr/worgod: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/worrrrrr/worgod/resolve/main/tools/cache.py
- Command line
-
hf download hf://spaces/worrrrrr/worgod/tools/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/worrrrrr/worgod/resolve/main/tools/cache.py
2 kB
| # Purpose: LRU Cache with TTL for tool/LLM responses (no LLM/GPU) | |
| from __future__ import annotations | |
| import time | |
| import json | |
| from typing import Optional, Any | |
| CACHE_PREFIXES = ("/cache",) | |
| # In-memory store | |
| _STORE: dict[str, tuple[float, Any]] = {} | |
| _MAX_SIZE = 100 | |
| _DEFAULT_TTL = 3600 # 1 hour | |
| def get(key: str) -> Optional[Any]: | |
| if key not in _STORE: | |
| return None | |
| expires_at, val = _STORE[key] | |
| if time.time() > expires_at: | |
| del _STORE[key] | |
| return None | |
| return val | |
| def set(key: str, val: Any, ttl: int = _DEFAULT_TTL) -> None: | |
| if len(_STORE) >= _MAX_SIZE: | |
| # evict oldest expired or first item | |
| try: | |
| oldest_key = next(iter(_STORE)) | |
| del _STORE[oldest_key] | |
| except Exception: | |
| _STORE.clear() | |
| _STORE[key] = (time.time() + ttl, val) | |
| def clear() -> int: | |
| n = len(_STORE) | |
| _STORE.clear() | |
| return n | |
| def stats() -> dict: | |
| now = time.time() | |
| active = sum(1 for exp, _ in _STORE.values() if now <= exp) | |
| return { | |
| "total_items": len(_STORE), | |
| "active_items": active, | |
| "max_size": _MAX_SIZE, | |
| } | |
| def should_bypass_llm(message: str) -> bool: | |
| if not message or not message.strip(): | |
| return False | |
| low = message.strip().lower() | |
| for p in CACHE_PREFIXES: | |
| if low.startswith(p): | |
| return True | |
| return False | |
| def solve(query: str) -> str: | |
| q = query.strip().lower() | |
| if "clear" in q: | |
| n = clear() | |
| return f"🧹 cache cleared: removed {n} items" | |
| if "stats" in q or "info" in q: | |
| st = stats() | |
| return f"📊 Cache Stats: active={st['active_items']}, total={st['total_items']}, max={st['max_size']}" | |
| return f"📦 Cache usage: `/cache stats` or `/cache clear` (active items: {stats()['active_items']})" | |
| def try_solve(message: str) -> Optional[str]: | |
| if not should_bypass_llm(message): | |
| return None | |
| if len(message) > 200: | |
| return None | |
| return solve(message) | |