File size: 2,452 Bytes
1b4b6d2 | 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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | """
مدير التخزين المؤقت لاستجابات الذكاء الاصطناعي (AI Response Caching)
يحفظ استجابات AI سحابياً/محلياً بصيغة JSON باستخدام هاش الملف لتجنب الاستدعاء المتكرر وتوفير التكلفة.
"""
import os
import hashlib
import json
import numpy as np
CACHE_DIR = ".qto_cache"
def get_file_hash(data) -> str:
"""Computes SHA256 of files, bytes, or numpy arrays to index the cache."""
hasher = hashlib.sha256()
if isinstance(data, str):
# File path
if not os.path.exists(data):
return ""
try:
with open(data, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
hasher.update(chunk)
except Exception:
return ""
elif isinstance(data, bytes):
hasher.update(data)
elif isinstance(data, np.ndarray):
hasher.update(data.tobytes())
else:
# Fallback to string representation
hasher.update(str(data).encode("utf-8"))
return hasher.hexdigest()
def get_cached_response(file_hash: str, prompt_key: str) -> str:
"""Reads response from local JSON cache if exists."""
if not file_hash or not prompt_key:
return None
cache_file = os.path.join(CACHE_DIR, f"{file_hash}.json")
if os.path.exists(cache_file):
try:
with open(cache_file, "r", encoding="utf-8") as f:
cache_data = json.load(f)
return cache_data.get(prompt_key)
except Exception:
pass
return None
def save_cached_response(file_hash: str, prompt_key: str, response_text: str):
"""Saves AI response in the local JSON cache."""
if not file_hash or not prompt_key or not response_text:
return
os.makedirs(CACHE_DIR, exist_ok=True)
cache_file = os.path.join(CACHE_DIR, f"{file_hash}.json")
cache_data = {}
if os.path.exists(cache_file):
try:
with open(cache_file, "r", encoding="utf-8") as f:
cache_data = json.load(f)
except Exception:
pass
cache_data[prompt_key] = response_text
try:
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(cache_data, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"[Cache Write Error] {e}")
|