From aeb789b360220d5716315030ffd3dccfa4864fa0 Mon Sep 17 00:00:00 2001 From: CloudGPU <129925370+cloudgpuapp@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:29:39 +0800 Subject: [PATCH] Add an append-only JSON Lines label store --- README.rst | 10 +++ news/label-store.rst | 3 + src/diffpy/diffchooser/labels.py | 114 +++++++++++++++++++++++++++++++ tests/test_label_store.py | 100 +++++++++++++++++++++++++++ 4 files changed, 227 insertions(+) create mode 100644 news/label-store.rst create mode 100644 src/diffpy/diffchooser/labels.py create mode 100644 tests/test_label_store.py diff --git a/README.rst b/README.rst index 8eeae03..7ef9681 100644 --- a/README.rst +++ b/README.rst @@ -135,3 +135,13 @@ Acknowledgements ---------------- ``diffpy.diffchooser`` is built and maintained with `scikit-package `_. + +Label storage +------------- + +Use ``diffpy.diffchooser.labels.LabelStore(path)`` to append schema-1 +records to a UTF-8 JSON Lines file. ``latest()`` returns the most +recently appended record for each image ID, ``history(image_id)`` returns +all revisions in append order, and ``query(**filters)`` searches current +records by exact field value. Use ``make_image_id(master_file, frame_index)`` +to construct a stable image identifier. diff --git a/news/label-store.rst b/news/label-store.rst new file mode 100644 index 0000000..64724f1 --- /dev/null +++ b/news/label-store.rst @@ -0,0 +1,3 @@ +**Added:** + +* Append and query versioned label records in a JSON Lines file. diff --git a/src/diffpy/diffchooser/labels.py b/src/diffpy/diffchooser/labels.py new file mode 100644 index 0000000..90bfc7f --- /dev/null +++ b/src/diffpy/diffchooser/labels.py @@ -0,0 +1,114 @@ +"""Append-only JSON Lines storage for label records.""" + +import json +from collections.abc import Iterator, Mapping +from pathlib import Path +from typing import Any + +_REQUIRED_FIELDS = { + "schema", + "image_id", + "sample_id", + "puck", + "position", + "run", + "master_file", + "frame_index", + "omega_deg", + "label", + "ice_severity", + "note", + "source", + "labeled_by", + "confidence", + "datetime", + "beamline", + "detector", + "wavelength_A", + "distance_mm", + "beam_center_px", +} + + +def _validate(record: Mapping[str, Any]) -> None: + missing = _REQUIRED_FIELDS.difference(record) + if missing: + raise ValueError(f"Missing label fields: {', '.join(sorted(missing))}") + if type(record["schema"]) is not int or record["schema"] != 1: + raise ValueError("Label schema must be 1") + if not isinstance(record["image_id"], str) or not record["image_id"]: + raise ValueError("image_id must be a nonempty string") + if record["label"] not in ("good", "ice", "empty"): + raise ValueError("label must be good, ice, or empty") + if record["label"] != "ice" and record["ice_severity"] is not None: + raise ValueError("ice_severity must be null for a non-ice label") + if record["source"] not in ("human", "model"): + raise ValueError("source must be human or model") + + +def make_image_id(master_file: str | Path, frame_index: int) -> str: + """Build a label ID from the master file name and a frame index.""" + name = str(master_file).replace("\\", "/").rsplit("/", 1)[-1] + suffix = "_master.h5" + if not name.endswith(suffix) or name == suffix: + raise ValueError("master_file must end with _master.h5") + if type(frame_index) is not int or frame_index < 0: + raise ValueError("frame_index must be a nonnegative integer") + return f"{name.removesuffix(suffix)}_f{frame_index:04d}" + + +class LabelStore: + """Store labels as UTF-8 JSON Lines, with append order defining + recency.""" + + def __init__(self, path: str | Path) -> None: + self.path = Path(path) + + def add(self, record: Mapping[str, Any]) -> None: + """Validate and append a record without rewriting earlier + entries.""" + _validate(record) + line = json.dumps(dict(record), ensure_ascii=False, allow_nan=False) + with self.path.open("a", encoding="utf-8", newline="\n") as stream: + stream.write(line + "\n") + stream.flush() + + def _records(self) -> Iterator[dict[str, Any]]: + try: + stream = self.path.open(encoding="utf-8") + except FileNotFoundError: + return + with stream: + for number, line in enumerate(stream, 1): + if not line.strip(): + continue + try: + record = json.loads(line) + if not isinstance(record, dict): + raise ValueError("label must be a JSON object") + _validate(record) + except ValueError as exc: + raise ValueError( + f"Invalid label at line {number} in {self.path}: {exc}" + ) from exc + yield record + + def latest(self) -> dict[str, dict[str, Any]]: + """Return the most recently appended record for each image + ID.""" + return {record["image_id"]: record for record in self._records()} + + def history(self, image_id: str) -> list[dict[str, Any]]: + """Return the records for one image in append order.""" + return [r for r in self._records() if r["image_id"] == image_id] + + def query(self, **filters: Any) -> list[dict[str, Any]]: + """Match current records by exact field values.""" + return [ + record + for record in self.latest().values() + if all( + key in record and record[key] == value + for key, value in filters.items() + ) + ] diff --git a/tests/test_label_store.py b/tests/test_label_store.py new file mode 100644 index 0000000..0b67133 --- /dev/null +++ b/tests/test_label_store.py @@ -0,0 +1,100 @@ +import json + +import pytest + +from diffpy.diffchooser.labels import LabelStore, make_image_id + + +def record(image_id="sample_f0001", **updates): + return { + "schema": 1, + "image_id": image_id, + "sample_id": "sample", + "puck": "A", + "position": "01", + "run": "0001", + "master_file": "sample_master.h5", + "frame_index": 1, + "omega_deg": 0.0, + "label": "good", + "ice_severity": None, + "note": "", + "source": "human", + "labeled_by": "fixture", + "confidence": None, + "datetime": "2026-12-01T00:00:00+00:00", + "beamline": "fixture", + "detector": "fixture", + "wavelength_A": 1.0, + "distance_mm": 100.0, + "beam_center_px": [10.0, 10.0], + **updates, + } + + +def test_add_latest_history_and_query(tmp_path): + path = tmp_path / "labels.jsonl" + store = LabelStore(path) + assert store.latest() == {} + assert store.history("unknown") == [] + assert store.query(label="good") == [] + old = record(note="first\nline", extra={"fixture": True}) + other = record("sample_f0002") + new = record(label="ice", ice_severity="light") + for entry in (old, other, new): + store.add(entry) + assert [json.loads(line) for line in path.read_text().splitlines()] == [ + old, + other, + new, + ] + assert LabelStore(path).latest() == { + new["image_id"]: new, + other["image_id"]: other, + } + assert store.history(old["image_id"]) == [old, new] + assert store.query(label="ice", source="human") == [new] + assert store.query(label="good") == [other] + + +@pytest.mark.parametrize( + ("changes", "error"), + [ + ({"schema": 2}, "schema"), + ({"image_id": ""}, "image_id"), + ({"label": "other"}, "label"), + ({"ice_severity": "light"}, "ice_severity"), + ({"source": "other"}, "source"), + ], +) +def test_invalid_records_are_not_written(tmp_path, changes, error): + path = tmp_path / "labels.jsonl" + store = LabelStore(path) + with pytest.raises(ValueError, match=error): + store.add(record(**changes)) + missing = record() + del missing["note"] + with pytest.raises(ValueError, match="note"): + store.add(missing) + assert not path.exists() + + +def test_image_id_uses_the_file_name(): + assert make_image_id("/data/example_master.h5", 12) == "example_f0012" + assert ( + make_image_id(r"C:\data\example_master.h5", 10000) == "example_f10000" + ) + with pytest.raises(ValueError, match="master_file"): + make_image_id("example.h5", 1) + with pytest.raises(ValueError, match="frame_index"): + make_image_id("example_master.h5", -1) + + +def test_reports_corrupt_lines(tmp_path): + path = tmp_path / "labels.jsonl" + store = LabelStore(path) + store.add(record()) + with path.open("a", encoding="utf-8") as stream: + stream.write("invalid json\n") + with pytest.raises(ValueError, match="line 2"): + store.latest()