polish-dynaword / src /fetch_saos.py
Fundacja Hospicjum
Add pinned SAOS Polish court judgments snapshot
960e3ec
Raw History Blame
47.5 kB
#!/usr/bin/env python3
"""Build a pinned PiotrSty SAOS snapshot for Polish DynaWord."""
from __future__ import annotations
import argparse
import collections
import concurrent.futures
import datetime as dt
import hashlib
import html
import importlib.metadata
import json
import pathlib
import platform
import re
import shutil
import sys
import unicodedata
from typing import Any
SOURCE_NAME = "saos"
SOURCE_REPOSITORY = "PiotrSty/saos-polish-court-judgments"
TARGET_REPOSITORY = "SlayerLab/polish-dynaword"
OFFICIAL_API = "https://www.saos.org.pl/api/dump/judgments"
OFFICIAL_API_DOCS = "https://www.saos.org.pl/help/index.php/dokumentacja-api/api-pobierania-danych"
SOURCE_LICENSE = "public-domain (official documents)"
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"
COMMIT_PATTERN = re.compile(r"^[0-9a-f]{40}$")
EXPECTED_FIELDS = (
"id", "text", "source", "added", "created", "token_count", "license", "author"
)
POLISH_RE = re.compile(r"[\u0105\u0107\u0119\u0142\u0144\u00f3\u015b\u017a\u017c\u0104\u0106\u0118\u0141\u0143\u00d3\u015a\u0179\u017b]")
ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE)
HTML_TAG = re.compile(
r"</?(?:p|div|span|br|h[1-6]|table|tbody|thead|tr|td|th|ul|ol|li|strong|em|b|i|a|section)"
r"\s*/?>",
re.I,
)
EMAIL = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
PESEL = re.compile(r"(?<!\d)\d{11}(?!\d)")
LABELLED_IDENTIFIER = re.compile(
r"(?i)\b(?:NIP|REGON)\s*[:.]?\s*\d(?:[\s-]?\d){8,13}\b"
)
LABELLED_PHONE = re.compile(
r"(?i)(?:\btel\.?|\btelefon|\+48)\s*[:.]?\s*(?:\(?\d{2,3}\)?[\s.-]?){3,5}\d{2,3}"
)
BANK_ACCOUNT = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[\s-]*\d{4}){6}(?!\d)", re.I)
SPACE_RUN = re.compile(r"[ \t\v\f]+")
BLANK_RUN = re.compile(r"\n{3,}")
CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
TRANSLATION = str.maketrans({
"\u00a0": " ", "\u2007": " ", "\u202f": " ", "\u200b": "",
"\ufeff": "", "\u00ad": "", "\u2010": "-", "\u2011": "-",
"\u2012": "-", "\u2013": "-", "\u2014": "-", "\u2212": "-",
"\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"',
"\u2026": "...",
})
class BuildError(ValueError):
pass
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def sha256_file(path: pathlib.Path) -> str:
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 canonical_sha256(value: Any) -> str:
payload = json.dumps(
value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def write_json(path: pathlib.Path, payload: Any) -> None:
path.write_text(
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True, default=str) + "\n",
encoding="utf-8",
)
def first_text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, dict):
return str(value.get("name") or value.get("caseNumber") or value.get("id") or "").strip()
return str(value).strip()
def list_text(value: Any) -> list[str]:
if not isinstance(value, list):
return [first_text(value)] if first_text(value) else []
return [text for item in value if (text := first_text(item))]
def normalize_text(value: Any) -> tuple[str, collections.Counter[str]]:
stats: collections.Counter[str] = collections.Counter()
original = str(value or "")
text = html.unescape(unicodedata.normalize("NFKC", original)).translate(TRANSLATION)
text, controls = CONTROL.subn("", text)
stats["control_characters_removed"] += controls
lines = [SPACE_RUN.sub(" ", line).strip() for line in text.replace("\r", "\n").split("\n")]
text = BLANK_RUN.sub("\n\n", "\n".join(lines)).strip()
if text != original.strip():
stats["normalized_records"] += 1
for pattern, key, replacement in (
(EMAIL, "emails_redacted", "[PII:EMAIL]"),
(LABELLED_IDENTIFIER, "labelled_identifiers_redacted", "[PII:IDENTIFIER]"),
(PESEL, "pesel_candidates_redacted", "[PII:PESEL]"),
(LABELLED_PHONE, "labelled_phones_redacted", "[PII:PHONE]"),
(BANK_ACCOUNT, "bank_accounts_redacted", "[PII:ACCOUNT]"),
):
text, count = pattern.subn(replacement, text)
stats[key] += count
return text, stats
def polish_ratio(text: str) -> float:
letters = ALPHA_RE.findall(text)
return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0
def normalize_date(value: Any) -> tuple[str, str, bool]:
raw = value.isoformat() if isinstance(value, (dt.date, dt.datetime)) else str(value or "")
candidate = raw[:10]
try:
parsed = dt.date.fromisoformat(candidate)
except ValueError:
return "", raw, False
valid = 1900 <= parsed.year <= dt.date.today().year + 1
return (parsed.isoformat() if valid else ""), raw, valid
def output_schema(pa: Any) -> Any:
return 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()),
])
def process_source_shard(task: tuple[str, str, str, str, int, int]) -> dict[str, Any]:
"""Transform one pinned source shard into a deterministic intermediate part."""
shard_name, part_name, added_date, source_revision, batch_size, token_threads = task
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
shard = pathlib.Path(shard_name)
part_dir = pathlib.Path(part_name)
part_dir.mkdir(parents=True, exist_ok=True)
parquet_path = part_dir / "data.parquet"
sidecar_path = part_dir / "attribution.jsonl"
identity_path = part_dir / "identities.tsv"
schema = output_schema(pa)
encoder = tiktoken.get_encoding("cl100k_base")
counts: collections.Counter[str] = collections.Counter()
normalization: collections.Counter[str] = collections.Counter()
court_types: collections.Counter[str] = collections.Counter()
judgment_types: collections.Counter[str] = collections.Counter()
seen_ids: set[str] = set()
seen_texts: set[bytes] = set()
dates: list[str] = []
source_parquet = pq.ParquetFile(shard)
required = {"id", "textContent", "judgmentDate", "courtType", "judgmentType", "caseNumbers", "judges", "source"}
if not required <= set(source_parquet.schema_arrow.names):
raise BuildError(f"unexpected source schema in {shard.name}")
writer = pq.ParquetWriter(parquet_path, schema, compression="zstd")
try:
with sidecar_path.open("w", encoding="utf-8") as sidecar, identity_path.open("w", encoding="ascii") as identities:
for batch in source_parquet.iter_batches(batch_size=batch_size):
prepared = []
for row in batch.to_pylist():
counts["source_rows"] += 1
source_id = str(row.get("id") or "").strip()
if not source_id or source_id in seen_ids:
counts["drop_duplicate_or_empty_id"] += 1
continue
seen_ids.add(source_id)
text, changes = normalize_text(row.get("textContent"))
normalization.update(changes)
if HTML_TAG.search(text):
raise BuildError(f"HTML residue in source record {source_id}")
if len(text) < 200:
counts["drop_short"] += 1
continue
if polish_ratio(text) < 0.005:
counts["drop_lang"] += 1
continue
text_digest = hashlib.sha1(text.encode("utf-8")).digest()
if text_digest in seen_texts:
counts["drop_dup"] += 1
continue
seen_texts.add(text_digest)
created, raw_date, valid_date = normalize_date(row.get("judgmentDate"))
if not valid_date:
counts["invalid_dates"] += 1
else:
dates.append(created)
judges = list_text(row.get("judges"))
author = "; ".join(judges)
court_type = str(row.get("courtType") or "")
judgment_type = str(row.get("judgmentType") or "")
court_types[court_type] += 1
judgment_types[judgment_type] += 1
prepared.append((source_id, text, text_digest, created, raw_date, author, judges, court_type, judgment_type, row))
texts = [item[1] for item in prepared]
token_counts = [
len(tokens) for tokens in encoder.encode_ordinary_batch(texts, num_threads=token_threads)
] if texts else []
documents = []
for item, token_count in zip(prepared, token_counts):
source_id, text, text_digest, created, raw_date, author, judges, court_type, judgment_type, row = item
document_id = f"{SOURCE_NAME}_{source_id}"
documents.append({
"id": document_id, "text": text, "source": SOURCE_NAME,
"added": added_date, "created": created, "token_count": token_count,
"license": SOURCE_LICENSE, "author": author,
})
source_meta = row.get("source") if isinstance(row.get("source"), dict) else {}
sidecar.write(json.dumps({
"id": document_id,
"source_id": source_id,
"official_url": f"https://www.saos.org.pl/judgments/{source_id}",
"upstream_judgment_url": source_meta.get("judgmentUrl"),
"upstream_source_code": source_meta.get("code"),
"court_type": court_type,
"judgment_type": judgment_type,
"case_numbers": list_text(row.get("caseNumbers")),
"judges": judges,
"judgment_date_raw": raw_date,
"judgment_date_status": "valid" if created else "invalid_or_implausible",
"source_revision": source_revision,
"source_shard": shard.name,
}, ensure_ascii=False, sort_keys=True, default=str) + "\n")
identities.write(f"{source_id}\t{text_digest.hex()}\n")
counts["kept"] += 1
counts["chars"] += len(text)
counts["tokens"] += token_count
counts["authors_with_value"] += bool(author)
if documents:
writer.write_table(pa.Table.from_pylist(documents, schema=schema))
finally:
writer.close()
return {
"shard": shard.name,
"parquet": str(parquet_path),
"sidecar": str(sidecar_path),
"identities": str(identity_path),
"counts": dict(counts),
"normalization": dict(normalization),
"court_types": dict(court_types),
"judgment_types": dict(judgment_types),
"created_min": min(dates) if dates else "",
"created_max": max(dates) if dates else "",
}
def registry_entry(stats: dict[str, Any], source_revision: str) -> str:
return (
f' "{SOURCE_NAME}": {{\n'
f' "file_key": "{SOURCE_NAME}",\n'
' "pretty": "SAOS - Polish court judgments (pinned partial snapshot)",\n'
f' "license": "{SOURCE_LICENSE}",\n'
' "license_spdx": "LicenseRef-Polish-Official-Documents",\n'
' "traceable": "Court judgments are documented as official materials outside "\n'
' "copyright under Polish Copyright Act art. 4(2); formal legal "\n'
' "review has not been performed and statutory limitations remain.",\n'
f' "upstream": "{OFFICIAL_API}",\n'
' "provenance": "Converted from the immutable "\n'
f' "{SOURCE_REPOSITORY}@{source_revision} snapshot; per-record "\n'
' "SAOS URLs and source identifiers are preserved in a sidecar.",\n'
' "domain": "legal/judicial",\n'
f' "created": "{stats["created_min"]}, {stats["created_max"]}",\n'
' "is_ocr": False,\n'
' "custom_datasheet": True,\n'
' },\n'
)
def update_registry(registry: str, stats: dict[str, Any], source_revision: str) -> str:
if re.search(rf'^\s{{4}}["\']{SOURCE_NAME}["\']\s*:', registry, re.MULTILINE):
raise BuildError(f"{SOURCE_NAME} already exists in the target registry")
marker = ' "dziennik_ustaw": {'
if registry.count(marker) != 1:
raise BuildError("cannot locate the dziennik_ustaw registry entry")
return registry.replace(marker, registry_entry(stats, source_revision) + marker, 1)
def update_findings(findings: str, stats: dict[str, Any], args: argparse.Namespace) -> str:
marker = "### SAOS snapshot contribution update (2026-09-04)"
if marker in findings:
raise BuildError("SAOS findings update already exists")
coverage = stats["source_rows"] / args.official_total_results
addition = f"""
{marker}
`{SOURCE_REPOSITORY}@{args.source_revision}` contains **{stats['source_rows']:,}**
processed judgments. The official SAOS dump exposed **{args.official_total_results:,}**
items when checked on {args.official_count_observed_at}; the pinned snapshot is
therefore a **partial snapshot** ({coverage:.1%} of that live count), not a claim
of current SAOS completeness. The contribution preserves this limitation in its
ontology Evidence, Claim, attestation and datasheet. It contributes the available
cleaned legal text now while leaving a later incremental SAOS synchronization as
a separate versioned task.
"""
return findings.rstrip() + addition + "\n"
def legal_evidence(args: argparse.Namespace) -> dict[str, Any]:
return {
"status": "documented-statutory-basis-review-needed",
"formal_legal_review": "not_performed",
"dataset_record_license": SOURCE_LICENSE,
"hf_source_card_license": "unknown",
"provider": "System Analizy Orzeczen Sadowych (SAOS)",
"official_source": OFFICIAL_API,
"official_source_documentation": OFFICIAL_API_DOCS,
"copyright_basis": {
"act": "Polish Copyright and Related Rights Act",
"article": "4(2)",
"finding": "official documents and materials are excluded from copyright",
"url": COPYRIGHT_ACT,
},
"reuse_basis": {
"act": "Polish Open Data and Reuse of Public Sector Information Act",
"articles": ["2(12)", "5", "6", "14(1)", "15", "17"],
"url": OPEN_DATA_ACT,
},
"limitations": [
"formal legal review has not been performed",
"privacy and personal-data exceptions remain",
"third-party works quoted or embedded in judgments may retain separate rights",
"no upstream Creative Commons grant is asserted",
"the pinned source snapshot is incomplete relative to the live SAOS count",
],
"pinned_source": f"hf://datasets/{SOURCE_REPOSITORY}@{args.source_revision}",
"pinned_target_base": f"hf://datasets/{TARGET_REPOSITORY}@{args.target_revision}",
}
def datasheet(stats: dict[str, Any], args: argparse.Namespace) -> str:
coverage = stats["source_rows"] / args.official_total_results
court_rows = "\n".join(
f"| `{key}` | {value:,} |" for key, value in stats["by_court_type"].items()
)
return f"""# {SOURCE_NAME}
Polish court judgments from the System Analizy Orzeczen Sadowych (SAOS),
converted from a pinned `PiotrSty` snapshot into the DynaWord source schema.
## Dataset description
- Official origin: {OFFICIAL_API}
- API documentation: {OFFICIAL_API_DOCS}
- Pinned source: `{SOURCE_REPOSITORY}@{args.source_revision}`
- Domain: legal/judicial
- Language: Polish (`pl`)
- License label: `{SOURCE_LICENSE}`
- Valid judgment dates: {stats['created_min']} through {stats['created_max']}
- Added: {args.added_date}
- Contributor: Piotr Sty\u0142a (`PiotrSty` on Hugging Face; `PiotrStyla` on GitHub)
## Snapshot scope and completeness
The source contains **{stats['source_rows']:,}** processed records. A direct query
of the official SAOS API on {args.official_count_observed_at} returned
**{args.official_total_results:,}** items. This version therefore represents
approximately **{coverage:.1%}** of the live count and MUST NOT be described as a
complete or current copy of SAOS. The immutable snapshot remains useful as a
large, auditable legal-language contribution; later synchronization belongs in a
new dataset Version and Run.
## Content and provenance
Each DynaWord row uses the normalized full judgment text. The attribution
sidecar preserves the source ID, canonical SAOS URL, upstream source URL, court
type, judgment type, case numbers, named judges acting in an official capacity,
raw judgment date, source shard and pinned source revision. Generated SAOS
enrichment fields are not used as training-text claims.
## Courts represented
| court type | source rows |
|---|---:|
{court_rows}
## Processing
- NFKC Unicode normalization, normalized spaces/quotes/dashes and preserved paragraphs.
- Article and section numbering is retained because it is substantive legal content.
- Exact normalized-text deduplication with SHA-1 fingerprints.
- Minimum 200 characters and the DynaWord Polish-diacritic ratio gate (`>= 0.005`).
- Pattern scrubbing for email, PESEL candidates, labelled NIP/REGON, labelled phones and bank accounts.
- Implausible or unparsable judgment dates are left empty in the training schema and preserved raw in the sidecar.
- HTML residue causes a build failure rather than silently entering the corpus.
## Statistics
| measure | value |
|---|---:|
| Source records | {stats['source_rows']:,} |
| Documents published | {stats['kept']:,} |
| Dropped under 200 characters | {stats['drop_short']:,} |
| Dropped by Polish-language gate | {stats['drop_lang']:,} |
| Exact normalized duplicates removed | {stats['drop_dup']:,} |
| Records with invalid/implausible dates | {stats['invalid_dates']:,} |
| Documents with judge attribution | {stats['authors_with_value']:,} |
| Characters | {stats['chars']:,} |
| Tokens (`cl100k_base` proxy) | {stats['tokens']:,} |
## Licensing and privacy
Court judgments are documented here as official materials excluded from
copyright under article 4(2) of the Polish Copyright Act, with reuse considered
under the Polish Open Data Act. The source card itself declares `license:
unknown`, no Creative Commons grant is asserted, and no formal legal opinion was
performed. Privacy exceptions and separate rights in quoted or embedded works
remain. This is provenance and engineering documentation, not legal advice.
The source reports prior PII scrubbing. This conversion reruns conservative
pattern-based scrubbing, but does not claim perfect de-identification. Court-
published anonymization is retained; names of judges acting publicly in their
official capacity are preserved as attribution.
## Known limitations
- Partial historical snapshot, not the complete current SAOS database.
- Legal/judicial register is already heavily represented in Polish DynaWord;
inclusion changes the training mix and should be evaluated through ablations.
- Pattern-based PII detection can have false negatives and false positives.
- Upstream source transformations are described in its card but the repository
does not include the original collection code or standalone audit artifacts.
"""
def contract_test() -> str:
return fr'''"""Contract and ontology 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"
FIELDS = {list(EXPECTED_FIELDS)!r}
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_data_schema_and_stats():
parquet = DATA / "{SOURCE_NAME}.parquet"
stats = json.loads((DATA / "{SOURCE_NAME}.stats.json").read_text(encoding="utf-8"))
source_values, license_values, ids = set(), set(), set()
rows = chars = tokens = authors = 0
for batch in pq.ParquetFile(parquet).iter_batches(batch_size=256):
assert batch.schema.names == FIELDS
for row in batch.to_pylist():
rows += 1
assert row["id"] not in ids
ids.add(row["id"])
assert len(row["text"]) >= 200
assert row["token_count"] > 0
assert not re.search(
r"</?(?:p|div|span|br|h[1-6]|table|tbody|thead|tr|td|th|ul|ol|li|strong|em|b|i|a|section)\s*/?>",
row["text"],
re.I,
)
assert not row["created"] or re.fullmatch(r"20\d{{2}}-\d{{2}}-\d{{2}}|19\d{{2}}-\d{{2}}-\d{{2}}", row["created"])
source_values.add(row["source"])
license_values.add(row["license"])
chars += len(row["text"])
tokens += row["token_count"]
authors += bool(row["author"])
assert rows == stats["kept"]
assert chars == stats["chars"]
assert tokens == stats["tokens"]
assert authors == stats["authors_with_value"]
assert source_values == {{"{SOURCE_NAME}"}}
assert license_values == {{"{SOURCE_LICENSE}"}}
def test_sidecar_legal_and_snapshot_honesty():
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["formal_legal_review"] == "not_performed"
assert legal["hf_source_card_license"] == "unknown"
assert legal["pinned_source"].endswith(stats["source_revision"])
assert stats["official_total_results"] > stats["source_rows"]
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"]}}
version = manifest["version"]
assert version["object_id"] == manifest["object"]["id"]
assert version["created_by"] in actor_ids
assert re.fullmatch(r"sha256:[0-9a-f]{{64}}", version["digest"])
assert re.search(r"@[0-9a-f]{{40}}/", 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.search(r"@[0-9a-f]{{40}}/", protocol_version["payload_uri"])
assert sha256_file(ROOT / protocol["specification"]["source_path"]) == protocol_version["code_sha256"]
run = manifest["run"]
assert run["actor_id"] in actor_ids
assert run["started_at"] <= run["finished_at"]
assert {{"python", "platform", "machine", "packages", "determinism"}} <= set(run["environment"])
evidence_ids = {{item["id"] for item in manifest["evidence"]}}
claim_ids = {{item["id"] for item in manifest["claims"]}}
assert len(evidence_ids) == len(manifest["evidence"])
assert len(claim_ids) == len(manifest["claims"])
for item in manifest["evidence"]:
assert item["run_id"] == run["id"]
assert item["subject_version"] == version["id"]
for item in manifest["claims"]:
assert item["scope"] == version["id"]
assert item["asserted_by"] in actor_ids
assert item["falsification_condition"]
assert set(item["supported_by"]) <= evidence_ids
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"}}
for attestation in manifest["attestations"]:
assert attestation["actor_id"] in actor_ids
assert attestation["subject_version"] == version["id"]
assert set(attestation["supported_by"]) <= evidence_ids
assert any(item["type"] == "source_completeness" and item["value"] == "partial_snapshot" for item in manifest["attestations"])
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)
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",
"datasheet_sha256": DATA / "{SOURCE_NAME}.md",
"legal_evidence_sha256": DATA / "{SOURCE_NAME}.license-evidence.json",
"source_inventory_sha256": ROOT / "artifacts" / "{SOURCE_NAME}_source_inventory.json",
"source_profile_sha256": ROOT / "artifacts" / "{SOURCE_NAME}_source_profile.json",
}}
assert {{name: sha256_file(path) for name, path in paths.items()}} == checksums
'''
def build(args: argparse.Namespace) -> dict[str, Any]:
run_started_at = utc_now()
for name in ("source_revision", "target_revision", "dataset_payload_commit", "protocol_payload_commit"):
if not COMMIT_PATTERN.fullmatch(getattr(args, name)):
raise BuildError(f"{name} must be a 40-character commit")
for path in (args.target_registry, args.target_findings, args.source_profile):
if not path.is_file():
raise BuildError(f"required input is missing: {path}")
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
source_shards = sorted((args.source_dir / "data").glob("*.parquet"))
if not source_shards:
raise BuildError("no source Parquet shards found")
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)
source_inventory = {
"repository": SOURCE_REPOSITORY,
"revision": args.source_revision,
"files": [
{"path": f"data/{path.name}", "size": path.stat().st_size, "sha256": sha256_file(path)}
for path in source_shards
],
}
source_inventory["aggregate_digest"] = f"sha256:{canonical_sha256(source_inventory)}"
inventory_path = artifact_dir / f"{SOURCE_NAME}_source_inventory.json"
profile_path = artifact_dir / f"{SOURCE_NAME}_source_profile.json"
write_json(inventory_path, source_inventory)
source_profile = json.loads(args.source_profile.read_text(encoding="utf-8"))
source_profile.pop("samples", None)
write_json(profile_path, source_profile)
schema = output_schema(pa)
parquet_path = data_dir / f"{SOURCE_NAME}.parquet"
sidecar_path = data_dir / f"{SOURCE_NAME}.attribution.jsonl"
parts_dir = output / "_parts"
parts_dir.mkdir(parents=True, exist_ok=True)
worker_count = min(max(1, args.workers), len(source_shards))
worker_token_threads = max(1, args.token_threads // worker_count)
tasks = [
(
str(shard),
str(parts_dir / f"part-{index:05d}"),
args.added_date,
args.source_revision,
args.batch_size,
worker_token_threads,
)
for index, shard in enumerate(source_shards)
]
if worker_count == 1:
parts = [process_source_shard(task) for task in tasks]
else:
with concurrent.futures.ProcessPoolExecutor(max_workers=worker_count) as pool:
parts = list(pool.map(process_source_shard, tasks))
counts: collections.Counter[str] = collections.Counter()
normalization: collections.Counter[str] = collections.Counter()
court_types: collections.Counter[str] = collections.Counter()
judgment_types: collections.Counter[str] = collections.Counter()
seen_ids: set[str] = set()
seen_texts: set[bytes] = set()
dates: list[str] = []
writer = pq.ParquetWriter(parquet_path, schema, compression="zstd")
try:
with sidecar_path.open("wb") as sidecar:
for part in parts:
metadata_parquet = pq.ParquetFile(part["parquet"])
try:
part_rows = metadata_parquet.metadata.num_rows
finally:
metadata_parquet.close()
identity_rows = 0
with pathlib.Path(part["identities"]).open(encoding="ascii") as identities:
for line in identities:
source_id, text_digest_hex = line.rstrip("\n").split("\t", 1)
text_digest = bytes.fromhex(text_digest_hex)
if source_id in seen_ids:
raise BuildError(f"cross-shard duplicate source id: {source_id}")
if text_digest in seen_texts:
raise BuildError(f"cross-shard duplicate normalized text in {part['shard']}")
seen_ids.add(source_id)
seen_texts.add(text_digest)
identity_rows += 1
if identity_rows != part_rows:
raise BuildError(f"identity count mismatch in {part['shard']}")
with pathlib.Path(part["sidecar"]).open("rb") as source_sidecar:
shutil.copyfileobj(source_sidecar, sidecar, length=1024 * 1024)
part_parquet = pq.ParquetFile(part["parquet"])
try:
for row_group in range(part_parquet.metadata.num_row_groups):
writer.write_table(part_parquet.read_row_group(row_group))
finally:
part_parquet.close()
counts.update(part["counts"])
normalization.update(part["normalization"])
court_types.update(part["court_types"])
judgment_types.update(part["judgment_types"])
if part["created_min"]:
dates.append(part["created_min"])
if part["created_max"]:
dates.append(part["created_max"])
finally:
writer.close()
shutil.rmtree(parts_dir)
if not counts["kept"]:
raise BuildError("no records survived the build")
stats: dict[str, Any] = {
**counts,
"source_rows": counts["source_rows"],
"kept": counts["kept"],
"drop_short": counts["drop_short"],
"drop_lang": counts["drop_lang"],
"drop_dup": counts["drop_dup"],
"invalid_dates": counts["invalid_dates"],
"authors_with_value": counts["authors_with_value"],
"chars": counts["chars"],
"tokens": counts["tokens"],
"created_min": min(dates) if dates else "",
"created_max": max(dates) if dates else "",
"by_court_type": dict(sorted(court_types.items())),
"by_judgment_type": dict(sorted(judgment_types.items())),
"normalization": dict(sorted(normalization.items())),
"license": SOURCE_LICENSE,
"licenses": {SOURCE_LICENSE: counts["kept"]},
"added": args.added_date,
"source_revision": args.source_revision,
"target_base_revision": args.target_revision,
"official_total_results": args.official_total_results,
"official_count_observed_at": args.official_count_observed_at,
"snapshot_live_count_ratio": counts["source_rows"] / args.official_total_results,
"stats_recomputed_from_parquet": True,
}
stats_path = data_dir / f"{SOURCE_NAME}.stats.json"
legal_path = data_dir / f"{SOURCE_NAME}.license-evidence.json"
datasheet_path = data_dir / f"{SOURCE_NAME}.md"
write_json(stats_path, stats)
write_json(legal_path, legal_evidence(args))
datasheet_path.write_text(datasheet(stats, args), encoding="utf-8")
(data_dir / "NOTICE.md").write_text(
"# Source attribution\n\nOfficial source: System Analizy Orzeczen Sadowych "
"(SAOS), https://www.saos.org.pl/. Per-record canonical SAOS URLs are "
"preserved in saos.attribution.jsonl. Snapshot 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),
"datasheet_sha256": sha256_file(datasheet_path),
"legal_evidence_sha256": sha256_file(legal_path),
"source_inventory_sha256": sha256_file(inventory_path),
"source_profile_sha256": sha256_file(profile_path),
}
version_digest = canonical_sha256({
"source_revision": args.source_revision,
"target_revision": args.target_revision,
"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_config = {
"source_revision": args.source_revision,
"minimum_characters": 200,
"minimum_polish_diacritic_ratio": 0.005,
"deduplication": {"algorithm": "sha1", "field": "normalized_text", "scope": "within_source"},
"tokenizer": "cl100k_base",
"date_valid_year_range": [1900, dt.date.today().year + 1],
"normalization": ["NFKC", "space_quote_dash", "paragraph_preserving_whitespace", "pattern_PII_scrub"],
"execution": {
"record_batch_size": args.batch_size,
"source_workers": args.workers,
"token_threads": args.token_threads,
"token_threads_per_worker": max(1, args.token_threads // min(max(1, args.workers), len(source_shards))),
"parquet_compression": "zstd",
},
}
protocol_spec = {
"entrypoint": "python src/fetch_saos.py",
"source_path": "src/fetch_saos.py",
"summary": "Deterministic normalization and projection of a pinned SAOS judgment snapshot.",
"configuration": protocol_config,
"required_inputs": ["14 pinned source Parquet shards", "source profile", "target registry", "target findings log"],
"outputs": ["DynaWord Parquet", "attribution sidecar", "datasheet", "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_spec,
})
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 = utc_now()
def evidence(kind: str, payload: Any) -> dict[str, Any]:
digest = canonical_sha256({"run": args.run_id, "subject": version_id, "kind": kind, "payload": payload})
return {
"id": f"slayer://evidence/{SOURCE_NAME}/{kind}@sha256:{digest}",
"run_id": args.run_id,
"subject_version": version_id,
"observation_type": kind,
"payload": payload,
"observed_at": run_finished_at,
}
evidence_items = [
evidence("dataset_record_counts", stats),
evidence("artifact_checksums", artifact_digests),
evidence("pinned_source_inventory", source_inventory),
evidence("source_completeness_observation", {
"snapshot_rows": stats["source_rows"],
"official_total_results": args.official_total_results,
"observed_at": args.official_count_observed_at,
"ratio": stats["snapshot_live_count_ratio"],
"complete": False,
}),
evidence("normalization_and_pii_metrics", stats["normalization"]),
evidence("schema_validation", {"schema": list(EXPECTED_FIELDS), "records": stats["kept"], "valid": True}),
evidence("legal_provenance_review", {
"status": "documented-statutory-basis-review-needed",
"formal_legal_review": "not_performed",
"artifact": f"data/{SOURCE_NAME}/{SOURCE_NAME}.license-evidence.json",
"sha256": artifact_digests["legal_evidence_sha256"],
}),
]
evidence_by_type = {item["observation_type"]: item["id"] for item in evidence_items}
def claim(statement: str, falsification: str, support: list[str]) -> dict[str, Any]:
digest = canonical_sha256({"scope": version_id, "statement": statement, "falsification": falsification})
return {
"id": f"slayer://claim/{SOURCE_NAME}@sha256:{digest}",
"scope": version_id,
"statement": statement,
"asserted_by": args.actor,
"supported_by": support,
"falsification_condition": falsification,
}
claims = [
claim(
"The contribution is derived from the 14 files of the pinned PiotrSty SAOS snapshot.",
"A source file is missing or its recorded size or SHA-256 differs.",
[evidence_by_type["pinned_source_inventory"]],
),
claim(
"The contributed dataset is a partial historical SAOS snapshot and not a complete current copy.",
"The pinned snapshot row count equals the official live count observed for this run.",
[evidence_by_type["source_completeness_observation"]],
),
claim(
"All retained rows conform to the DynaWord source schema and recorded artifact checksums.",
"A retained row violates the schema or an artifact checksum differs.",
[evidence_by_type["schema_validation"], evidence_by_type["artifact_checksums"]],
),
claim(
"Pattern-based PII scrubbing and documented text normalization were applied, without asserting perfect de-identification.",
"The committed protocol omits a documented transformation or a retained match contradicts its recorded metric.",
[evidence_by_type["normalization_and_pii_metrics"]],
),
claim(
"The records are court materials with a documented statutory reuse argument, pending formal legal review and subject to stated limitations.",
"The records are not official materials or legal review rejects the documented statutory basis.",
[evidence_by_type["legal_provenance_review"]],
),
]
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(kind: str, value: Any, support: list[str]) -> dict[str, Any]:
digest = canonical_sha256({"type": kind, "value": value, "actor": args.actor, "subject": version_id, "support": support})
return {
"id": f"slayer://attestation/{SOURCE_NAME}/{kind}@sha256:{digest}",
"type": kind,
"value": value,
"actor_id": args.actor,
"subject_version": version_id,
"supported_by": support,
"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": "legal/judicial", "provider": "SAOS"},
},
"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": run_finished_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_saos.py",
"created_at": run_finished_at,
"created_by": args.actor,
},
"specification": protocol_spec,
},
"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_config,
"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": [path.name for path in source_shards]},
},
"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("source_completeness", "partial_snapshot", [evidence_by_type["source_completeness_observation"]]),
attestation("provenance", "pinned_and_hashed", [evidence_by_type["pinned_source_inventory"]]),
attestation("pii_scrubbing", "pattern_scrub_applied_not_guaranteed", [evidence_by_type["normalization_and_pii_metrics"]]),
attestation("legal_status", "review_needed_documented_official_materials", [evidence_by_type["legal_provenance_review"]]),
],
}
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"), stats, args.source_revision),
encoding="utf-8",
)
(artifact_dir / "source_findings.md").write_text(
update_findings(args.target_findings.read_text(encoding="utf-8"), stats, args),
encoding="utf-8",
)
shutil.copy2(pathlib.Path(__file__).resolve(), src_dir / "fetch_saos.py")
(src_dir / "test_saos_contract.py").write_text(contract_test(), encoding="utf-8")
print(json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True))
return stats
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", type=pathlib.Path, required=True)
parser.add_argument("--source-profile", type=pathlib.Path, required=True)
parser.add_argument("--target-registry", type=pathlib.Path, required=True)
parser.add_argument("--target-findings", 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("--official-total-results", type=int, required=True)
parser.add_argument("--official-count-observed-at", required=True)
parser.add_argument("--added-date", required=True)
parser.add_argument("--actor", default="hf:PiotrSty")
parser.add_argument("--run-id", required=True)
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--workers", type=int, default=1)
parser.add_argument("--token-threads", type=int, default=4)
args = parser.parse_args()
build(args)
return 0
if __name__ == "__main__":
raise SystemExit(main())