Mirrored from https://github.com/Camo67/OCIU-npo.git
Synced Nov 21, 04:45 UTC
fix/restore-static-site
| 1 | import sqlite3 |
| 2 | import os |
| 3 | import json |
| 4 | import time |
| 5 | from typing import Optional |
| 6 | |
| 7 | class AICache: |
| 8 | def __init__(self, db_path="ai_cache.db"): |
| 9 | self.db_path = db_path |
| 10 | self._init_db() |
| 11 | |
| 12 | def _init_db(self): |
| 13 | with sqlite3.connect(self.db_path) as conn: |
| 14 | conn.execute(""" |
| 15 | CREATE TABLE IF NOT EXISTS cache ( |
| 16 | prompt_hash TEXT PRIMARY KEY, |
| 17 | response TEXT, |
| 18 | timestamp REAL |
| 19 | ) |
| 20 | """) |
| 21 | |
| 22 | def get(self, prompt: str) -> Optional[str]: |
| 23 | import hashlib |
| 24 | prompt_hash = hashlib.sha256(prompt.encode()).hexdigest() |
| 25 | with sqlite3.connect(self.db_path) as conn: |
| 26 | cursor = conn.execute("SELECT response FROM cache WHERE prompt_hash = ?", (prompt_hash,)) |
| 27 | row = cursor.fetchone() |
| 28 | if row: |
| 29 | return row[0] |
| 30 | return None |
| 31 | |
| 32 | def set(self, prompt: str, response: str): |
| 33 | import hashlib |
| 34 | prompt_hash = hashlib.sha256(prompt.encode()).hexdigest() |
| 35 | with sqlite3.connect(self.db_path) as conn: |
| 36 | conn.execute( |
| 37 | "INSERT OR REPLACE INTO cache (prompt_hash, response, timestamp) VALUES (?, ?, ?)", |
| 38 | (prompt_hash, response, time.time()) |
| 39 | ) |
| 40 | |
| 41 | ai_cache = AICache() |