cache.py

파일 다운로드

"""공개한 정형 질문만 보관하는 버전·기한 있는 답변 캐시."""
from pathlib import Path
import hashlib
import json
import sqlite3
import time
import settings
from embedding_client import embedding_config
from task_settings import task_config

ROOT = Path(__file__).resolve().parent
DATA_FILES = ['source/documents.json', 'documents.jsonl', 'chunks.jsonl', 'document_build.json',
              'search_index.json', 'aliases.json', 'public_cache_questions.json']


def digest(value):
    return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
                                    separators=(',', ':')).encode('utf-8')).hexdigest()


def runtime_signature(root=ROOT):
    root = Path(root)
    files = sorted([p for p in root.glob('*.py')]) + [root / 'data' / name for name in DATA_FILES]
    hashes = {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
    config = {'generation_base_url': settings.BASE_URL, 'demo': settings.DEMO_MODE,
              'tasks': {name: task_config(name) for name in ['rag', 'order', 'classify', 'summary']},
              'embedding': embedding_config(), 'files': hashes}
    return {'id': digest(config), 'components': config}


def cache_key(question, history, as_of, signature):
    return digest({'schema': 1, 'task': 'public_rag', 'question': question.strip(),
                   'history': history or [], 'as_of': as_of, 'signature': signature['id']})


def cache_allowed(question, history=None):
    public = json.loads((ROOT / 'data/public_cache_questions.json').read_text(encoding='utf-8'))
    return not history and question.strip() in public and not settings.DEMO_MODE


class AnswerCache:
    def __init__(self, path, ttl=300):
        self.path, self.ttl = Path(path), ttl
        if not 0 < ttl <= 86400:
            raise ValueError('캐시 유효 시간은 1~86400초입니다.')
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.connect() as db:
            db.execute('CREATE TABLE IF NOT EXISTS answers (key TEXT PRIMARY KEY, expires REAL NOT NULL, value TEXT NOT NULL)')

    def connect(self):
        return sqlite3.connect(self.path, timeout=10)

    def get(self, key, now=None):
        now = time.time() if now is None else now
        with self.connect() as db:
            row = db.execute('SELECT expires,value FROM answers WHERE key=?', (key,)).fetchone()
            if row is None:
                return None
            if row[0] <= now:
                db.execute('DELETE FROM answers WHERE key=?', (key,))
                return None
            try:
                return json.loads(row[1])
            except (ValueError, TypeError):
                db.execute('DELETE FROM answers WHERE key=?', (key,))
                return None

    def put(self, key, value, now=None):
        now = time.time() if now is None else now
        with self.connect() as db:
            db.execute('INSERT OR REPLACE INTO answers VALUES (?,?,?)',
                       (key, now+self.ttl, json.dumps(value, ensure_ascii=False)))

    def clear(self):
        with self.connect() as db:
            count = db.execute('SELECT COUNT(*) FROM answers').fetchone()[0]
            db.execute('DELETE FROM answers')
        return count