Spaces:
Runtime error
Runtime error
| # memory_layer.py | |
| import json, os, threading, time, hashlib | |
| MEM_PATH = "memory.json" | |
| _LOCK = threading.Lock() | |
| def _normalize_key(text: str) -> str: | |
| base = (text or "").strip().lower() | |
| # اختياري: لو بدك مفتاح ثابت حتى مع نص طويل | |
| return hashlib.sha1(base.encode("utf-8")).hexdigest() | |
| def _load_memory() -> dict: | |
| if not os.path.exists(MEM_PATH): | |
| return {} | |
| try: | |
| with open(MEM_PATH, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| except Exception: | |
| return {} | |
| def _save_memory(mem: dict) -> None: | |
| tmp = MEM_PATH + ".tmp" | |
| with open(tmp, "w", encoding="utf-8") as f: | |
| json.dump(mem, f, ensure_ascii=False, indent=2) | |
| os.replace(tmp, MEM_PATH) | |
| def get_from_memory(key_text: str): | |
| k = _normalize_key(key_text) | |
| with _LOCK: | |
| mem = _load_memory() | |
| item = mem.get(k) | |
| if not item: | |
| return None | |
| # اختياري: صلاحية زمنية TTL بالثواني (مثلاً 90 يوم) | |
| ttl = item.get("_ttl_seconds") | |
| ts = item.get("_timestamp") | |
| if ttl and ts and (time.time() - ts) > ttl: | |
| # منتهي، نحذفه | |
| mem.pop(k, None) | |
| _save_memory(mem) | |
| return None | |
| return item.get("response") | |
| def save_to_memory(key_text: str, response_text: str, ttl_seconds: int | None = None): | |
| k = _normalize_key(key_text) | |
| with _LOCK: | |
| mem = _load_memory() | |
| mem[k] = { | |
| "response": response_text, | |
| "_timestamp": time.time(), | |
| "_ttl_seconds": ttl_seconds | |
| } | |
| _save_memory(mem) |