File size: 33,623 Bytes
81fafcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the 2011-2022 remainder of PiotrSty Sejm speeches for DynaWord."""

from __future__ import annotations

import argparse
import collections
import datetime as dt
import hashlib
import importlib.metadata
import json
import pathlib
import platform
import re
import shutil
import sys
from typing import Any


SOURCE_NAME = "sejm_api_2011_2022"
SOURCE_REPOSITORY = "PiotrSty/sejm-speeches-corpus"
SOURCE_RELEASE = "v1.0.1"
TARGET_REPOSITORY = "SlayerLab/polish-dynaword"
SOURCE_LICENSE = "public-domain (official documents)"
START_DATE = "2011-01-01"
END_DATE = "2022-12-31"
EXPECTED_FIELDS = (
    "id", "text", "source", "added", "created", "token_count", "license", "author"
)
SOURCE_FIELDS = (
    "text", "speaker", "date", "term", "source_url", "char_count", "word_count", "has_events"
)
COPYRIGHT_ACT = "https://eli.gov.pl/api/acts/DU/2025/24/text/O/D20250024.pdf"
OPEN_DATA_ACT = "https://eli.gov.pl/api/acts/DU/2023/1524/text.html"
SEJM_API = "https://api.sejm.gov.pl/"
SEJM_API_DOCUMENTATION = "https://api.sejm.gov.pl/sejm.html"
COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$")


class BuildError(ValueError):
    pass


import sejm_api_common as common
from sejm_api_common import canonical_sha256, sha256_file, write_json





def stable_id(row: dict[str, Any]) -> str:
    return common.stable_document_id(row, SOURCE_NAME)


def registry_entry() -> str:
    return (
        f'    "{SOURCE_NAME}": {{\n'
        f'        "file_key": "{SOURCE_NAME}",\n'
        '        "pretty": "Sejm API parliamentary speeches (2011-2022)",\n'
        f'        "license": "{SOURCE_LICENSE}",\n'
        '        "license_spdx": "LicenseRef-Polish-Official-Documents",\n'
        '        "traceable": "Official parliamentary materials excluded from copyright "\n'
        '                     "under Polish Copyright Act art. 4(2); reusable under "\n'
        '                     "the Polish Open Data Act.",\n'
        f'        "upstream": "{SEJM_API}",\n'
        '        "provenance": "Official Sejm API records from the immutable "\n'
        '                      "PiotrSty/sejm-speeches-corpus v1.0.1 release, with "\n'
        '                      "speech-level source URLs and speaker attribution.",\n'
        '        "domain": "political/spoken",\n'
        f'        "created": "{START_DATE}, {END_DATE}",\n'
        '        "is_ocr": False,\n'
        '    },\n'
    )


def update_registry(registry: str) -> str:
    if re.search(rf'^\s{{4}}["\']{SOURCE_NAME}["\']\s*:', registry, re.MULTILINE):
        required = (
            '"file_key": "sejm_api_2011_2022"',
            '"license_spdx": "LicenseRef-Polish-Official-Documents"',
            '"upstream": "https://api.sejm.gov.pl/"',
        )
        if not all(value in registry for value in required):
            raise BuildError(f"existing {SOURCE_NAME} registry entry differs from the contract")
        return registry
    marker = '    "sejm_api": {'
    if registry.count(marker) != 1:
        raise BuildError("cannot locate the accepted sejm_api registry entry")
    return registry.replace(marker, registry_entry() + marker, 1)


def legal_evidence(source_revision: str, target_revision: str) -> dict[str, Any]:
    return common.legal_evidence(
        source_revision,
        target_revision,
        source_name=SOURCE_NAME,
        source_license=SOURCE_LICENSE,
        source_repository=SOURCE_REPOSITORY,
        target_repository=TARGET_REPOSITORY,
    )


def datasheet(stats: dict[str, Any], source_revision: str, target_revision: str) -> str:
    return f"""# {SOURCE_NAME}

