File size: 952 Bytes
18bfb47
 
 
 
 
 
 
 
441eef9
18bfb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e71ec
 
18bfb47
 
 
 
 
 
 
 
 
 
 
 
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 os
import json
from pgsoft.pgdate.date_utils import beijing

cache_ai = {}


def normalize_text(text: str) -> str:
    text = text.lower()
    tmp = text.split(" ")
    tmp = [word for word in tmp if word != ""]
    return " ".join(tmp)


def load_cache(filepath: str):
    """load cached ai calling from a json file"""
    global cache_ai
    if os.path.exists(filepath):
        with open(filepath, "r+") as f:
            cache_ai = json.load(f)


def add_cache(command: str, result: dict):
    """add a cache of ai calling"""
    command = normalize_text(command)
    result["command"] = command

    global cache_ai
    cache_ai[command] = result
    print(f'[cache] added "{command}"')


def get_cache(command: str) -> dict | None:
    """return a cached ai calling with new "timestamp" """
    command = normalize_text(command)
    outp = cache_ai.get(command)
    if outp:
        outp["timestamp"] = beijing().__str__()
    return outp