kacperwikiel PiotrSty commited on
Commit
1564cb0
·
1 Parent(s): bade8e7

Add UZP public-procurement rulings (KIO/SO/SA/SN) (#39)

Browse files

- Add UZP public-procurement rulings (KIO/SO/SA/SN) (1a1c510a22dce0fd2e8a314c3884870221d3805d)


Co-authored-by: Piotr Styla <PiotrSty@users.noreply.huggingface.co>

.gitattributes CHANGED
@@ -60,3 +60,5 @@ data/samorzad_gov_pl/*.jsonl filter=lfs diff=lfs merge=lfs -text
60
  *.mp4 filter=lfs diff=lfs merge=lfs -text
61
  *.webm filter=lfs diff=lfs merge=lfs -text
62
  data/sejm_api/sejm_api.attribution.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
 
60
  *.mp4 filter=lfs diff=lfs merge=lfs -text
61
  *.webm filter=lfs diff=lfs merge=lfs -text
62
  data/sejm_api/sejm_api.attribution.jsonl filter=lfs diff=lfs merge=lfs -text
63
+ data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.attribution.jsonl filter=lfs diff=lfs merge=lfs -text
64
+ data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.decisions.jsonl filter=lfs diff=lfs merge=lfs -text
artifacts/uzp_orzeczenia_pl_ontology_manifest.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "actors": [
3
+ {
4
+ "id": "actor:piotrsty",
5
+ "type": "Contributor"
6
+ },
7
+ {
8
+ "id": "actor:uzp",
9
+ "type": "Organization"
10
+ },
11
+ {
12
+ "id": "actor:devin",
13
+ "type": "Agent"
14
+ }
15
+ ],
16
+ "claims": [
17
+ {
18
+ "falsification_condition": "The pinned Parquet, decisions or overlap report do not reproduce these counts.",
19
+ "id": "claim:uzp-target-retention",
20
+ "statement": "The proposed DynaWord slice contains 34715 records after excluding 0 signature overlaps.",
21
+ "supported_by": [
22
+ "evidence:uzp-target-stats:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0",
23
+ "evidence:uzp-target-overlap:d70053726c85373e3411cc28da26c3aeffbd25cf9adf7c30a3ecdda3ebeaef10"
24
+ ]
25
+ },
26
+ {
27
+ "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties.",
28
+ "id": "claim:uzp-training-value-untested",
29
+ "statement": "Net text novelty and training benefit remain untested hypotheses.",
30
+ "supported_by": [
31
+ "evidence:uzp-target-overlap:d70053726c85373e3411cc28da26c3aeffbd25cf9adf7c30a3ecdda3ebeaef10"
32
+ ]
33
+ }
34
+ ],
35
+ "evidence": [
36
+ {
37
+ "artifact": "data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.stats.json",
38
+ "content_address": "57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0",
39
+ "id": "evidence:uzp-target-stats:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0",
40
+ "observation_type": "target_slice_counts",
41
+ "produced_by": "run:uzp-orzeczenia-dynaword-integration:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0"
42
+ },
43
+ {
44
+ "artifact": "data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.overlap_audit.json",
45
+ "content_address": "d70053726c85373e3411cc28da26c3aeffbd25cf9adf7c30a3ecdda3ebeaef10",
46
+ "id": "evidence:uzp-target-overlap:d70053726c85373e3411cc28da26c3aeffbd25cf9adf7c30a3ecdda3ebeaef10",
47
+ "observation_type": "metadata_overlap_audit",
48
+ "produced_by": "run:uzp-orzeczenia-dynaword-integration:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0"
49
+ }
50
+ ],
51
+ "objects": [
52
+ {
53
+ "id": "object:dataset:uzp-orzeczenia-pl",
54
+ "type": "Dataset"
55
+ },
56
+ {
57
+ "id": "object:dataset:uzp-orzeczenia-pl-dynaword-slice",
58
+ "type": "Dataset"
59
+ }
60
+ ],
61
+ "pending": [
62
+ "formal legal review of art. 4(2) application",
63
+ "cross-source text deduplication",
64
+ "benchmark contamination check",
65
+ "review of quoted third-party text",
66
+ "controlled training ablation"
67
+ ],
68
+ "protocols": [
69
+ {
70
+ "id": "protocol:uzp-orzeczenia-dynaword-integration-v1",
71
+ "procedure": "exclude source-QA failures and signature overlaps with pinned saos; preserve attribution and pending text-level gates"
72
+ }
73
+ ],
74
+ "relations": [
75
+ {
76
+ "predicate": "DERIVED_FROM",
77
+ "source": "version:dataset:uzp-orzeczenia-pl-dynaword:2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
78
+ "target": "hf:dataset:PiotrSty/uzp-orzeczenia-pl@696485691e9f8cb85d1a34221897250e25359ba0"
79
+ },
80
+ {
81
+ "predicate": "GENERATED_BY",
82
+ "source": "version:dataset:uzp-orzeczenia-pl-dynaword:2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
83
+ "target": "run:uzp-orzeczenia-dynaword-integration:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0"
84
+ },
85
+ {
86
+ "predicate": "VALIDATED_AGAINST",
87
+ "source": "version:dataset:uzp-orzeczenia-pl-dynaword:2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
88
+ "target": "hf:dataset:SlayerLab/polish-dynaword@bade8e7cae51bd30e9530c3be38dd0e3eeba1f70"
89
+ }
90
+ ],
91
+ "runs": [
92
+ {
93
+ "actor": "actor:devin",
94
+ "finished_at": "2026-09-19T06:14:52.208957+00:00",
95
+ "id": "run:uzp-orzeczenia-dynaword-integration:57384373cb2c3883fb240ab0468d309dc62893a01ccd939f25081a931a1c20c0",
96
+ "protocol": "protocol:uzp-orzeczenia-dynaword-integration-v1",
97
+ "started_at": "2026-09-19T06:14:52.208957+00:00",
98
+ "stats": {
99
+ "added": "2026-09-17",
100
+ "characters": 1110428704,
101
+ "enumerated": 35694,
102
+ "kept": 34715,
103
+ "license_counts": {
104
+ "public-domain (official documents)": 34715
105
+ },
106
+ "per_kind": {
107
+ "KIO": 34412,
108
+ "SA": 3,
109
+ "SN": 2,
110
+ "SO": 1277
111
+ },
112
+ "sample_count": 12,
113
+ "source_slice_kept": 34715,
114
+ "target_overlap_excluded": 0,
115
+ "target_revision": "bade8e7cae51bd30e9530c3be38dd0e3eeba1f70",
116
+ "tokens": 422043881
117
+ },
118
+ "success": true
119
+ }
120
+ ],
121
+ "schema": "slayer-research-ontology-profile-v1",
122
+ "versions": [
123
+ {
124
+ "content_address": "696485691e9f8cb85d1a34221897250e25359ba0",
125
+ "id": "hf:dataset:PiotrSty/uzp-orzeczenia-pl@696485691e9f8cb85d1a34221897250e25359ba0",
126
+ "object": "object:dataset:uzp-orzeczenia-pl"
127
+ },
128
+ {
129
+ "content_address": "2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
130
+ "id": "version:dataset:uzp-orzeczenia-pl-dynaword:2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
131
+ "object": "object:dataset:uzp-orzeczenia-pl-dynaword-slice"
132
+ }
133
+ ]
134
+ }
data/uzp_orzeczenia_pl/NOTICE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Attribution and legal basis
2
+
3
+ Source: UZP decision search service, https://orzeczenia.uzp.gov.pl/ (Urzad Zamowien Publicznych / Public Procurement Office).
4
+
5
+ Records are official rulings (KIO, district courts, administrative courts, Supreme Court) in public procurement matters. Working basis: Polish Copyright Act art. 4(2) excludes official documents from copyright; no per-record license field exists on the service. Formal legal review has not been performed. Consult `artifacts/attribution.jsonl` for per-record provenance (organ, signature, issue date, URLs, checksums).
6
+
7
+ Preparation: Piotr Styla with Devin (Cognition). Changes: service-PDF text extraction, running-head and page-number removal, Unicode/whitespace normalization, line-wrap repair, limited email/phone/IP/identifier/account pattern redaction, language/quality filtering and within-source deduplication. Names of parties and adjudicators remain as part of the official record. No endorsement by UZP, KIO or the courts is implied.
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.attribution.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37e2a74646232784622a504a10f1b05aca0a16a6a9c647c4611d12c3f13726a5
3
+ size 39221303
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.checksums.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "NOTICE.md": "7c9174db26e75108686bec4c2f68e07c7a778ccb774add23eb60c19e131e9867",
3
+ "uzp_orzeczenia_pl.attribution.jsonl": "37e2a74646232784622a504a10f1b05aca0a16a6a9c647c4611d12c3f13726a5",
4
+ "uzp_orzeczenia_pl.decisions.jsonl": "e80c5cac3c5c2786aeaeeb4babe6adcdf9355262e2657e06de61604f64b3cb60",
5
+ "uzp_orzeczenia_pl.md": "2c046f70c82f03fd051fb57f6b4028b70d42017d5883f7821f057db6f59bcbbd",
6
+ "uzp_orzeczenia_pl.overlap_audit.json": "584de6d8816921fb2bc3b312cbaa190ecfb829bbb471d97346db7d2989c4d72c",
7
+ "uzp_orzeczenia_pl.parquet": "2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a",
8
+ "uzp_orzeczenia_pl.qa.json": "2cd46cf726277064d051f96df0d99e4a5c7ee391ce53a15cabca9c5d9860219f",
9
+ "uzp_orzeczenia_pl.sample.jsonl": "d47fd82b7df915bc4957d8335fbc763749ceca796acd7afe4e504d1f37bdfe55",
10
+ "uzp_orzeczenia_pl.stats.json": "0dbc1b8a1fc7605178a012e1451baf0372eaefd1ad66e19243c73caad3e39e60"
11
+ }
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.decisions.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e80c5cac3c5c2786aeaeeb4babe6adcdf9355262e2657e06de61604f64b3cb60
3
+ size 11277464
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # UZP Orzeczenia - Polish public-procurement rulings (KIO/SO/SA/SN)
2
+
3
+ This slice is derived from the deterministic enumeration of the official UZP
4
+ decision search service (https://orzeczenia.uzp.gov.pl/): all rulings of the
5
+ National Appeals Chamber (KIO), district courts (SO), administrative courts (SA)
6
+ and the Supreme Court (SN) in public procurement matters.
7
+
8
+ - Enumerated documents: 35,694 (per kind: {'KIO': 34412, 'SA': 3, 'SN': 2, 'SO': 1277})
9
+ - Source slice retained after QA: 34715
10
+ - Signature overlaps with `saos` excluded: 0
11
+ - Proposed records: 34715
12
+ - Proposed tokens: 422,043,881 (`cl100k_base` proxy)
13
+ - Characters: 1,110,428,704
14
+ - License label: `public-domain (official documents)` (LicenseRef-Polish-Official-Documents)
15
+ - Immutable source snapshot: https://huggingface.co/datasets/PiotrSty/uzp-orzeczenia-pl/tree/696485691e9f8cb85d1a34221897250e25359ba0
16
+
17
+ Per-record attribution, landing URLs, PDF URLs and checksums are preserved.
18
+ Rulings are official documents; the working basis is Polish Copyright Act
19
+ art. 4(2) - no formal legal review has been performed. Cross-source text
20
+ deduplication and benchmark checks remain integration gates. pypdf-derived
21
+ text can retain layout artifacts and flattened tables. Names of parties and
22
+ adjudicators remain part of the official record; pattern-based PII checks are
23
+ not comprehensive de-identification.
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.overlap_audit.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "candidate_records": 35694,
3
+ "colliding_ids": [],
4
+ "collisions": [],
5
+ "method": "case-normalized signature match against SAOS attribution strings",
6
+ "observed_at": "2026-09-18T04:34:43.880281+00:00",
7
+ "saos_rows": 0,
8
+ "signature_collisions": 0,
9
+ "target": "SlayerLab/polish-dynaword:data/saos",
10
+ "target_revision": "bade8e7cae51bd30e9530c3be38dd0e3eeba1f70",
11
+ "text_overlap": "not tested; target-wide text dedup remains an integration gate"
12
+ }
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c7a13f99ee5571aa66a4d576a6b6705a3a896675ffc93d889447ca0ed9aae1a
3
+ size 328263070
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.qa.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark_overlap": "pending",
3
+ "cross_source_text_dedup": "pending target integration",
4
+ "known_target_signature_overlap_excluded": 0,
5
+ "limitations": [
6
+ "pypdf extraction may retain layout artifacts; tables may be flattened",
7
+ "pattern checks are not comprehensive de-identification; natural-person names of parties and adjudicators remain part of the official record",
8
+ "official-document status does not cover third-party material quoted inside rulings",
9
+ "sequential IDs contain gaps; enumeration follows the server-side result list, not the ID range"
10
+ ],
11
+ "scope": "DynaWord proposal derived from the UZP procurement-rulings corpus",
12
+ "source_text_qa_rejected": 979,
13
+ "within_source_exact_and_near_dedup": true
14
+ }
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.sample.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/uzp_orzeczenia_pl/uzp_orzeczenia_pl.stats.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added": "2026-09-17",
3
+ "characters": 1110428704,
4
+ "enumerated": 35694,
5
+ "kept": 34715,
6
+ "license_counts": {
7
+ "public-domain (official documents)": 34715
8
+ },
9
+ "per_kind": {
10
+ "KIO": 34412,
11
+ "SA": 3,
12
+ "SN": 2,
13
+ "SO": 1277
14
+ },
15
+ "sample_count": 12,
16
+ "source_slice_kept": 34715,
17
+ "target_overlap_excluded": 0,
18
+ "target_revision": "bade8e7cae51bd30e9530c3be38dd0e3eeba1f70",
19
+ "tokens": 422043881
20
+ }
src/build_uzp_orzeczenia_pl.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build an auditable corpus of UZP public-procurement rulings (KIO/SO/SA/SN).
3
+
4
+ Source: https://orzeczenia.uzp.gov.pl - the official decision search service of
5
+ the Polish Public Procurement Office (Urzad Zamowien Publicznych). Documents
6
+ are official rulings of the National Appeals Chamber (KIO), district courts
7
+ (SO), administrative courts (SA) and the Supreme Court (SN) in public
8
+ procurement matters. Legal basis: official documents are excluded from
9
+ copyright under Polish Copyright Act art. 4(2) (same basis as the SAOS slice).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ from collections import Counter
15
+ from concurrent.futures import ThreadPoolExecutor, as_completed
16
+ from datetime import datetime, timezone
17
+ import gzip
18
+ import hashlib
19
+ import html as html_module
20
+ import io
21
+ import ipaddress
22
+ import json
23
+ from pathlib import Path
24
+ import re
25
+ import time
26
+
27
+ import requests
28
+
29
+
30
+ SOURCE = "uzp_orzeczenia_pl"
31
+ OWN_REPO = "PiotrSty/uzp-orzeczenia-pl"
32
+ TARGET = "SlayerLab/polish-dynaword"
33
+ BASE = "https://orzeczenia.uzp.gov.pl"
34
+ SEARCH_URL = BASE + "/Home/Search"
35
+ RESULTS_URL = BASE + "/Home/GetResults"
36
+ SOURCE_URL = BASE + "/"
37
+ FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
38
+ UA = "UzpOrzeczeniaCorpusResearch/0.1 (PiotrSty; open research slice)"
39
+ LICENSE_LABEL = "public-domain (official documents)"
40
+ LICENSE_SPDX = "LicenseRef-Polish-Official-Documents"
41
+ LEGAL_BASIS = ("Polish Copyright Act art. 4(2): official documents are not subject to copyright; "
42
+ "UZP search service republishes KIO/SO/SA/SN rulings in public procurement matters")
43
+ MIN_TEXT_CHARS = 1_500
44
+ PAGE_SIZE = 10 # fixed server-side; #sp-page-size is not a serialized form field
45
+ KINDS = ("KIO", "SO", "SA", "SN")
46
+
47
+ EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
48
+ PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b")
49
+ IPV4_RE = re.compile(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")
50
+ IPV6_RE = re.compile(r"(?i)\b(?:[0-9a-f]{1,4}:){3,}[0-9a-f]{1,4}\b")
51
+ IPV6_CANDIDATE_RE = re.compile(r"(?<![\w:])(?:[0-9a-fA-F]{0,4}:){2,}[0-9a-fA-F:.]*(?![\w:])")
52
+ NATIONAL_ID_RE = re.compile(r"(?i)\b(PESEL|NIP|REGON)\s*[:=]?\s*\d(?:[ -]?\d){8,13}\b")
53
+ BANK_ACCOUNT_RE = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[ -]?\d){24}(?!\d)")
54
+ DETAILS_LINK_RE = re.compile(r'href="/Home/Details/(\d+)"')
55
+ RESULT_COUNTS_RE = re.compile(r'value="([\d,]+)"\s+id="resultCounts"')
56
+ PDF_LINK_RE = re.compile(r'href="(/Home/PdfContent/(\d+)\?Kind=([A-Z]+))"')
57
+ SYGN_RE = re.compile(r"^Sygn\.\s*akt\b", re.I)
58
+ PAGE_NUM_RE = re.compile(r"^\d{1,4}$")
59
+
60
+
61
+ def now():
62
+ return datetime.now(timezone.utc).isoformat()
63
+
64
+
65
+ def digest(value):
66
+ if not isinstance(value, bytes):
67
+ value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
68
+ return hashlib.sha256(value).hexdigest()
69
+
70
+
71
+ def save(path, value):
72
+ path.parent.mkdir(parents=True, exist_ok=True)
73
+ path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8")
74
+
75
+
76
+ def write_lines(path, rows):
77
+ path.parent.mkdir(parents=True, exist_ok=True)
78
+ path.write_text("".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows), encoding="utf-8")
79
+
80
+
81
+ def read_lines(path):
82
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line]
83
+
84
+
85
+ def load(path):
86
+ return json.loads(path.read_text(encoding="utf-8"))
87
+
88
+
89
+ def is_ipv6(value):
90
+ try:
91
+ return ipaddress.ip_address(value.rstrip(".")).version == 6
92
+ except ValueError:
93
+ return False
94
+
95
+
96
+ def redact_pii(text):
97
+ counts = Counter()
98
+
99
+ def replace_ipv6(match):
100
+ value = match.group().rstrip(".")
101
+ if not is_ipv6(value):
102
+ return match.group()
103
+ counts["ipv6"] += 1
104
+ return "[REDACTED:IP]" + match.group()[len(value):]
105
+
106
+ text = IPV6_CANDIDATE_RE.sub(replace_ipv6, text)
107
+ for name, pattern, replacement in (
108
+ ("email", EMAIL_RE, "[REDACTED:EMAIL]"),
109
+ ("labelled_phone", PHONE_RE, "[REDACTED:PHONE]"),
110
+ ("ipv4", IPV4_RE, "[REDACTED:IP]"),
111
+ ("ipv6_legacy_pattern", IPV6_RE, "[REDACTED:IP]"),
112
+ ("national_identifier", NATIONAL_ID_RE, lambda match: match.group(1) + " [REDACTED:ID]"),
113
+ ("account_candidate", BANK_ACCOUNT_RE, "[REDACTED:ACCOUNT]"),
114
+ ):
115
+ text, count = pattern.subn(replacement, text)
116
+ counts[name] += count
117
+ return text, counts
118
+
119
+
120
+ def iso_date(text):
121
+ match = re.match(r"(\d{2})-(\d{2})-(\d{4})", (text or "").strip())
122
+ if match:
123
+ day, month, year = match.groups()
124
+ return f"{year}-{month}-{day}"
125
+ return ""
126
+
127
+
128
+ def strip_html(fragment):
129
+ return html_module.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", fragment))).strip()
130
+
131
+
132
+ def parse_result_items(page_html):
133
+ """Parse /Home/GetResults response into per-document records."""
134
+ records = []
135
+ for block in re.findall(r'<div class="search-list-item".*?(?=<div class="search-list-item"|$)',
136
+ page_html, flags=re.S):
137
+ link = DETAILS_LINK_RE.search(block)
138
+ if not link:
139
+ continue
140
+ fields = dict()
141
+ for label, value in re.findall(r"<label>([^<]+)</label>\s*([^<]+)", block):
142
+ fields[label.strip().rstrip(":")] = strip_html(value)
143
+ records.append({
144
+ "doc_id": int(link.group(1)),
145
+ "organ": fields.get("Organ wydający", ""),
146
+ "doc_type": fields.get("Rodzaj dokumentu", ""),
147
+ "signature": fields.get("Sygnatura", ""),
148
+ "issued": fields.get("Data wydania", ""),
149
+ })
150
+ counts = RESULT_COUNTS_RE.search(page_html)
151
+ totals = [int(value) for value in counts.group(1).split(",")] if counts else []
152
+ return records, totals
153
+
154
+
155
+ def parse_counts(page_html):
156
+ """Return dict kind -> count from the resultCounts hidden field."""
157
+ _records, totals = parse_result_items(page_html)
158
+ kinds = ["ALL", "KIO", "SO", "SA", "SN"]
159
+ return {kinds[index]: value for index, value in enumerate(totals)} if totals else {}
160
+
161
+
162
+ def parse_details(page_html, doc_id):
163
+ """Parse /Home/Details/{id} metadata page."""
164
+ pdf = PDF_LINK_RE.search(page_html)
165
+ body = re.sub(r"<script.*?</script>", " ", page_html, flags=re.S)
166
+ fields = {}
167
+ for label, value in re.findall(r"<label>([^<]+)</label>\s*([^<]+)", body):
168
+ fields[label.strip().rstrip(":")] = strip_html(value)
169
+ return {
170
+ "doc_id": doc_id,
171
+ "organ": fields.get("Organ wydający", ""),
172
+ "doc_type": fields.get("Rodzaj dokumentu", ""),
173
+ "issued": fields.get("Data wydania rozstrzygnięcia", ""),
174
+ "chairman": fields.get("Przewodniczący", ""),
175
+ "purchaser": fields.get("Zamawiający", ""),
176
+ "city": fields.get("Miejscowość", ""),
177
+ "signature": fields.get("Sygnatura akt / Sposób rozstrzygnięcia",
178
+ fields.get("Sygnatura akt / Sygnatura KIO / Sposób rozstrzygnięcia", "")),
179
+ "provisions": fields.get("Kluczowe przepisy ustawy Pzp", ""),
180
+ "pdf_path_url": BASE + pdf.group(1) if pdf else "",
181
+ "pdf_kind": pdf.group(3) if pdf else "",
182
+ }
183
+
184
+
185
+ def session():
186
+ s = requests.Session()
187
+ s.headers.update({"User-Agent": UA})
188
+ s.get(SEARCH_URL, timeout=20)
189
+ return s
190
+
191
+
192
+ def post_results(sess, kind, page, attempts=5):
193
+ data = {"Phrase": "", "Fle": "1", "SCnt": "1", "CountStats": "true",
194
+ "Kind": kind, "Srt": "", "Pg": str(page)}
195
+ for attempt in range(attempts):
196
+ try:
197
+ r = sess.post(RESULTS_URL, data=data, timeout=30)
198
+ if r.status_code in (429, 500, 502, 503, 504):
199
+ time.sleep(2 ** attempt)
200
+ continue
201
+ r.raise_for_status()
202
+ return r.text
203
+ except requests.RequestException:
204
+ if attempt == attempts - 1:
205
+ raise
206
+ time.sleep(2 ** attempt)
207
+ raise RuntimeError("unreachable")
208
+
209
+
210
+ def request(url, attempts=5, timeout=(15, 90), binary=False, sess=None):
211
+ client = sess or requests
212
+ response = None
213
+ for attempt in range(attempts):
214
+ response = client.get(url, headers={"User-Agent": UA}, timeout=timeout)
215
+ if response.status_code not in (429, 500, 502, 503, 504):
216
+ response.raise_for_status()
217
+ return response.content if binary else response.content.decode("utf-8", "replace")
218
+ time.sleep(2 ** attempt)
219
+ response.raise_for_status()
220
+
221
+
222
+ def request_json(url):
223
+ return json.loads(request(url))
224
+
225
+
226
+ def discover(out, workers):
227
+ """Enumerate every document via the kind-filtered result pages."""
228
+ seen = {}
229
+ counts = {}
230
+ for kind in KINDS:
231
+ body = post_results(session(), kind, 1)
232
+ first, totals = parse_result_items(body)
233
+ all_counts = parse_counts(body)
234
+ counts[kind] = all_counts.get(kind, len(first))
235
+ total = counts[kind]
236
+ pages = max(1, -(-total // PAGE_SIZE)) if total else 1
237
+ for record in first:
238
+ record["kind"] = kind
239
+ seen[record["doc_id"]] = record
240
+
241
+ def fetch_page(page):
242
+ return page, post_results(session(), kind, page)
243
+
244
+ with ThreadPoolExecutor(max_workers=workers) as pool:
245
+ futures = {pool.submit(fetch_page, p): p for p in range(2, pages + 1)}
246
+ for index, future in enumerate(as_completed(futures), 1):
247
+ _, body = future.result()
248
+ for record in parse_result_items(body)[0]:
249
+ record["kind"] = kind
250
+ seen[record["doc_id"]] = record
251
+ if index % 200 == 0:
252
+ print(f" {kind} {index}/{pages - 1} pages", flush=True)
253
+ print(f" {kind}: {pages} pages, total {total}", flush=True)
254
+ records = sorted(seen.values(), key=lambda record: record["doc_id"])
255
+ write_lines(out / "source_manifest.jsonl", records)
256
+ selection = {
257
+ "observed_at": now(), "search_url": SEARCH_URL,
258
+ "reported_totals": counts, "enumerated": len(records),
259
+ "per_kind": dict(Counter(record["kind"] for record in records)),
260
+ "selected": len(records),
261
+ "selected_ids": [record["doc_id"] for record in records],
262
+ "source_manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
263
+ }
264
+ save(out / "selection.json", selection)
265
+ print(json.dumps(selection, ensure_ascii=False, indent=2))
266
+
267
+
268
+ def acquire(out, workers):
269
+ selection = load(out / "selection.json")
270
+ manifest = {record["doc_id"]: record for record in read_lines(out / "source_manifest.jsonl")}
271
+ (out / "raw_pages").mkdir(parents=True, exist_ok=True)
272
+ (out / "raw_pdf").mkdir(parents=True, exist_ok=True)
273
+ (out / "raw_text").mkdir(parents=True, exist_ok=True)
274
+ results = []
275
+
276
+ def fetch(doc_id):
277
+ record = manifest[doc_id]
278
+ page_path = out / "raw_pages" / f"{doc_id}.html.gz"
279
+ pdf_path = out / "raw_pdf" / f"{doc_id}.pdf"
280
+ text_path = out / "raw_text" / f"{doc_id}.txt"
281
+ if pdf_path.is_file() and text_path.is_file() and page_path.is_file():
282
+ return record, digest(pdf_path.read_bytes()), pdf_path.stat().st_size, \
283
+ digest(text_path.read_bytes()), "cached", json.loads(
284
+ gzip.decompress(page_path.read_bytes()).decode("utf-8"))["details"]
285
+ sess = session()
286
+ body = request(BASE + f"/Home/Details/{doc_id}", sess=sess)
287
+ details = parse_details(body, doc_id)
288
+ if not details["pdf_path_url"]:
289
+ raise ValueError(f"no PdfContent link on details page: {doc_id}")
290
+ page_path.write_bytes(gzip.compress(json.dumps(
291
+ {"doc_id": doc_id, "details": details}, ensure_ascii=False).encode("utf-8")))
292
+ payload = request(details["pdf_path_url"], binary=True, sess=sess)
293
+ if not payload.startswith(b"%PDF"):
294
+ raise ValueError("not a PDF: " + str(doc_id))
295
+ pdf_path.write_bytes(payload)
296
+ from pypdf import PdfReader
297
+ reader = PdfReader(io.BytesIO(payload))
298
+ text = "\n".join(page.extract_text() or "" for page in reader.pages)
299
+ text_path.write_text(text, encoding="utf-8")
300
+ return record, digest(payload), len(payload), digest(text.encode("utf-8")), \
301
+ str(len(reader.pages)), details
302
+
303
+ with ThreadPoolExecutor(max_workers=workers) as pool:
304
+ futures = {pool.submit(fetch, doc_id): doc_id for doc_id in selection["selected_ids"]}
305
+ for index, future in enumerate(as_completed(futures), 1):
306
+ doc_id = futures[future]
307
+ record = manifest[doc_id]
308
+ try:
309
+ record, pdf_sha, pdf_bytes, text_sha, pages, details = future.result()
310
+ results.append({**record, "details": details, "pdf_sha256": pdf_sha,
311
+ "pdf_bytes": pdf_bytes, "text_sha256": text_sha, "pdf_pages": pages,
312
+ "pdf_path": f"raw_pdf/{doc_id}.pdf", "text_path": f"raw_text/{doc_id}.txt"})
313
+ except Exception as error:
314
+ results.append({**record, "error": f"{type(error).__name__}: {error}"})
315
+ if index % 100 == 0:
316
+ print(f" {index}/{len(selection['selected_ids'])}", flush=True)
317
+ results.sort(key=lambda record: record["doc_id"])
318
+ acquisition = {
319
+ "observed_at": now(), "target": selection["selected"],
320
+ "acquired": sum("pdf_sha256" in record for record in results),
321
+ "failed": [record["doc_id"] for record in results if "error" in record],
322
+ "selected": results,
323
+ }
324
+ save(out / "acquisition.json", acquisition)
325
+ print(json.dumps({key: acquisition[key] for key in ("target", "acquired", "failed")},
326
+ ensure_ascii=False, indent=2))
327
+
328
+
329
+ def normalize(text):
330
+ import unicodedata
331
+ text = unicodedata.normalize("NFKC", text or "").replace("­", "").replace("​", "")
332
+ text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
333
+ lines = [re.sub(r"[ \t   ]+", " ", line).strip() for line in text.splitlines()]
334
+ # drop repeated running-head signature lines and bare page numbers
335
+ seen_sygn = 0
336
+ kept = []
337
+ for line in lines:
338
+ if SYGN_RE.match(line):
339
+ seen_sygn += 1
340
+ if seen_sygn > 1:
341
+ continue
342
+ if PAGE_NUM_RE.match(line):
343
+ continue
344
+ kept.append(line)
345
+ text = "\n".join(kept)
346
+ text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text)
347
+ text = re.sub(r"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text)
348
+ return re.sub(r"\n{3,}", "\n\n", text).strip()
349
+
350
+
351
+ def shingle_sketch(text, limit=5_000):
352
+ words = re.findall(r"\w+", text.casefold())
353
+ hashes = set()
354
+ for index in range(max(0, len(words) - 4)):
355
+ value = " ".join(words[index:index + 5]).encode("utf-8")
356
+ hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big"))
357
+ if len(hashes) > limit:
358
+ return set(sorted(hashes)[:limit])
359
+ return hashes
360
+
361
+
362
+ DF_FRACTION = 0.02 # shingles in >2% of docs are boilerplate (KIO formula openings)
363
+
364
+
365
+ def shingle_document_frequencies(sketches):
366
+ df = Counter()
367
+ for sketch in sketches:
368
+ df.update(sketch)
369
+ return df
370
+
371
+
372
+ def filter_sketch(sketch, df, max_df):
373
+ """Drop high document-frequency shingles (boilerplate) from a sketch."""
374
+ return {h for h in sketch if df[h] <= max_df}
375
+
376
+
377
+ class NearDuplicateIndex:
378
+ def __init__(self):
379
+ self.postings = {}
380
+ self.records = []
381
+ self.comparisons = 0
382
+
383
+ @staticmethod
384
+ def prefix(sketch):
385
+ return sorted(sketch)[:len(sketch) - (9 * len(sketch) + 9) // 10 + 1]
386
+
387
+ def find(self, sketch):
388
+ candidates = set()
389
+ for value in self.prefix(sketch):
390
+ candidates.update(self.postings.get(value, ()))
391
+ for position in sorted(candidates):
392
+ row_id, other = self.records[position]
393
+ if 10 * min(len(sketch), len(other)) < 9 * max(len(sketch), len(other)):
394
+ continue
395
+ self.comparisons += 1
396
+ intersection = len(sketch & other)
397
+ score = intersection / max(len(sketch) + len(other) - intersection, 1)
398
+ if score >= 0.90:
399
+ return row_id, score
400
+ return None, 0.0
401
+
402
+ def add(self, row_id, sketch):
403
+ position = len(self.records)
404
+ self.records.append((row_id, sketch))
405
+ for value in self.prefix(sketch):
406
+ self.postings.setdefault(value, []).append(position)
407
+
408
+
409
+ def language_vote(identifier, text):
410
+ chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]]
411
+ classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()}
412
+ votes = [classified[chunk] for chunk in chunks if chunk in classified]
413
+ languages = Counter(language for language, _ in votes)
414
+ return (languages.most_common(1)[0][0] if languages else "unknown", votes)
415
+
416
+
417
+ def audit_target(out):
418
+ info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
419
+ revision = info["sha"]
420
+ tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}?recursive=true&expand=false")
421
+ discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions?status=open&p=0")
422
+ paths = sorted(item.get("path", "") for item in tree)
423
+ open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"),
424
+ "author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])]
425
+ terms = ("uzp", "kio", "orzeczenia_uzp", "zamowienia_publiczne")
426
+ matches = [path for path in paths if any(term in path.casefold() for term in terms)]
427
+ discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold()
428
+ for term in terms)]
429
+ report = {
430
+ "target": TARGET, "revision": revision, "last_modified": info.get("lastModified"),
431
+ "tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows,
432
+ "matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches,
433
+ "observed_at": now(),
434
+ }
435
+ save(out / "target_audit.json", report)
436
+ print(json.dumps({"revision": revision, "source_absent": report["source_absent"],
437
+ "tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2))
438
+
439
+
440
+ def audit_overlap(out):
441
+ """Compare our signatures/ids against the shipped SAOS shard (closest legal corpus)."""
442
+ import pyarrow.parquet as pq
443
+ from huggingface_hub import HfApi, HfFileSystem
444
+
445
+ revision = HfApi().dataset_info(TARGET).sha
446
+ remote = f"datasets/{TARGET}@{revision}/data/saos/saos.parquet"
447
+ try:
448
+ with HfFileSystem().open(remote, "rb") as handle:
449
+ table = pq.read_table(handle, columns=["id", "attribution"])
450
+ saos_rows = table.to_pylist()
451
+ except Exception as error:
452
+ saos_rows = []
453
+ print("saos shard unavailable:", error)
454
+ saos_sigs = set()
455
+ for row in saos_rows:
456
+ attribution = row.get("attribution") or ""
457
+ for sig in re.findall(r"[IVXLCDM]*\s*[A-Z][a-zA-Z]*\s*\d+/\d+", attribution):
458
+ saos_sigs.add(sig.strip().casefold())
459
+ manifest = read_lines(out / "source_manifest.jsonl")
460
+ results = []
461
+ for record in manifest:
462
+ sig = (record.get("signature") or "").strip()
463
+ if sig and sig.casefold() in saos_sigs:
464
+ results.append({"doc_id": record["doc_id"], "signature": sig, "kind": record["kind"]})
465
+ report = {
466
+ "target": f"{TARGET}:data/saos", "target_revision": revision,
467
+ "method": "case-normalized signature match against SAOS attribution strings",
468
+ "saos_rows": len(saos_rows), "candidate_records": len(manifest),
469
+ "signature_collisions": len(results),
470
+ "text_overlap": "not tested; target-wide text dedup remains an integration gate",
471
+ "observed_at": now(),
472
+ "colliding_ids": [r["doc_id"] for r in results],
473
+ "collisions": results[:500],
474
+ }
475
+ save(out / "overlap_audit.json", report)
476
+ print(json.dumps({key: report[key] for key in ("target_revision", "saos_rows",
477
+ "candidate_records", "signature_collisions")},
478
+ ensure_ascii=False, indent=2))
479
+
480
+
481
+ def build(out):
482
+ import pyarrow as pa
483
+ import pyarrow.parquet as pq
484
+ import tiktoken
485
+ from langid.langid import LanguageIdentifier, model
486
+
487
+ acquisition = load(out / "acquisition.json")
488
+ selection = load(out / "selection.json")
489
+ encoder = tiktoken.get_encoding("cl100k_base")
490
+ identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
491
+ identifier.set_languages(["pl", "en", "de", "uk", "ru"])
492
+ rows, attribution, decisions = [], [], []
493
+ exact_seen = {}
494
+ near = NearDuplicateIndex()
495
+
496
+ # pass 1: document frequencies of shingles, to drop boilerplate-heavy
497
+ # formulas (identical opening lines in ~every KIO ruling) from sketches.
498
+ df_sketches = []
499
+ for record in acquisition["selected"]:
500
+ if "error" in record:
501
+ continue
502
+ raw = (out / record["text_path"]).read_text(encoding="utf-8")
503
+ df_sketches.append((record["doc_id"], shingle_sketch(normalize(raw))))
504
+ df = shingle_document_frequencies(sketch for _, sketch in df_sketches)
505
+ max_df = max(1, int(len(df_sketches) * DF_FRACTION))
506
+ del df_sketches
507
+ print(f"df pass done: {len(df)} distinct shingles, max_df={max_df}", flush=True)
508
+ pii = Counter()
509
+ added = acquisition["observed_at"][:10]
510
+ for record in acquisition["selected"]:
511
+ row_id = f"{SOURCE}_{record['doc_id']}"
512
+ if "error" in record:
513
+ decisions.append({"id": row_id, "selected": False,
514
+ "reason": "acquisition_failed", "error": record["error"]})
515
+ continue
516
+ pdf_path = out / record["pdf_path"]
517
+ text_path = out / record["text_path"]
518
+ if digest(pdf_path.read_bytes()) != record["pdf_sha256"]:
519
+ raise ValueError("PDF checksum mismatch: " + str(record["doc_id"]))
520
+ raw = text_path.read_text(encoding="utf-8")
521
+ text = normalize(raw)
522
+ replacement_count = text.count("\ufffd")
523
+ letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text))
524
+ language, votes = language_vote(identifier, text)
525
+ reason = ""
526
+ if len(text) < MIN_TEXT_CHARS:
527
+ reason = "too_little_extractable_text"
528
+ elif letters / max(len(text), 1) < 0.55:
529
+ reason = "low_letter_ratio"
530
+ elif replacement_count > 100 or replacement_count / max(len(text), 1) > 0.002:
531
+ reason = "excessive_replacement_characters"
532
+ elif language != "pl":
533
+ reason = "non_polish_text"
534
+ text = text.replace("\ufffd", "[UNREADABLE_GLYPH]")
535
+ text, counts = redact_pii(text)
536
+ pii.update(counts)
537
+ if not reason and len(text) < MIN_TEXT_CHARS:
538
+ reason = "too_little_text_after_redaction"
539
+ exact_key = digest(" ".join(text.casefold().split()).encode("utf-8"))
540
+ duplicate_of, duplicate_score = None, 0.0
541
+ if not reason and exact_key in exact_seen:
542
+ reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0
543
+ if not reason:
544
+ sketch = filter_sketch(shingle_sketch(text), df, max_df)
545
+ if sketch:
546
+ duplicate_of, duplicate_score = near.find(sketch)
547
+ if duplicate_of:
548
+ reason = "near_duplicate"
549
+ decision = {
550
+ "id": row_id, "selected": not bool(reason), "reason": reason or "include",
551
+ "characters": len(text), "letter_ratio": letters / max(len(text), 1),
552
+ "replacement_characters": replacement_count, "language": language,
553
+ "language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes],
554
+ }
555
+ if duplicate_of:
556
+ decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score})
557
+ decisions.append(decision)
558
+ if reason:
559
+ continue
560
+ exact_seen[exact_key] = row_id
561
+ near.add(row_id, sketch)
562
+ details = record.get("details") or {}
563
+ organ = record.get("organ") or details.get("organ") or "Unknown"
564
+ created = iso_date(record.get("issued") or details.get("issued", ""))
565
+ row = {
566
+ "id": row_id, "text": text, "source": SOURCE, "added": added,
567
+ "created": created, "token_count": len(encoder.encode_ordinary(text)),
568
+ "license": LICENSE_LABEL, "author": organ,
569
+ }
570
+ rows.append(row)
571
+ attribution.append({
572
+ "id": row_id, "doc_id": record["doc_id"], "kind": record["kind"],
573
+ "organ": organ, "doc_type": record.get("doc_type") or details.get("doc_type", ""),
574
+ "signature": record.get("signature") or details.get("signature", ""),
575
+ "issued": record.get("issued") or details.get("issued", ""),
576
+ "chairman": details.get("chairman", ""), "purchaser": details.get("purchaser", ""),
577
+ "provisions": details.get("provisions", ""),
578
+ "landing_url": f"{BASE}/Home/Details/{record['doc_id']}",
579
+ "pdf_url": details.get("pdf_path_url", ""),
580
+ "pdf_sha256": record["pdf_sha256"], "pdf_bytes": record["pdf_bytes"],
581
+ "license": LICENSE_LABEL, "license_spdx": LICENSE_SPDX,
582
+ "legal_basis": LEGAL_BASIS,
583
+ "text_sha256": digest(text.encode("utf-8")),
584
+ "transformations": ["per-document PDF via /Home/PdfContent", "pypdf text extraction",
585
+ "repeated signature running-head and page-number removal",
586
+ "Unicode/whitespace normalization", "line-wrap repair",
587
+ "email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction"],
588
+ })
589
+ root = out / "hf_repo"
590
+ (root / "data").mkdir(parents=True, exist_ok=True)
591
+ (root / "artifacts").mkdir(parents=True, exist_ok=True)
592
+ schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS])
593
+ pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet",
594
+ compression="zstd")
595
+ write_lines(root / "artifacts/attribution.jsonl", attribution)
596
+ write_lines(root / "artifacts/decisions.jsonl", decisions)
597
+ write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl"))
598
+ sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12]
599
+ write_lines(root / "artifacts/sample.jsonl", sample)
600
+ save(root / "artifacts/selection.json", selection)
601
+ save(root / "artifacts/acquisition.json", acquisition)
602
+ overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None
603
+ target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None
604
+ if overlap:
605
+ save(root / "artifacts/overlap_audit.json", overlap)
606
+ if target_audit:
607
+ save(root / "artifacts/target_audit.json", target_audit)
608
+ stats = {
609
+ "reported_totals": selection["reported_totals"],
610
+ "enumerated": selection["enumerated"], "per_kind": selection["per_kind"],
611
+ "acquired": acquisition["acquired"], "failed": len(acquisition["failed"]),
612
+ "kept": len(rows), "rejected": len(decisions) - len(rows),
613
+ "rejection_reasons": dict(Counter(d["reason"] for d in decisions if not d["selected"])),
614
+ "tokens": sum(row["token_count"] for row in rows),
615
+ "characters": sum(len(row["text"]) for row in rows),
616
+ "license_counts": dict(Counter(row["license"] for row in rows)),
617
+ "sample_count": len(sample), "added": added,
618
+ }
619
+ save(root / "artifacts/stats.json", stats)
620
+ qa = {
621
+ "scope": "all rulings enumerated via /Home/GetResults on orzeczenia.uzp.gov.pl (KIO/SO/SA/SN in public procurement matters)",
622
+ "license_gate": "official documents excluded from copyright under Polish Copyright Act art. 4(2); no per-record license field exists",
623
+ "language_gate": "three-window langid vote (pl/en/de/uk/ru)",
624
+ "pii_pattern_matches": dict(pii),
625
+ "exact_dedup": True,
626
+ "near_dedup": "deterministic prefix-indexed capped 5-word-shingle Jaccard >= 0.90 within source; high document-frequency shingles (>2% of docs, i.e. KIO opening-formula boilerplate) excluded from sketches",
627
+ "near_dedup_comparisons": near.comparisons,
628
+ "saos_overlap": overlap or "pending",
629
+ "cross_source_text_dedup": "pending target integration",
630
+ "limitations": [
631
+ "pypdf extraction may retain layout artifacts; tables may be flattened",
632
+ "pattern checks are not comprehensive de-identification; natural-person names of parties and adjudicators remain part of the official record",
633
+ "official-document status does not cover third-party material quoted inside rulings",
634
+ "sequential IDs contain gaps; enumeration follows the server-side result list, not the ID range",
635
+ ],
636
+ }
637
+ save(root / "artifacts/qa.json", qa)
638
+ protocol_id = "protocol:uzp-orzeczenia-v1"
639
+ run = {
640
+ "id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection,
641
+ "acquisition": digest(acquisition)}),
642
+ "protocol": protocol_id, "started_at": selection["observed_at"], "finished_at": now(),
643
+ "success": True, "actor": "actor:devin", "stats": stats,
644
+ }
645
+ save(root / "artifacts/run.json", run)
646
+ excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"}
647
+ checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*"))
648
+ if path.is_file()
649
+ and path.relative_to(root).as_posix() not in excluded
650
+ and not path.relative_to(root).as_posix().startswith("src/")}
651
+ save(root / "artifacts/checksums.json", checks)
652
+ source_version = "version:source:" + digest({"manifest": selection["source_manifest_sha256"]})
653
+ dataset_version = "version:dataset:" + digest(checks)
654
+ selection_evidence = "evidence:selection:" + digest(selection)
655
+ acquisition_evidence = "evidence:acquisition:" + digest(acquisition)
656
+ qa_evidence = "evidence:qa:" + digest(qa)
657
+ evidence = [
658
+ {"id": selection_evidence, "observation_type": "source_inventory_and_selection",
659
+ "artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]},
660
+ {"id": acquisition_evidence, "observation_type": "pdf_acquisition_and_extraction",
661
+ "artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]},
662
+ {"id": qa_evidence, "observation_type": "source_qa", "artifact": "artifacts/qa.json",
663
+ "content_address": digest(qa), "produced_by": run["id"]},
664
+ ]
665
+ overlap_evidence = None
666
+ if overlap:
667
+ overlap_evidence = "evidence:overlap:" + digest(overlap)
668
+ evidence.append({"id": overlap_evidence, "observation_type": "metadata_overlap_audit",
669
+ "artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap),
670
+ "produced_by": run["id"]})
671
+ target_evidence = None
672
+ if target_audit:
673
+ target_evidence = "evidence:target:" + digest(target_audit)
674
+ evidence.append({"id": target_evidence, "observation_type": "target_registry_audit",
675
+ "artifact": "artifacts/target_audit.json", "content_address": digest(target_audit),
676
+ "produced_by": run["id"]})
677
+ ontology = {
678
+ "schema": "slayer-research-ontology-profile-v1",
679
+ "objects": [{"id": "object:source:uzp-orzeczenia", "type": "Source"},
680
+ {"id": "object:dataset:uzp-orzeczenia-pl", "type": "Dataset"}],
681
+ "versions": [{"id": source_version, "object": "object:source:uzp-orzeczenia",
682
+ "content_address": source_version.rsplit(":", 1)[-1]},
683
+ {"id": dataset_version, "object": "object:dataset:uzp-orzeczenia-pl",
684
+ "content_address": dataset_version.rsplit(":", 1)[-1]}],
685
+ "protocols": [{"id": protocol_id,
686
+ "procedure": "enumerate /Home/GetResults per kind; fetch /Home/Details metadata and /Home/PdfContent PDF; pypdf extraction; running-head/page-number removal; normalization; PII patterns; exact and near dedup"}],
687
+ "runs": [run], "evidence": evidence,
688
+ "claims": [
689
+ {"id": "claim:enumeration-complete",
690
+ "statement": f"The result-list enumeration observed {selection['enumerated']} documents across kinds {selection['per_kind']} matching server-reported totals {selection['reported_totals']}.",
691
+ "supported_by": [selection_evidence],
692
+ "falsification_condition": "The preserved manifest does not reproduce the counts or the server totals differ."},
693
+ {"id": "claim:official-documents",
694
+ "statement": "Retained records are official rulings of KIO, district courts, administrative courts and the Supreme Court in public procurement matters, excluded from copyright under Polish Copyright Act art. 4(2).",
695
+ "supported_by": [selection_evidence, qa_evidence],
696
+ "falsification_condition": "A retained record is shown to be a non-official or non-ruling document."},
697
+ {"id": "claim:slice-retention",
698
+ "statement": f"The slice retained {stats['kept']} records after text QA and within-source deduplication.",
699
+ "supported_by": [acquisition_evidence, qa_evidence],
700
+ "falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."},
701
+ {"id": "claim:training-value-untested",
702
+ "statement": "Net corpus novelty and training benefit remain untested hypotheses.",
703
+ "supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []),
704
+ "falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."},
705
+ ],
706
+ "actors": [{"id": "actor:piotrsty", "type": "Contributor"},
707
+ {"id": "actor:uzp", "type": "Organization"}, {"id": "actor:devin", "type": "Agent"}],
708
+ "relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version},
709
+ {"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] +
710
+ ([{"source": dataset_version, "predicate": "VALIDATED_AGAINST",
711
+ "target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []),
712
+ "pending": ["formal legal review of art. 4(2) application", "cross-source text deduplication",
713
+ "benchmark contamination check", "third-party quoted material review",
714
+ "controlled training ablation"],
715
+ }
716
+ save(root / "artifacts/ontology.json", ontology)
717
+ card = f"""---
718
+ license: other
719
+ language:
720
+ - pl
721
+ task_categories:
722
+ - text-generation
723
+ configs:
724
+ - config_name: default
725
+ data_files:
726
+ - split: train
727
+ path: data/train-00000-of-00001.parquet
728
+ ---
729
+
730
+ # UZP Orzeczenia - Polish public-procurement rulings (KIO/SO/SA/SN)
731
+
732
+ Polish-language rulings from the official decision search service of the Public
733
+ Procurement Office (https://orzeczenia.uzp.gov.pl/): the National Appeals Chamber
734
+ (KIO), district courts (SO), administrative courts (SA) and the Supreme Court
735
+ (SN) in public procurement matters.
736
+
737
+ - Enumerated documents: {stats['enumerated']:,} (per kind: {stats['per_kind']})
738
+ - Acquired PDFs: {stats['acquired']:,} (failed: {stats['failed']})
739
+ - Retained after text QA and within-source deduplication: {stats['kept']:,}
740
+ - Characters: {stats['characters']:,}
741
+ - Tokens: {stats['tokens']:,} (`cl100k_base` proxy)
742
+ - License label: `{LICENSE_LABEL}`
743
+
744
+ ## Provenance and rights
745
+
746
+ Rulings are official documents excluded from copyright under Polish Copyright
747
+ Act art. 4(2) (LicenseRef-Polish-Official-Documents). No Creative Commons grant
748
+ is asserted. Each row links to its `/Home/Details` landing URL, PDF URL and
749
+ checksum; `artifacts/attribution.jsonl` carries organ, document type,
750
+ signature, issue date, chairman, purchaser and key provisions per record.
751
+
752
+ ## Processing and limitations
753
+
754
+ Text was extracted from the service PDFs with pypdf, then normalized:
755
+ repeated signature running-heads and page numbers removed, Unicode/whitespace
756
+ normalization, line-wrap repair, and limited email/phone/IP/identifier/account
757
+ pattern redaction. Language is checked independently across three text windows;
758
+ exact and deterministic near deduplication run within the source.
759
+
760
+ Pattern checks are not comprehensive de-identification: names of parties,
761
+ adjudicators and quoted natural persons remain part of the official record.
762
+ PDF-derived text may retain layout artifacts and flattened tables.
763
+
764
+ ## Review artifacts
765
+
766
+ See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`,
767
+ `source_manifest.jsonl`, `overlap_audit.json`, `stats.json`, `qa.json`,
768
+ `checksums.json`, `run.json` and `ontology.json`.
769
+ """
770
+ (root / "README.md").write_text(card, encoding="utf-8")
771
+ (root / "NOTICE.md").write_text(
772
+ "# Attribution and legal basis\n\n"
773
+ "Source: UZP decision search service, https://orzeczenia.uzp.gov.pl/ "
774
+ "(Urzad Zamowien Publicznych / Public Procurement Office).\n\n"
775
+ "Records are official rulings (KIO, district courts, administrative courts, Supreme Court) in public "
776
+ "procurement matters. Working basis: Polish Copyright Act art. 4(2) excludes official documents from "
777
+ "copyright; no per-record license field exists on the service. Formal legal review has not been performed. "
778
+ "Consult `artifacts/attribution.jsonl` for per-record provenance (organ, signature, issue date, URLs, checksums).\n\n"
779
+ "Preparation: Piotr Styla with Devin (Cognition). Changes: service-PDF text extraction, running-head and "
780
+ "page-number removal, Unicode/whitespace normalization, line-wrap repair, limited email/phone/IP/"
781
+ "identifier/account pattern redaction, language/quality filtering and within-source deduplication. "
782
+ "Names of parties and adjudicators remain as part of the official record. No endorsement by UZP, KIO "
783
+ "or the courts is implied.\n",
784
+ encoding="utf-8",
785
+ )
786
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
787
+
788
+
789
+ def verify(out):
790
+ import pyarrow.parquet as pq
791
+ import tiktoken
792
+
793
+ root = out / "hf_repo"
794
+ table = pq.read_table(root / "data/train-00000-of-00001.parquet")
795
+ rows = table.to_pylist()
796
+ stats = load(root / "artifacts/stats.json")
797
+ decisions = read_lines(root / "artifacts/decisions.jsonl")
798
+ attribution = read_lines(root / "artifacts/attribution.jsonl")
799
+ sample = read_lines(root / "artifacts/sample.jsonl")
800
+ assert table.column_names == FIELDS
801
+ assert len(rows) == stats["kept"] == len(attribution)
802
+ assert sum(item["selected"] for item in decisions) == len(rows)
803
+ encoder = tiktoken.get_encoding("cl100k_base")
804
+ assert sum(row["token_count"] for row in rows) == stats["tokens"]
805
+ for row in rows:
806
+ assert len(encoder.encode_ordinary(row["text"])) == row["token_count"]
807
+ assert all(row["source"] == SOURCE and row["license"] == LICENSE_LABEL for row in rows)
808
+ assert all(EMAIL_RE.search(row["text"]) is None for row in rows)
809
+ assert all(len(row["text"]) >= MIN_TEXT_CHARS for row in rows)
810
+ by_id = {row["id"]: row for row in rows}
811
+ assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample)
812
+ # reconstruct every retained text from the extracted source
813
+ for att in attribution:
814
+ doc_id = att["doc_id"]
815
+ raw = (out / "raw_text" / f"{doc_id}.txt").read_text(encoding="utf-8")
816
+ text = normalize(raw).replace("\ufffd", "[UNREADABLE_GLYPH]")
817
+ text, _ = redact_pii(text)
818
+ assert text == by_id[att["id"]]["text"], f"text mismatch: {doc_id}"
819
+ assert digest(text.encode("utf-8")) == att["text_sha256"]
820
+ ontology = load(root / "artifacts/ontology.json")
821
+ evidence = {item["id"] for item in ontology["evidence"]}
822
+ assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"])
823
+ checks = load(root / "artifacts/checksums.json")
824
+ assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum
825
+ for path, checksum in checks.items())
826
+ for item in ontology["evidence"]:
827
+ artifact = root / item["artifact"]
828
+ assert artifact.is_file() and digest(load(artifact)) == item["content_address"]
829
+ # residual PII pattern scan
830
+ residual = {
831
+ name: sum(bool(pattern.search(row["text"])) for row in rows)
832
+ for name, pattern in {"email": EMAIL_RE, "labelled_phone": PHONE_RE,
833
+ "ipv4": IPV4_RE, "ipv6": IPV6_RE}.items()
834
+ }
835
+ report = {"verified": True, "residual_patterns": residual, **stats}
836
+ save(out / "validation_report.json", report)
837
+ print(json.dumps(report, ensure_ascii=False, indent=2))
838
+
839
+
840
+ def main():
841
+ parser = argparse.ArgumentParser()
842
+ parser.add_argument("--output", type=Path, required=True)
843
+ parser.add_argument("--workers", type=int, default=8)
844
+ parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap",
845
+ "build", "verify"])
846
+ args = parser.parse_args()
847
+ if args.command == "discover":
848
+ discover(args.output, args.workers)
849
+ elif args.command == "acquire":
850
+ acquire(args.output, args.workers)
851
+ elif args.command == "audit_target":
852
+ audit_target(args.output)
853
+ elif args.command == "audit_overlap":
854
+ audit_overlap(args.output)
855
+ elif args.command == "build":
856
+ build(args.output)
857
+ else:
858
+ verify(args.output)
859
+
860
+
861
+ if __name__ == "__main__":
862
+ main()
src/sources.py CHANGED
@@ -15,6 +15,21 @@ intermediate aggregator, upstream license/attribution is preserved per source.
15
  # Large cultural/academic sources require per-record rights metadata and should
16
  # be rebuilt from direct upstream/export scripts rather than blind SpeakLeash pulls.
17
  SOURCES = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  'rock_pollub_pl': {'file_key': 'rock_pollub_pl',
19
  'pretty': 'ROCK Politechnika Lubelska - Polish academic books',
20
  'license': 'CC-BY-SA-4.0',
 
15
  # Large cultural/academic sources require per-record rights metadata and should
16
  # be rebuilt from direct upstream/export scripts rather than blind SpeakLeash pulls.
17
  SOURCES = {
18
+ "uzp_orzeczenia_pl": {
19
+ "added": "2026-09-17",
20
+ "release": None,
21
+ "file_key": "uzp_orzeczenia_pl",
22
+ "pretty": "UZP Orzeczenia - KIO/SO/SA/SN public-procurement rulings",
23
+ "license": "public-domain (official documents)",
24
+ "license_spdx": "LicenseRef-Polish-Official-Documents",
25
+ "traceable": "Every retained ruling links to its /Home/Details landing URL, PDF URL and sha256; organ, document type, signature, issue date, chairman, purchaser and key provisions are kept per record.",
26
+ "upstream": "https://orzeczenia.uzp.gov.pl/",
27
+ "provenance": "Enumerated deterministically via the service's kind-filtered /Home/GetResults pagination matching server-reported totals; per-document /Home/Details metadata and /Home/PdfContent PDFs fetched, extracted with pypdf, normalized, PII patterns redacted, language/quality filtered and within-source deduplicated. Polish Copyright Act art. 4(2): official documents are not subject to copyright; UZP search service republishes KIO/SO/SA/SN rulings in public procurement matters.",
28
+ "domain": "legal/judicial",
29
+ "created": "2009-2026",
30
+ "is_ocr": False,
31
+ "custom_datasheet": True,
32
+ },
33
  'rock_pollub_pl': {'file_key': 'rock_pollub_pl',
34
  'pretty': 'ROCK Politechnika Lubelska - Polish academic books',
35
  'license': 'CC-BY-SA-4.0',
src/test_build_uzp_orzeczenia_pl.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ from pathlib import Path
3
+
4
+
5
+ SCRIPT = Path(__file__).with_name("build_uzp_orzeczenia_pl.py")
6
+ SPEC = importlib.util.spec_from_file_location("build_uzp_orzeczenia_pl", SCRIPT)
7
+ MODULE = importlib.util.module_from_spec(SPEC)
8
+ SPEC.loader.exec_module(MODULE)
9
+
10
+
11
+ def results_page(ids, counts="35694,34412,1277,3,2"):
12
+ items = "".join(
13
+ f'<div class="search-list-item">'
14
+ f'<label>Organ wydający:</label> Krajowa Izba Odwoławcza'
15
+ f'<p><label>Rodzaj dokumentu:</label> wyrok</p>'
16
+ f'<p><label>Sygnatura:</label> KIO {i}/26</p>'
17
+ f'<p><label>Data wydania:</label> 07-08-2026</p>'
18
+ f'<a class="link-details" href="/Home/Details/{i}">Wyświetl szczegóły</a>'
19
+ f'</div>'
20
+ for i in ids)
21
+ return f'<input type="hidden" value="{counts}" id="resultCounts" />' + items
22
+
23
+
24
+ def details_page(doc_id=36097, kind="KIO", signature="KIO 3640/26"):
25
+ return (
26
+ f'<html><body><label>Organ wydający</label> Krajowa Izba Odwoławcza'
27
+ f'<label>Rodzaj dokumentu</label> postanowienie'
28
+ f'<label>Data wydania rozstrzygnięcia</label> 07-08-2026'
29
+ f'<label>Przewodniczący</label> Jan Kowalski'
30
+ f'<label>Zamawiający</label> Szpital Miejski'
31
+ f'<label>Miejscowość</label> Warszawa'
32
+ f'<label>Sygnatura akt / Sposób rozstrzygnięcia</label> {signature} / umorzenie'
33
+ f'<label>Kluczowe przepisy ustawy Pzp</label> art. 568 pkt 2'
34
+ f'<a href="/Home/PdfContent/{doc_id}?Kind={kind}">Pobierz treść PDF</a>'
35
+ f'</body></html>')
36
+
37
+
38
+ def test_parse_result_items_extracts_records_and_totals():
39
+ records, totals = MODULE.parse_result_items(results_page([36097, 36096, 36095]))
40
+ assert [r["doc_id"] for r in records] == [36097, 36096, 36095]
41
+ assert records[0]["organ"].startswith("Krajowa Izba")
42
+ assert records[0]["doc_type"] == "wyrok"
43
+ assert records[0]["signature"] == "KIO 36097/26"
44
+ assert records[0]["issued"] == "07-08-2026"
45
+ assert totals == [35694, 34412, 1277, 3, 2]
46
+
47
+
48
+ def test_parse_counts_maps_kinds():
49
+ counts = MODULE.parse_counts(results_page([1]))
50
+ assert counts == {"ALL": 35694, "KIO": 34412, "SO": 1277, "SA": 3, "SN": 2}
51
+
52
+
53
+ def test_parse_details_extracts_metadata_and_pdf_link():
54
+ details = MODULE.parse_details(details_page(), 36097)
55
+ assert details["doc_id"] == 36097
56
+ assert details["organ"] == "Krajowa Izba Odwoławcza"
57
+ assert details["chairman"] == "Jan Kowalski"
58
+ assert details["purchaser"] == "Szpital Miejski"
59
+ assert details["signature"] == "KIO 3640/26 / umorzenie"
60
+ assert details["pdf_path_url"] == "https://orzeczenia.uzp.gov.pl/Home/PdfContent/36097?Kind=KIO"
61
+ assert details["pdf_kind"] == "KIO"
62
+
63
+
64
+ def test_parse_details_so_kind():
65
+ details = MODULE.parse_details(details_page(9036, "SO", "X Ga 286/13"), 9036)
66
+ assert details["pdf_path_url"].endswith("?Kind=SO")
67
+ assert details["pdf_kind"] == "SO"
68
+
69
+
70
+ def test_iso_date_dd_mm_yyyy():
71
+ assert MODULE.iso_date("07-08-2026") == "2026-08-07"
72
+ assert MODULE.iso_date("03-10-2013") == "2013-10-03"
73
+ assert MODULE.iso_date("") == ""
74
+
75
+
76
+ def test_normalize_drops_repeated_signature_and_page_numbers():
77
+ raw = "Sygn. akt KIO 1/26\nPierwszy akapit\n3\nSygn. akt KIO 1/26\nDrugi akapit"
78
+ out = MODULE.normalize(raw)
79
+ assert out.count("Sygn. akt") == 1
80
+ assert "\n3\n" not in "\n" + out + "\n"
81
+ assert "Pierwszy akapit" in out and "Drugi akapit" in out
82
+
83
+
84
+ def test_normalize_repairs_line_wraps():
85
+ raw = "To jest dłu-\ngi wyraz\noraz kolejna\nlinia tekstu."
86
+ out = MODULE.normalize(raw)
87
+ assert "długi wyraz" in out
88
+ assert "oraz kolejna linia tekstu." in out
89
+
90
+
91
+ def test_redact_pii_masks_patterns():
92
+ text = "Kontakt: jan@example.com tel. 601 234 567 PESEL 44051401458 " \
93
+ "rachunek 12 3456 7890 1234 5678 9012 3456 IP 10.0.0.1"
94
+ out, counts = MODULE.redact_pii(text)
95
+ assert "[REDACTED:EMAIL]" in out
96
+ assert "[REDACTED:PHONE]" in out
97
+ assert "[REDACTED:ID]" in out
98
+ assert "[REDACTED:ACCOUNT]" in out
99
+ assert "[REDACTED:IP]" in out
100
+ assert "jan@example.com" not in out
101
+ assert counts["email"] == 1 and counts["national_identifier"] == 1
102
+
103
+
104
+ def test_redact_pii_compressed_ipv6():
105
+ out, counts = MODULE.redact_pii("adres ::1 oraz 2001:db8::ff00:42:8329 w tekście")
106
+ assert "[REDACTED:IP]" in out
107
+ assert counts["ipv6"] >= 1
108
+
109
+
110
+ def test_filter_sketch_drops_boilerplate_shingles():
111
+ boiler = MODULE.shingle_sketch("Krajowa Izba Odwoławcza w składzie Przewodniczący")
112
+ own_a = MODULE.shingle_sketch("sygnatura sprawa alfa unikalna treść alfa")
113
+ own_b = MODULE.shingle_sketch("sygnatura sprawa beta unikalna treść beta")
114
+ df = MODULE.shingle_document_frequencies([boiler | own_a, boiler | own_b])
115
+ max_df = 1 # boiler appears in both docs -> df=2 > max_df
116
+ filtered = MODULE.filter_sketch(boiler | own_a, df, max_df)
117
+ assert filtered <= own_a
118
+ assert filtered == own_a
119
+
120
+
121
+ def test_near_duplicate_index_matches_exhaustive():
122
+ base = " ".join(f"słowo{i}" for i in range(300))
123
+ near = MODULE.NearDuplicateIndex()
124
+ near.add("doc_a", MODULE.shingle_sketch(base))
125
+ hit, score = near.find(MODULE.shingle_sketch(base + " dodatkowy koniec"))
126
+ assert hit == "doc_a" and score >= 0.90
127
+ distinct = " ".join(f"inne{i}" for i in range(300))
128
+ assert near.find(MODULE.shingle_sketch(distinct)) == (None, 0.0)
129
+ # regression: index must agree with exhaustive pairwise comparison
130
+ sketches = {f"d{i}": MODULE.shingle_sketch(" ".join(f"x{i}w{j}" for j in range(200)))
131
+ for i in range(30)}
132
+ sketches["dup"] = MODULE.shingle_sketch(" ".join(f"x0w{j}" for j in range(200)))
133
+ index = MODULE.NearDuplicateIndex()
134
+ added = {}
135
+ for rid, sk in sketches.items():
136
+ other, score = index.find(sk)
137
+ expected = None
138
+ for oid, osk in added.items():
139
+ inter = len(sk & osk)
140
+ s = inter / max(len(sk) + len(osk) - inter, 1)
141
+ if s >= 0.90:
142
+ expected = oid
143
+ break
144
+ assert (other is not None) == (expected is not None), rid
145
+ index.add(rid, sk)
146
+ added[rid] = sk
src/uzp_orzeczenia_requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ requests==2.32.5
2
+ pyarrow==23.0.1
3
+ tiktoken==0.12.0
4
+ langid==1.1.6
5
+ pypdf==5.9.0
6
+ huggingface_hub>=1.0,<2
7
+ pytest>=8,<10