File size: 46,227 Bytes
1dfac10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae3214b
a5f6d2e
 
1dfac10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae3214b
1dfac10
 
 
ae3214b
1dfac10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae3214b
1dfac10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
#!/usr/bin/env python3
"""Build an auditable pilot of permissively licensed Polish OPEN ICM texts."""
from __future__ import annotations

import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from difflib import SequenceMatcher, get_close_matches
import gzip
import hashlib
import json
import os
from pathlib import Path
import re
import time
import unicodedata

import requests

from biblioteka_nauki_overlap import fetch_attribution_targets, normalize_title
from language_gate import language_vote


SOURCE = "open_icm_pl"
OWN_REPO = "PiotrSty/open-icm-pl-publications"
TARGET = "SlayerLab/polish-dynaword"
API = "https://open.icm.edu.pl/server/api"
SOURCE_URL = "https://open.icm.edu.pl/home"
FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
UA = "OpenICMPolishCorpusResearch/0.1 (PiotrSty; open research pilot)"
MAX_TEXT_BYTES = 20 * 1024 * 1024
MIN_TEXT_CHARS = 3_000
POOL_MULTIPLIER = 2
EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b")

LICENSES = {
    "Uznanie autorstwa-Na tych samych warunkach 3.0 Polska": "CC-BY-SA-3.0-PL",
    "Uznanie autorstwa 3.0 Polska": "CC-BY-3.0-PL",
    "Uznanie autorstwa 4.0 Międzynarodowe": "CC-BY-4.0",
    "Uznanie autorstwa-Na tych samych warunkach 4.0 Międzynarodowe": "CC-BY-SA-4.0",
    "Uznanie autorstwa 3.0 Unported": "CC-BY-3.0",
    "Uznanie autorstwa-Na tych samych warunkach 3.0 Unported": "CC-BY-SA-3.0",
    "Uznanie autorstwa 2.0 Polska": "CC-BY-2.0-PL",
    "Uznanie autorstwa-Na tych samych warunkach 3.0": "CC-BY-SA-3.0",
}


class AcquisitionBarrier(RuntimeError):
    """Raised when OPEN ICM returns an interactive download barrier."""


def now():
    return datetime.now(timezone.utc).isoformat()


def digest(value):
    if not isinstance(value, bytes):
        value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(value).hexdigest()


def save(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")


def write_lines(path, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows), encoding="utf-8")


def read_lines(path):
    # JSONL records may contain Unicode line-separator characters inside strings.
    return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line]


def load(path):
    return json.loads(path.read_text(encoding="utf-8"))


def values(metadata, key):
    return [str(item.get("value", "")).strip() for item in metadata.get(key, []) if str(item.get("value", "")).strip()]


def request(url, params=None, attempts=5, timeout=(15, 60)):
    response = None
    for attempt in range(attempts):
        response = requests.get(url, params=params, headers={"User-Agent": UA}, timeout=timeout)
        if response.status_code not in (429, 500, 502, 503, 504):
            response.raise_for_status()
            return response
        time.sleep(2 ** attempt)
    response.raise_for_status()


def request_json(url, params=None):
    return request(url, params=params).json()


def embedded(payload, name):
    return payload.get("_embedded", {}).get(name, [])


def item_objects(payload):
    result = payload.get("_embedded", {}).get("searchResult", {})
    objects = result.get("_embedded", {}).get("objects", [])
    return [row.get("_embedded", {}).get("indexableObject", {}) for row in objects]


def compact_item(item):
    metadata = item.get("metadata", {})
    keys = [
        "dc.contributor.author", "dc.contributor.editor", "dc.date.issued", "dc.description.abstract",
        "dc.identifier.doi", "dc.identifier.uri", "dc.language.iso", "dc.publisher", "dc.rights",
        "dc.subject", "dc.title", "dc.type",
    ]
    return {
        "item_id": item.get("uuid") or item.get("id"),
        "title": item.get("name", ""),
        "handle": item.get("handle"),
        "last_modified": item.get("lastModified"),
        "metadata": {key: metadata.get(key, []) for key in keys if metadata.get(key)},
    }


def is_polish_open_item(item):
    metadata = item.get("metadata", {})
    languages = {value.casefold() for value in values(metadata, "dc.language.iso")}
    rights = set(values(metadata, "dc.rights"))
    return any(language == "pl" or language.startswith("pl_") for language in languages) and bool(rights & LICENSES.keys())


def deterministic_pool(items, target):
    unique = {}
    for item in items:
        item_id = item["item_id"]
        if item_id not in unique:
            unique[item_id] = item
        else:
            old_rights = set(values(unique[item_id]["metadata"], "dc.rights"))
            new_rights = set(values(item["metadata"], "dc.rights"))
            unique[item_id]["metadata"]["dc.rights"] = [{"value": value} for value in sorted(old_rights | new_rights)]
    ordered = sorted(unique.values(), key=lambda item: digest(("open-icm-pilot:" + item["item_id"]).encode("utf-8")))
    chosen = []
    for license_label in LICENSES:
        match = next((item for item in ordered if license_label in values(item["metadata"], "dc.rights")), None)
        if match and match["item_id"] not in {row["item_id"] for row in chosen}:
            chosen.append(match)
    wanted = min(len(ordered), target * POOL_MULTIPLIER)
    chosen_ids = {row["item_id"] for row in chosen}
    chosen.extend(item for item in ordered if item["item_id"] not in chosen_ids and len(chosen) < wanted)
    return chosen[:wanted]


