Skip to content

Commit

Permalink
Method to resize cache
Browse files Browse the repository at this point in the history
  • Loading branch information
erikogabrielsson committed Nov 22, 2024
1 parent fe03c53 commit 33b8ded
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
18 changes: 16 additions & 2 deletions wsidicom/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ def __init__(self, maxsize: int):
self._cache: Dict[CacheKeyType, CacheItemType] = {}
self._maxsize = maxsize

@property
def maxsize(self) -> int:
return self._maxsize

def get(self, key: CacheKeyType) -> Optional[CacheItemType]:
with self._lock:
item = self._cache.pop(key, None)
Expand All @@ -45,6 +49,13 @@ def clear(self) -> None:
with self._lock:
self._cache.clear()

def resize(self, maxsize: int) -> None:
with self._lock:
self._maxsize = maxsize
if len(self._cache) > maxsize:
for _ in range(len(self._cache) - maxsize):
self._cache.pop(next(iter(self._cache)))


class FrameCache(Generic[CacheItemType]):
def __init__(self, size: int):
Expand All @@ -57,7 +68,7 @@ def get_tile_frame(
frame_index: int,
frame_getter: Callable[[int], CacheItemType],
) -> CacheItemType:
if self._size < 1:
if self._lru_cache.maxsize < 1:
return frame_getter(frame_index)
frame = self._lru_cache.get((image_data_id, frame_index))
if frame is None:
Expand All @@ -71,7 +82,7 @@ def get_tile_frames(
frame_indices: Sequence[int],
frames_getter: Callable[[Iterable[int]], Iterator[CacheItemType]],
) -> Iterator[CacheItemType]:
if self._size < 1:
if self._lru_cache.maxsize < 1:
return frames_getter(frame_indices)
cached_frames = {
frame_index: frame
Expand All @@ -96,6 +107,9 @@ def get_tile_frames(
def clear(self) -> None:
self._lru_cache.clear()

def resize(self, size: int) -> None:
self._lru_cache.resize(size)


EncodedFrameCache = FrameCache[bytes]
DecodedFrameCache = FrameCache[Image]
5 changes: 5 additions & 0 deletions wsidicom/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,8 @@ def clear_cache(self) -> None:
"""Clear the frame caches."""
self._decoded_frame_cache.clear()
self._encoded_frame_cache.clear()

def resize_cache(self, size: int) -> None:
"""Clear the frame caches."""
self._decoded_frame_cache.resize(size)
self._encoded_frame_cache.resize(size)
4 changes: 4 additions & 0 deletions wsidicom/wsidicom.py
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,10 @@ def clear_cache(self):
"""Clear cache of encoded and decoded tiles."""
self._source.clear_cache()

def resize_cache(self, size: int):
"""Resize cache of encoded and decoded tiles."""
self._source.resize_cache(size)

def _validate_collection(self) -> SlideUids:
"""
Check that no files or instance in collection is duplicate, and, if
Expand Down

0 comments on commit 33b8ded

Please sign in to comment.