File size: 1,653 Bytes
40d06ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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)