def discover(out, target):
    if (out / "source_manifest.jsonl").exists():
        raise ValueError("source manifest exists; use a fresh directory for an immutable discovery run")
    out.mkdir(parents=True, exist_ok=True)
    raw_pages = out / "raw_api"
    all_items, pages, counts = [], [], {}
    for license_index, license_label in enumerate(LICENSES):
        page = 0
        while True:
            params = [
                ("size", 100), ("page", page), ("sort", "dc.date.issued,DESC"),
                ("query", "dc.language.iso:pl"), ("f.license", f"{license_label},equals"),
            ]
            response = request(f"{API}/discover/search/objects", params=params)
            raw = response.content
            payload = response.json()
            result = payload.get("_embedded", {}).get("searchResult", {})
            page_info = result.get("page", {})
            items = [compact_item(item) for item in item_objects(payload) if is_polish_open_item(item)]
            compressed_path = raw_pages / f"license-{license_index:02d}" / f"page-{page:04d}.json.gz"
            compressed_path.parent.mkdir(parents=True, exist_ok=True)
            compressed_path.write_bytes(gzip.compress(raw, mtime=0))
            pages.append({
                "license": license_label, "page": page, "response_sha256": digest(raw),
                "compressed_path": compressed_path.relative_to(out).as_posix(), "items": len(items),
                "reported_total": int(page_info.get("totalElements", 0)),
            })
            all_items.extend(items)
            counts[license_label] = int(page_info.get("totalElements", 0))
            if page + 1 >= int(page_info.get("totalPages", 0)):
                break
            page += 1
    unique = {item["item_id"]: item for item in all_items}
    manifest = sorted(unique.values(), key=lambda item: item["item_id"])
    pool = deterministic_pool(manifest, target)
    write_lines(out / "source_manifest.jsonl", manifest)
    write_lines(out / "selection_pool.jsonl", pool)
    save(out / "api_pages.json", pages)
    selection = {
        "source": SOURCE, "source_url": SOURCE_URL, "observed_at": now(), "target": target,
        "pool_size": len(pool), "eligible_records": len(manifest), "reported_counts_by_license": counts,
        "accepted_licenses": LICENSES, "language_query": "dc.language.iso:pl",
        "selection_method": "one deterministic representative per license, then lowest SHA-256 ranks",
        "source_manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
        "api_pages_sha256": digest(pages),
    }
    save(out / "selection.json", selection)
    print(json.dumps({"eligible": len(manifest), "pool": len(pool), "target": target, "counts": counts}, ensure_ascii=False, indent=2))


def bundle_map(item_id):
    payload = request_json(f"{API}/core/items/{item_id}/bundles", {"size": 20})
    return {bundle.get("name"): bundle for bundle in embedded(payload, "bundles")}


def bundle_bitstreams(bundle):
    if not bundle:
        return []
    return embedded(request_json(f"{API}/core/bundles/{bundle['uuid']}/bitstreams", {"size": 100}), "bitstreams")


def bitstream_summary(bitstream):
    return {
        "id": bitstream.get("uuid") or bitstream.get("id"), "name": bitstream.get("name"),
        "bytes": int(bitstream.get("sizeBytes", 0)), "checksum": bitstream.get("checkSum"),
        "content_url": bitstream.get("_links", {}).get("content", {}).get("href"),
        "metadata_rights": values(bitstream.get("metadata", {}), "dc.rights"),
    }


def choose_text(bitstreams):
    candidates = [item for item in bitstreams if item.get("_links", {}).get("content", {}).get("href")]
    if not candidates:
        raise ValueError("missing downloadable TEXT bitstream")
    return max(candidates, key=lambda item: (int(item.get("sizeBytes", 0)), item.get("name", "")))


def verify_checksum(payload, metadata):
    checksum = metadata.get("checkSum") or {}
    algorithm = str(checksum.get("checkSumAlgorithm", "")).upper()
    expected = checksum.get("value")
    if algorithm == "MD5" and expected and hashlib.md5(payload).hexdigest() != expected:
        raise ValueError("downloaded bitstream MD5 differs from repository metadata")


def detect_download_barrier(response):
    final_url = str(getattr(response, "url", ""))
    content_type = str(getattr(response, "headers", {}).get("Content-Type", "")).casefold()
    prefix = bytes(getattr(response, "content", b""))[:512].lower()
    if "/captcha.html" in final_url or ("text/html" in content_type and b"<html" in prefix):
        raise AcquisitionBarrier(
            "OPEN ICM returned an interactive CAPTCHA page instead of the bitstream; "
            "request an official bulk-download route before acquisition"
        )


