FastAPI-Img2CSV / cache.py
utkarsh134's picture
Upload cache.py
3d687fc verified
Raw History Blame
2.73 kB
import time
import uuid
from typing import Dict, Tuple, Optional
# Simple in-memory cache
class TextractCache:
def __init__(self, expiry_seconds: int = 3600): # Default expiry: 1 hour
self._cache: Dict[str, Tuple[str, float]] = {}
self._id_mapping: Dict[str, str] = {} # Maps extraction IDs to file hashes
self._expiry_seconds = expiry_seconds
def get(self, key: str) -> Optional[str]:
"""Get cached text if it exists and hasn't expired"""
# Check if key is an extraction ID and map it to file hash if so
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:
# Clean up expired entry
del self._cache[key]
# Clean up any ID mappings to this hash
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())
# Generate a unique ID for this extraction
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:
# Check if key is an extraction ID
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]
# Clean up any ID mappings to this hash
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
# Singleton instance
textract_cache = TextractCache()