MDU-RiskText / scripts /build_release.py
ErenJaegerYeager's picture
Upload folder using huggingface_hub
4b8d886 verified
Raw
History Blame Contribute Delete
30.9 kB
#!/usr/bin/env python3
"""Build the public MDU-RiskText and MDU-RiskBench Hugging Face bundle.
The internal experiment JSONL files contain several redundant pipeline views.
This builder publishes the complete model-facing evidence packages used by the
benchmark, frozen labels and splits, while replacing internal participant IDs
with stable public IDs.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import io
import json
import re
import shutil
from collections import Counter
from pathlib import Path
from typing import Any, Iterable
SETTINGS = ("video_only", "non_video_only", "all_filtered_text")
SPLITS = ("train", "validation", "test")
RISK_LEVELS = (
"no_observed_risk",
"mild_risk",
"moderate_risk",
"high_risk",
)
SETTING_ALIASES = {"all_privacy_filtered_text": "all_filtered_text"}
BLOCKED_TEXT_PATTERNS = {
"developer_home": re.compile(r"/home/[A-Za-z0-9._-]+/"),
"mounted_drive": re.compile(r"/mnt/[A-Za-z]/"),
"windows_user": re.compile(r"[A-Za-z]:\\\\Users\\\\[^\\\\]+\\\\"),
"internal_evidence_id": re.compile(r"evidence_internal_[A-Za-z0-9_-]+"),
"internal_person_id": re.compile(r"\binternal_[A-Za-z0-9_-]+\b"),
"source_subset": re.compile(r"strict850|schemafix", re.I),
"spreadsheet": re.compile(r"\.xlsx?\b", re.I),
}
def compact_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_text(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value.rstrip() + "\n", encoding="utf-8")
class DeterministicGzipJsonlWriter:
def __init__(self, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
self.raw = path.open("wb")
self.gz = gzip.GzipFile(filename="", mode="wb", fileobj=self.raw, mtime=0)
self.text = io.TextIOWrapper(self.gz, encoding="utf-8", newline="\n")
def write(self, value: Any) -> None:
self.text.write(compact_json(value) + "\n")
def close(self) -> None:
self.text.flush()
self.text.detach()
self.gz.close()
self.raw.close()
def __enter__(self) -> "DeterministicGzipJsonlWriter":
return self
def __exit__(self, *_: Any) -> None:
self.close()
def iter_jsonl(path: Path) -> Iterable[dict[str, Any]]:
with path.open(encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if not line.strip():
continue
value = json.loads(line)
if not isinstance(value, dict):
raise ValueError(f"{path}:{line_number}: expected a JSON object")
yield value
def transform_strings(value: Any, old_id: str, public_id: str) -> Any:
if isinstance(value, dict):
return {
key: transform_strings(item, old_id, public_id)
for key, item in value.items()
if key not in {"internal_debug"}
}
if isinstance(value, list):
return [transform_strings(item, old_id, public_id) for item in value]
if isinstance(value, str):
value = value.replace(old_id, public_id)
return SETTING_ALIASES.get(value, value)
return value
def public_target_label(source: dict[str, Any]) -> dict[str, Any]:
risk_level = source.get("risk_level")
if risk_level not in RISK_LEVELS:
raise ValueError(f"unexpected target label: {risk_level!r}")
counts = source.get("risk_label_counts", {})
if not isinstance(counts, dict):
counts = {}
return {
"risk_level": risk_level,
"available": True,
"aggregation_method": "majority_vote_over_non_insufficient_windows",
"window_label_counts": {
str(key): int(value)
for key, value in sorted(counts.items())
if isinstance(value, (int, float))
},
}
def build_record(
source: dict[str, Any], setting: str, public_id: str
) -> dict[str, Any]:
old_id = source.get("sample_id")
if not isinstance(old_id, str):
raise ValueError("record lacks sample_id")
split = source.get("split")
if split not in SPLITS:
raise ValueError(f"unexpected split: {split!r}")
package_text = source.get("text_evidence")
if not isinstance(package_text, str):
raise ValueError(f"{old_id}: text_evidence is not a string")
package = json.loads(package_text)
package = transform_strings(package, old_id, public_id)
package["sample_id"] = public_id
package["benchmark_setting"] = setting
return {
"schema_version": "mdu_risktext.participant_record.v1",
"sample_id": public_id,
"split": split,
"target_label": public_target_label(source.get("target_label", {})),
"benchmark_setting": setting,
"llm_evidence_package": package,
"text_evidence": compact_json(package),
}
def collect_sources(paths: dict[str, Path]) -> dict[str, dict[str, dict[str, Any]]]:
records: dict[str, dict[str, dict[str, Any]]] = {}
for setting, path in paths.items():
setting_rows: dict[str, dict[str, Any]] = {}
for row in iter_jsonl(path):
sample_id = row.get("sample_id")
if not isinstance(sample_id, str):
raise ValueError(f"{path}: record lacks a string sample_id")
if sample_id in setting_rows:
raise ValueError(f"{path}: duplicate sample_id {sample_id}")
setting_rows[sample_id] = row
records[setting] = setting_rows
base_ids = set(records["video_only"])
if len(base_ids) != 850:
raise ValueError(f"expected 850 participants, found {len(base_ids)}")
for setting in SETTINGS:
if set(records[setting]) != base_ids:
raise ValueError(f"participant mismatch for {setting}")
for sample_id in base_ids:
base = records["video_only"][sample_id]
other = records[setting][sample_id]
if base.get("split") != other.get("split"):
raise ValueError(f"split mismatch for {sample_id} in {setting}")
if base.get("target_label", {}).get("risk_level") != other.get(
"target_label", {}
).get("risk_level"):
raise ValueError(f"label mismatch for {sample_id} in {setting}")
return records
def make_public_id_map(internal_ids: Iterable[str]) -> dict[str, str]:
return {
internal_id: f"MDURT_{index:06d}"
for index, internal_id in enumerate(sorted(internal_ids), 1)
}
def dataset_card() -> str:
return """---
pretty_name: MDU-RiskText and MDU-RiskBench
language:
- en
- zh
license: other
task_categories:
- text-classification
tags:
- privacy
- video-to-text
- ordinal-classification
- youth-digital-use
- evidence-grounding
configs:
- config_name: video_only
data_files:
- split: train
path: MDU-RiskText/video_only/train.jsonl.gz
- split: validation
path: MDU-RiskText/video_only/validation.jsonl.gz
- split: test
path: MDU-RiskText/video_only/test.jsonl.gz
- config_name: non_video_only
data_files:
- split: train
path: MDU-RiskText/non_video_only/train.jsonl.gz
- split: validation
path: MDU-RiskText/non_video_only/validation.jsonl.gz
- split: test
path: MDU-RiskText/non_video_only/test.jsonl.gz
- config_name: all_filtered_text
data_files:
- split: train
path: MDU-RiskText/all_filtered_text/train.jsonl.gz
- split: validation
path: MDU-RiskText/all_filtered_text/validation.jsonl.gz
- split: test
path: MDU-RiskText/all_filtered_text/test.jsonl.gz
---
# MDU-RiskText and MDU-RiskBench
This repository contains the public 850-participant release associated with
PriVTE: Privacy-Preserving Video-to-Text Evidence Encoding for Youth Digital
Use Risk Screening.
## Data products
- **MDU-RiskText** contains participant-level, privacy-filtered textual
evidence, the frozen ordinal target, and participant-disjoint split for all
850 participants.
- **MDU-RiskBench** defines the task, label order, three headline evidence
settings, participant index, evaluation protocol, and reference metric code.
The frozen cohort contains 9,831 selected source videos. It is split into 593
train, 131 validation, and 126 test participants. Target counts are 226
`no_observed_risk`, 432 `mild_risk`, 172 `moderate_risk`, and 20 `high_risk`.
## Load with Hugging Face Datasets
```python
from datasets import load_dataset
video = load_dataset("Herrieson/MDU-RiskText", "video_only")
non_video = load_dataset("Herrieson/MDU-RiskText", "non_video_only")
combined = load_dataset("Herrieson/MDU-RiskText", "all_filtered_text")
```
Replace `Herrieson/MDU-RiskText` if the final dataset repository uses a
different owner or name. Each row includes `sample_id`, `split`,
`target_label`, `benchmark_setting`, `llm_evidence_package`, and
`text_evidence`. The last field is the compact JSON string supplied to the
text-only model runners.
## Headline settings
| Configuration | Model-facing evidence |
|---|---|
| `video_only` | PriVTE evidence derived from locally processed video |
| `non_video_only` | Coarsened app-category, heart-rate-bin, and questionnaire-risk text |
| `all_filtered_text` | PriVTE video evidence plus the coarsened auxiliary text |
## Labels and evaluation
The four risk labels are ordinal in the order listed above.
`insufficient_evidence` is reserved for model abstention and is not a fifth
severity. The benchmark reports exact accuracy and macro-F1, together with
ordinal MAE and RMSE on non-abstained predictions and prediction coverage.
## Data construction
The source cohort was collected in school-based field studies involving young
participants in primary, middle, and high school settings in Beijing,
Zhejiang, Inner Mongolia, and other regions. Participants completed an
approximately 45-minute tablet-use session. PriVTE processes source video
locally and emits ordered observable-behavior evidence with quality gates,
relative stages, and evidence references. Auxiliary inputs are released only
as coarse categories or risk-signal bins.
Each participant contributes at most 12 videos selected uniformly over source
order. Every selected file was required to be nonempty, parseable, contain a
video stream of known duration, and provide at least four seconds of video.
The selection protocol does not replace a failed selected file with a nearby
file.
## Public record design
Public sample IDs (`MDURT_######`) are consistent across all three settings.
The release records contain the complete model-facing evidence used by
MDU-RiskBench, but omit redundant internal preprocessing/debug copies and
operational provenance fields. `MANIFEST.json` reports row counts, byte sizes,
and SHA-256 hashes for every release artifact.
## Intended use
The resource supports research on privacy-preserving behavioral evidence,
text-only ordinal screening, evidence grounding, selective prediction, and
comparison with direct-video systems. The targets are field-derived screening
judgments rather than clinical diagnoses. Model outputs are intended for
research analysis and human review rather than automated punitive decisions.
## License and citation
See `LICENSE_DATA.md` for the dataset terms and `CITATION.cff` for citation
metadata. Software scripts are released under the accompanying code license;
the data terms apply to MDU-RiskText and MDU-RiskBench records.
"""
def mdu_risktext_readme() -> str:
return """# MDU-RiskText
MDU-RiskText contains all 850 participant-level textual evidence records for
the three headline evidence settings. Each setting is split into train,
validation, and test gzip-compressed JSONL files.
Every row has the following fields:
- `schema_version`: public participant-record schema version;
- `sample_id`: stable public participant ID shared across settings;
- `split`: `train`, `validation`, or `test`;
- `target_label`: ordinal risk label and aggregated window-label counts;
- `benchmark_setting`: evidence configuration name;
- `llm_evidence_package`: structured model-facing JSON object;
- `text_evidence`: compact serialization of that same package.
The public files preserve the complete model-facing inputs. They intentionally
exclude redundant internal feature blocks, source paths, source filenames,
internal participant IDs, and preprocessing debug views that were not supplied
to benchmark models.
"""
def benchmark_readme() -> str:
return """# MDU-RiskBench
MDU-RiskBench is the benchmark definition paired with MDU-RiskText. It
contains:
- `benchmark.json`: cohort, labels, settings, and metric definitions;
- `participants.jsonl.gz`: the frozen 850-participant index;
- `prediction.schema.json`: submission record contract;
- `reference_results/`: aggregate result tables when available;
- `../scripts/evaluate_predictions.py`: reference evaluator;
- `../scripts/verify_release.py`: integrity and alignment validator.
A prediction JSONL contains one object per participant:
```json
{"sample_id":"MDURT_000001","risk_level":"mild_risk"}
```
Models may additionally output `confidence`, evidence references, rationale,
and review flags; the reference evaluator uses `sample_id` and `risk_level`.
"""
def data_license() -> str:
return """# MDU-RiskText / MDU-RiskBench Data Terms
Copyright (c) 2026 PriVTE contributors.
Permission is granted to use, reproduce, and redistribute the released
MDU-RiskText and MDU-RiskBench files for research, education, evaluation, and
non-commercial development, provided that users:
1. cite the dataset and PriVTE paper;
2. do not attempt to identify or contact participants or institutions;
3. do not combine the records with external data for re-identification;
4. do not use the data or derived systems for automated punishment,
disciplinary action, eligibility denial, or individual surveillance; and
5. preserve these terms and the dataset attribution in redistributions.
The data are provided as-is, without warranty. These terms cover the dataset
records and benchmark metadata; separately released source code may use a
different software license.
"""
def verify_script() -> str:
return r'''#!/usr/bin/env python3
"""Verify MDU-RiskText/MDU-RiskBench row alignment and file hashes."""
from __future__ import annotations
import gzip
import hashlib
import json
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SETTINGS = ("video_only", "non_video_only", "all_filtered_text")
SPLITS = ("train", "validation", "test")
def digest(path: Path) -> str:
value = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
value.update(chunk)
return value.hexdigest()
def rows(path: Path):
with gzip.open(path, "rt", encoding="utf-8") as handle:
for line in handle:
if line.strip():
yield json.loads(line)
def main() -> None:
manifest = json.loads((ROOT / "MANIFEST.json").read_text(encoding="utf-8"))
for entry in manifest["files"]:
path = ROOT / entry["path"]
if path.stat().st_size != entry["bytes"]:
raise SystemExit(f"size mismatch: {entry['path']}")
if digest(path) != entry["sha256"]:
raise SystemExit(f"hash mismatch: {entry['path']}")
identities = {}
for setting in SETTINGS:
current = {}
for split in SPLITS:
path = ROOT / "MDU-RiskText" / setting / f"{split}.jsonl.gz"
for row in rows(path):
if row["split"] != split or row["benchmark_setting"] != setting:
raise SystemExit(f"metadata mismatch: {path}")
package = row["llm_evidence_package"]
if package["sample_id"] != row["sample_id"]:
raise SystemExit(f"package ID mismatch: {row['sample_id']}")
if json.loads(row["text_evidence"]) != package:
raise SystemExit(f"text package mismatch: {row['sample_id']}")
current[row["sample_id"]] = (
split,
row["target_label"]["risk_level"],
)
if len(current) != 850:
raise SystemExit(f"{setting}: expected 850 records, got {len(current)}")
if identities and current != identities:
raise SystemExit(f"cross-setting identity mismatch: {setting}")
identities = current
split_counts = Counter(split for split, _ in identities.values())
label_counts = Counter(label for _, label in identities.values())
expected_splits = {"train": 593, "validation": 131, "test": 126}
expected_labels = {
"no_observed_risk": 226,
"mild_risk": 432,
"moderate_risk": 172,
"high_risk": 20,
}
if dict(split_counts) != expected_splits:
raise SystemExit(f"split counts differ: {dict(split_counts)}")
if dict(label_counts) != expected_labels:
raise SystemExit(f"label counts differ: {dict(label_counts)}")
print("Verified 850 aligned participants across 3 settings and 9 data files.")
if __name__ == "__main__":
main()
'''
def evaluator_script() -> str:
return r'''#!/usr/bin/env python3
"""Evaluate MDU-RiskBench participant-level prediction JSONL."""
from __future__ import annotations
import argparse
import gzip
import json
import math
from collections import Counter
from pathlib import Path
ORDER = {
"no_observed_risk": 0,
"mild_risk": 1,
"moderate_risk": 2,
"high_risk": 3,
}
ABSTAIN = "insufficient_evidence"
def read_jsonl(path: Path):
opener = gzip.open if path.suffix == ".gz" else open
with opener(path, "rt", encoding="utf-8") as handle:
for line in handle:
if line.strip():
yield json.loads(line)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--gold", type=Path, required=True)
parser.add_argument("--predictions", type=Path, required=True)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
gold = {
row["sample_id"]: row["target_label"]["risk_level"]
for row in read_jsonl(args.gold)
}
pred = {row["sample_id"]: row["risk_level"] for row in read_jsonl(args.predictions)}
unknown = sorted(set(pred) - set(gold))
if unknown:
raise SystemExit(f"unknown prediction IDs: {unknown[:5]}")
labels = list(ORDER)
total = len(gold)
covered = [(gold[sid], pred.get(sid)) for sid in gold if pred.get(sid) in ORDER]
abstained = total - len(covered)
exact = sum(actual == predicted for actual, predicted in covered)
distances = [abs(ORDER[actual] - ORDER[predicted]) for actual, predicted in covered]
squared = [value * value for value in distances]
f1_values = []
for label in labels:
tp = sum(actual == label and predicted == label for actual, predicted in covered)
fp = sum(actual != label and predicted == label for actual, predicted in covered)
fn = sum(actual == label and predicted != label for actual, predicted in covered)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1_values.append(
2 * precision * recall / (precision + recall) if precision + recall else 0.0
)
n = len(covered)
report = {
"gold_records": total,
"prediction_records": len(pred),
"covered_records": n,
"abstained_or_missing_records": abstained,
"coverage": n / total if total else 0.0,
"selective_accuracy": exact / n if n else None,
"selective_macro_f1": sum(f1_values) / len(f1_values) if n else None,
"ordinal_mae": sum(distances) / n if n else None,
"ordinal_rmse": math.sqrt(sum(squared) / n) if n else None,
"prediction_distribution": dict(sorted(Counter(pred.values()).items())),
}
rendered = json.dumps(report, indent=2) + "\n"
if args.output:
args.output.write_text(rendered, encoding="utf-8")
print(rendered, end="")
if __name__ == "__main__":
main()
'''
def prediction_schema() -> dict[str, Any]:
return {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "MDU-RiskBench prediction record",
"type": "object",
"required": ["sample_id", "risk_level"],
"properties": {
"sample_id": {"type": "string", "pattern": "^MDURT_[0-9]{6}$"},
"risk_level": {
"enum": [*RISK_LEVELS, "insufficient_evidence"]
},
"confidence": {"enum": ["low", "medium", "high"]},
"evidence_used": {"type": "array", "items": {"type": "string"}},
"needs_human_review": {"type": "boolean"},
},
"additionalProperties": True,
}
def record_schema() -> dict[str, Any]:
return {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "MDU-RiskText participant record",
"type": "object",
"required": [
"schema_version",
"sample_id",
"split",
"target_label",
"benchmark_setting",
"llm_evidence_package",
"text_evidence",
],
"properties": {
"schema_version": {"const": "mdu_risktext.participant_record.v1"},
"sample_id": {"type": "string", "pattern": "^MDURT_[0-9]{6}$"},
"split": {"enum": list(SPLITS)},
"benchmark_setting": {"enum": list(SETTINGS)},
"target_label": {
"type": "object",
"required": ["risk_level", "available"],
"properties": {"risk_level": {"enum": list(RISK_LEVELS)}},
},
"llm_evidence_package": {"type": "object"},
"text_evidence": {"type": "string"},
},
}
def benchmark_definition() -> dict[str, Any]:
return {
"schema_version": "mdu_riskbench.v1",
"name": "MDU-RiskBench",
"paired_dataset": "MDU-RiskText v1",
"task": "Text-only Youth Digital Use Risk Screening",
"participant_count": 850,
"selected_source_video_count": 9831,
"participant_disjoint_splits": True,
"split_counts": {"train": 593, "validation": 131, "test": 126},
"ordinal_labels": list(RISK_LEVELS),
"abstention_label": "insufficient_evidence",
"label_counts": {
"no_observed_risk": 226,
"mild_risk": 432,
"moderate_risk": 172,
"high_risk": 20,
},
"headline_settings": {
"video_only": "PriVTE privacy-filtered video-to-text evidence",
"non_video_only": (
"coarse app-category, heart-rate-bin, and questionnaire-risk text"
),
"all_filtered_text": "PriVTE evidence plus coarse auxiliary text",
},
"primary_metrics": [
"accuracy",
"macro_f1",
"ordinal_mae",
"ordinal_rmse",
"coverage",
],
"ordinal_metric_policy": (
"MAE and RMSE are computed on predictions in the four ordinal labels; "
"insufficient_evidence is reported through coverage."
),
"source_video_selection": {
"maximum_selected_per_participant": 12,
"selection": "uniform_over_ordered_source_inventory",
"minimum_video_stream_duration_seconds": 4.0,
"all_selected_files_must_pass_technical_validation": True,
"replacement_after_selected_file_failure": False,
},
}
def citation_cff() -> str:
return """cff-version: 1.2.0
message: "If you use MDU-RiskText or MDU-RiskBench, please cite this dataset and the PriVTE paper."
title: "MDU-RiskText and MDU-RiskBench"
type: dataset
authors:
- name: "PriVTE Authors"
version: "1.0.0"
date-released: "2026-07-28"
repository-code: "https://github.com/Herrieson/privte-public"
"""
def write_base_files(output: Path) -> None:
write_text(output / "README.md", dataset_card())
write_text(output / "LICENSE_DATA.md", data_license())
write_text(output / "CITATION.cff", citation_cff())
write_text(output / "MDU-RiskText" / "README.md", mdu_risktext_readme())
write_text(output / "MDU-RiskBench" / "README.md", benchmark_readme())
write_json(output / "MDU-RiskText" / "record.schema.json", record_schema())
write_json(output / "MDU-RiskBench" / "benchmark.json", benchmark_definition())
write_json(
output / "MDU-RiskBench" / "prediction.schema.json", prediction_schema()
)
write_text(output / "scripts" / "verify_release.py", verify_script())
write_text(output / "scripts" / "evaluate_predictions.py", evaluator_script())
shutil.copy2(Path(__file__).resolve(), output / "scripts" / "build_release.py")
def copy_reference_results(source: Path | None, output: Path) -> None:
if source is None or not source.exists():
return
destination = output / "MDU-RiskBench" / "reference_results"
destination.mkdir(parents=True, exist_ok=True)
for name in (
"trained_video_only_baselines.csv",
"trained_video_only_baselines.json",
"llm_full_matrix.csv",
"llm_full_matrix.json",
"llm_setting_means.csv",
"llm_setting_means.json",
"direct_video_comparison.csv",
"direct_video_comparison.json",
):
candidate = source / name
if candidate.exists():
shutil.copy2(candidate, destination / name)
def audit_text(value: Any, context: str) -> None:
rendered = compact_json(value)
for name, pattern in BLOCKED_TEXT_PATTERNS.items():
match = pattern.search(rendered)
if match:
raise ValueError(f"{context}: blocked {name}: {match.group(0)!r}")
def build(args: argparse.Namespace) -> None:
output = args.output.resolve()
if output.exists():
if not args.overwrite:
raise SystemExit(f"output exists; pass --overwrite: {output}")
shutil.rmtree(output)
output.mkdir(parents=True)
paths = {
"video_only": args.video_only.resolve(),
"non_video_only": args.non_video_only.resolve(),
"all_filtered_text": args.all_filtered_text.resolve(),
}
records = collect_sources(paths)
public_ids = make_public_id_map(records["video_only"])
writers = {
(setting, split): DeterministicGzipJsonlWriter(
output / "MDU-RiskText" / setting / f"{split}.jsonl.gz"
)
for setting in SETTINGS
for split in SPLITS
}
participant_writer = DeterministicGzipJsonlWriter(
output / "MDU-RiskBench" / "participants.jsonl.gz"
)
row_counts: Counter[tuple[str, str]] = Counter()
split_counts: Counter[str] = Counter()
label_counts: Counter[str] = Counter()
try:
for internal_id in sorted(public_ids):
public_id = public_ids[internal_id]
base = records["video_only"][internal_id]
split = base["split"]
target = public_target_label(base["target_label"])
participant_writer.write(
{
"sample_id": public_id,
"split": split,
"target_label": target,
}
)
split_counts[split] += 1
label_counts[target["risk_level"]] += 1
for setting in SETTINGS:
record = build_record(records[setting][internal_id], setting, public_id)
audit_text(record, f"{setting}/{public_id}")
writers[(setting, split)].write(record)
row_counts[(setting, split)] += 1
finally:
participant_writer.close()
for writer in writers.values():
writer.close()
expected_splits = {"train": 593, "validation": 131, "test": 126}
expected_labels = {
"no_observed_risk": 226,
"mild_risk": 432,
"moderate_risk": 172,
"high_risk": 20,
}
if dict(split_counts) != expected_splits:
raise ValueError(f"unexpected split counts: {dict(split_counts)}")
if dict(label_counts) != expected_labels:
raise ValueError(f"unexpected label counts: {dict(label_counts)}")
write_base_files(output)
copy_reference_results(args.reference_results, output)
files = []
for path in sorted(output.rglob("*")):
if not path.is_file() or path.name == "MANIFEST.json":
continue
relative = path.relative_to(output).as_posix()
entry: dict[str, Any] = {
"path": relative,
"bytes": path.stat().st_size,
"sha256": sha256(path),
}
if path.name.endswith(".jsonl.gz"):
if relative == "MDU-RiskBench/participants.jsonl.gz":
entry["rows"] = 850
else:
parts = path.relative_to(output / "MDU-RiskText").parts
setting = parts[0]
split = path.name.removesuffix(".jsonl.gz")
entry["rows"] = row_counts[(setting, split)]
files.append(entry)
manifest = {
"schema_version": "mdu_risk_huggingface_release_manifest.v1",
"release_version": "1.0.0",
"participant_count": 850,
"selected_source_video_count": 9831,
"settings": list(SETTINGS),
"split_counts": expected_splits,
"label_counts": expected_labels,
"files": files,
}
write_json(output / "MANIFEST.json", manifest)
print(f"Built Hugging Face release at {output}")
print(f"Participants: {sum(split_counts.values())}")
print(f"Compressed bundle bytes: {sum(p.stat().st_size for p in output.rglob('*') if p.is_file())}")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--video-only", type=Path, required=True)
parser.add_argument("--non-video-only", type=Path, required=True)
parser.add_argument("--all-filtered-text", type=Path, required=True)
parser.add_argument("--reference-results", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--overwrite", action="store_true")
return parser.parse_args()
if __name__ == "__main__":
build(parse_args())