Download src/core/cache_utils.py from AnhLee0/AI-Coach: direct link, hf CLI and curl.
- Browser
- Download file 1.6 kB
-
https://huggingface.co/spaces/AnhLee0/AI-Coach/resolve/main/src/core/cache_utils.py
- Command line
-
hf download hf://spaces/AnhLee0/AI-Coach/src/core/cache_utils.py
-
curl -L -o cache_utils.py https://huggingface.co/spaces/AnhLee0/AI-Coach/resolve/main/src/core/cache_utils.py
1.6 kB
| import hashlib | |
| import json | |
| import os | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| CACHE_DIR = "outputs/cache" | |
| def get_file_hash(file_path): | |
| """Calculates MD5 hash of a file.""" | |
| hasher = hashlib.md5() | |
| with open(file_path, 'rb') as f: | |
| buf = f.read(65536) | |
| while len(buf) > 0: | |
| hasher.update(buf) | |
| buf = f.read(65536) | |
| return hasher.hexdigest() | |
| def get_cache_path(file_path, suffix=".json"): | |
| """Returns the path to the cache file based on the input file's MD5 hash.""" | |
| if not os.path.exists(CACHE_DIR): | |
| os.makedirs(CACHE_DIR) | |
| file_hash = get_file_hash(file_path) | |
| return os.path.join(CACHE_DIR, f"{file_hash}{suffix}") | |
| def save_to_cache(file_path, data): | |
| """Saves data to a cache file.""" | |
| cache_path = get_cache_path(file_path) | |
| try: | |
| with open(cache_path, 'w', encoding='utf-8') as f: | |
| json.dump(data, f, ensure_ascii=False) | |
| logger.info(f"Saved landmarks to cache: {cache_path}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Error saving to cache: {e}") | |
| return False | |
| def load_from_cache(file_path): | |
| """Loads data from a cache file if it exists.""" | |
| cache_path = get_cache_path(file_path) | |
| if os.path.exists(cache_path): | |
| try: | |
| with open(cache_path, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| logger.info(f"Loaded landmarks from cache: {cache_path}") | |
| return data | |
| except Exception as e: | |
| logger.error(f"Error loading from cache: {e}") | |
| return None | |