Datasets:
Download code/export_hub.py from rvashurin/coqar-clarifications: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/datasets/rvashurin/coqar-clarifications/resolve/main/code/export_hub.py
- Command line
-
hf download hf://datasets/rvashurin/coqar-clarifications/code/export_hub.py
-
curl -L -o export_hub.py https://huggingface.co/datasets/rvashurin/coqar-clarifications/resolve/main/code/export_hub.py
20.4 kB
| """Build two lossless placement configurations from the frozen paired CoQAR run. | |
| Offline only: this module never generates new model outputs or contacts the Hub. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| from pathlib import Path | |
| import platform | |
| import shlex | |
| import shutil | |
| import socket | |
| import subprocess | |
| import sys | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| ROOT = Path(__file__).resolve().parent | |
| VERSION = "coqar-placements-v1" | |
| BUNDLED_RENAMES = {"test_export_hub.py": "check_export_hub.py", | |
| "test_publish_hub.py": "check_publish_hub.py"} | |
| SOURCE_HASHES = { | |
| "subset.json": "2f4bd4532b5844658c92556f71e27ebce81d529ad49936d63f5ab7e213183c58", | |
| "original_validation.json": "a0166311735f6e2e41472bb1e92fddaf7b168993b77e6f55857cdcaddb18bee7", | |
| "modified_validation.json": "c245e77812226e6e80732d587c84ceb037ab6c374f0d38624ebf8d55d9b4ba89", | |
| } | |
| def canonical(value): | |
| return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False) | |
| def digest(path): | |
| h = hashlib.sha256() | |
| with Path(path).open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def save_json(path, value): | |
| Path(path).write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n") | |
| def require(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| def validate_example(example, source): | |
| original = example["original_story"] | |
| require(original == source["story"], "Original passage differs from raw source") | |
| q = next(q for q in source["questions"] if q["turn_id"] == example["turn_id"]) | |
| require(example["question"] == next(s for s in q["paraphrase"] if s.strip()), | |
| "Question differs from the first nonempty rewrite") | |
| a = next(a for a in source["answers"] if a["turn_id"] == example["turn_id"]) | |
| require(a == example["gold_answer_annotation"], "Rationale annotation differs from raw source") | |
| start, end = a["span_start"], a["span_end"] | |
| require(0 <= start < end <= len(original), "Invalid rationale interval") | |
| expected = [s for s in example["sentences"] if s["start"] < end and start < s["end"]] | |
| removed = example["removed_sentences"] | |
| require(removed == expected and bool(removed), "Wrong overlapping sentences") | |
| cursor, fragments = 0, [] | |
| for sentence in removed: | |
| lo, hi = sentence["start"], sentence["end"] | |
| require(cursor <= lo < hi <= len(original), "Unsorted or invalid deletion bounds") | |
| require(original[lo:hi] == sentence["text"], "Deleted sentence text mismatch") | |
| fragments.append(original[cursor:lo]) | |
| cursor = hi | |
| fragments.append(original[cursor:]) | |
| require("".join(fragments) == example["modified_story"], "Retained passage mismatch") | |
| return removed[0]["start"], removed[-1]["end"] | |
| def place_addition(story, raw_addition, placement, anchor): | |
| """Return reversible insertion metadata without changing existing characters.""" | |
| require(placement in ("appended", "inserted"), "Unknown placement") | |
| require(type(anchor) is int and 0 <= anchor <= len(story), "Invalid insertion offset") | |
| addition = raw_addition.strip() | |
| if placement == "appended": | |
| anchor = len(story) | |
| prefix = ("\n\n" if placement == "appended" or anchor > 0 else "") if addition else "" | |
| suffix = "\n\n" if addition and placement == "inserted" and anchor < len(story) else "" | |
| block = prefix + addition + suffix | |
| text = story[:anchor] + block + story[anchor:] | |
| result = { | |
| "applied_addition": addition, "clarified_story": text, "unchanged": text == story, | |
| "inserted_block_start": anchor, "inserted_block_end": anchor + len(block), | |
| "addition_start": anchor + len(prefix), "addition_end": anchor + len(prefix) + len(addition), | |
| "prefix_separator": prefix, "suffix_separator": suffix, | |
| } | |
| require(text[:result["inserted_block_start"]] + text[result["inserted_block_end"]:] == story, | |
| "Insertion is not reversible") | |
| require(text[result["addition_start"]:result["addition_end"]] == addition, | |
| "Inserted content differs from generated addition") | |
| return result | |
| def verify_call(call, story, question, menu=None, selected_id=None): | |
| require(call and call["status"] == "completed", "Missing completed generation call") | |
| request = call["request"] | |
| require(hashlib.sha256(canonical(request).encode()).hexdigest() == call["request_sha256"], | |
| "Generation request hash mismatch") | |
| require(json.loads(call["text"]) == call["parsed"], "Generation response mismatch") | |
| require(request["input"].startswith("Input JSON:\n"), "Unexpected request input") | |
| payload = json.loads(request["input"][len("Input JSON:\n"):]) | |
| expected = {"story": story, "question": question} | |
| if menu is not None: | |
| expected.update(menu=menu, selected_id=selected_id) | |
| require(payload == expected, "Unexpected model-visible fields or values") | |
| return request | |
| def recovery_record(row): | |
| if not row.get("recovery_history"): | |
| return None | |
| def trim_call(call): | |
| return {k: call.get(k) for k in ("id", "attempt_id", "status", "request", "request_sha256", "text")} | |
| return { | |
| "initial_failed_stages": row["initial_failed_stages"], | |
| "history": row["recovery_history"], | |
| "initial_failed_stage_calls": {stage: [trim_call(c) for c in calls] | |
| for stage, calls in row["initial_failed_stage_calls"].items()}, | |
| "recovery_attempt_calls": [trim_call(c) for c in row.get("recovery_attempt_calls", [])], | |
| "original_result_sha256": row["recovery_original_sha256"], | |
| } | |
| def make_row(example, saved, condition, placement, anchors): | |
| damaged = condition == "damaged" | |
| story = example["modified_story" if damaged else "original_story"] | |
| require(saved["input_story"] == story and saved["question"] == example["question"], | |
| "Saved generation uses different inputs") | |
| require(saved["original_story"] == example["original_story"] | |
| and saved["modified_story"] == example["modified_story"], "Source pair differs") | |
| require(not saved.get("missing") and len(saved["clarifications"]) == 5, "Incomplete source row") | |
| anchor = len(story) if placement == "appended" else anchors[0 if damaged else 1] | |
| menu = saved["interpretation_stage"]["menu"] | |
| menu_call = saved["interpretation_stage"]["call"] | |
| verify_call(menu_call, story, example["question"]) | |
| recovery = recovery_record(saved) | |
| samples = [] | |
| for index, sample in enumerate(saved["clarifications"]): | |
| require(sample["sample_index"] == index and sample["valid_format"], "Invalid sample ordering/format") | |
| require(not sample["provenance_errors"], "Source sample has provenance errors") | |
| request = verify_call(sample["generation_call"], story, example["question"], menu, sample["selected_id"]) | |
| parsed = sample["generation_call"]["parsed"] | |
| for key in ("status", "addition", "justification"): | |
| require(sample[key] == parsed[key], "Saved sample differs from raw model output") | |
| expected_append = story + "\n\n" + sample["addition"].strip() if sample["addition"].strip() else story | |
| require(sample["clarified_story"] == expected_append, "Saved appended story differs") | |
| materialized = place_addition(story, sample["addition"], placement, anchor) | |
| if placement == "appended": | |
| require(materialized["clarified_story"] == sample["clarified_story"], "Appended export differs") | |
| samples.append({ | |
| **{k: sample[k] for k in ("sample_index", "status", "addition", "justification", "selected_id", | |
| "uniform_draw", "seed_text", "normalization")}, | |
| **materialized, "generation_request_json": canonical(request), | |
| "generation_response_text": sample["generation_call"]["text"], | |
| "audit_json": canonical(sample["audit_assessment"]) if sample.get("audit_assessment") else None, | |
| "audit_applies_to_placement": "appended" if sample.get("audit_assessment") else None, | |
| "contract_errors": sample.get("business_contract_errors", []), | |
| }) | |
| return { | |
| "id": example["id"] + ":" + condition, "pair_id": example["id"], | |
| "source_split": example["split"], "story_id": example["story_id"], "turn_id": example["turn_id"], | |
| "source": example["source"], "condition": condition, "is_underspecified": damaged, | |
| "placement": placement, "question": example["question"], "input_story": story, | |
| "original_story": example["original_story"], "damaged_story": example["modified_story"], | |
| "gold_answer_original": example["gold_answer"], | |
| "rationale_start": example["span_diagnostics"]["start"], | |
| "rationale_end": example["span_diagnostics"]["end"], | |
| "rationale_text": example["span_diagnostics"]["offset_text"], | |
| "rationale_sentences": example["removed_sentences"], | |
| "removed_sentences": example["removed_sentences"] if damaged else [], | |
| "insertion_offset": anchor, | |
| "menu_json": canonical(menu), "menu_request_json": canonical(menu_call["request"]), | |
| "menu_response_text": menu_call["text"], | |
| "menu_contract_errors": saved["interpretation_stage"]["business_contract_errors"], | |
| "recovery_kind": "+".join(saved["initial_failed_stages"]) if recovery else None, | |
| "recovery_history_json": canonical(recovery) if recovery else None, | |
| "clarifications": samples, | |
| } | |
| def arrow_schema(metadata): | |
| sentence = pa.struct([(k, t) for k, t in (("sentence_index", pa.int64()), ("start", pa.int64()), | |
| ("end", pa.int64()), ("text", pa.string()))]) | |
| sample = pa.struct([ | |
| ("sample_index", pa.int64()), ("status", pa.string()), ("addition", pa.string()), | |
| ("applied_addition", pa.string()), ("justification", pa.string()), ("clarified_story", pa.string()), | |
| ("unchanged", pa.bool_()), ("selected_id", pa.string()), ("uniform_draw", pa.float64()), | |
| ("seed_text", pa.string()), ("normalization", pa.float64()), | |
| *[(key, pa.int64()) for key in ("inserted_block_start", "inserted_block_end", "addition_start", "addition_end")], | |
| *[(key, pa.string()) for key in ("prefix_separator", "suffix_separator", "generation_request_json", | |
| "generation_response_text", "audit_json", "audit_applies_to_placement")], | |
| ("contract_errors", pa.list_(pa.string())), | |
| ]) | |
| fields = [(k, pa.string()) for k in ("id", "pair_id", "source_split", "story_id")] | |
| fields += [("turn_id", pa.int64()), ("source", pa.string()), ("condition", pa.string()), | |
| ("is_underspecified", pa.bool_())] | |
| fields += [(k, pa.string()) for k in ("placement", "question", "input_story", "original_story", | |
| "damaged_story", "gold_answer_original")] | |
| fields += [("rationale_start", pa.int64()), ("rationale_end", pa.int64()), ("rationale_text", pa.string()), | |
| ("rationale_sentences", pa.list_(sentence)), ("removed_sentences", pa.list_(sentence)), | |
| ("insertion_offset", pa.int64())] | |
| fields += [(k, pa.string()) for k in ("menu_json", "menu_request_json", "menu_response_text")] | |
| fields += [("menu_contract_errors", pa.list_(pa.string())), ("recovery_kind", pa.string()), | |
| ("recovery_history_json", pa.string()), ("clarifications", pa.list_(sample))] | |
| return pa.schema(fields, metadata={b"coqar_provenance": canonical(metadata).encode()}) | |
| def capture_metadata(run, repo_id, manifest): | |
| def git(*args): | |
| return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() | |
| require(not git("status", "--porcelain", "--untracked-files=all"), "Commit export code before generating artifacts") | |
| commit = git("rev-parse", "HEAD") | |
| sources = {name: digest(run / name) for name in (*SOURCE_HASHES, "manifest.json")} | |
| for name, expected in SOURCE_HASHES.items(): | |
| require(sources[name] == expected, f"Frozen source changed: {name}") | |
| for name, expected in manifest["implementation"].items(): | |
| require(digest(ROOT / name) == expected, f"Frozen generation code changed: {name}") | |
| publication_id = hashlib.sha256(canonical({"version": VERSION, "sources": sources, "commit": commit}).encode()).hexdigest() | |
| return { | |
| "schema_version": VERSION, "publication_id": publication_id, "commit_hash": commit, | |
| "bundled_source_renames": BUNDLED_RENAMES, | |
| "repo": {"path": str(ROOT), "remote": git("config", "--get-regexp", "^remote\\..*\\.url$") if git("remote") else None}, | |
| "git_clean": True, "timestamp_utc": datetime.now(timezone.utc).isoformat(), | |
| "commands": [{"cwd": str(Path.cwd()), "command": shlex.join([sys.executable, *sys.argv])}], | |
| "configs": {"repo_id": repo_id, "visibility": "public", "configurations": ["appended", "inserted"], | |
| "split": "dev", "rows_per_config": 2000, "samples_per_row": 5, | |
| "offsets": "half-open Python Unicode character indices", "empty_additions": "exact input preserved", | |
| "inserted_damaged_anchor": "first removed sentence start", "inserted_undamaged_anchor": "last overlapping sentence end", | |
| "inserted_separators": "two newlines on each nonempty input side; retain all existing whitespace"}, | |
| "dataset": {"name": "CoQAR", "upstream": manifest["dataset"], "source_file_sha256": sources}, | |
| "model": manifest["model"], "generation_commit_hash": manifest["commit_hash"], | |
| "generation_experiment_fingerprint": manifest["experiment_fingerprint"], | |
| "seeds": manifest["seeds"], "prompts": manifest["prompts"], | |
| "environment": {"python": sys.version, "platform": platform.platform(), | |
| "packages": {name: importlib.metadata.version(name) for name in ("pyarrow", "datasets", "huggingface_hub")}}, | |
| "compute": {"hostname": socket.gethostname(), "execution": "local CPU; offline transformation"}, | |
| } | |
| def public_metadata(metadata): | |
| """Keep provenance facts; omit host identity and local absolute paths from Hub files.""" | |
| result = json.loads(canonical(metadata)) | |
| result["repo"]["path"] = "coqar_experiment (absolute local path withheld)" | |
| result["commands"] = [{"cwd": "coqar_experiment", "command": "python export_hub.py --repo-id " + result["configs"]["repo_id"]}] | |
| result["commands_note"] = "Portable equivalent; exact invocation retained in local export_provenance.json" | |
| result["compute"]["hostname"] = "withheld from public release" | |
| for source in result["dataset"]["upstream"]["sources"]: | |
| source["path"] = Path(source["path"]).name | |
| return result | |
| def export_bundle(run, output, repo_id): | |
| manifest = json.loads((run / "manifest.json").read_text()) | |
| metadata = capture_metadata(run, repo_id, manifest) | |
| require(not output.exists() or not any(output.iterdir()), "Output bundle already exists; choose a new directory") | |
| output.mkdir(parents=True, exist_ok=True) | |
| save_json(output.parent / "export_provenance.json", metadata) | |
| metadata = public_metadata(metadata) | |
| subset = json.loads((run / "subset.json").read_text()) | |
| examples = subset["examples"] | |
| require(len(examples) == 1000 and len({e["id"] for e in examples}) == 1000, "Expected 1000 distinct turns") | |
| raw_path = ROOT / manifest["configs"]["source_path"] | |
| require(digest(raw_path) == manifest["dataset"]["sources"][0]["sha256"], "Raw source hash changed") | |
| raw = {s["id"]: s for s in json.loads(raw_path.read_text())["data"]} | |
| anchors = {e["id"]: validate_example(e, raw[e["story_id"]]) for e in examples} | |
| rows = {"appended": [], "inserted": []} | |
| for internal, condition in (("original", "undamaged"), ("modified", "damaged")): | |
| source = json.loads((run / f"{internal}_validation.json").read_text())["samples"] | |
| require(set(source) == {e["id"] for e in examples}, "Export membership differs from subset") | |
| for example in examples: | |
| pair = [make_row(example, source[example["id"]], condition, placement, anchors[example["id"]]) | |
| for placement in rows] | |
| for sample_a, sample_b in zip(pair[0]["clarifications"], pair[1]["clarifications"]): | |
| for key in ("addition", "generation_request_json", "generation_response_text", "selected_id", "uniform_draw"): | |
| require(sample_a[key] == sample_b[key], "Placement changed generation or sampling") | |
| for placement, row in zip(rows, pair): | |
| rows[placement].append(row) | |
| del source | |
| stats = {} | |
| for placement, records in rows.items(): | |
| path = output / "data" / placement / "dev.parquet" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| table = pa.Table.from_pylist(records, schema=arrow_schema({**metadata, "placement": placement})) | |
| pq.write_table(table, path, compression="zstd", row_group_size=25) | |
| loaded = pq.read_table(path) | |
| require(loaded.to_pylist() == records, "Parquet round trip changed data") | |
| require(json.loads(loaded.schema.metadata[b"coqar_provenance"])["publication_id"] == metadata["publication_id"], | |
| "Embedded provenance missing") | |
| stats[placement] = {"rows": len(records), "outputs": sum(len(r["clarifications"]) for r in records), | |
| "conditions": dict(Counter(r["condition"] for r in records)), | |
| "unchanged": {c: sum(s["unchanged"] for r in records if r["condition"] == c for s in r["clarifications"]) | |
| for c in ("undamaged", "damaged")}} | |
| shutil.copyfile(ROOT / "hub_dataset_card.md", output / "README.md") | |
| shutil.copyfile(ROOT / "hub_LICENSE.txt", output / "LICENSE") | |
| save_json(output / "provenance.json", metadata) | |
| code = output / "code" | |
| code.mkdir() | |
| names = ["export_hub.py", "publish_hub.py", "test_export_hub.py", "test_publish_hub.py", "requirements-hub.txt", | |
| "hub_dataset_card.md", "hub_LICENSE.txt", "SCALE_RUN.md", "build_dataset.py", "scale_prepare.py", "scale_pipeline.py", | |
| "scale_client.py", "scale_export.py", "scale_recover.py", "scale_recovery_export.py", "scale_costs.py", "run_pilot.py", | |
| "requirements.txt", "configs/coqar_dev1000_low.json", "prompts/latent_v2_menu.txt", "prompts/latent_v2_render.txt", "prompts/audit_samples.txt"] | |
| for name in names: | |
| # Older datasets loaders scan test_* filenames before reading configs; | |
| # keep runnable test sources without advertising a spurious test split. | |
| destination = code / BUNDLED_RENAMES.get(name, name) | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(ROOT / name, destination) | |
| validation = {"metadata": metadata, "passed": True, "configurations": stats, | |
| "checks": ["source hashes", "all 1000 source reconstructions", "all 10000 generation requests and outputs", | |
| "exact saved appended outputs", "reversible insertion for every output", "paired additions and draws", | |
| "Parquet round trip and embedded provenance"], | |
| "published_files": {str(p.relative_to(output)): digest(p) for p in sorted(output.rglob("*")) if p.is_file()}} | |
| save_json(output / "validation.json", validation) | |
| return {"bundle": str(output), "publication_id": metadata["publication_id"], "configurations": stats, | |
| "bytes": sum(p.stat().st_size for p in output.rglob("*") if p.is_file())} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--run-dir", type=Path, default=ROOT / "results/dev1000_low_seed20260911") | |
| parser.add_argument("--output-dir", type=Path, default=ROOT / "results/huggingface_coqar_v1") | |
| parser.add_argument("--repo-id", default="rvashurin/coqar-clarifications") | |
| args = parser.parse_args() | |
| print(json.dumps(export_bundle(args.run_dir.resolve(), args.output_dir.resolve(), args.repo_id), indent=2)) | |
| if __name__ == "__main__": | |
| main() | |