-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
45 lines (33 loc) · 1.08 KB
/
Copy pathcache.py
File metadata and controls
45 lines (33 loc) · 1.08 KB
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
"""Cache module: LRU-cached token estimator wrapper.
Wraps an existing estimator with content-keyed caching to avoid
redundant estimation of the same text.
"""
from __future__ import annotations
import threading
from collections import OrderedDict
from typing import Callable
def create_cached_estimator(
estimator: Callable[[str], int],
max_size: int = 1000,
) -> Callable[[str], int]:
"""Create a cached token estimator using an LRU cache.
Args:
estimator: The base token estimator to wrap.
max_size: Maximum cache entries (default: 1000).
Returns:
A cached estimator function with the same signature.
"""
cache: OrderedDict[str, int] = OrderedDict()
lock = threading.Lock()
def cached(text: str) -> int:
with lock:
if text in cache:
cache.move_to_end(text)
return cache[text]
result = estimator(text)
with lock:
if len(cache) >= max_size:
cache.popitem(last=False)
cache[text] = result
return result
return cached