doco-talk / cache.py
rahul7star's picture
Create cache.py
d830fd3 verified
import hashlib
import os
import pickle
CACHE_DIR = "/tmp/qa_cache"
os.makedirs(CACHE_DIR, exist_ok=True)
memory_cache = {}
def _key(text):
return hashlib.md5(text.encode()).hexdigest()
def get(text):
k = _key(text)
if k in memory_cache:
return memory_cache[k]
path = os.path.join(CACHE_DIR, k)
if os.path.exists(path):
with open(path, "rb") as f:
memory_cache[k] = pickle.load(f)
return memory_cache[k]
return None
def set(text, value):
k = _key(text)
memory_cache[k] = value
with open(os.path.join(CACHE_DIR, k), "wb") as f:
pickle.dump(value, f)