Official Polish Sejm plenary speeches from 2011 through 2022. This contribution
adds the part of `PiotrSty/sejm-speeches-corpus` that was intentionally excluded
from the already merged `sejm_api` 2023-onward artifact.

## Dataset description

- Source: {SEJM_API}
- Source documentation: {SEJM_API_DOCUMENTATION}
- Domain: political/spoken
- Language: Polish (`pl`)
- License: `{SOURCE_LICENSE}`
- Created: {stats['created_min']} through {stats['created_max']}
- Added: {stats['added']}
- Contributor: Piotr Sty\u0142a (`PiotrSty` on Hugging Face; `PiotrStyla` on GitHub)

## Provenance and reproducibility

- Immutable source release: `{SOURCE_REPOSITORY}@{SOURCE_RELEASE}`
- Pinned source commit: `{source_revision}`
- Pinned DynaWord base: `{target_revision}`
- Rebuild: `python src/fetch_sejm_api_2011_2022.py --help`
- Per-speech official URLs are preserved in `{SOURCE_NAME}.attribution.jsonl`

## Existing-source overlap

This PR intentionally does not claim temporal novelty. The 2011-2019 portion
overlaps the date range of `parliamentary`, whose released records do not expose
machine-readable author metadata. The 2015-2022 portion overlaps the registered
`parlamint_pl` candidate range; at the pinned target commit no
`data/parlamint_pl/*.parquet` artifact exists. The contribution is submitted as
a speech-level, fully attributed, immutable-source-backed alternative so the
maintainers can decide whether to merge it whole, cap it, or select only the
currently missing years. Exact duplicates within this contribution are removed.

## Statistics

| Measure | Value |
|---|---:|
| Source rows inspected | {stats['read']:,} |
| Rows after 2022-12-31 excluded | {stats['drop_after_end']:,} |
| Rows before 2011-01-01 excluded | {stats['drop_before_start']:,} |
| Exact duplicate texts removed | {stats['drop_dup']:,} |
| Documents published | {stats['kept']:,} |
| Characters | {stats['chars']:,} |
| Tokens (`cl100k_base` proxy) | {stats['tokens']:,} |
| Documents with speaker attribution | {stats['authors_with_value']:,} |

The canonical schema is `id, text, source, added, created, token_count, license, author`.

## Licensing and privacy

