File size: 1,603 Bytes
1c58706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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