File size: 1,025 Bytes
76022ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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()