import time import uuid from typing import Dict, Tuple, Optional class TextractCache: def __init__(self, expiry_seconds: int = 3600): self._cache: Dict[str, Tuple[str, float]] = {} self._id_mapping: Dict[str, str] = {} self._expiry_seconds = expiry_seconds def get(self, key: str) -> Optional[str]: """Get cached text if it exists and hasn't expired""" if key in self._id_mapping: key = self._id_mapping[key] if key in self._cache: text, timestamp = self._cache[key] if time.time() - timestamp < self._expiry_seconds: return text else: del self._cache[key] self._id_mapping = { k: v for k, v in self._id_mapping.items() if v != key } return None def set(self, key: str, text: str) -> str: """Cache extracted text with current timestamp and return a unique ID""" self._cache[key] = (text, time.time()) extraction_id = str(uuid.uuid4()) self._id_mapping[extraction_id] = key return extraction_id def clear(self, key: str = None) -> None: """Clear a specific entry or the entire cache""" if key is not None: if key in self._id_mapping: file_hash = self._id_mapping[key] if file_hash in self._cache: del self._cache[file_hash] del self._id_mapping[key] elif key in self._cache: del self._cache[key] self._id_mapping = { k: v for k, v in self._id_mapping.items() if v != key } else: self._cache.clear() self._id_mapping.clear() def is_valid_id(self, extraction_id: str) -> bool: """Check if an extraction ID exists and is valid""" if extraction_id in self._id_mapping: file_hash = self._id_mapping[extraction_id] if file_hash in self._cache: _, timestamp = self._cache[file_hash] return time.time() - timestamp < self._expiry_seconds return False textract_cache = TextractCache()