watermelon / cache.py
steveagi's picture
cache
662501a
raw
history blame
981 Bytes
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__()
outp["cache"] = True
return outp