File size: 3,397 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""JSON and JSONL I/O helpers."""

import json
import hashlib
import os
from pathlib import Path
import tempfile
from typing import TypeVar, Type

from pydantic import BaseModel

T = TypeVar("T", bound=BaseModel)


def sha256_file(path: Path) -> str:
    """Hash files in bounded memory, including transferable image payloads."""
    digest = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def append_jsonl(path: Path, item: BaseModel) -> None:
    """Append a single Pydantic model as one JSON line."""
    with open(path, "a") as f:
        f.write(item.model_dump_json() + "\n")


def write_jsonl(path: Path, items: list[BaseModel]) -> None:
    """Write multiple Pydantic models as JSONL (append mode)."""
    with open(path, "a") as f:
        for item in items:
            f.write(item.model_dump_json() + "\n")


def write_jsonl_atomic(path: Path, items: list[BaseModel]) -> None:
    """Replace a JSONL artifact atomically rather than appending to it."""
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
    temporary_path = Path(temporary)
    try:
        os.fchmod(fd, 0o644)
        with os.fdopen(fd, "w") as f:
            for item in items:
                f.write(item.model_dump_json() + "\n")
            f.flush()
            os.fsync(f.fileno())
        os.replace(temporary_path, path)
    except BaseException:
        temporary_path.unlink(missing_ok=True)
        raise


def read_jsonl(path: Path, model_class: Type[T]) -> list[T]:
    """Read a JSONL file and validate each line as a Pydantic model."""
    items: list[T] = []
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line:
                items.append(model_class.model_validate_json(line))
    return items


def write_json(path: Path, data: dict | BaseModel) -> None:
    """Write a dict or Pydantic model to a JSON file."""
    with open(path, "w") as f:
        if isinstance(data, BaseModel):
            f.write(data.model_dump_json(indent=2))
        else:
            json.dump(data, f, indent=2, default=str)


def write_json_atomic(path: Path, data: dict | BaseModel) -> None:
    """Write JSON via an adjacent temporary file, then atomically replace it."""
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
    temporary_path = Path(temporary)
    try:
        # ``mkstemp`` deliberately starts at 0600. Result manifests are moved
        # between a root-run Docker container and the unprivileged host user,
        # so retain the normal JSON-file readability of ``open(..., "w")``.
        os.fchmod(fd, 0o644)
        with os.fdopen(fd, "w") as f:
            if isinstance(data, BaseModel):
                f.write(data.model_dump_json(indent=2))
            else:
                json.dump(data, f, indent=2, default=str)
            f.flush()
            os.fsync(f.fileno())
        os.replace(temporary_path, path)
    except BaseException:
        temporary_path.unlink(missing_ok=True)
        raise


def read_json(path: Path) -> dict:
    """Read a JSON file and return as dict."""
    with open(path) as f:
        return json.load(f)