File size: 30,862 Bytes
4b8d886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
#!/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())