1010from PIL import Image
1111import tifffile as tiff
1212
13- from ai_agent .utils .cache_db import get_cache_db
13+ from ai_agent .utils .cache_db import CacheDB , get_cache_db
1414
1515# ---------------------------------------------------------------------------
1616# SQLite-backed metadata cache (keyed by resolved-path + mtime + size)
1717# Avoids re-reading large files (e.g. TIFF stacks) on every retrieval call.
18+ #
19+ # PRIVACY NOTE: DICOM-derived metadata can contain sensitive identifying
20+ # fields (Study/Series descriptions, institution names, patient context).
21+ # By default the metadata namespace uses an in-memory-only CacheDB so
22+ # nothing is written to disk. Set IMAGE_META_CACHE_PERSIST=1 to opt into
23+ # on-disk persistence (e.g. for long-running servers with large TIFF stacks).
1824# ---------------------------------------------------------------------------
1925_META_CACHE_MAX = int (os .getenv ("IMAGE_META_CACHE_MAX" , "128" ))
26+ _META_CACHE_PERSIST = os .getenv ("IMAGE_META_CACHE_PERSIST" , "0" ).strip () == "1"
2027
2128_META_NS = "meta"
2229
2330_meta_log = __import__ ("logging" ).getLogger ("cache_db.meta" )
2431
32+ # In-memory-only DB used when persistence is disabled (the default).
33+ _meta_mem_db : CacheDB | None = None if _META_CACHE_PERSIST else CacheDB (":memory:" )
34+
35+
36+ def _get_meta_db () -> CacheDB :
37+ """Return the CacheDB instance to use for image metadata."""
38+ return get_cache_db () if _META_CACHE_PERSIST else _meta_mem_db # type: ignore[return-value]
39+
2540
2641def _meta_cache_key (p : Path ) -> str :
2742 """Stable cache key derived from resolved path, mtime, and size."""
@@ -34,15 +49,15 @@ def _meta_cache_key(p: Path) -> str:
3449
3550def _meta_cache_get (key : str ) -> Optional [str ]:
3651 try :
37- return get_cache_db ().get (_META_NS , key )
52+ return _get_meta_db ().get (_META_NS , key )
3853 except Exception :
3954 _meta_log .warning ("Metadata cache get failed; skipping cache." , exc_info = True )
4055 return None
4156
4257
4358def _meta_cache_set (key : str , value : str ) -> None :
4459 try :
45- get_cache_db ().set (_META_NS , key , value , max_entries = _META_CACHE_MAX )
60+ _get_meta_db ().set (_META_NS , key , value , max_entries = _META_CACHE_MAX )
4661 except Exception :
4762 _meta_log .warning ("Metadata cache set failed; continuing without caching." , exc_info = True )
4863
0 commit comments