Anand Sharma
Clean Deployment v2
76022ae
Raw
History Blame Contribute Delete
1.03 kB
import json
import os
import hashlib
from typing import Optional, Any
CACHE_FILE = "backend/data/semantic_cache.json"
class SemanticCache:
def __init__(self):
self._cache = {}
self._load()
def _load(self):
if os.path.exists(CACHE_FILE):
try:
with open(CACHE_FILE, "r") as f:
self._cache = json.load(f)
except Exception:
self._cache = {}
def _save(self):
os.makedirs(os.path.dirname(CACHE_FILE), exist_ok=True)
with open(CACHE_FILE, "w") as f:
json.dump(self._cache, f)
def _hash(self, query: str) -> str:
return hashlib.sha256(query.strip().lower().encode()).hexdigest()
def get(self, query: str) -> Optional[Any]:
h = self._hash(query)
return self._cache.get(h)
def set(self, query: str, response: Any):
h = self._hash(query)
self._cache[h] = response
self._save()
# Global instance
semantic_cache = SemanticCache()