File size: 2,886 Bytes
c512e69
 
 
 
 
 
 
 
 
 
 
 
f76c3bf
c512e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8867798
 
 
 
 
 
 
 
c512e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f76c3bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c512e69
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""In-memory response cache of the Spaces (agents/embedspeed; user decision 2026-10-20): a size-bounded LRU of finished
predictions keyed by the prepared layout (ground and conductor geometry, names) and every setting of the request. Entries live
only in this process's memory while the Space runs. TLSQ_RESPONSE_CACHE = max entries (0 = off), TLSQ_RESPONSE_CACHE_MB =
max total size of the pickled entries."""
from __future__ import annotations

import copy
import hashlib
import os
import pickle
import threading
from collections import OrderedDict
from pathlib import Path

_LRU: OrderedDict = OrderedDict()
_LOCK = threading.Lock()
_BYTES = [0]


def _limits() -> tuple:
    return int(os.environ.get("TLSQ_RESPONSE_CACHE", "0")), float(os.environ.get("TLSQ_RESPONSE_CACHE_MB", "1024")) * 2**20


def key(lay, *settings) -> str:
    import shapely
    h = hashlib.sha256(repr((settings, list(lay.names))).encode())
    for g in [lay.ground, *lay.conductors]:
        h.update(shapely.to_wkb(g))
    return h.hexdigest()


def has(lay, settings: tuple) -> bool:
    if _limits()[0] <= 0:
        return False
    k = key(lay, *settings)
    with _LOCK:
        return k in _LRU


def cached(lay, settings: tuple, fn):
    """fn() through the cache (a deep copy is stored and returned, so callers may modify their result)."""
    n, mb = _limits()
    if n <= 0:
        return fn()
    k = key(lay, *settings)
    with _LOCK:
        if k in _LRU:
            _LRU.move_to_end(k)
            res = copy.deepcopy(_LRU[k][0])
            if isinstance(res.get("timing_s"), dict):
                res["timing_s"]["response_cache_hit"] = True
            return res
    res = fn()
    size = len(pickle.dumps(res, protocol=5))
    if size > mb:
        return res
    with _LOCK:
        _LRU[k] = (copy.deepcopy(res), size)
        _BYTES[0] += size
        while len(_LRU) > n or _BYTES[0] > mb:
            _, (_, s) = _LRU.popitem(last=False)
            _BYTES[0] -= s
    return res


def dump(path) -> int:
    """Pickle the entries (image build: the bundled examples, loaded back by load_items + put_many at start)."""
    with _LOCK:
        items = list(_LRU.items())
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_bytes(pickle.dumps(items, protocol=5))
    return len(items)


def load_items(path) -> list:
    return pickle.loads(Path(path).read_bytes())


def put_many(items) -> int:
    n, mb = _limits()
    if n <= 0:
        return 0
    with _LOCK:
        for k, (res, size) in items:
            if k not in _LRU:
                _LRU[k] = (res, size)
                _BYTES[0] += size
        while len(_LRU) > n or _BYTES[0] > mb:
            _, (_, s) = _LRU.popitem(last=False)
            _BYTES[0] -= s
        return len(_LRU)


def stats() -> dict:
    with _LOCK:
        return {"entries": len(_LRU), "mb": _BYTES[0] / 2**20}