Add caching functionality, and have Tex and Text both use it for saved svg strings

This commit is contained in:
Grant Sanderson
2024-12-04 19:51:01 -06:00
parent 88370d4d5d
commit 129e512b0c
7 changed files with 64 additions and 46 deletions

33
manimlib/utils/cache.py Normal file
View File

@ -0,0 +1,33 @@
import appdirs
import os
from diskcache import Cache
from contextlib import contextmanager
CACHE_SIZE = 1e9 # 1 Gig
def get_cached_value(key, value_func, message=""):
cache_dir = appdirs.user_cache_dir("manim")
cache = Cache(cache_dir, size_limit=CACHE_SIZE)
value = cache.get(key)
if value is None:
with display_during_execution(message):
value = value_func()
cache.set(key, value)
return value
@contextmanager
def display_during_execution(message: str):
# Merge into a single line
to_print = message.replace("\n", " ")
max_characters = os.get_terminal_size().columns - 1
if len(to_print) > max_characters:
to_print = to_print[:max_characters - 3] + "..."
try:
print(to_print, end="\r")
yield
finally:
print(" " * len(to_print), end="\r")