Research-Stack/4-Infrastructure/lib/jsonl.py
Devin AI e5f04ee6c3 refactor(infra): extract shared utilities from duplicated code patterns
Create 4-Infrastructure/lib/ with canonical implementations of:
- hashing.py: sha256_bytes, sha256_text, sha256_file
- q16.py: Q16_16 fixed-point constants and arithmetic
- jsonl.py: load_json, load_jsonl, write_jsonl, stable_json, canonical_json_bytes
- fraction_utils.py: Fraction serialization helpers for hardware probes

Refactor 66 files across 4-Infrastructure/{hardware,shim,infra} and
5-Applications/{scripts,tools-scripts,hutter_prize,text-to-cad} to import
from the shared library instead of maintaining local copies.

4-Infrastructure/auto/lib/q16.py now re-exports from lib.q16.

Net: -743 lines (490 added, 1233 removed)

Build: not applicable (Python-only change, py_compile verified on all 71 files)
Co-Authored-By: Allaun Silverfox <bigdataiscoming+9i37y6j2@protonmail.com>
2026-06-15 02:26:45 +00:00

40 lines
1.3 KiB
Python

"""Shared JSON / JSONL I/O and canonical serialization helpers."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def load_json(path: Path) -> dict[str, Any]:
"""Read a JSON file and return its contents as a dict."""
return json.loads(path.read_text(encoding="utf-8"))
def load_jsonl(path: Path) -> list[dict[str, Any]]:
"""Read a JSONL file and return a list of dicts (skips blank lines)."""
rows: list[dict[str, Any]] = []
with path.open("r", encoding="utf-8") as fh:
for line in fh:
s = line.strip()
if s:
rows.append(json.loads(s))
return rows
def write_jsonl(path: Path, rows: list[dict[str, Any]], *, append: bool = False) -> None:
"""Write a list of dicts as JSONL."""
mode = "a" if append else "w"
with path.open(mode, encoding="utf-8") as fh:
for row in rows:
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
def stable_json(obj: Any) -> str:
"""Deterministic JSON string (sorted keys, compact separators, ASCII-safe)."""
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
def canonical_json_bytes(obj: Any) -> bytes:
"""Deterministic JSON as bytes — suitable for hashing."""
return stable_json(obj).encode("utf-8")