File size: 1,143 Bytes
4a8b134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Screening Cache — persists screening results so identical requests skip recomputation.
"""
import json
import os
import hashlib
from typing import Optional

CACHE_DIR = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "data",
    "screening_cache"
)


def _ensure_cache_dir():
    os.makedirs(CACHE_DIR, exist_ok=True)


def _cache_key(request) -> str:
    raw = f"{request.disease_name}_{request.top_n_targets}_{request.min_score}_{hash(tuple(request.known_drugs or []))}"
    return hashlib.md5(raw.encode()).hexdigest()


def load_cached_screening(request) -> Optional[dict]:
    path = os.path.join(CACHE_DIR, f"{_cache_key(request)}.json")
    if os.path.exists(path):
        try:
            with open(path) as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return None
    return None


def save_cached_screening(request, data: dict):
    _ensure_cache_dir()
    path = os.path.join(CACHE_DIR, f"{_cache_key(request)}.json")
    try:
        with open(path, "w") as f:
            json.dump(data, f, indent=2)
    except IOError:
        pass