Official parliamentary documents and materials are excluded from copyright by
article 4(2) of the Polish Copyright Act. Reuse is documented under the Polish
Open Data Act. The source release heuristically redacts email addresses, PESEL
identifiers and unambiguous Polish telephone numbers. Public-official names and
speech attribution remain. Downstream users must still review privacy,
third-party rights and provider-specific limitations.
"""


def contract_test() -> str:
    return f'''"""Contract checks for the {SOURCE_NAME} contribution."""

import hashlib
import json
import pathlib
import re

import pyarrow.parquet as pq


ROOT = pathlib.Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / "{SOURCE_NAME}"
MANIFEST = ROOT / "artifacts" / "{SOURCE_NAME}_ontology_manifest.json"


def sha256_file(path):
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def test_artifacts_and_schema():
    parquet = DATA / "{SOURCE_NAME}.parquet"
    stats = json.loads((DATA / "{SOURCE_NAME}.stats.json").read_text(encoding="utf-8"))
    table = pq.read_table(parquet)
    assert table.column_names == {list(EXPECTED_FIELDS)!r}
    assert table.num_rows == stats["kept"]
    assert stats["authors_with_value"] == stats["kept"]
    assert stats["created_min"] >= "{START_DATE}"
    assert stats["created_max"] <= "{END_DATE}"
    assert set(table.column("source").to_pylist()) == {{"{SOURCE_NAME}"}}
    assert set(table.column("license").to_pylist()) == {{"{SOURCE_LICENSE}"}}


def test_attribution_count_and_legal_evidence():
    stats = json.loads((DATA / "{SOURCE_NAME}.stats.json").read_text(encoding="utf-8"))
    sidecar = DATA / "{SOURCE_NAME}.attribution.jsonl"
    assert sum(1 for _ in sidecar.open(encoding="utf-8")) == stats["kept"]
    legal = json.loads((DATA / "{SOURCE_NAME}.license-evidence.json").read_text(encoding="utf-8"))
    assert legal["status"] == "reviewed-open-official-materials"
    assert legal["pinned_source"].endswith(stats["source_revision"])


def test_ontology_kernel_and_references():
    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
    required = {{
        "object", "version", "protocol", "run", "relations", "evidence",
        "claims", "claim_evidence", "actors", "attestations",
    }}
    assert required <= set(manifest)
    assert manifest["ontology_version"] == "slayer.ai/research-ontology/v0.1"

    actor_ids = {{item["id"] for item in manifest["actors"]}}
    assert manifest["run"]["actor_id"] in actor_ids
    assert manifest["version"]["object_id"] == manifest["object"]["id"]
    assert manifest["version"]["created_by"] in actor_ids
    assert re.fullmatch(r"sha256:[0-9a-f]{{64}}", manifest["version"]["digest"])
    assert re.search(r"@[0-9a-f]{{40}}/", manifest["version"]["payload_uri"])

    protocol = manifest["protocol"]
    protocol_version = protocol["version"]
    assert protocol_version["object_id"] == protocol["id"]
    assert manifest["run"]["protocol_version_id"] == protocol_version["id"]
    assert re.fullmatch(r"sha256:[0-9a-f]{{64}}", protocol_version["digest"])
    assert re.search(r"@[0-9a-f]{{40}}/", protocol_version["payload_uri"])
    script = ROOT / protocol["specification"]["source_path"]
    assert sha256_file(script) == protocol_version["code_sha256"]

    run = manifest["run"]
    assert run["started_at"] <= run["finished_at"]
    assert run["git_commit"] in protocol_version["payload_uri"]
    assert {{"python", "platform", "machine", "packages", "determinism"}} <= set(run["environment"])

    evidence_ids = {{item["id"] for item in manifest["evidence"]}}
    assert len(evidence_ids) == len(manifest["evidence"])
    for item in manifest["evidence"]:
        assert item["run_id"] == run["id"]
        assert item["subject_version"] == manifest["version"]["id"]
        assert re.search(r"@sha256:[0-9a-f]{{64}}$", item["id"])

    claim_ids = {{item["id"] for item in manifest["claims"]}}
    assert len(claim_ids) == len(manifest["claims"])
    for item in manifest["claims"]:
        assert item["scope"] == manifest["version"]["id"]
        assert item["asserted_by"] in actor_ids
        assert item["supported_by"]
        assert set(item["supported_by"]) <= evidence_ids
        assert item["falsification_condition"]

    for link in manifest["claim_evidence"]:
        assert link["claim_id"] in claim_ids
        assert link["evidence_id"] in evidence_ids
        assert link["relation"] in {{"SUPPORTS", "REFUTES", "QUALIFIES"}}

    edges = {{}}
    for relation in manifest["relations"]:
        source = relation["source_version_id"]
        target = relation["target_version_id"]
        assert source != target
        assert relation["introduced_by_run"] == run["id"]
        if target.startswith("slayer://version/"):
            edges.setdefault(source, set()).add(target)

    visiting, visited = set(), set()
    def visit(node):
        assert node not in visiting, "version lineage must be acyclic"
        if node in visited:
            return
        visiting.add(node)
        for target in edges.get(node, ()):
            visit(target)
        visiting.remove(node)
        visited.add(node)
    for node in edges:
        visit(node)

    for attestation in manifest["attestations"]:
        assert attestation["actor_id"] in actor_ids
        assert attestation["subject_version"] == manifest["version"]["id"]
        assert attestation["supported_by"]
        assert set(attestation["supported_by"]) <= evidence_ids


def test_manifest_artifact_checksums():
    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
    checksums = next(
        item["payload"] for item in manifest["evidence"]
        if item["observation_type"] == "artifact_checksums"
    )
    paths = {{
        "parquet_sha256": DATA / "{SOURCE_NAME}.parquet",
        "attribution_sha256": DATA / "{SOURCE_NAME}.attribution.jsonl",
        "stats_sha256": DATA / "{SOURCE_NAME}.stats.json",
        "legal_evidence_sha256": DATA / "{SOURCE_NAME}.license-evidence.json",
    }}
    assert {{name: sha256_file(path) for name, path in paths.items()}} == checksums
'''


def build(args: argparse.Namespace) -> dict[str, Any]:
    run_started_at = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    if not COMMIT_PATTERN.fullmatch(args.source_revision):
        raise BuildError("source revision must be a 40-character commit")
    if not COMMIT_PATTERN.fullmatch(args.target_revision):
        raise BuildError("target revision must be a 40-character commit")
    if not COMMIT_PATTERN.fullmatch(args.dataset_payload_commit):
        raise BuildError("dataset payload commit must be a 40-character commit")
    if not COMMIT_PATTERN.fullmatch(args.protocol_payload_commit):
        raise BuildError("protocol payload commit must be a 40-character commit")
    if not args.target_registry.is_file():
        raise BuildError("target sources.py is missing")

    import pyarrow as pa
    import pyarrow.parquet as pq
    import tiktoken

    output = args.output
    data_dir = output / "data" / SOURCE_NAME
    artifact_dir = output / "artifacts"
    src_dir = output / "src"
    for directory in (data_dir, artifact_dir, src_dir):
        directory.mkdir(parents=True, exist_ok=True)

    schema = pa.schema([
        ("id", pa.string()), ("text", pa.string()), ("source", pa.string()),
        ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()),
        ("license", pa.string()), ("author", pa.string()),
    ])
    encoder = tiktoken.get_encoding("cl100k_base")
    parquet_path = data_dir / f"{SOURCE_NAME}.parquet"
    sidecar_path = data_dir / f"{SOURCE_NAME}.attribution.jsonl"
    counter: collections.Counter[str] = collections.Counter({
        "read": 0, "kept": 0, "drop_before_start": 0, "drop_after_end": 0,
        "drop_dup": 0, "chars": 0, "tokens": 0, "authors_with_value": 0,
    })
    years: collections.Counter[str] = collections.Counter()
    terms: collections.Counter[str] = collections.Counter()
    splits: collections.Counter[str] = collections.Counter()
    seen: set[str] = set()
    dates: list[str] = []
    batch_rows: list[dict[str, Any]] = []

    with pq.ParquetWriter(parquet_path, schema, compression="zstd") as writer:
        with sidecar_path.open("w", encoding="utf-8") as sidecar:
            for split in ("train", "validation"):
                source_file = args.source_dir / "data" / f"{split}.parquet"
                if not source_file.is_file():
                    raise BuildError(f"missing source split: {source_file}")
                source_parquet = pq.ParquetFile(source_file)
                if set(source_parquet.schema_arrow.names) != set(SOURCE_FIELDS):
                    raise BuildError(f"unexpected source schema: {source_parquet.schema_arrow.names}")
                for batch in source_parquet.iter_batches(batch_size=512):
                    for row in batch.to_pylist():
                        counter["read"] += 1
                        created = dt.date.fromisoformat(str(row["date"])[:10]).isoformat()
                        if created < START_DATE:
                            counter["drop_before_start"] += 1
                            continue
                        if created > END_DATE:
                            counter["drop_after_end"] += 1
                            continue
                        text = str(row["text"]).strip()
                        author = str(row["speaker"]).strip()
                        source_url = str(row["source_url"]).strip()
                        term = str(row["term"]).strip()
                        if len(text) < 200 or not author:
                            raise BuildError("pinned source violates the accepted text/author contract")
                        if not source_url.startswith(SEJM_API) or term not in {"7", "8", "9"}:
                            raise BuildError(f"unexpected source row: term={term!r}, url={source_url!r}")
                        fingerprint = hashlib.sha1(text.encode("utf-8")).hexdigest()
                        if fingerprint in seen:
                            counter["drop_dup"] += 1
                            continue
                        seen.add(fingerprint)
                        document_id = stable_id(row)
                        token_count = len(encoder.encode_ordinary(text))
                        document = {
                            "id": document_id, "text": text, "source": SOURCE_NAME,
                            "added": args.added_date, "created": created,
                            "token_count": token_count, "license": SOURCE_LICENSE,
                            "author": author,
                        }
                        attribution = {
                            "id": document_id, "source_url": source_url, "speaker": author,
                            "created": created, "term": term, "has_events": bool(row["has_events"]),
                            "word_count": int(row["word_count"]), "char_count": int(row["char_count"]),
                            "provider": "Kancelaria Sejmu RP", "source_revision": args.source_revision,
                            "source_split": split,
                            "source_release": f"hf://datasets/{SOURCE_REPOSITORY}@{SOURCE_RELEASE}",
                        }
                        sidecar.write(json.dumps(attribution, ensure_ascii=False, sort_keys=True) + "\n")
                        batch_rows.append(document)
                        counter["kept"] += 1
                        counter["chars"] += len(text)
                        counter["tokens"] += token_count
                        counter["authors_with_value"] += 1
                        years[created[:4]] += 1
                        terms[term] += 1
                        splits[split] += 1
                        dates.append(created)
                        if len(batch_rows) >= 1024:
                            writer.write_table(pa.Table.from_pylist(batch_rows, schema=schema))
                            batch_rows.clear()
            if batch_rows:
                writer.write_table(pa.Table.from_pylist(batch_rows, schema=schema))

    if not counter["kept"] or counter["authors_with_value"] != counter["kept"]:
        raise BuildError("empty output or incomplete attribution")
    stats: dict[str, Any] = {
        **counter, "license": SOURCE_LICENSE, "licenses": {SOURCE_LICENSE: counter["kept"]},
        "added": args.added_date, "created_min": min(dates), "created_max": max(dates),
        "by_year": dict(sorted(years.items())), "by_term": dict(sorted(terms.items())),
        "by_source_split": dict(sorted(splits.items())), "stats_recomputed_from_parquet": True,
        "source_revision": args.source_revision, "target_base_revision": args.target_revision,
    }
    stats_path = data_dir / f"{SOURCE_NAME}.stats.json"
    legal_path = data_dir / f"{SOURCE_NAME}.license-evidence.json"
    write_json(stats_path, stats)
    write_json(legal_path, legal_evidence(args.source_revision, args.target_revision))
    (data_dir / f"{SOURCE_NAME}.md").write_text(
        datasheet(stats, args.source_revision, args.target_revision), encoding="utf-8"
    )
    (data_dir / "NOTICE.md").write_text(
        "# Source attribution\n\nOfficial materials: Kancelaria Sejmu RP, "
        "API Sejmu - https://api.sejm.gov.pl/.\n\nSpeech attribution and official "
        "source URLs are preserved in the attribution sidecar. Corpus preparation "
        "and contribution: Piotr Sty\u0142a (PiotrSty / PiotrStyla).\n",
        encoding="utf-8",
    )

    artifact_digests = {
        "parquet_sha256": sha256_file(parquet_path),
        "attribution_sha256": sha256_file(sidecar_path),
        "stats_sha256": sha256_file(stats_path),
        "legal_evidence_sha256": sha256_file(legal_path),
    }
    expected_digests = {
        "parquet_sha256": args.expected_parquet_sha256,
        "attribution_sha256": args.expected_attribution_sha256,
    }
    supplied_expected = {key: value for key, value in expected_digests.items() if value}
    mismatches = {
        key: {"expected": expected, "actual": artifact_digests[key]}
        for key, expected in supplied_expected.items()
        if artifact_digests[key] != expected
    }
    if mismatches:
        raise BuildError(f"reproduction digest mismatch: {mismatches}")

    version_digest = canonical_sha256({
        "source_revision": args.source_revision, "target_revision": args.target_revision,
        "range": [START_DATE, END_DATE], "artifacts": artifact_digests,
    })
    object_id = f"slayer://object/dataset-source/{SOURCE_NAME}"
    version_id = f"slayer://version/dataset-source/{SOURCE_NAME}@sha256:{version_digest}"
    protocol_object_id = f"slayer://object/protocol/{SOURCE_NAME}-filter"
    protocol_configuration = {
        "date_range": [START_DATE, END_DATE],
        "deduplication": {"algorithm": "sha1", "field": "text", "scope": "within_source"},
        "id_generation": {"algorithm": "sha256", "fields": ["date", "term", "speaker", "text"]},
        "minimum_text_characters": 200,
        "parquet": {"compression": "zstd", "write_batch_size": 1024},
        "source_splits": ["train", "validation"],
        "speaker_required": True,
        "tokenizer": "cl100k_base",
    }
    protocol_specification = {
        "entrypoint": "python src/fetch_sejm_api_2011_2022.py",
        "source_path": "src/fetch_sejm_api_2011_2022.py",
        "summary": "Deterministic date filtering, exact-text deduplication, attribution preservation and DynaWord projection.",
        "configuration": protocol_configuration,
        "required_inputs": ["pinned source Parquet splits", "pinned target sources.py"],
        "outputs": ["DynaWord Parquet", "attribution sidecar", "stats", "legal evidence", "ontology manifest"],
    }
    protocol_code_digest = sha256_file(pathlib.Path(__file__).resolve())
    protocol_digest = canonical_sha256({
        "object_id": protocol_object_id,
        "code_sha256": protocol_code_digest,
        "specification": protocol_specification,
    })
    protocol_version_id = f"slayer://version/protocol/{SOURCE_NAME}-filter@sha256:{protocol_digest}"
    source_version_id = f"hf://datasets/{SOURCE_REPOSITORY}@{args.source_revision}"
    target_version_id = f"hf://datasets/{TARGET_REPOSITORY}@{args.target_revision}"
    run_finished_at = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    environment = {
        "python": sys.version,
        "python_executable": sys.executable,
        "platform": platform.platform(),
        "machine": platform.machine(),
        "packages": {
            "pyarrow": pa.__version__,
            "tiktoken": importlib.metadata.version("tiktoken"),
        },
        "container_image": None,
        "environment_limitation": "No container image was used; material runtime and package versions are recorded.",
        "determinism": {"sampling": "none", "seed": None, "input_order": ["train", "validation"]},
    }

    def evidence(observation_type: str, payload: Any) -> dict[str, Any]:
        evidence_digest = canonical_sha256({
            "run_id": args.run_id,
            "subject_version": version_id,
            "observation_type": observation_type,
            "payload": payload,
        })
        return {
            "id": f"slayer://evidence/{SOURCE_NAME}/{observation_type}@sha256:{evidence_digest}",
            "run_id": args.run_id,
            "subject_version": version_id,
            "observation_type": observation_type,
            "payload": payload,
            "observed_at": run_finished_at,
        }

    evidence_items = [
        evidence("dataset_record_counts", stats),
        evidence("speaker_attribution_coverage", {
            "records": counter["kept"], "non_empty_authors": counter["authors_with_value"],
            "coverage": counter["authors_with_value"] / counter["kept"],
        }),
        evidence("known_temporal_overlap", {
            "parliamentary_registered_range": "1991-2019",
            "parlamint_pl_registered_range": "2015-2022",
            "novelty_claimed": False,
        }),
        evidence("artifact_checksums", artifact_digests),
        evidence("legal_provenance_review", {
            "status": "reviewed-open-official-materials",
            "artifact": f"data/{SOURCE_NAME}/{SOURCE_NAME}.license-evidence.json",
            "sha256": artifact_digests["legal_evidence_sha256"],
            "limitations_retained": True,
        }),
        evidence("schema_validation", {
            "schema": list(EXPECTED_FIELDS), "records": counter["kept"], "valid": True,
        }),
        evidence("pinned_input_reproduction", {
            "expected": supplied_expected,
            "actual": {key: artifact_digests[key] for key in supplied_expected},
            "matches": bool(supplied_expected) and not mismatches,
        }),
    ]
    evidence_by_type = {item["observation_type"]: item["id"] for item in evidence_items}

    def claim(statement: str, falsification_condition: str, supported_by: list[str]) -> dict[str, Any]:
        claim_digest = canonical_sha256({
            "scope": version_id,
            "statement": statement,
            "falsification_condition": falsification_condition,
        })
        return {
            "id": f"slayer://claim/{SOURCE_NAME}@sha256:{claim_digest}",
            "scope": version_id,
            "statement": statement,
            "asserted_by": args.actor,
            "supported_by": supported_by,
            "falsification_condition": falsification_condition,
        }

    claims = [
        claim(
            "All retained records from the pinned source dated 2011-2022 are included after exact within-source deduplication.",
            "A qualifying pinned-source record is absent without a recorded drop reason.",
            [evidence_by_type["dataset_record_counts"]],
        ),
        claim(
            "Every contributed document has non-empty speaker attribution.",
            "Any contributed author field is empty.",
            [evidence_by_type["speaker_attribution_coverage"]],
        ),
        claim(
            "The contribution does not establish temporal novelty relative to every target source because registered ranges overlap.",
            "The cited target-source ranges do not overlap 2011-2022.",
            [evidence_by_type["known_temporal_overlap"]],
        ),
        claim(
            "The contributed records are official Sejm materials documented for statutory reuse, subject to retained privacy and third-party limitations.",
            "The records are not official materials or the cited legal basis and provider conditions contradict the documented reuse status.",
            [evidence_by_type["legal_provenance_review"]],
        ),
        claim(
            "The generated artifact set conforms to the DynaWord source schema and recorded checksums.",
            "A contract field is missing, a row violates the schema, or a recorded artifact checksum differs.",
            [evidence_by_type["schema_validation"], evidence_by_type["artifact_checksums"]],
        ),
    ]
    if supplied_expected:
        claims.append(claim(
            "Rebuilding from pinned inputs reproduced the expected Parquet and attribution-sidecar digests.",
            "A rebuilt Parquet or attribution-sidecar digest differs from the expected digest.",
            [evidence_by_type["pinned_input_reproduction"]],
        ))

    claim_evidence = [
        {
            "claim_id": item["id"], "evidence_id": evidence_id,
            "relation": "SUPPORTS", "introduced_by_run": args.run_id,
        }
        for item in claims for evidence_id in item["supported_by"]
    ]

    def attestation(attestation_type: str, value: Any, supported_by: list[str]) -> dict[str, Any]:
        attestation_digest = canonical_sha256({
            "type": attestation_type, "value": value, "actor_id": args.actor,
            "subject_version": version_id, "supported_by": supported_by,
        })
        return {
            "id": f"slayer://attestation/{SOURCE_NAME}/{attestation_type}@sha256:{attestation_digest}",
            "type": attestation_type,
            "value": value,
            "actor_id": args.actor,
            "subject_version": version_id,
            "supported_by": supported_by,
            "created_at": run_finished_at,
        }

    manifest = {
        "schema_version": "slayer.ai/dataset-source-contribution/v1",
        "ontology_version": "slayer.ai/research-ontology/v0.1",
        "object": {
            "id": object_id, "kind": "dataset_source", "name": SOURCE_NAME,
            "metadata": {"language": "pl", "domain": "political/spoken", "provider": "Kancelaria Sejmu RP"},
        },
        "version": {
            "id": version_id,
            "object_id": object_id,
            "digest": f"sha256:{version_digest}",
            "schema_version": "slayer.ai/dataset-source/v1",
            "payload_uri": f"hf://datasets/{TARGET_REPOSITORY}@{args.dataset_payload_commit}/data/{SOURCE_NAME}/{SOURCE_NAME}.parquet",
            "created_at": args.version_created_at,
            "created_by": args.actor,
        },
        "protocol": {
            "id": protocol_object_id,
            "kind": "dataset_filtering",
            "name": f"{SOURCE_NAME}-filter",
            "version": {
                "id": protocol_version_id,
                "object_id": protocol_object_id,
                "digest": f"sha256:{protocol_digest}",
                "code_sha256": protocol_code_digest,
                "schema_version": "slayer.ai/protocol/v1",
                "payload_uri": f"hf://datasets/{TARGET_REPOSITORY}@{args.protocol_payload_commit}/src/fetch_sejm_api_2011_2022.py",
                "created_at": run_finished_at,
                "created_by": args.actor,
            },
            "specification": protocol_specification,
        },
        "run": {
            "id": args.run_id,
            "protocol_version_id": protocol_version_id,
            "actor_id": args.actor,
            "git_commit": args.protocol_payload_commit,
            "started_at": run_started_at,
            "finished_at": run_finished_at,
            "config": protocol_configuration,
            "environment": environment,
            "inputs": [
                {"role": "source", "version_id": source_version_id},
                {"role": "target_base", "version_id": target_version_id},
            ],
            "outputs": [{"role": "dataset_source", "version_id": version_id}],
        },
        "relations": [
            {"source_version_id": version_id, "predicate": "DERIVED_FROM", "target_version_id": source_version_id, "introduced_by_run": args.run_id},
            {"source_version_id": version_id, "predicate": "COMPATIBLE_WITH", "target_version_id": target_version_id, "introduced_by_run": args.run_id},
            {"source_version_id": version_id, "predicate": "FILTERED_BY", "target_version_id": protocol_version_id, "introduced_by_run": args.run_id},
        ],
        "evidence": evidence_items,
        "claims": claims,
        "claim_evidence": claim_evidence,
        "actors": [{
            "id": args.actor, "kind": "human", "identity": "Piotr Sty\u0142a",
            "identifiers": {"hugging_face": "PiotrSty", "github": "PiotrStyla"},
        }],
        "attestations": [
            attestation("schema_valid", True, [evidence_by_type["schema_validation"], evidence_by_type["artifact_checksums"]]),
            attestation("temporal_overlap", "known_and_disclosed", [evidence_by_type["known_temporal_overlap"]]),
            attestation("speaker_attribution", "100_percent", [evidence_by_type["speaker_attribution_coverage"]]),
            attestation("legal_status", "documented_open_official_materials_with_limitations", [evidence_by_type["legal_provenance_review"]]),
            attestation("pinned_input_reproduction", bool(supplied_expected), [evidence_by_type["pinned_input_reproduction"]]),
        ],
    }
    write_json(artifact_dir / f"{SOURCE_NAME}_ontology_manifest.json", manifest)
    (src_dir / "sources.py").write_text(
        update_registry(args.target_registry.read_text(encoding="utf-8")), encoding="utf-8"
    )
    shutil.copy2(pathlib.Path(__file__).resolve(), src_dir / "fetch_sejm_api_2011_2022.py")
    (src_dir / "test_sejm_api_2011_2022_contract.py").write_text(contract_test(), encoding="utf-8")
    return stats


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-dir", type=pathlib.Path, required=True)
    parser.add_argument("--target-registry", type=pathlib.Path, required=True)
    parser.add_argument("--output", type=pathlib.Path, required=True)
    parser.add_argument("--source-revision", required=True)
    parser.add_argument("--target-revision", required=True)
    parser.add_argument("--dataset-payload-commit", required=True)
    parser.add_argument("--protocol-payload-commit", required=True)
    parser.add_argument("--version-created-at", default="2026-08-31T09:59:00Z")
    parser.add_argument("--expected-parquet-sha256")
    parser.add_argument("--expected-attribution-sha256")
    parser.add_argument("--added-date", default=dt.datetime.now(dt.timezone.utc).date().isoformat())
    parser.add_argument("--actor", default="hf:PiotrSty")
    parser.add_argument("--run-id", default=f"sejm-api-2011-2022-{dt.datetime.now(dt.timezone.utc).strftime('%Y%m%dT%H%M%SZ')}")
    args = parser.parse_args()
    stats = build(args)
    print(json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())