utkarsh134 commited on
Commit
3d687fc
·
verified ·
1 Parent(s): bec3131

Upload cache.py

Browse files
Files changed (1) hide show
  1. cache.py +72 -0
cache.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import uuid
3
+ from typing import Dict, Tuple, Optional
4
+
5
+
6
+ # Simple in-memory cache
7
+ class TextractCache:
8
+ def __init__(self, expiry_seconds: int = 3600): # Default expiry: 1 hour
9
+ self._cache: Dict[str, Tuple[str, float]] = {}
10
+ self._id_mapping: Dict[str, str] = {} # Maps extraction IDs to file hashes
11
+ self._expiry_seconds = expiry_seconds
12
+
13
+ def get(self, key: str) -> Optional[str]:
14
+ """Get cached text if it exists and hasn't expired"""
15
+ # Check if key is an extraction ID and map it to file hash if so
16
+ if key in self._id_mapping:
17
+ key = self._id_mapping[key]
18
+
19
+ if key in self._cache:
20
+ text, timestamp = self._cache[key]
21
+ if time.time() - timestamp < self._expiry_seconds:
22
+ return text
23
+ else:
24
+ # Clean up expired entry
25
+ del self._cache[key]
26
+ # Clean up any ID mappings to this hash
27
+ self._id_mapping = {
28
+ k: v for k, v in self._id_mapping.items() if v != key
29
+ }
30
+ return None
31
+
32
+ def set(self, key: str, text: str) -> str:
33
+ """Cache extracted text with current timestamp and return a unique ID"""
34
+ self._cache[key] = (text, time.time())
35
+
36
+ # Generate a unique ID for this extraction
37
+ extraction_id = str(uuid.uuid4())
38
+ self._id_mapping[extraction_id] = key
39
+
40
+ return extraction_id
41
+
42
+ def clear(self, key: str = None) -> None:
43
+ """Clear a specific entry or the entire cache"""
44
+ if key is not None:
45
+ # Check if key is an extraction ID
46
+ if key in self._id_mapping:
47
+ file_hash = self._id_mapping[key]
48
+ if file_hash in self._cache:
49
+ del self._cache[file_hash]
50
+ del self._id_mapping[key]
51
+ elif key in self._cache:
52
+ del self._cache[key]
53
+ # Clean up any ID mappings to this hash
54
+ self._id_mapping = {
55
+ k: v for k, v in self._id_mapping.items() if v != key
56
+ }
57
+ else:
58
+ self._cache.clear()
59
+ self._id_mapping.clear()
60
+
61
+ def is_valid_id(self, extraction_id: str) -> bool:
62
+ """Check if an extraction ID exists and is valid"""
63
+ if extraction_id in self._id_mapping:
64
+ file_hash = self._id_mapping[extraction_id]
65
+ if file_hash in self._cache:
66
+ _, timestamp = self._cache[file_hash]
67
+ return time.time() - timestamp < self._expiry_seconds
68
+ return False
69
+
70
+
71
+ # Singleton instance
72
+ textract_cache = TextractCache()