def probe_download_access(item):
    bundles = bundle_map(item["item_id"])
    text_stream = choose_text(bundle_bitstreams(bundles.get("TEXT")))
    response = request(text_stream["_links"]["content"]["href"], timeout=(15, 120))
    detect_download_barrier(response)


def text_stream_metadata(item):
    bundles = bundle_map(item["item_id"])
    return {
        "text_stream": choose_text(bundle_bitstreams(bundles.get("TEXT"))),
        "license_streams": bundle_bitstreams(bundles.get("LICENSE")),
        "original_streams": bundle_bitstreams(bundles.get("ORIGINAL")),
    }


def acquire_one(out, item):
    item_id = item["item_id"]
    streams = text_stream_metadata(item)
    text_stream = streams["text_stream"]
    licenses = streams["license_streams"]
    originals = streams["original_streams"]
    text_bytes = int(text_stream.get("sizeBytes", 0))
    if text_bytes <= 0 or text_bytes > MAX_TEXT_BYTES:
        raise ValueError(f"TEXT bitstream outside 1..{MAX_TEXT_BYTES} byte pilot bound")
    response = request(text_stream["_links"]["content"]["href"], timeout=(15, 120))
    detect_download_barrier(response)
    payload = response.content
    if len(payload) != text_bytes:
        raise ValueError("downloaded TEXT byte count differs from repository metadata")
    verify_checksum(payload, text_stream)
    raw_path = out / "raw_text" / f"{item_id}.txt"
    raw_path.parent.mkdir(parents=True, exist_ok=True)
    raw_path.write_bytes(payload)
    license_evidence = []
    for index, stream in enumerate(licenses):
        content_url = stream.get("_links", {}).get("content", {}).get("href")
        if not content_url or int(stream.get("sizeBytes", 0)) > 1_000_000:
            continue
        license_payload = request(content_url).content
        verify_checksum(license_payload, stream)
        license_path = out / "license_evidence" / f"{item_id}-{index:02d}.txt"
        license_path.parent.mkdir(parents=True, exist_ok=True)
        license_path.write_bytes(license_payload)
        license_evidence.append({**bitstream_summary(stream), "sha256": digest(license_payload),
                                 "path": license_path.relative_to(out).as_posix()})
    return {
        **item, "landing_url": f"https://open.icm.edu.pl/items/{item_id}",
        "accepted_license_labels": sorted(set(values(item["metadata"], "dc.rights")) & LICENSES.keys()),
        "text_bitstream": {**bitstream_summary(text_stream), "sha256": digest(payload),
                           "path": raw_path.relative_to(out).as_posix()},
        "license_evidence": license_evidence,
        "original_bitstreams": [bitstream_summary(stream) for stream in originals],
        "observed_at": now(),
    }


def manual_acquisition(out):
    path = out / "manual_acquisition.json"
    if path.exists():
        return load(path)
    selection = load(out / "selection.json")
    return {
        "source": SOURCE, "observed_at": now(), "target": int(selection["target"]),
        "pool_size": int(selection["pool_size"]), "mode": "manual_browser_download",
        "selected": [], "rejected": [],
    }


def sync_manual_acquisition(out, state):
    state["observed_at"] = now()
    state["attempted"] = len(state["selected"]) + len(state["rejected"])
    state["target_reached"] = len(state["selected"]) >= int(state["target"])
    state["manual_confirmation_required"] = not state["target_reached"]
    save(out / "manual_acquisition.json", state)
    save(out / "acquisition.json", state)


def prepare_manual(out):
    pool = read_lines(out / "selection_pool.jsonl")
    state = manual_acquisition(out)
    completed = {record["item_id"] for record in state["selected"]}
    completed.update(record["item_id"] for record in state["rejected"])
    for item in pool:
        if item["item_id"] in completed:
            continue
        try:
            streams = text_stream_metadata(item)
            text_stream = streams["text_stream"]
            text_bytes = int(text_stream.get("sizeBytes", 0))
            if text_bytes <= 0 or text_bytes > MAX_TEXT_BYTES:
                raise ValueError(f"TEXT bitstream outside 1..{MAX_TEXT_BYTES} byte pilot bound")
            if text_bytes < MIN_TEXT_CHARS:
                raise ValueError(f"TEXT bitstream has {text_bytes} bytes and cannot pass the {MIN_TEXT_CHARS}-character QA gate")
        except Exception as error:
            state["rejected"].append({"item_id": item["item_id"], "title": item["title"],
                                      "reason": str(error), "observed_at": now()})
            sync_manual_acquisition(out, state)
            continue
        pending = {
            "source": SOURCE, "prepared_at": now(), "item": item,
            "landing_url": f"https://open.icm.edu.pl/items/{item['item_id']}",
            "accepted_license_labels": sorted(set(values(item["metadata"], "dc.rights")) & LICENSES.keys()),
            "text_bitstream": bitstream_summary(text_stream),
            "license_evidence": [{**bitstream_summary(stream), "downloaded": False}
                                 for stream in streams["license_streams"]],
            "original_bitstreams": [bitstream_summary(stream) for stream in streams["original_streams"]],
            "progress": {"acquired": len(state["selected"]), "target": state["target"]},
        }
        save(out / "manual_pending.json", pending)
        print(json.dumps({
            "item_id": item["item_id"], "title": item["title"],
            "content_url": pending["text_bitstream"]["content_url"],
            "bytes": pending["text_bitstream"]["bytes"],
            "acquired": len(state["selected"]), "target": state["target"],
        }, ensure_ascii=False, indent=2))
        return
    raise RuntimeError("manual acquisition pool exhausted")


