File size: 926 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any


@dataclass
class DiskCache:
    """Simple JSON-on-disk cache for reproducible intermediate artifacts."""

    cache_dir: Path

    def __post_init__(self) -> None:
        self.cache_dir.mkdir(parents=True, exist_ok=True)

    def _path(self, key: str) -> Path:
        safe_key = key.replace("/", "_")
        return self.cache_dir / f"{safe_key}.json"

    def set(self, key: str, value: Any) -> Path:
        target = self._path(key)
        with target.open("w", encoding="utf-8") as handle:
            json.dump(value, handle, indent=2)
        return target

    def get(self, key: str) -> Any | None:
        target = self._path(key)
        if not target.exists():
            return None
        with target.open("r", encoding="utf-8") as handle:
            return json.load(handle)