File size: 5,454 Bytes
7c6ffa6 | 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | from __future__ import annotations
import hashlib
import json
from datetime import datetime, timezone
from typing import Any
from sqlalchemy.orm import Session
from app.core.database import SessionLocal
from app.models.generation_cache import GenerationCache
from app.services.provider_quota import record_usage
from app.services.provider_registry import normalize_task_type
def stable_hash(value: Any) -> str:
if isinstance(value, str):
payload = value
else:
payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def scene_plan_cache_key(
*,
document_id: str,
material_hash: str,
video_mode: str,
target_duration_seconds: int | float,
language: str,
evidence_level: str,
prompt_version: str,
) -> str:
return _key(
"scene_plan",
{
"document_id": document_id,
"material_hash": material_hash,
"video_mode": video_mode,
"target_duration_seconds": target_duration_seconds,
"language": language,
"evidence_level": evidence_level,
"prompt_version": prompt_version,
},
)
def tts_cache_key(*, provider: str, voice: str, language: str, narration_text: str) -> str:
return _key(
"tts",
{
"provider": provider,
"voice": voice,
"language": language,
"narration_text": narration_text,
},
)
def study_material_cache_key(
*,
document_id: str,
content_hash: str,
task_type: str,
evidence_level: str,
prompt_version: str,
) -> str:
return _key(
normalize_task_type(task_type),
{
"document_id": document_id,
"content_hash": content_hash,
"task_type": normalize_task_type(task_type),
"evidence_level": evidence_level,
"prompt_version": prompt_version,
},
)
def image_asset_cache_key(*, prompt_hash: str, style: str, aspect_ratio: str) -> str:
return _key(
"image_asset",
{
"prompt_hash": prompt_hash,
"style": style,
"aspect_ratio": aspect_ratio,
},
)
def get_cached_generation(
*,
cache_key: str,
task_type: str,
provider: str,
user_id: str | None = None,
db: Session | None = None,
) -> GenerationCache | None:
session, close = _db_or_new(db)
try:
cached = session.get(GenerationCache, cache_key)
if cached is None:
return None
if cached.task_type != normalize_task_type(task_type):
return None
if cached.expires_at is not None and _as_aware(cached.expires_at) <= datetime.now(timezone.utc):
return None
record_usage(
provider=provider,
task_type=task_type,
request_units=0,
response_units=0,
estimated_cost_usd=0,
status="success",
user_id=user_id,
cache_hit=True,
db=session,
)
if close:
session.commit()
session.refresh(cached)
return cached
finally:
if close:
session.close()
def store_generation_cache(
*,
cache_key: str,
task_type: str,
provider: str,
input_hash: str,
output_json: dict[str, Any] | None = None,
output_text: str | None = None,
output_file_path: str | None = None,
metadata_json: dict[str, Any] | None = None,
expires_at: datetime | None = None,
db: Session | None = None,
) -> GenerationCache:
session, close = _db_or_new(db)
try:
cached = session.get(GenerationCache, cache_key)
if cached is None:
cached = GenerationCache(cache_key=cache_key)
cached.task_type = normalize_task_type(task_type)
cached.provider = provider
cached.input_hash = input_hash
cached.output_json = output_json
cached.output_text = output_text
cached.output_file_path = output_file_path
cached.metadata_json = metadata_json or {}
cached.expires_at = expires_at
session.add(cached)
session.commit()
session.refresh(cached)
return cached
finally:
if close:
session.close()
def invalidate_document_generation_cache(*, document_id: str, db: Session | None = None) -> int:
session, close = _db_or_new(db)
try:
rows = session.query(GenerationCache).all()
deleted = 0
for row in rows:
metadata = row.metadata_json or {}
key_mentions_document = document_id in row.cache_key
metadata_mentions_document = metadata.get("document_id") == document_id
if key_mentions_document or metadata_mentions_document:
session.delete(row)
deleted += 1
session.commit()
return deleted
finally:
if close:
session.close()
def _key(prefix: str, payload: dict[str, Any]) -> str:
return f"{prefix}:{stable_hash(payload)}"
def _db_or_new(db: Session | None) -> tuple[Session, bool]:
if db is not None:
return db, False
return SessionLocal(), True
def _as_aware(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
|