def ingest_manual(out, download_file):
    if not download_file:
        raise ValueError("--download-file is required for ingest_manual")
    pending = load(out / "manual_pending.json")
    stream = pending["text_bitstream"]
    payload = download_file.read_bytes()
    prefix = payload[:512].lower()
    if b"<html" in prefix or b"<!doctype html" in prefix:
        raise AcquisitionBarrier("downloaded file is HTML rather than the declared TEXT bitstream")
    if len(payload) != int(stream["bytes"]):
        raise ValueError(f"downloaded file has {len(payload)} bytes; expected {stream['bytes']}")
    checksum = stream.get("checksum") or {}
    if str(checksum.get("checkSumAlgorithm", "")).upper() == "MD5":
        actual_md5 = hashlib.md5(payload).hexdigest()
        if actual_md5 != checksum.get("value"):
            raise ValueError(f"downloaded file MD5 {actual_md5} differs from repository metadata")
    state = manual_acquisition(out)
    item = pending["item"]
    if any(record["item_id"] == item["item_id"] for record in state["selected"]):
        raise ValueError("pending item is already present in manual acquisition")
    raw_path = out / "raw_text" / f"{item['item_id']}.txt"
    raw_path.parent.mkdir(parents=True, exist_ok=True)
    raw_path.write_bytes(payload)
    record = {
        **item, "landing_url": pending["landing_url"],
        "accepted_license_labels": pending["accepted_license_labels"],
        "text_bitstream": {**stream, "sha256": digest(payload),
                           "path": raw_path.relative_to(out).as_posix()},
        "license_evidence": pending["license_evidence"],
        "original_bitstreams": pending["original_bitstreams"],
        "observed_at": now(), "acquisition_mode": "manual_browser_download",
        "download_filename": download_file.name,
    }
    state["selected"].append(record)
    state["selected"].sort(key=lambda row: row["item_id"])
    sync_manual_acquisition(out, state)
    pending["ingested_at"] = now()
    pending["download_sha256"] = digest(payload)
    save(out / "manual_pending.json", pending)
    print(json.dumps({"ingested": item["item_id"], "acquired": len(state["selected"]),
                      "target": state["target"], "target_reached": state["target_reached"]},
                     ensure_ascii=False, indent=2))


def acquire(out, workers):
    selection = load(out / "selection.json")
    pool = read_lines(out / "selection_pool.jsonl")
    target = int(selection["target"])
    selected, rejected = [], []
    try:
        probe_download_access(pool[0])
    except AcquisitionBarrier as error:
        acquisition = {
            "source": SOURCE, "observed_at": now(), "target": target, "pool_size": len(pool),
            "attempted": 1, "selected": [],
            "rejected": [{"item_id": pool[0]["item_id"], "title": pool[0]["title"], "reason": str(error)}],
            "target_reached": False, "blocked": True,
            "blocker": {
                "type": "interactive_captcha",
                "scope": "bitstream_content",
                "resolution": "Obtain an official bulk-download route or written API access from OPEN ICM.",
            },
        }
        save(out / "acquisition.json", acquisition)
        print(json.dumps({"selected": 0, "rejected": 1, "target_reached": False,
                          "blocked": True, "reason": str(error)}, ensure_ascii=False, indent=2))
        return
    next_index = 0
    while len(selected) < target and next_index < len(pool):
        batch = pool[next_index:min(len(pool), next_index + max(workers * 2, target - len(selected)))]
        next_index += len(batch)
        with ThreadPoolExecutor(max_workers=workers) as executor:
            futures = {executor.submit(acquire_one, out, item): item for item in batch}
            for future in as_completed(futures):
                item = futures[future]
                try:
                    record = future.result()
                    if len(selected) < target:
                        selected.append(record)
                        print(f"Acquired {len(selected)}/{target}: {record['title']}", flush=True)
                    else:
                        Path(out / record["text_bitstream"]["path"]).unlink(missing_ok=True)
                        for evidence in record["license_evidence"]:
                            Path(out / evidence["path"]).unlink(missing_ok=True)
                except Exception as error:
                    rejected.append({"item_id": item["item_id"], "title": item["title"], "reason": str(error)})
        if len(selected) >= target:
            break
    selected.sort(key=lambda item: item["item_id"])
    acquisition = {
        "source": SOURCE, "observed_at": now(), "target": target, "pool_size": len(pool),
        "attempted": len(selected) + len(rejected), "selected": selected, "rejected": rejected,
        "target_reached": len(selected) == target,
    }
    save(out / "acquisition.json", acquisition)
    print(json.dumps({"selected": len(selected), "rejected": len(rejected), "target_reached": acquisition["target_reached"]}, ensure_ascii=False, indent=2))


