Download scripts/build_qa.py from chiron-group/Blog_Authorship_Corpus: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/chiron-group/Blog_Authorship_Corpus/resolve/main/scripts/build_qa.py
- Command line
-
hf download hf://datasets/chiron-group/Blog_Authorship_Corpus/scripts/build_qa.py
-
curl -L -o build_qa.py https://huggingface.co/datasets/chiron-group/Blog_Authorship_Corpus/resolve/main/scripts/build_qa.py
11.1 kB
| #!/usr/bin/env python3 | |
| """Build the per-individual QA dataset (Parquet shards) for the Blog domain. | |
| Input | |
| ----- | |
| ``data_*.zst``: zstd-compressed JSON arrays. Each element is one individual | |
| with fields ``observations`` (list[str]), ``predictions`` (list of | |
| ``{question, ground_truth}``), ``data_source`` (str), ``split`` (str), and | |
| ``extra_info`` (dict). The upstream split label is ignored — this script | |
| re-derives train / val / test deterministically. | |
| Output | |
| ------ | |
| ``<output-dir>/<split>-00000-of-00001.parquet`` for split in {train, val, test}. | |
| Per-row schema | |
| ~~~~~~~~~~~~~~ | |
| :: | |
| observations: list[str] | |
| predictions: list[{question, ground_truth}] | |
| data_source: str ("Blog Authorship Corpus") | |
| split: str ("train" | "val" | "test") | |
| held_out_predictions: list[{question, ground_truth}] # train only; absent on val/test | |
| extra_info: {interview_id, n_observations, n_predictions, [n_held_out_predictions]} | |
| Selection / split policy | |
| ~~~~~~~~~~~~~~~~~~~~~~~~ | |
| * Drop individuals with fewer than ``MIN_OBSERVATIONS`` observations. | |
| * If observations exceed ``MAX_OBSERVATIONS``, deterministically subsample. | |
| * Per individual, shuffle predictions with ``SEED + interview_id`` and split | |
| ~2/3 -> ``predictions`` and ~1/3 -> ``held_out``. | |
| * Drop individuals with fewer than ``MIN_PREDICTIONS`` predictions or fewer | |
| than ``MIN_HELD_OUT`` held-out items. | |
| * Globally shuffle qualified individuals with ``SEED`` and assign 90/5/5 | |
| to train/val/test. | |
| * For val/test, the held-out slice is folded into ``predictions`` so the eval | |
| pool is the union; the ``held_out_predictions`` field is dropped. | |
| Self-contained: depends only on ``pyarrow`` (+ ``zstd`` binary on PATH). | |
| No chiron imports. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import re | |
| import subprocess | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Iterator | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| # --- fixed policy ----------------------------------------------------------- | |
| SEED = 42 | |
| MIN_OBSERVATIONS = 20 | |
| MAX_OBSERVATIONS = 200 | |
| HELD_OUT_FRACTION = 1.0 / 3.0 # 2/3 -> predictions, 1/3 -> held-out | |
| MIN_PREDICTIONS = 5 | |
| MIN_HELD_OUT = 3 | |
| TRAIN_RATIO = 0.9 | |
| VAL_RATIO = 0.05 | |
| TEST_RATIO = 0.05 | |
| DATA_SOURCE = "Blog Authorship Corpus" | |
| # --- helpers ----------------------------------------------------------------- | |
| class _Row: | |
| interview_id: str | |
| observations: list[str] | |
| predictions: list[dict[str, str]] | |
| held_out: list[dict[str, str]] | |
| def _decompress_zst(path: Path) -> bytes: | |
| return subprocess.check_output(["zstd", "-dcf", str(path)]) | |
| def _iter_records(input_dir: Path) -> Iterator[dict]: | |
| files = sorted(input_dir.glob("data_*.zst")) | |
| if not files: | |
| raise SystemExit(f"no data_*.zst files in {input_dir}") | |
| for p in files: | |
| arr = json.loads(_decompress_zst(p)) | |
| for r in arr: | |
| yield r | |
| def _interview_seed(interview_id: str) -> int: | |
| try: | |
| return SEED + int(interview_id) | |
| except (TypeError, ValueError): | |
| return SEED + (hash(str(interview_id)) & 0x7FFFFFFF) | |
| def _normalize_ground_truth(value: str) -> str: | |
| """Return number-only labels; accepts legacy values like 'Option 2'.""" | |
| m = re.search(r"(?:option\s*)?(\d+)", value.strip(), re.IGNORECASE) | |
| if not m: | |
| raise ValueError(f"cannot parse ground_truth: {value!r}") | |
| return m.group(1) | |
| def _record_to_row(rec: dict) -> _Row | None: | |
| extra = rec.get("extra_info") or {} | |
| interview_id = str(extra.get("interview_id") or "") | |
| if not interview_id: | |
| return None | |
| observations = list(rec.get("observations") or []) | |
| predictions = list(rec.get("predictions") or []) | |
| if len(observations) < MIN_OBSERVATIONS: | |
| return None | |
| if not predictions: | |
| return None | |
| rng = random.Random(_interview_seed(interview_id)) | |
| # Cap observations by deterministic subsample (preserve order after sample). | |
| if len(observations) > MAX_OBSERVATIONS: | |
| idxs = sorted(rng.sample(range(len(observations)), MAX_OBSERVATIONS)) | |
| observations = [observations[i] for i in idxs] | |
| # Per-individual split predictions -> (predictions, held_out). | |
| pred_pool = list(predictions) | |
| rng.shuffle(pred_pool) | |
| n_held = max(1, int(round(len(pred_pool) * HELD_OUT_FRACTION))) | |
| n_held = min(n_held, len(pred_pool) - 1) # ensure at least one prediction left | |
| if n_held < 1: | |
| return None | |
| n_pred = len(pred_pool) - n_held | |
| if n_pred < MIN_PREDICTIONS or n_held < MIN_HELD_OUT: | |
| return None | |
| pred_slice = pred_pool[:n_pred] | |
| held_slice = pred_pool[n_pred:] | |
| def _clean(items: list[dict]) -> list[dict[str, str]]: | |
| out = [] | |
| for it in items: | |
| q = it.get("question") | |
| gt = it.get("ground_truth") | |
| if not isinstance(q, str) or not isinstance(gt, str): | |
| continue | |
| out.append({"question": q, "ground_truth": _normalize_ground_truth(gt)}) | |
| return out | |
| pred_clean = _clean(pred_slice) | |
| held_clean = _clean(held_slice) | |
| if len(pred_clean) < MIN_PREDICTIONS or len(held_clean) < MIN_HELD_OUT: | |
| return None | |
| return _Row( | |
| interview_id=interview_id, | |
| observations=observations, | |
| predictions=pred_clean, | |
| held_out=held_clean, | |
| ) | |
| def _partition_split_counts(n: int) -> tuple[int, int, int]: | |
| n_val = round(n * VAL_RATIO) | |
| n_test = round(n * TEST_RATIO) | |
| n_train = n - n_val - n_test | |
| if n_train < 1 and n > 0: | |
| half = max(0, n - 1) // 2 | |
| n_train, n_val, n_test = 1, half, n - 1 - half | |
| return n_train, n_val, n_test | |
| def _record_to_dict(rec: _Row, split: str) -> dict[str, Any]: | |
| extra: dict[str, Any] = { | |
| "interview_id": rec.interview_id, | |
| "n_observations": len(rec.observations), | |
| } | |
| if split == "train": | |
| out = { | |
| "observations": rec.observations, | |
| "predictions": rec.predictions, | |
| "data_source": DATA_SOURCE, | |
| "split": "train", | |
| "held_out_predictions": rec.held_out, | |
| } | |
| extra["n_predictions"] = len(rec.predictions) | |
| extra["n_held_out_predictions"] = len(rec.held_out) | |
| else: | |
| merged = list(rec.predictions) + list(rec.held_out) | |
| out = { | |
| "observations": rec.observations, | |
| "predictions": merged, | |
| "data_source": DATA_SOURCE, | |
| "split": split, | |
| } | |
| extra["n_predictions"] = len(merged) | |
| out["extra_info"] = extra | |
| return out | |
| # --- arrow schemas (explicit so train and val/test are stable) --------------- | |
| _PRED_TYPE = pa.struct([ | |
| pa.field("question", pa.string()), | |
| pa.field("ground_truth", pa.string()), | |
| ]) | |
| _TRAIN_SCHEMA = pa.schema([ | |
| pa.field("observations", pa.list_(pa.string())), | |
| pa.field("predictions", pa.list_(_PRED_TYPE)), | |
| pa.field("data_source", pa.string()), | |
| pa.field("split", pa.string()), | |
| pa.field("held_out_predictions", pa.list_(_PRED_TYPE)), | |
| pa.field("extra_info", pa.struct([ | |
| pa.field("interview_id", pa.string()), | |
| pa.field("n_observations", pa.int32()), | |
| pa.field("n_predictions", pa.int32()), | |
| pa.field("n_held_out_predictions", pa.int32()), | |
| ])), | |
| ]) | |
| _EVAL_SCHEMA = pa.schema([ | |
| pa.field("observations", pa.list_(pa.string())), | |
| pa.field("predictions", pa.list_(_PRED_TYPE)), | |
| pa.field("data_source", pa.string()), | |
| pa.field("split", pa.string()), | |
| pa.field("extra_info", pa.struct([ | |
| pa.field("interview_id", pa.string()), | |
| pa.field("n_observations", pa.int32()), | |
| pa.field("n_predictions", pa.int32()), | |
| ])), | |
| ]) | |
| def _write_split(records: list[dict], split: str, output_dir: Path, *, | |
| compression: str | None, compression_level: int | None) -> Path: | |
| schema = _TRAIN_SCHEMA if split == "train" else _EVAL_SCHEMA | |
| table = pa.Table.from_pylist(records, schema=schema) | |
| out_path = output_dir / f"{split}-00000-of-00001.parquet" | |
| pq.write_table( | |
| table, out_path, | |
| compression=compression, | |
| compression_level=compression_level, | |
| use_dictionary=True, | |
| ) | |
| return out_path | |
| def parse_args() -> argparse.Namespace: | |
| domain_dir = Path(__file__).resolve().parent.parent | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument( | |
| "--input-dir", | |
| type=Path, | |
| default=domain_dir / "upstream", | |
| help="Directory containing the upstream data_*.zst shards.", | |
| ) | |
| p.add_argument("--output-dir", type=Path, default=domain_dir / "qa_parquet") | |
| p.add_argument("--max-rows", type=int, default=0, | |
| help="Debug: stop after this many input rows (0 = all).") | |
| p.add_argument("--compression", default="zstd", | |
| choices=["zstd", "gzip", "snappy", "brotli", "lz4", "none"]) | |
| p.add_argument("--compression-level", type=int, default=None) | |
| return p.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| pool: list[_Row] = [] | |
| raw_seen = 0 | |
| skipped = 0 | |
| for rec in _iter_records(args.input_dir): | |
| raw_seen += 1 | |
| if args.max_rows and raw_seen > args.max_rows: | |
| break | |
| row = _record_to_row(rec) | |
| if row is None: | |
| skipped += 1 | |
| continue | |
| pool.append(row) | |
| rng = random.Random(SEED) | |
| rng.shuffle(pool) | |
| n = len(pool) | |
| n_train, n_val, _n_test = _partition_split_counts(n) | |
| splits = { | |
| "train": pool[:n_train], | |
| "val": pool[n_train : n_train + n_val], | |
| "test": pool[n_train + n_val :], | |
| } | |
| # Preserve the published IID test policy: exclude the historical training | |
| # prefix, then retain only the first test row for each adapter identity. | |
| train_ids = {str(rec.interview_id) for rec in splits["train"][:4366]} | |
| seen_test_ids: set[str] = set() | |
| clean_test: list[_Row] = [] | |
| for rec in splits["test"]: | |
| sample_id = str(rec.interview_id) | |
| if sample_id in train_ids or sample_id in seen_test_ids: | |
| continue | |
| seen_test_ids.add(sample_id) | |
| clean_test.append(rec) | |
| splits["test"] = clean_test | |
| comp = None if args.compression == "none" else args.compression | |
| written: dict[str, dict] = {} | |
| for split_name, recs in splits.items(): | |
| if not recs: | |
| continue | |
| records = [_record_to_dict(r, split_name) for r in recs] | |
| path = _write_split(records, split_name, args.output_dir, | |
| compression=comp, compression_level=args.compression_level) | |
| written[split_name] = {"rows": len(records), "path": str(path)} | |
| print(json.dumps({ | |
| "raw_lines_seen": raw_seen, | |
| "samples_built": n, | |
| "skipped_insufficient_data": skipped, | |
| "split_counts": {k: len(v) for k, v in splits.items()}, | |
| "written": written, | |
| }, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |