File size: 2,222 Bytes
c7abc3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()