def normalize(text):
    text = unicodedata.normalize("NFKC", text or "").replace("\u00ad", "").replace("\u200b", "")
    text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
    lines = [re.sub(r"[ \t\xa0]+", " ", line).strip() for line in text.splitlines()]
    lines = [line for line in lines if not re.fullmatch(r"\d{1,4}", line)]
    text = "\n".join(lines)
    text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text)
    text = re.sub(r"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text)
    return re.sub(r"\n{3,}", "\n\n", text).strip()


def shingle_sketch(text, limit=5_000):
    words = re.findall(r"\w+", text.casefold())
    hashes = set()
    for index in range(max(0, len(words) - 4)):
        value = " ".join(words[index:index + 5]).encode("utf-8")
        hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big"))
    if len(hashes) > limit:
        return set(sorted(hashes)[:limit])
    return hashes


def build(out):
    import pyarrow as pa
    import pyarrow.parquet as pq
    import tiktoken
    from langid.langid import LanguageIdentifier, model

    acquisition = load(out / "acquisition.json")
    selection = load(out / "selection.json")
    encoder = tiktoken.get_encoding("cl100k_base")
    identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
    identifier.set_languages(["pl", "en", "de", "uk", "ru"])
    rows, attribution, decisions, exact_seen, sketches = [], [], [], {}, {}
    pii = Counter()
    added = acquisition["observed_at"][:10]
    for record in acquisition["selected"]:
        raw_path = out / record["text_bitstream"]["path"]
        raw = raw_path.read_bytes()
        if digest(raw) != record["text_bitstream"]["sha256"]:
            raise ValueError("TEXT checksum mismatch: " + record["item_id"])
        text = normalize(raw.decode("utf-8-sig", errors="replace"))
        replacement_count = text.count("\ufffd")
        letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text))
        language, votes = language_vote(identifier, text)
        reason = ""
        if len(text) < MIN_TEXT_CHARS:
            reason = "too_little_extractable_text"
        elif letters / max(len(text), 1) < 0.55:
            reason = "low_letter_ratio"
        elif replacement_count > 20 or replacement_count / max(len(text), 1) > 0.0001:
            reason = "excessive_replacement_characters"
        elif language != "pl":
            reason = "non_polish_text"
        text = text.replace("\ufffd", "[UNREADABLE_GLYPH]")
        text, emails = EMAIL_RE.subn("[REDACTED:EMAIL]", text)
        text, phones = PHONE_RE.subn("[REDACTED:PHONE]", text)
        pii.update(email=emails, labelled_phone=phones)
        exact_key = digest(" ".join(text.casefold().split()).encode("utf-8"))
        duplicate_of, duplicate_score = None, 0.0
        if not reason and exact_key in exact_seen:
            reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0
        sketch = shingle_sketch(text)
        if not reason:
            for other_id, other_sketch in sketches.items():
                score = len(sketch & other_sketch) / max(len(sketch | other_sketch), 1)
                if score >= 0.90:
                    reason, duplicate_of, duplicate_score = "near_duplicate", other_id, score
                    break
        row_id = f"{SOURCE}_{record['item_id']}"
        decision = {
            "id": row_id, "selected": not bool(reason), "reason": reason or "include",
            "characters": len(text), "letter_ratio": letters / max(len(text), 1),
            "replacement_characters": replacement_count, "language": language,
            "language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes],
        }
        if duplicate_of:
            decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score})
        decisions.append(decision)
        if reason:
            continue
        exact_seen[exact_key] = row_id
        sketches[row_id] = sketch
        metadata = record["metadata"]
        authors = values(metadata, "dc.contributor.author") or values(metadata, "dc.contributor.editor")
        author = "; ".join(authors or ["Unknown"])
        issued = values(metadata, "dc.date.issued")
        accepted_labels = record["accepted_license_labels"]
        spdx = LICENSES[accepted_labels[0]]
        row = {
            "id": row_id, "text": text, "source": SOURCE, "added": added,
            "created": issued[0] if issued else "unknown", "token_count": len(encoder.encode_ordinary(text)),
            "license": spdx, "author": author,
        }
        rows.append(row)
        attribution.append({
            "id": row_id, "item_id": record["item_id"], "title": record["title"], "authors": authors,
            "publisher": values(metadata, "dc.publisher"), "issued": issued,
            "doi": values(metadata, "dc.identifier.doi"), "handle": record["handle"],
            "landing_url": record["landing_url"], "repository_license_labels": accepted_labels,
            "license": spdx, "text_bitstream": record["text_bitstream"],
            "license_evidence": record["license_evidence"], "original_bitstreams": record["original_bitstreams"],
            "text_sha256": digest(text.encode("utf-8")),
            "transformations": ["repository TEXT bundle", "Unicode/whitespace normalization", "page-number-only removal",
                                "line-wrap repair", "email and labelled-phone pattern redaction"],
        })
    root = out / "hf_repo"
    (root / "data").mkdir(parents=True, exist_ok=True)
    (root / "artifacts" / "source_pages").mkdir(parents=True, exist_ok=True)
    schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS])
    pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet", compression="zstd")
    write_lines(root / "artifacts/attribution.jsonl", attribution)
    write_lines(root / "artifacts/decisions.jsonl", decisions)
    write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl"))
    sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12]
    write_lines(root / "artifacts/sample.jsonl", sample)
    save(root / "artifacts/selection.json", selection)
    save(root / "artifacts/acquisition.json", acquisition)
    save(root / "artifacts/api_pages.json", load(out / "api_pages.json"))
    for source_page in sorted((out / "raw_api").rglob("*.json.gz")):
        destination = root / "artifacts" / "source_pages" / source_page.relative_to(out / "raw_api")
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_bytes(source_page.read_bytes())
    overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None
    target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None
    if overlap:
        save(root / "artifacts/overlap_audit.json", overlap)
    if target_audit:
        save(root / "artifacts/target_audit.json", target_audit)
    stats = {
        "eligible_source_records": selection["eligible_records"], "selection_pool": selection["pool_size"],
        "pilot_target": acquisition["target"], "acquired": len(acquisition["selected"]),
        "kept": len(rows), "rejected_by_text_qa": len(decisions) - len(rows),
        "tokens": sum(row["token_count"] for row in rows), "characters": sum(len(row["text"]) for row in rows),
        "author_coverage": sum(row["author"] != "Unknown" for row in rows) / len(rows) if rows else 0,
        "license_counts": dict(Counter(row["license"] for row in rows)), "sample_count": len(sample), "added": added,
    }
    qa = {
        "scope": "deterministic 100-record pilot, not a complete-corpus claim",
        "license_gate": "repository item metadata is an allowlisted CC BY or CC BY-SA label",
        "language_gate": "dc.language.iso:pl plus independent three-window langid vote",
        "pii_pattern_matches": dict(pii), "exact_dedup": True,
        "near_dedup": "deterministic capped 5-word-shingle hash Jaccard >= 0.90 within pilot",
        "biblioteka_nauki_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration",
        "benchmark_overlap": "pending", "limitations": [
            "repository-generated TEXT may inherit PDF extraction errors",
            "figures are omitted and tables may be flattened",
            "item-level license metadata does not prove every quoted third-party passage is reusable",
            "pattern checks are not comprehensive de-identification",
            "pilot yield and token counts must not be extrapolated to all 6183 eligible records",
        ],
    }
    save(root / "artifacts/stats.json", stats)
    save(root / "artifacts/qa.json", qa)
    protocol_id = "protocol:open-icm-pilot-v1"
    run = {
        "id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection,
                                  "acquisition": digest(acquisition)}),
        "protocol": protocol_id, "started_at": selection["observed_at"], "finished_at": now(),
        "success": True, "actor": "actor:codex", "stats": stats,
    }
    save(root / "artifacts/run.json", run)
    excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"}
    checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*"))
              if path.is_file()
              and path.relative_to(root).as_posix() not in excluded
              and not path.relative_to(root).as_posix().startswith("src/")}
    save(root / "artifacts/checksums.json", checks)
    source_version = "version:source:" + digest({"manifest": selection["source_manifest_sha256"],
                                                  "api_pages": selection["api_pages_sha256"]})
    dataset_version = "version:dataset:" + digest(checks)
    selection_evidence = "evidence:selection:" + digest(selection)
    acquisition_evidence = "evidence:acquisition:" + digest(acquisition)
    qa_evidence = "evidence:qa:" + digest(qa)
    evidence = [
        {"id": selection_evidence, "observation_type": "source_inventory_and_selection",
         "artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]},
        {"id": acquisition_evidence, "observation_type": "bitstream_acquisition",
         "artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]},
        {"id": qa_evidence, "observation_type": "pilot_qa", "artifact": "artifacts/qa.json",
         "content_address": digest(qa), "produced_by": run["id"]},
    ]
    overlap_evidence = None
    if overlap:
        overlap_evidence = "evidence:overlap:" + digest(overlap)
        evidence.append({"id": overlap_evidence, "observation_type": "metadata_overlap_audit",
                         "artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap),
                         "produced_by": run["id"]})
    target_evidence = None
    if target_audit:
        target_evidence = "evidence:target:" + digest(target_audit)
        evidence.append({"id": target_evidence, "observation_type": "target_registry_audit",
                         "artifact": "artifacts/target_audit.json", "content_address": digest(target_audit),
                         "produced_by": run["id"]})
    ontology = {
        "schema": "slayer-research-ontology-profile-v1",
        "objects": [{"id": "object:source:open-icm", "type": "Source"},
                    {"id": "object:dataset:open-icm-pl-pilot", "type": "Dataset"}],
        "versions": [{"id": source_version, "object": "object:source:open-icm",
                      "content_address": source_version.rsplit(":", 1)[-1]},
                     {"id": dataset_version, "object": "object:dataset:open-icm-pl-pilot",
                      "content_address": dataset_version.rsplit(":", 1)[-1]}],
        "protocols": [{"id": protocol_id, "procedure": "pinned discovery; allowlisted item license; Polish metadata and language vote; TEXT checksum; normalization; PII patterns; exact and near dedup"}],
        "runs": [run], "evidence": evidence,
        "claims": [
            {"id": "claim:eligible-count-observed", "statement": f"The pinned discovery run observed {selection['eligible_records']} unique Polish records carrying an allowlisted CC BY or CC BY-SA label.",
             "supported_by": [selection_evidence], "falsification_condition": "The preserved API pages and manifest do not reproduce the count and filters."},
            {"id": "claim:pilot-retention", "statement": f"The pilot retained {stats['kept']} records after text QA and within-pilot deduplication.",
             "supported_by": [acquisition_evidence, qa_evidence], "falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."},
            {"id": "claim:source-absence-at-audit", "statement": "OPEN ICM was not registered as a source in the pinned DynaWord data tree or open pull-request list at audit time.",
             "supported_by": [target_evidence] if target_evidence else [qa_evidence], "falsification_condition": "The pinned target evidence contains an OPEN ICM source or matching proposal."},
            {"id": "claim:training-value-untested", "statement": "Net corpus novelty and training benefit remain untested hypotheses.",
             "supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []),
             "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."},
        ],
        "actors": [{"id": "actor:piotrsty", "type": "Contributor"},
                   {"id": "actor:icm-uw", "type": "Organization"}, {"id": "actor:codex", "type": "Agent"}],
        "relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version},
                      {"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] +
                     ([{"source": dataset_version, "predicate": "VALIDATED_AGAINST",
                        "target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []),
        "pending": ["complete-corpus acquisition", "cross-source text deduplication", "benchmark contamination check",
                    "review of third-party quoted text", "controlled training ablation"],
    }
    save(root / "artifacts/ontology.json", ontology)
    card = f"""---
license: other
license_name: per-record-cc-by-or-cc-by-sa
language:
- pl
task_categories:
- text-generation
configs:
- config_name: default
  data_files:
  - split: train
    path: data/train-00000-of-00001.parquet
---

# OPEN ICM Polish publications pilot

A deterministic 100-record research pilot of Polish full-text publications
whose OPEN ICM item metadata declares an allowlisted CC BY or CC BY-SA license.
This is not a complete-corpus release.

- Acquired records: {stats['acquired']}
- Retained after text QA and within-source deduplication: {stats['kept']}
- Characters: {stats['characters']:,}
- Tokens: {stats['tokens']:,} (`cl100k_base` proxy)
- Author coverage: {stats['author_coverage']:.1%}
- License field: preserved per record

## Provenance and rights

Every row is linked to its OPEN ICM item, authors, repository license label,
normalized license identifier, selected TEXT bitstream metadata and checksums.
The accepted source labels are limited to CC BY and CC BY-SA variants. License
and attribution obligations remain applicable per record. Item-level licensing
does not establish the status of every quoted third-party passage.

## Processing and limitations

The repository-generated TEXT bundle is normalized for Unicode, whitespace,
page-number-only lines and wrapped lines. Email and labelled-phone patterns are
redacted. Language is checked independently across three text windows. Exact
and deterministic near deduplication are performed within the pilot.

PDF-derived text may contain extraction errors; figures are omitted and tables
may be flattened. Pattern checks are not comprehensive de-identification.
Cross-source text deduplication, benchmark contamination checks, quoted-text
review and controlled training ablations remain downstream gates.

## Review artifacts

See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`,
`overlap_audit.json`, `stats.json`, `qa.json`, `checksums.json`, `run.json` and
`ontology.json`. The ontology separates content-addressed Objects and Versions,
Protocols, actual Runs, Evidence, falsifiable Claims, Actors and typed lineage.
"""
    (root / "README.md").write_text(card, encoding="utf-8")
    (root / "NOTICE.md").write_text(
        "# Attribution and license notice\n\n"
        "Source: OPEN ICM, https://open.icm.edu.pl/home\n\n"
        "Each record retains its item URL, authorship, repository license label, normalized license identifier, "
        "bitstream metadata and license evidence where exposed by OPEN ICM. The applicable CC BY or CC BY-SA "
        "terms and attribution obligations apply per record; consult `artifacts/attribution.jsonl`.\n\n"
        "Preparation: Piotr Styla with OpenAI Codex. Changes: repository TEXT selection, Unicode and whitespace "
        "normalization, page-number-only removal, line-wrap repair, limited email and labelled-phone redaction, "
        "language/quality filtering and within-source deduplication. No endorsement by OPEN ICM or credited "
        "authors is implied.\n",
        encoding="utf-8",
    )
    print(json.dumps(stats, ensure_ascii=False, indent=2))


def audit_target(out):
    info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
    revision = info["sha"]
    tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}",
                        {"recursive": "true", "expand": "false"})
    discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions",
                               {"status": "open", "p": 0})
    paths = sorted(item.get("path", "") for item in tree)
    open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"),
                  "author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])]
    matches = [path for path in paths if any(term in path.casefold() for term in ("open_icm", "ceon"))]
    discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold()
                                                          for term in ("open icm", "ceon"))]
    report = {
        "target": TARGET, "revision": revision, "last_modified": info.get("lastModified"),
        "tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows,
        "matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches,
        "observed_at": now(),
    }
    save(out / "target_audit.json", report)
    print(json.dumps({"revision": revision, "source_absent": report["source_absent"],
                      "tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2))


def audit_overlap(out):
    from huggingface_hub import HfApi

    acquisition = load(out / "acquisition.json")
    revision = HfApi().dataset_info(TARGET).sha
    target = fetch_attribution_targets(TARGET, revision)
    target_by_title = {}
    for row_id, attribution, normalized in target:
        if normalized:
            target_by_title.setdefault(normalized, []).append((row_id, attribution))
    target_titles = list(target_by_title)
    results = []
    for record in acquisition["selected"]:
        title = normalize_title(record["title"])
        dois = [value.casefold() for value in values(record["metadata"], "dc.identifier.doi")]
        exact = [{"id": row_id, "attribution": attribution} for row_id, attribution, normalized in target
                 if (title and title in normalized) or any(doi in attribution.casefold() for doi in dois)]
        fuzzy = []
        if not exact and title:
            matches = get_close_matches(title, target_titles, n=3, cutoff=0.90)
            for normalized in matches:
                score = SequenceMatcher(None, title, normalized).ratio()
                fuzzy.extend({"score": score, "id": row_id, "attribution": attribution}
                             for row_id, attribution in target_by_title[normalized])
            fuzzy = fuzzy[:3]
        results.append({"item_id": record["item_id"], "title": record["title"], "doi": dois,
                        "exact_title_or_doi_matches": exact, "fuzzy_title_matches": fuzzy})
    report = {
        "target": f"{TARGET}:data/biblioteka_nauki", "target_revision": revision,
        "method": "DOI or normalized title substring; fallback SequenceMatcher >= 0.90 over attribution titles",
        "target_rows": len(target), "candidate_records": len(results),
        "records_with_exact_match": sum(bool(row["exact_title_or_doi_matches"]) for row in results),
        "records_with_fuzzy_match": sum(bool(row["fuzzy_title_matches"]) for row in results),
        "text_overlap": "not tested; target-wide text dedup remains an integration gate",
        "observed_at": now(), "results": results,
    }
    save(out / "overlap_audit.json", report)
    print(json.dumps({key: report[key] for key in ("target_revision", "target_rows", "candidate_records",
                                                    "records_with_exact_match", "records_with_fuzzy_match")},
                     ensure_ascii=False, indent=2))


def verify(out):
    import pyarrow.parquet as pq

    root = out / "hf_repo"
    table = pq.read_table(root / "data/train-00000-of-00001.parquet")
    rows = table.to_pylist()
    stats = load(root / "artifacts/stats.json")
    decisions = read_lines(root / "artifacts/decisions.jsonl")
    attribution = read_lines(root / "artifacts/attribution.jsonl")
    sample = read_lines(root / "artifacts/sample.jsonl")
    assert table.column_names == FIELDS
    assert len(rows) == stats["kept"] == len(attribution)
    assert len(decisions) == stats["acquired"]
    assert sum(item["selected"] for item in decisions) == len(rows)
    assert sum(row["token_count"] for row in rows) == stats["tokens"]
    assert all(row["source"] == SOURCE and row["license"] in LICENSES.values() for row in rows)
    assert all(EMAIL_RE.search(row["text"]) is None for row in rows)
    by_id = {row["id"]: row for row in rows}
    assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample)
    ontology = load(root / "artifacts/ontology.json")
    evidence = {item["id"] for item in ontology["evidence"]}
    assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"])
    checks = load(root / "artifacts/checksums.json")
    assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum for path, checksum in checks.items())
    for item in ontology["evidence"]:
        artifact = root / item["artifact"]
        assert artifact.is_file() and digest(load(artifact)) == item["content_address"]
    print(json.dumps({"verified": True, **stats}, ensure_ascii=False, indent=2))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--limit", type=int, default=100)
    parser.add_argument("--workers", type=int, default=8)
    parser.add_argument("--download-file", type=Path)
    parser.add_argument("command", choices=["discover", "acquire", "prepare_manual", "ingest_manual",
                                            "audit_target", "audit_overlap", "build", "verify"])
    args = parser.parse_args()
    if args.command == "discover":
        discover(args.output, args.limit)
    elif args.command == "acquire":
        acquire(args.output, args.workers)
    elif args.command == "prepare_manual":
        prepare_manual(args.output)
    elif args.command == "ingest_manual":
        ingest_manual(args.output, args.download_file)
    elif args.command == "audit_target":
        audit_target(args.output)
    elif args.command == "audit_overlap":
        audit_overlap(args.output)
    elif args.command == "build":
        build(args.output)
    else:
        verify(args.output)


if __name__ == "__main__":
    main()