"""Append consented private-archive records to an existing public dataset.""" from __future__ import annotations import argparse from collections import Counter from hashlib import sha256 import json from pathlib import Path from build_public_dataset09 import _json, _points, _write_jsonl CONTENT_FIELDS = ( "source_partition", "target_display", "target_cells", "target_relations", "formula_cells", "ownership_status", "label_status", "canvas", "strokes", "stroke_count", "point_count", "pressure_available", ) def _rows(path: Path) -> list[dict]: return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] def _fingerprint(row: dict) -> str: payload = {key: row[key] for key in CONTENT_FIELDS} return sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest() def _content(record: dict) -> dict: strokes, point_count = _points(record) return { "source_partition": str(record.get("source") or "unknown"), "target_display": str(record.get("target_display") or ""), "target_cells": record.get("target_cells") or [], "target_relations": record.get("target_relations") or [], "formula_cells": record.get("formula_cells") or [], "ownership_status": str(record.get("ownership_status") or "unreviewed"), "label_status": str(record.get("label_status") or "unknown"), "canvas": record["canvas"], "strokes": strokes, "stroke_count": len(strokes), "point_count": point_count, "pressure_available": any("pressure" in point for stroke in strokes for point in stroke["points"]), } def _next_alias(existing: set[str], prefix: str, count: int) -> list[str]: highest = max((int(value.rsplit("_", 1)[1]) for value in existing), default=0) return [f"{prefix}_{highest + index:03d}" for index in range(1, count + 1)] def append(args: argparse.Namespace) -> dict: dataset = args.dataset_root by_status = {status: _rows(dataset / "data" / f"formulas_{status}.jsonl") for status in ("valid", "pending", "reject")} existing = [row for rows in by_status.values() for row in rows] if len(existing) != args.expected_base_records: raise ValueError(f"expected {args.expected_base_records} base records, found {len(existing)}") existing_by_fingerprint = {_fingerprint(row): row for row in existing} arrival = _json(args.arrival_index)["records"] raw = [] writer_map, session_map = {}, {} for path in sorted(args.archive_root.glob("samples/*/*.json")): record = _json(path) relative = "samples/" + "/".join(path.parts[-2:]) content = _content(record) prior = existing_by_fingerprint.get(_fingerprint(content)) if prior: writer_map[str(record.get("contributor_id") or record["session_id"])] = prior["writer_id"] session_map[str(record["session_id"])] = prior["session_group"] else: raw.append((path, relative, record, content, arrival[relative])) invalid = [relative for _, relative, record, _, _ in raw if record.get("consent_scope") != args.consent_scope] if invalid: raise ValueError(f"records without required consent: {invalid}") new_writers = sorted({str(record.get("contributor_id") or record["session_id"]) for _, _, record, _, _ in raw} - writer_map.keys()) new_sessions = sorted({str(record["session_id"]) for _, _, record, _, _ in raw} - session_map.keys()) writer_map.update(zip(new_writers, _next_alias({row["writer_id"] for row in existing}, "writer", len(new_writers)))) session_map.update(zip(new_sessions, _next_alias({row["session_group"] for row in existing}, "session", len(new_sessions)))) next_id = max(int(row["sample_id"].rsplit("_", 1)[1]) for row in existing) + 1 for offset, (_, _, record, content, review) in enumerate(raw): status = str(review.get("decision") or "pending") if review.get("reviewStatus") == "reviewed" else "pending" if status not in by_status: raise ValueError(f"unexpected review status: {status}") writer_key = str(record.get("contributor_id") or record["session_id"]) row = { "schema": "aiflow-public-math-ink/v1", "sample_id": f"aiflow_{next_id + offset:04d}", "writer_id": writer_map[writer_key], "session_group": session_map[str(record["session_id"])], "quality_status": status, **content, } by_status[status].append(row) for status, rows in by_status.items(): _write_jsonl(dataset / "data" / f"formulas_{status}.jsonl", rows) all_rows = [row for rows in by_status.values() for row in rows] manifest = _json(dataset / "dataset_info.json") manifest.update({ "records": len(all_rows), "quality_status": {status: len(rows) for status, rows in by_status.items()}, "sources": dict(sorted(Counter(row["source_partition"] for row in all_rows).items())), "writers": len({row["writer_id"] for row in all_rows}), "sessions": len({row["session_group"] for row in all_rows}), "target_label_counts": dict(sorted(Counter(str(cell["token"]) for row in all_rows for cell in row["target_cells"]).items())), }) manifest["files"] = {} for path in sorted((dataset / "data").glob("*.jsonl")): manifest["files"][path.name] = {"bytes": path.stat().st_size, "sha256": sha256(path.read_bytes()).hexdigest()} (dataset / "dataset_info.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return {"base_records": len(existing), "appended": len(raw), "total": len(all_rows), "writers": manifest["writers"], "sessions": manifest["sessions"]} def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--archive-root", type=Path, required=True) parser.add_argument("--arrival-index", type=Path, required=True) parser.add_argument("--dataset-root", type=Path, required=True) parser.add_argument("--expected-base-records", type=int, required=True) parser.add_argument("--consent-scope", default="commercial_model_training:aiflow_math_ink") print(json.dumps(append(parser.parse_args()), ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())