File size: 1,005 Bytes
af4937c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, json, tempfile

_DATA_DIR = os.environ.get("PRECIZ_DATA_DIR", "/tmp")


def _data_dir(username=None):
    d = _DATA_DIR
    if username:
        d = os.path.join(d, username)
    return d


def load_memory():
    p = os.path.join(_data_dir(), "memory", "memory.json")
    os.makedirs(os.path.dirname(p), exist_ok=True)
    if not os.path.exists(p):
        return {"ttl_days": 7, "model_cache": {}}
    try:
        with open(p) as f:
            return json.load(f)
    except json.JSONDecodeError:
        return {"ttl_days": 7, "model_cache": {}}


def save_memory(memory):
    p = os.path.join(_data_dir(), "memory", "memory.json")
    os.makedirs(os.path.dirname(p), exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=os.path.dirname(p), suffix=".json")
    try:
        with os.fdopen(fd, "w") as f:
            json.dump(memory, f, indent=2)
        os.replace(tmp, p)
    except Exception:
        try:
            os.unlink(tmp)
        except Exception:
            pass
        raise