#!/usr/bin/env python3
"""Build an auditable corpus of UZP public-procurement rulings (KIO/SO/SA/SN).
Source: https://orzeczenia.uzp.gov.pl - the official decision search service of
the Polish Public Procurement Office (Urzad Zamowien Publicznych). Documents
are official rulings of the National Appeals Chamber (KIO), district courts
(SO), administrative courts (SA) and the Supreme Court (SN) in public
procurement matters. Legal basis: official documents are excluded from
copyright under Polish Copyright Act art. 4(2) (same basis as the SAOS slice).
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timedelta, timezone
import gzip
import hashlib
import html as html_module
import importlib.util
import io
import ipaddress
import json
from pathlib import Path
import re
import shutil
import sys
import threading
import time
import requests
from language_gate import language_vote
SOURCE = "uzp_orzeczenia_pl"
OWN_REPO = "PiotrSty/uzp-orzeczenia-pl"
TARGET = "SlayerLab/polish-dynaword"
BASE = "https://orzeczenia.uzp.gov.pl"
SEARCH_URL = BASE + "/Home/Search"
RESULTS_URL = BASE + "/Home/GetResults"
SOURCE_URL = BASE + "/"
FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"]
UA = "UzpOrzeczeniaCorpusResearch/0.1 (PiotrSty; open research slice)"
LICENSE_LABEL = "public-domain (official documents)"
LICENSE_SPDX = "LicenseRef-Polish-Official-Documents"
LEGAL_BASIS = ("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")
MIN_TEXT_CHARS = 1_500
PAGE_SIZE = 10 # fixed server-side; #sp-page-size is not a serialized form field
KINDS = ("KIO", "SO", "SA", "SN")
EMAIL_RE = re.compile(r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b")
PHONE_RE = re.compile(r"(?i)(?:\btelefon|\btel\.|\bphone)\s*:?[ \t]*(?:\+48[ \t]*)?\d(?:[ .-]?\d){8}\b")
# Dotted quads are mostly clause numbers ("pkt 1.2.3.4"), CPV/PKWiU codes and table cells, and valid
# IPv6 forms mostly times ("18:12::18") and list colons ("Zadanie 2::"), so an address outside a longer
# dotted chain is redacted only in network context (in_ip_context).
IPV4_RE = re.compile(r"(?]+>", " ", fragment))).strip()
def parse_result_items(page_html):
"""Parse /Home/GetResults response into per-document records."""
records = []
for block in re.findall(r'
([^<]+)\s*([^<]+)", block):
fields[label.strip().rstrip(":")] = strip_html(value)
records.append({
"doc_id": int(link.group(1)),
"organ": fields.get("Organ wydający", ""),
"doc_type": fields.get("Rodzaj dokumentu", ""),
"signature": fields.get("Sygnatura", ""),
"issued": fields.get("Data wydania", ""),
})
counts = RESULT_COUNTS_RE.search(page_html)
totals = [int(value) for value in counts.group(1).split(",")] if counts else []
return records, totals
def parse_counts(page_html):
"""Return dict kind -> count from the resultCounts hidden field."""
_records, totals = parse_result_items(page_html)
kinds = ["ALL", "KIO", "SO", "SA", "SN"]
return {kinds[index]: value for index, value in enumerate(totals)} if totals else {}
def parse_details(page_html, doc_id):
"""Parse /Home/Details/{id} metadata page."""
pdf = PDF_LINK_RE.search(page_html)
body = re.sub(r"", " ", page_html, flags=re.S)
fields = {}
for label, value in re.findall(r"\s*([^<]+)", body):
fields[label.strip().rstrip(":")] = strip_html(value)
return {
"doc_id": doc_id,
"organ": fields.get("Organ wydający", ""),
"doc_type": fields.get("Rodzaj dokumentu", ""),
"issued": fields.get("Data wydania rozstrzygnięcia", ""),
"chairman": fields.get("Przewodniczący", ""),
"purchaser": fields.get("Zamawiający", ""),
"city": fields.get("Miejscowość", ""),
"signature": fields.get("Sygnatura akt / Sposób rozstrzygnięcia",
fields.get("Sygnatura akt / Sygnatura KIO / Sposób rozstrzygnięcia", "")),
"provisions": fields.get("Kluczowe przepisy ustawy Pzp", ""),
"pdf_path_url": BASE + pdf.group(1) if pdf else "",
"pdf_kind": pdf.group(3) if pdf else "",
}
def session():
s = requests.Session()
s.headers.update({"User-Agent": UA})
s.get(SEARCH_URL, timeout=20)
return s
def post_results(sess, kind, page, attempts=5):
data = {"Phrase": "", "Fle": "1", "SCnt": "1", "CountStats": "true",
"Kind": kind, "Srt": "", "Pg": str(page)}
for attempt in range(attempts):
try:
r = sess.post(RESULTS_URL, data=data, timeout=30)
if r.status_code in (429, 500, 502, 503, 504):
time.sleep(2 ** attempt)
continue
r.raise_for_status()
return r.text
except requests.RequestException:
if attempt == attempts - 1:
raise
time.sleep(2 ** attempt)
raise RuntimeError("unreachable")
def request(url, attempts=5, timeout=(15, 90), binary=False, sess=None):
client = sess or requests
response = None
for attempt in range(attempts):
response = client.get(url, headers={"User-Agent": UA}, timeout=timeout)
if response.status_code not in (429, 500, 502, 503, 504):
response.raise_for_status()
return response.content if binary else response.content.decode("utf-8", "replace")
time.sleep(2 ** attempt)
response.raise_for_status()
def request_json(url):
return json.loads(request(url))
def discover(out, workers):
"""Enumerate every document via the kind-filtered result pages."""
seen = {}
counts = {}
for kind in KINDS:
body = post_results(session(), kind, 1)
first, totals = parse_result_items(body)
all_counts = parse_counts(body)
counts[kind] = all_counts.get(kind, len(first))
total = counts[kind]
pages = max(1, -(-total // PAGE_SIZE)) if total else 1
for record in first:
record["kind"] = kind
seen[record["doc_id"]] = record
def fetch_page(page):
return page, post_results(session(), kind, page)
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(fetch_page, p): p for p in range(2, pages + 1)}
for index, future in enumerate(as_completed(futures), 1):
_, body = future.result()
for record in parse_result_items(body)[0]:
record["kind"] = kind
seen[record["doc_id"]] = record
if index % 200 == 0:
print(f" {kind} {index}/{pages - 1} pages", flush=True)
print(f" {kind}: {pages} pages, total {total}", flush=True)
records = sorted(seen.values(), key=lambda record: record["doc_id"])
write_lines(out / "source_manifest.jsonl", records)
selection = {
"observed_at": now(), "search_url": SEARCH_URL,
"reported_totals": counts, "enumerated": len(records),
"per_kind": dict(Counter(record["kind"] for record in records)),
"selected": len(records),
"selected_ids": [record["doc_id"] for record in records],
"source_manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
}
save(out / "selection.json", selection)
print(json.dumps(selection, ensure_ascii=False, indent=2))
def pdf_text(payload):
"""pypdf page texts joined by newlines, and the page count."""
from pypdf import PdfReader
reader = PdfReader(io.BytesIO(payload))
return "\n".join(page.extract_text() or "" for page in reader.pages), len(reader.pages)
def acquire(out, workers):
selection = load(out / "selection.json")
manifest = {record["doc_id"]: record for record in read_lines(out / "source_manifest.jsonl")}
(out / "raw_pages").mkdir(parents=True, exist_ok=True)
(out / "raw_pdf").mkdir(parents=True, exist_ok=True)
(out / "raw_text").mkdir(parents=True, exist_ok=True)
results = []
def fetch(doc_id):
record = manifest[doc_id]
page_path = out / "raw_pages" / f"{doc_id}.html.gz"
pdf_path = out / "raw_pdf" / f"{doc_id}.pdf"
text_path = out / "raw_text" / f"{doc_id}.txt"
if pdf_path.is_file() and text_path.is_file() and page_path.is_file():
return record, digest(pdf_path.read_bytes()), pdf_path.stat().st_size, \
digest(text_path.read_bytes()), "cached", json.loads(
gzip.decompress(page_path.read_bytes()).decode("utf-8"))["details"]
sess = session()
body = request(BASE + f"/Home/Details/{doc_id}", sess=sess)
details = parse_details(body, doc_id)
if not details["pdf_path_url"]:
raise ValueError(f"no PdfContent link on details page: {doc_id}")
page_path.write_bytes(gzip.compress(json.dumps(
{"doc_id": doc_id, "details": details}, ensure_ascii=False).encode("utf-8")))
payload = request(details["pdf_path_url"], binary=True, sess=sess)
if not payload.startswith(b"%PDF"):
raise ValueError("not a PDF: " + str(doc_id))
pdf_path.write_bytes(payload)
text, pages = pdf_text(payload)
text_path.write_text(text, encoding="utf-8")
return record, digest(payload), len(payload), digest(text.encode("utf-8")), str(pages), details
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(fetch, doc_id): doc_id for doc_id in selection["selected_ids"]}
for index, future in enumerate(as_completed(futures), 1):
doc_id = futures[future]
record = manifest[doc_id]
try:
record, pdf_sha, pdf_bytes, text_sha, pages, details = future.result()
results.append({**record, "details": details, "pdf_sha256": pdf_sha,
"pdf_bytes": pdf_bytes, "text_sha256": text_sha, "pdf_pages": pages,
"pdf_path": f"raw_pdf/{doc_id}.pdf", "text_path": f"raw_text/{doc_id}.txt"})
except Exception as error:
results.append({**record, "error": f"{type(error).__name__}: {error}"})
if index % 100 == 0:
print(f" {index}/{len(selection['selected_ids'])}", flush=True)
results.sort(key=lambda record: record["doc_id"])
acquisition = {
"observed_at": now(), "target": selection["selected"],
"acquired": sum("pdf_sha256" in record for record in results),
"failed": [record["doc_id"] for record in results if "error" in record],
"selected": results,
}
save(out / "acquisition.json", acquisition)
print(json.dumps({key: acquisition[key] for key in ("target", "acquired", "failed")},
ensure_ascii=False, indent=2))
def restore_render_stamp(payload, pdf_sha256, hint):
"""`payload` with the /CreationDate stamp under which its SHA-256 is `pdf_sha256`, and that stamp's time.
The service renders every PDF on request and stamps the request time, so an unchanged ruling downloaded
again differs from its recorded bytes only in that stamp. Times within an hour of `hint` are tried first
(reacquire() fetches in id order, as the shipped build did), then every second of PINNED_RENDERS."""
stamps = list(PDF_CREATION_DATE_RE.finditer(payload))
if len(stamps) != 1:
raise ValueError(f"{len(stamps)} CreationDate stamps in the PDF")
start, end = stamps[0].span()
prefix, suffix = hashlib.sha256(payload[:start]), payload[end:]
def moments():
for offset in range(3600):
yield hint + timedelta(seconds=offset)
yield hint - timedelta(seconds=offset + 1)
moment = PINNED_RENDERS[0]
while moment < PINNED_RENDERS[1]:
yield moment
moment += timedelta(seconds=1)
for moment in moments():
stamp = (moment.strftime("D:%Y%m%d%H%M%S") + PINNED_RENDER_ZONE).encode("ascii")
candidate = prefix.copy()
candidate.update(stamp)
candidate.update(suffix)
if candidate.hexdigest() == pdf_sha256:
return payload[:start] + stamp + suffix, moment
raise ValueError("no CreationDate in PINNED_RENDERS reproduces the recorded pdf_sha256")
def write_atomic(path, payload):
"""Write through a temporary file, so an interrupted run leaves no truncated file for a resumed run to reuse."""
part = path.with_name(path.name + ".part")
part.write_bytes(payload)
part.replace(path)
def reacquire(out, data, workers):
"""Download the documents of the shipped build in `data` again into `out`, as acquire() stored them then.
Retained documents must come back as their recorded bytes (restore_render_stamp) and take their metadata
from the attribution sidecar. Rejected documents have no recorded PDF hash, so their Details page and PDF
are used as served now. Documents whose acquisition failed stay failed with the recorded error. Files
already in `out` are reused, so an interrupted run resumes. Writes source_manifest.jsonl, selection.json
and acquisition.json for build()."""
attribution = {item["doc_id"]: item for item in read_lines(data / f"{SOURCE}.attribution.jsonl")}
decisions = read_lines(data / f"{SOURCE}.decisions.jsonl")
doc_ids = sorted(int(item["id"].rsplit("_", 1)[1]) for item in decisions)
failed = {int(item["id"].rsplit("_", 1)[1]): item["error"]
for item in decisions if item["reason"] == "acquisition_failed"}
for name in ("raw_pages", "raw_pdf", "raw_text"):
(out / name).mkdir(parents=True, exist_ok=True)
started, local, hint = now(), threading.local(), [FIRST_RENDER]
def client():
if not hasattr(local, "session"):
local.session = session()
return local.session
def fetch(doc_id):
shipped = attribution.get(doc_id)
if shipped:
details = {"doc_id": doc_id, "pdf_path_url": shipped["pdf_url"], **{key: shipped[key] for key in (
"organ", "doc_type", "issued", "chairman", "purchaser", "signature", "provisions")}}
record = {key: shipped[key] for key in ("doc_id", "kind", "organ", "doc_type", "signature", "issued")}
else:
page_path = out / "raw_pages" / f"{doc_id}.json"
if not page_path.is_file():
details = parse_details(request(BASE + f"/Home/Details/{doc_id}", sess=client()), doc_id)
write_atomic(page_path, json.dumps(details, ensure_ascii=False).encode("utf-8"))
details = load(page_path)
record = {"doc_id": doc_id, "kind": details["pdf_kind"],
**{key: details[key] for key in ("organ", "doc_type", "signature", "issued")}}
if doc_id in failed:
return {**record, "error": failed[doc_id]}
if not details["pdf_path_url"]:
raise ValueError(f"no PdfContent link on details page: {doc_id}")
pdf_path, text_path = out / "raw_pdf" / f"{doc_id}.pdf", out / "raw_text" / f"{doc_id}.txt"
if pdf_path.is_file():
payload = pdf_path.read_bytes()
else:
payload = request(details["pdf_path_url"], binary=True, sess=client())
if not payload.startswith(b"%PDF"):
raise ValueError(f"not a PDF: {doc_id}")
if shipped:
if len(payload) != shipped["pdf_bytes"]:
raise ValueError(f"{len(payload)} bytes, {shipped['pdf_bytes']} recorded: {doc_id}")
payload, hint[0] = restore_render_stamp(payload, shipped["pdf_sha256"], hint[0])
write_atomic(pdf_path, payload)
if shipped and digest(payload) != shipped["pdf_sha256"]:
raise ValueError(f"PDF differs from the recorded pdf_sha256: {doc_id}")
if not text_path.is_file(): # ponytail: pypdf holds the GIL, ~65 documents/min; a process pool if that matters
write_atomic(text_path, pdf_text(payload)[0].encode("utf-8"))
return {**record, "details": details, "pdf_sha256": digest(payload), "pdf_bytes": len(payload),
"pdf_path": f"raw_pdf/{doc_id}.pdf", "text_path": f"raw_text/{doc_id}.txt",
"text_sha256": digest(text_path.read_bytes())}
results, errors = [], {}
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(fetch, doc_id): doc_id for doc_id in doc_ids}
for index, future in enumerate(as_completed(futures), 1):
try:
results.append(future.result())
except Exception as error:
errors[futures[future]] = f"{type(error).__name__}: {error}"
if index % 500 == 0:
print(f" {index}/{len(doc_ids)} errors={len(errors)}", flush=True)
if errors:
save(out / "reacquire_errors.json", errors)
raise RuntimeError(f"{len(errors)} documents not re-acquired, see {out / 'reacquire_errors.json'}")
results.sort(key=lambda record: record["doc_id"])
write_lines(out / "source_manifest.jsonl", [{key: record[key] for key in (
"doc_id", "kind", "organ", "doc_type", "signature", "issued")} for record in results])
save(out / "selection.json", {
"observed_at": started, "search_url": SEARCH_URL,
"reported_totals": f"pinned to the shipped build ({SOURCE}.decisions.jsonl)",
"enumerated": len(results), "per_kind": dict(Counter(record["kind"] for record in results)),
"selected": len(results), "selected_ids": [record["doc_id"] for record in results],
"source_manifest_sha256": digest((out / "source_manifest.jsonl").read_bytes()),
})
save(out / "acquisition.json", {
"observed_at": started, "target": len(results),
"acquired": sum("pdf_sha256" in record for record in results),
"failed": [record["doc_id"] for record in results if "error" in record],
"selected": results,
})
def normalize(text):
import unicodedata
text = unicodedata.normalize("NFKC", text or "").replace("", "").replace("", "")
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text)
lines = [re.sub(r"[ \t ]+", " ", line).strip() for line in text.splitlines()]
# drop repeated running-head signature lines and bare page numbers
seen_sygn = 0
kept = []
for line in lines:
if SYGN_RE.match(line):
seen_sygn += 1
if seen_sygn > 1:
continue
if PAGE_NUM_RE.match(line):
continue
kept.append(line)
text = "\n".join(kept)
text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text)
text = re.sub(r"(? limit:
return set(sorted(hashes)[:limit])
return hashes
DF_FRACTION = 0.02 # shingles in >2% of docs are boilerplate (KIO formula openings)
def shingle_document_frequencies(sketches):
df = Counter()
for sketch in sketches:
df.update(sketch)
return df
def filter_sketch(sketch, df, max_df):
"""Drop high document-frequency shingles (boilerplate) from a sketch."""
return {h for h in sketch if df[h] <= max_df}
class NearDuplicateIndex:
def __init__(self):
self.postings = {}
self.records = []
self.comparisons = 0
@staticmethod
def prefix(sketch):
return sorted(sketch)[:len(sketch) - (9 * len(sketch) + 9) // 10 + 1]
def find(self, sketch):
candidates = set()
for value in self.prefix(sketch):
candidates.update(self.postings.get(value, ()))
for position in sorted(candidates):
row_id, other = self.records[position]
if 10 * min(len(sketch), len(other)) < 9 * max(len(sketch), len(other)):
continue
self.comparisons += 1
intersection = len(sketch & other)
score = intersection / max(len(sketch) + len(other) - intersection, 1)
if score >= 0.90:
return row_id, score
return None, 0.0
def add(self, row_id, sketch):
position = len(self.records)
self.records.append((row_id, sketch))
for value in self.prefix(sketch):
self.postings.setdefault(value, []).append(position)
def audit_target(out):
info = request_json(f"https://huggingface.co/api/datasets/{TARGET}")
revision = info["sha"]
tree = request_json(f"https://huggingface.co/api/datasets/{TARGET}/tree/{revision}?recursive=true&expand=false")
discussions = request_json(f"https://huggingface.co/api/datasets/{TARGET}/discussions?status=open&p=0")
paths = sorted(item.get("path", "") for item in tree)
open_rows = [{"num": item.get("num"), "title": item.get("title"), "status": item.get("status"),
"author": item.get("author", {}).get("name")} for item in discussions.get("discussions", [])]
terms = ("uzp", "kio", "orzeczenia_uzp", "zamowienia_publiczne")
matches = [path for path in paths if any(term in path.casefold() for term in terms)]
discussion_matches = [row for row in open_rows if any(term in (row.get("title") or "").casefold()
for term in terms)]
report = {
"target": TARGET, "revision": revision, "last_modified": info.get("lastModified"),
"tree_paths": len(paths), "source_path_matches": matches, "open_discussions": open_rows,
"matching_open_discussions": discussion_matches, "source_absent": not matches and not discussion_matches,
"observed_at": now(),
}
save(out / "target_audit.json", report)
print(json.dumps({"revision": revision, "source_absent": report["source_absent"],
"tree_matches": matches, "discussion_matches": discussion_matches}, ensure_ascii=False, indent=2))
def audit_overlap(out):
"""Compare our signatures/ids against the shipped SAOS shard (closest legal corpus)."""
import pyarrow.parquet as pq
from huggingface_hub import HfApi, HfFileSystem
revision = HfApi().dataset_info(TARGET).sha
remote = f"datasets/{TARGET}@{revision}/data/saos/saos.parquet"
try:
with HfFileSystem().open(remote, "rb") as handle:
table = pq.read_table(handle, columns=["id", "attribution"])
saos_rows = table.to_pylist()
except Exception as error:
saos_rows = []
print("saos shard unavailable:", error)
saos_sigs = set()
for row in saos_rows:
attribution = row.get("attribution") or ""
for sig in re.findall(r"[IVXLCDM]*\s*[A-Z][a-zA-Z]*\s*\d+/\d+", attribution):
saos_sigs.add(sig.strip().casefold())
manifest = read_lines(out / "source_manifest.jsonl")
results = []
for record in manifest:
sig = (record.get("signature") or "").strip()
if sig and sig.casefold() in saos_sigs:
results.append({"doc_id": record["doc_id"], "signature": sig, "kind": record["kind"]})
report = {
"target": f"{TARGET}:data/saos", "target_revision": revision,
"method": "case-normalized signature match against SAOS attribution strings",
"saos_rows": len(saos_rows), "candidate_records": len(manifest),
"signature_collisions": len(results),
"text_overlap": "not tested; target-wide text dedup remains an integration gate",
"observed_at": now(),
"colliding_ids": [r["doc_id"] for r in results],
"collisions": results[:500],
}
save(out / "overlap_audit.json", report)
print(json.dumps({key: report[key] for key in ("target_revision", "saos_rows",
"candidate_records", "signature_collisions")},
ensure_ascii=False, indent=2))
def build(out, added=None):
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
from langid.langid import LanguageIdentifier, model
acquisition = load(out / "acquisition.json")
selection = load(out / "selection.json")
encoder = tiktoken.get_encoding("cl100k_base")
identifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)
identifier.set_languages(["pl", "en", "de", "uk", "ru"])
rows, attribution, decisions = [], [], []
exact_seen = {}
near = NearDuplicateIndex()
# pass 1: document frequencies of shingles, to drop boilerplate-heavy
# formulas (identical opening lines in ~every KIO ruling) from sketches.
df_sketches = []
for record in acquisition["selected"]:
if "error" in record:
continue
raw = (out / record["text_path"]).read_text(encoding="utf-8")
df_sketches.append((record["doc_id"], shingle_sketch(normalize(raw))))
df = shingle_document_frequencies(sketch for _, sketch in df_sketches)
max_df = max(1, int(len(df_sketches) * DF_FRACTION))
del df_sketches
print(f"df pass done: {len(df)} distinct shingles, max_df={max_df}", flush=True)
pii = Counter()
added = added or acquisition["observed_at"][:10]
for record in acquisition["selected"]:
row_id = f"{SOURCE}_{record['doc_id']}"
if "error" in record:
decisions.append({"id": row_id, "selected": False,
"reason": "acquisition_failed", "error": record["error"]})
continue
pdf_path = out / record["pdf_path"]
text_path = out / record["text_path"]
if digest(pdf_path.read_bytes()) != record["pdf_sha256"]:
raise ValueError("PDF checksum mismatch: " + str(record["doc_id"]))
raw = text_path.read_text(encoding="utf-8")
text = normalize(raw)
replacement_count = text.count("\ufffd")
letters = len(re.findall(r"[A-Za-zĄĆĘŁŃÓŚŹŻąćęłńóśźż]", text))
language, votes = language_vote(identifier, text)
reason = ""
if len(text) < MIN_TEXT_CHARS:
reason = "too_little_extractable_text"
elif letters / max(len(text), 1) < 0.55:
reason = "low_letter_ratio"
elif replacement_count > 100 or replacement_count / max(len(text), 1) > 0.002:
reason = "excessive_replacement_characters"
elif language != "pl":
reason = "non_polish_text"
text = text.replace("\ufffd", "[UNREADABLE_GLYPH]")
text, counts = redact_pii(text)
pii.update(counts)
if not reason and len(text) < MIN_TEXT_CHARS:
reason = "too_little_text_after_redaction"
exact_key = digest(" ".join(text.casefold().split()).encode("utf-8"))
duplicate_of, duplicate_score = None, 0.0
if not reason and exact_key in exact_seen:
reason, duplicate_of, duplicate_score = "normalized_duplicate", exact_seen[exact_key], 1.0
if not reason:
sketch = filter_sketch(shingle_sketch(text), df, max_df)
if sketch:
duplicate_of, duplicate_score = near.find(sketch)
if duplicate_of:
reason = "near_duplicate"
decision = {
"id": row_id, "selected": not bool(reason), "reason": reason or "include",
"characters": len(text), "letter_ratio": letters / max(len(text), 1),
"replacement_characters": replacement_count, "language": language,
"language_votes": [{"language": lang, "confidence": float(score)} for lang, score in votes],
}
if duplicate_of:
decision.update({"duplicate_of": duplicate_of, "jaccard": duplicate_score})
decisions.append(decision)
if reason:
continue
exact_seen[exact_key] = row_id
near.add(row_id, sketch)
details = record.get("details") or {}
organ = record.get("organ") or details.get("organ") or "Unknown"
created = iso_date(record.get("issued") or details.get("issued", ""))
row = {
"id": row_id, "text": text, "source": SOURCE, "added": added,
"created": created, "token_count": len(encoder.encode_ordinary(text)),
"license": LICENSE_LABEL, "author": organ,
}
rows.append(row)
attribution.append({
"id": row_id, "doc_id": record["doc_id"], "kind": record["kind"],
"organ": organ, "doc_type": record.get("doc_type") or details.get("doc_type", ""),
"signature": record.get("signature") or details.get("signature", ""),
"issued": record.get("issued") or details.get("issued", ""),
"chairman": details.get("chairman", ""), "purchaser": details.get("purchaser", ""),
"provisions": details.get("provisions", ""),
"landing_url": f"{BASE}/Home/Details/{record['doc_id']}",
"pdf_url": details.get("pdf_path_url", ""),
"pdf_sha256": record["pdf_sha256"], "pdf_bytes": record["pdf_bytes"],
"license": LICENSE_LABEL, "license_spdx": LICENSE_SPDX,
"legal_basis": LEGAL_BASIS,
"text_sha256": digest(text.encode("utf-8")),
"transformations": ["per-document PDF via /Home/PdfContent", "pypdf text extraction",
"repeated signature running-head and page-number removal",
"Unicode/whitespace normalization", "line-wrap repair",
"email/labelled-phone/IP/labelled-national-ID/account-candidate pattern redaction"],
})
root = out / "hf_repo"
(root / "data").mkdir(parents=True, exist_ok=True)
(root / "artifacts").mkdir(parents=True, exist_ok=True)
schema = pa.schema([(field, pa.int64() if field == "token_count" else pa.string()) for field in FIELDS])
pq.write_table(pa.Table.from_pylist(rows, schema=schema), root / "data/train-00000-of-00001.parquet",
compression="zstd")
write_lines(root / "artifacts/attribution.jsonl", attribution)
write_lines(root / "artifacts/decisions.jsonl", decisions)
write_lines(root / "artifacts/source_manifest.jsonl", read_lines(out / "source_manifest.jsonl"))
sample = sorted(rows, key=lambda row: digest(("sample:" + row["id"]).encode("utf-8")))[:12]
write_lines(root / "artifacts/sample.jsonl", sample)
save(root / "artifacts/selection.json", selection)
save(root / "artifacts/acquisition.json", acquisition)
overlap = load(out / "overlap_audit.json") if (out / "overlap_audit.json").exists() else None
target_audit = load(out / "target_audit.json") if (out / "target_audit.json").exists() else None
if overlap:
save(root / "artifacts/overlap_audit.json", overlap)
if target_audit:
save(root / "artifacts/target_audit.json", target_audit)
stats = {
"reported_totals": selection["reported_totals"],
"enumerated": selection["enumerated"], "per_kind": selection["per_kind"],
"acquired": acquisition["acquired"], "failed": len(acquisition["failed"]),
"kept": len(rows), "rejected": len(decisions) - len(rows),
"rejection_reasons": dict(Counter(d["reason"] for d in decisions if not d["selected"])),
"tokens": sum(row["token_count"] for row in rows),
"characters": sum(len(row["text"]) for row in rows),
"license_counts": dict(Counter(row["license"] for row in rows)),
"sample_count": len(sample), "added": added,
}
save(root / "artifacts/stats.json", stats)
qa = {
"scope": "all rulings enumerated via /Home/GetResults on orzeczenia.uzp.gov.pl (KIO/SO/SA/SN in public procurement matters)",
"license_gate": "official documents excluded from copyright under Polish Copyright Act art. 4(2); no per-record license field exists",
"language_gate": "three-window langid vote (pl/en/de/uk/ru)",
"pii_pattern_matches": dict(pii),
"exact_dedup": True,
"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",
"near_dedup_comparisons": near.comparisons,
"saos_overlap": overlap or "pending",
"cross_source_text_dedup": "pending target integration",
"limitations": [
"pypdf extraction may retain layout artifacts; tables may be flattened",
"pattern checks are not comprehensive de-identification; natural-person names of parties and adjudicators remain part of the official record",
"official-document status does not cover third-party material quoted inside rulings",
"sequential IDs contain gaps; enumeration follows the server-side result list, not the ID range",
],
}
save(root / "artifacts/qa.json", qa)
protocol_id = "protocol:uzp-orzeczenia-v1"
run = {
"id": "run:" + digest({"script": digest(Path(__file__).read_bytes()), "selection": selection,
"acquisition": digest(acquisition)}),
"protocol": protocol_id, "started_at": selection["observed_at"], "finished_at": now(),
"success": True, "actor": "actor:devin", "stats": stats,
}
save(root / "artifacts/run.json", run)
excluded = {"README.md", "NOTICE.md", "artifacts/checksums.json", "artifacts/ontology.json"}
checks = {path.relative_to(root).as_posix(): digest(path.read_bytes()) for path in sorted(root.rglob("*"))
if path.is_file()
and path.relative_to(root).as_posix() not in excluded
and not path.relative_to(root).as_posix().startswith("src/")}
save(root / "artifacts/checksums.json", checks)
source_version = "version:source:" + digest({"manifest": selection["source_manifest_sha256"]})
dataset_version = "version:dataset:" + digest(checks)
selection_evidence = "evidence:selection:" + digest(selection)
acquisition_evidence = "evidence:acquisition:" + digest(acquisition)
qa_evidence = "evidence:qa:" + digest(qa)
evidence = [
{"id": selection_evidence, "observation_type": "source_inventory_and_selection",
"artifact": "artifacts/selection.json", "content_address": digest(selection), "produced_by": run["id"]},
{"id": acquisition_evidence, "observation_type": "pdf_acquisition_and_extraction",
"artifact": "artifacts/acquisition.json", "content_address": digest(acquisition), "produced_by": run["id"]},
{"id": qa_evidence, "observation_type": "source_qa", "artifact": "artifacts/qa.json",
"content_address": digest(qa), "produced_by": run["id"]},
]
overlap_evidence = None
if overlap:
overlap_evidence = "evidence:overlap:" + digest(overlap)
evidence.append({"id": overlap_evidence, "observation_type": "metadata_overlap_audit",
"artifact": "artifacts/overlap_audit.json", "content_address": digest(overlap),
"produced_by": run["id"]})
target_evidence = None
if target_audit:
target_evidence = "evidence:target:" + digest(target_audit)
evidence.append({"id": target_evidence, "observation_type": "target_registry_audit",
"artifact": "artifacts/target_audit.json", "content_address": digest(target_audit),
"produced_by": run["id"]})
ontology = {
"schema": "slayer-research-ontology-profile-v1",
"objects": [{"id": "object:source:uzp-orzeczenia", "type": "Source"},
{"id": "object:dataset:uzp-orzeczenia-pl", "type": "Dataset"}],
"versions": [{"id": source_version, "object": "object:source:uzp-orzeczenia",
"content_address": source_version.rsplit(":", 1)[-1]},
{"id": dataset_version, "object": "object:dataset:uzp-orzeczenia-pl",
"content_address": dataset_version.rsplit(":", 1)[-1]}],
"protocols": [{"id": protocol_id,
"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"}],
"runs": [run], "evidence": evidence,
"claims": [
{"id": "claim:enumeration-complete",
"statement": f"The result-list enumeration observed {selection['enumerated']} documents across kinds {selection['per_kind']} matching server-reported totals {selection['reported_totals']}.",
"supported_by": [selection_evidence],
"falsification_condition": "The preserved manifest does not reproduce the counts or the server totals differ."},
{"id": "claim:official-documents",
"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).",
"supported_by": [selection_evidence, qa_evidence],
"falsification_condition": "A retained record is shown to be a non-official or non-ruling document."},
{"id": "claim:slice-retention",
"statement": f"The slice retained {stats['kept']} records after text QA and within-source deduplication.",
"supported_by": [acquisition_evidence, qa_evidence],
"falsification_condition": "The decisions, Parquet rows, or checksums do not reproduce the retention count."},
{"id": "claim:training-value-untested",
"statement": "Net corpus novelty and training benefit remain untested hypotheses.",
"supported_by": [qa_evidence] + ([overlap_evidence] if overlap_evidence else []),
"falsification_condition": "Target-wide text deduplication and controlled ablations establish those properties."},
],
"actors": [{"id": "actor:piotrsty", "type": "Contributor"},
{"id": "actor:uzp", "type": "Organization"}, {"id": "actor:devin", "type": "Agent"}],
"relations": [{"source": dataset_version, "predicate": "DERIVED_FROM", "target": source_version},
{"source": dataset_version, "predicate": "GENERATED_BY", "target": run["id"]}] +
([{"source": dataset_version, "predicate": "VALIDATED_AGAINST",
"target": f"hf:dataset:{TARGET}@{target_audit['revision']}"}] if target_audit else []),
"pending": ["cross-source text deduplication", "benchmark contamination check",
"third-party quoted material review",
"controlled training ablation"],
}
save(root / "artifacts/ontology.json", ontology)
card = f"""---
license: other
language:
- pl
task_categories:
- text-generation
configs:
- config_name: default
data_files:
- split: train
path: data/train-00000-of-00001.parquet
---
# UZP Orzeczenia - Polish public-procurement rulings (KIO/SO/SA/SN)
Polish-language rulings from the official decision search service of the Public
Procurement Office (https://orzeczenia.uzp.gov.pl/): the National Appeals Chamber
(KIO), district courts (SO), administrative courts (SA) and the Supreme Court
(SN) in public procurement matters.
- Enumerated documents: {stats['enumerated']:,} (per kind: {stats['per_kind']})
- Acquired PDFs: {stats['acquired']:,} (failed: {stats['failed']})
- Retained after text QA and within-source deduplication: {stats['kept']:,}
- Characters: {stats['characters']:,}
- Tokens: {stats['tokens']:,} (`cl100k_base` proxy)
- License label: `{LICENSE_LABEL}`
## Provenance and rights
Rulings are official documents excluded from copyright under Polish Copyright
Act art. 4(2) (LicenseRef-Polish-Official-Documents). No Creative Commons grant
is asserted. Each row links to its `/Home/Details` landing URL, PDF URL and
checksum; `artifacts/attribution.jsonl` carries organ, document type,
signature, issue date, chairman, purchaser and key provisions per record.
## Processing and limitations
Text was extracted from the service PDFs with pypdf, then normalized:
repeated signature running-heads and page numbers removed, Unicode/whitespace
normalization, line-wrap repair, and limited email/phone/IP/identifier/account
pattern redaction. Language is checked independently across three text windows;
exact and deterministic near deduplication run within the source.
Pattern checks are not comprehensive de-identification: names of parties,
adjudicators and quoted natural persons remain part of the official record.
PDF-derived text may retain layout artifacts and flattened tables.
## Review artifacts
See `artifacts/sample.jsonl`, `attribution.jsonl`, `decisions.jsonl`,
`source_manifest.jsonl`, `overlap_audit.json`, `stats.json`, `qa.json`,
`checksums.json`, `run.json` and `ontology.json`.
"""
(root / "README.md").write_text(card, encoding="utf-8")
(root / "NOTICE.md").write_text(
"# Attribution and legal basis\n\n"
"Source: UZP decision search service, https://orzeczenia.uzp.gov.pl/ "
"(Urzad Zamowien Publicznych / Public Procurement Office).\n\n"
"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. This is our assessment, not legal advice. "
"Consult `artifacts/attribution.jsonl` for per-record provenance (organ, signature, issue date, URLs, checksums).\n\n"
"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.\n",
encoding="utf-8",
)
print(json.dumps(stats, ensure_ascii=False, indent=2))
def verify(out):
import pyarrow.parquet as pq
import tiktoken
root = out / "hf_repo"
table = pq.read_table(root / "data/train-00000-of-00001.parquet")
rows = table.to_pylist()
stats = load(root / "artifacts/stats.json")
decisions = read_lines(root / "artifacts/decisions.jsonl")
attribution = read_lines(root / "artifacts/attribution.jsonl")
sample = read_lines(root / "artifacts/sample.jsonl")
assert table.column_names == FIELDS
assert len(rows) == stats["kept"] == len(attribution)
assert sum(item["selected"] for item in decisions) == len(rows)
encoder = tiktoken.get_encoding("cl100k_base")
assert sum(row["token_count"] for row in rows) == stats["tokens"]
for row in rows:
assert len(encoder.encode_ordinary(row["text"])) == row["token_count"]
assert all(row["source"] == SOURCE and row["license"] == LICENSE_LABEL for row in rows)
assert all(EMAIL_RE.search(row["text"]) is None for row in rows)
assert all(len(row["text"]) >= MIN_TEXT_CHARS for row in rows)
by_id = {row["id"]: row for row in rows}
assert len(sample) == stats["sample_count"] and all(by_id[row["id"]] == row for row in sample)
# reconstruct every retained text from the extracted source
for att in attribution:
doc_id = att["doc_id"]
raw = (out / "raw_text" / f"{doc_id}.txt").read_text(encoding="utf-8")
text = normalize(raw).replace("\ufffd", "[UNREADABLE_GLYPH]")
text, _ = redact_pii(text)
assert text == by_id[att["id"]]["text"], f"text mismatch: {doc_id}"
assert digest(text.encode("utf-8")) == att["text_sha256"]
ontology = load(root / "artifacts/ontology.json")
evidence = {item["id"] for item in ontology["evidence"]}
assert all(item["falsification_condition"] and set(item["supported_by"]) <= evidence for item in ontology["claims"])
checks = load(root / "artifacts/checksums.json")
assert all((root / path).is_file() and digest((root / path).read_bytes()) == checksum
for path, checksum in checks.items())
for item in ontology["evidence"]:
artifact = root / item["artifact"]
assert artifact.is_file() and digest(load(artifact)) == item["content_address"]
# residual PII pattern scan
residual = {
name: sum(bool(scan(row["text"])) for row in rows)
for name, scan in {"email": EMAIL_RE.search, "labelled_phone": PHONE_RE.search,
"ipv4": has_ipv4_address, "ipv6": has_ipv6_address}.items()
}
report = {"verified": True, "residual_patterns": residual, **stats}
save(out / "validation_report.json", report)
print(json.dumps(report, ensure_ascii=False, indent=2))
# G1 personal-data pass (polish-dynaword-v2#112). NERGAL with person names masks every person; this ruling's bench
# and clerk act in an official capacity and stay. Sole traders and civil partnerships trade under their own names, so
# their firm names and street addresses are masked too, and a sentence linking a person to a criminal or health fact
# is replaced whole. Run `g1` on the shard before the release upload, which must then pass mask_names=false so the
# pipeline does not mask the bench again.
NERGAL_VERSION = "2.0.4"
NERGAL_REVISION = "b21609b1cea264a4163ffceacc3dc99132888d92"
G1_BATCH = 64 # texts per NERGAL call, as in dynaword-pipeline's pii_mask stage
G1_TRANSFORMATION = (f"G1 personal-data pass: NERGAL {NERGAL_VERSION} with person names, this ruling's bench and "
"clerk kept; sole-trader and civil-partnership firm names and street addresses masked; "
"sentences linking a person to criminal or health data replaced")
FIRM_TAG, ADDRESS_TAG, SPECIAL_TAG = "[FIRM]", "[ADDRESS]", "[REDACTED:SPECIAL]"
UP, LO = "A-ZĄĆĘŁŃÓŚŹŻ", "a-ząćęłńóśźż"
TAG_RE = re.compile(r"\[(?:PERSON|PII|PHONE|FIRM|ADDRESS|UNREADABLE_GLYPH|REDACTED:[A-Z_]+)\]")
SPLIT_LETTER_RE = re.compile(r"(?<=\w) ([ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]) (?=\w)") # pypdf output such as "Skowro ń ski"
NAME_WORD_RE = re.compile(rf"[{UP}][{LO}]+(?:-[{UP}][{LO}]+)*")
ROLE_RE = re.compile(r"\b(?:Przewodnicząc[ya]|Członkowie|Członek|Członkini|Sędziowie|Sędzia|Protokolant\w*)\b")
HEADER_END_RE = re.compile(r"\bpo\s+rozpoznaniu|\bpo\s+rozpatrzeniu|\brozpoznawszy|\bna\s+(?:rozprawie|posiedzeniu)\b"
r"|\borzeka\b|\bpostanawia\b")
# pypdf often puts a court's role labels apart from the names ("Przewodniczący\nSędziowie:\nProtokolant:" first, the
# names later): a judge's or court secretary's title is then the only label. "SO", "SA" and "SR" only at a line start.
# Up to three name words on the title's line; the line's lower-case words end them ("Bury aplikant radcowski"). name_key
# joins a split capital to the word before it ("Agnieszka Ł ukasik" -> "AgnieszkaŁukasik"), so the space is optional.
BENCH_TITLE_RE = re.compile(rf"(?:\bSS[AONR]|^[ \t]*S[AOR])\b\.?(?:[ \t]*\(?del\.?\)?)?[ \t]+"
rf"|\b(?:st\.[ \t]*|starsz\w*[ \t]+)?sekr(?:\.|etarz\w*)[ \t]*[sS]ąd(?:\.|ow\w*)?[ \t]*"
rf"(?=[{UP}])", re.M)
BENCH_TITLE_NAMES_RE = re.compile(rf"{NAME_WORD_RE.pattern}(?: ?{NAME_WORD_RE.pattern}){{0,2}}")
# A court's covering letter is signed by a secretary who is not this ruling's clerk ("Z upoważnienia Kierownika
# Sekretariatu sekretarz sądowy ...", "Na zarządzenie Sędziego st. sekr. sąd. ...").
LETTER_SIGNATURE_RE = re.compile(r"(?i:zarządzen\w*\s+sędziego|kierownika\s+sekretariatu)\W*$")
SOLE_TRADER_RE = re.compile(r"(?i)działalnoś\w*\s+gospodarcz\w*(?:\s+\S+){0,6}?\s+(?:pod\s+(?:firmą|nazwą)|p\.\s?n\.|pn\.)"
r"|wspólni\w*\s+spółki\s+cywilnej(?:\s+pod\s+(?:firmą|nazwą)|\s+p\.\s?n\.)?")
SC_RE = re.compile(r"\b[sS]\.\s?[cC]\.(?!\w)|\bSpółka\s+Cywilna\b")
QUOTE_RE = re.compile(r"[„\"“][^„”\"“\n]{0,120}[”\"“]")
# A firm name ends at a comma, a colon ("M-BUD:\n„W związku", "TRAF LINE i:\n2.1."), a bracketed alias ("[dalej:"), a
# blank line, a numbered point, a postcode, a street, its seat ("w Poznaniu"), the next clause, a lower-case word after
# the owner's initials or name ("A.D. na podstawie", "[PERSON] od") and a sentence end (firm_after). A dash ends it
# only before a lower-case word or a role ("– dalej", "– Odwołujący"): "MAT - BUD", "Firma Geodezyjna - Andrzej Geszke"
# and "Usługi Leśne – P.M." are names.
FIRM_END_RE = re.compile(rf"[,;(]|(?:\s+i)?:\s|\s[\[{{](?=dalej|zwan)"
rf"|\s[–—-]\s+(?=[{LO}]|(?:Odwołując|Zamawiając|Przystępując|Wykonawc|Izb|Sąd)\w*)"
rf"|\n\s*\n|\n\s*\d+[.)]\s|\s\d{{2}}\s?-\s?\d{{3}}\b|\s(?:ul|al|Al|pl|os)\.|\swe?\s+(?=[{UP}])"
rf"|(?<=[{UP}]\.)\s+(?=[{LO}])|(?<=\[PERSON\])\s+(?=[{LO}])"
r"|\s(?:z\s+siedzib\w*|z/s|w\s+postępowaniu|przy\s+udziale|orzeka|postanawia|zgłaszając\w*"
r"|wni(?:ósł|osł\w*|esion\w*)|przeciwko|NIP|REGON|KRS|reprezentowan\w*|zwan\w*|dalej|oraz|przy)\b")
SENTENCE_START_RE = re.compile(rf"\s*[{UP}][{LO}]+\s+[{LO}]")
# A firm name before "s.c." starts after a comma, a dash, a blank line, a sentence end or a lower-case word ("w
# ofercie", "przez", "oraz").
FIRM_START_RE = re.compile(rf"[,;:()]|\s[–—-]\s|\n\s*\n|[.!?]\s+(?=[{UP}][{LO}]{{2,}}\s)|(?= 3
def address_window(text, start, end):
"""The part around a firm name that describes the same party: back to 200 and on to 250 characters, cut where the
text moves on to another party or the contracting authority."""
stops = list(ADDRESS_STOP_RE.finditer(text, max(0, start - 200), start))
after = ADDRESS_STOP_RE.search(text, end, min(len(text), end + 250))
return stops[-1].end() if stops else max(0, start - 200), after.start() if after else min(len(text), end + 250)
def firm_spans(text):
"""(start, end, tag): [FIRM] for a sole trader's or civil partnership's firm name, [ADDRESS] for street addresses of
the same party (address_window), and the same for every other occurrence of those strings in the ruling."""
spans = []
found = [firm_after(text, cue.end()) + (cue.start(),) for cue in SOLE_TRADER_RE.finditer(text)]
found += [firm_before(text, *marker.span()) + (marker.start(),) for marker in SC_RE.finditer(text)]
for start, end, cue in found:
if has_words(text[start:end]):
spans.append((start, end, FIRM_TAG))
spans += [(*match.span(), ADDRESS_TAG) for match in ADDRESS_RE.finditer(text, *address_window(text, cue, end))]
for value, tag in {(text[a:b], tag) for a, b, tag in spans}:
spans += [(*match.span(), tag) for match in re.finditer(rf"(? their tags; a span inside a longer one that starts earlier goes with it."""
out, counts, last = [], Counter(), 0
for start, end, tag in sorted(firm_spans(text), key=lambda span: (span[0], -span[1])):
if start < last:
continue # inside a longer span that starts earlier
out += [text[last:start], tag]
counts[tag] += 1
last = end
return "".join(out) + text[last:], counts[FIRM_TAG], counts[ADDRESS_TAG]
def sentences(text):
"""(start, end) of each sentence. A full stop after an abbreviation, an initial or a number does not end one."""
spans, start = [], 0
for match in SENTENCE_END_RE.finditer(text):
before = text[start:match.start()].split()
word = before[-1].lstrip("(„\"") if before else ""
if match.group() == "." and (word.casefold() in ABBREVIATIONS or word.isdigit() or re.fullmatch(f"[{UP}]", word)):
continue
spans.append((start, match.end()))
start = match.end()
return spans + [(start, len(text))]
def short_parts(text, start, end, breaks=(LAYOUT_BREAK_RE, CLAUSE_BREAK_RE)):
"""text[start:end] as one part if it has at most SPECIAL_MAX characters, else cut at the first of `breaks`, and
each piece still too long at the next one."""
if end - start <= SPECIAL_MAX or not breaks:
return [(start, end)]
cuts = [start] + [match.start() for match in breaks[0].finditer(text, start, end) if match.start() > start]
return [part for a, b in zip(cuts, cuts[1:] + [end]) for part in short_parts(text, a, b, breaks[1:])]
def special_spans(text):
"""(start, end) of each unit that names a person ([PERSON], initials, pan/pani) next to a criminal or health cue.
A sentence longer than SPECIAL_MAX is cut into short_parts first, and a part with the cue goes together with a
neighbouring part that names the person ("informacji z KRK w zakresie:\na) M.W. ...")."""
spans = []
for start, end in sentences(text):
parts = short_parts(text, start, end)
person = [bool(PERSON_REF_RE.search(text, a, b)) for a, b in parts]
cue = [bool(CRIMINAL_RE.search(text, a, b) or HEALTH_RE.search(text, a, b)) for a, b in parts]
hit = [p and c for p, c in zip(person, cue, strict=True)]
for i in range(len(parts) - 1):
if (person[i] and cue[i + 1]) or (cue[i] and person[i + 1]):
hit[i] = hit[i + 1] = True
spans += [part for part, h in zip(parts, hit, strict=True) if h]
return spans
def mask_special(text):
"""Each special_spans unit -> SPECIAL_TAG (with the unit's leading whitespace kept)."""
out, last, count, chars = [], 0, 0, 0
for start, end in special_spans(text):
start = end - len(text[start:end].lstrip())
out += [text[last:start], SPECIAL_TAG]
last, count, chars = end, count + 1, chars + end - start
return "".join(out) + text[last:], count, chars
def g1_rules(text):
"""The G1 rules applied after NERGAL: firms and addresses, then special-category sentences."""
text, firms, addresses = mask_firms(text)
text, special, special_chars = mask_special(text)
return text, {"firm": firms, "address": addresses, "special_sentences": special, "special_chars": special_chars}
def load_nergal(path, device=None, dtype="float32"):
"""(module, model) for NERGAL from a local snapshot directory of the pinned revision, with the person-name model."""
path = Path(path).resolve()
if path.name != NERGAL_REVISION or not (path / "nergal.py").is_file():
raise SystemExit(f"--nergal must be the SlayerLab/NERGAL snapshot directory of revision {NERGAL_REVISION}")
sys.path.insert(0, str(path)) # nergal.py imports scrub_pii from its own directory
spec = importlib.util.spec_from_file_location("nergal", path / "nergal.py")
module = importlib.util.module_from_spec(spec)
sys.modules["nergal"] = module
spec.loader.exec_module(module)
if module.VERSION != NERGAL_VERSION:
raise SystemExit(f"NERGAL {module.VERSION} found, {NERGAL_VERSION} expected")
return module, module.Nergal.from_pretrained(str(path), device=device, dtype=dtype, local_files_only=True, names=True)
def g1_names(module, nergal, texts):
"""(text, counts) per text: NERGAL's scrub_many with the bench taken out of the person spans. scrub_many has no
keep-list, so this repeats its three steps and filters the names in between."""
rows = []
for text, model_spans, name_spans in zip(texts, nergal.predict_many(texts), nergal.names.spans_many(texts),
strict=True):
private, kept = private_names(text, name_spans, bench_names(text))
masked, info = module.scrub_spans(text, nergal.rule_spans(text), model_spans, threshold=nergal.threshold,
module=nergal._scrub, name_spans=private)
rows.append((masked, {"person": info["person"], "pii": info["pii"], "phone": info["phone"],
"bench_kept": kept}))
return rows
def g1_batch(module, nergal, texts):
"""(text, counts) per text: g1_names, then g1_rules."""
rows = []
for named, counts in g1_names(module, nergal, texts):
masked, rule_counts = g1_rules(named)
rows.append((masked, {**counts, **rule_counts}))
return rows
def write_as_before(path, text):
"""Write `text` with the line endings `path` has now (the committed shard uses CRLF)."""
path.write_text(text, encoding="utf-8", newline="\r\n" if b"\r\n" in path.read_bytes() else "\n")
def json_text(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
def jsonl_text(rows):
return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows)
def shard_paths(data):
"""The committed shard files in `data` (data/uzp_orzeczenia_pl) by suffix."""
return {name: data / f"{SOURCE}.{name}" for name in ("parquet", "attribution.jsonl", "decisions.jsonl",
"sample.jsonl", "stats.json", "qa.json", "md", "checksums.json")}
def refresh_sidecars(path, rows, transformation=None):
"""Point the text-derived sidecars of the shard at `rows`, the rows now in its parquet: attribution text hashes
(recording `transformation` when given), sample rows, and the token and character counts in stats.json and the
datasheet. Nothing is written unless every datasheet count is found. Returns the stats before and after."""
by_id = {row["id"]: row for row in rows}
attribution = read_lines(path["attribution.jsonl"])
for item in attribution:
item["text_sha256"] = digest(by_id[item["id"]]["text"].encode("utf-8"))
if transformation:
item["transformations"].append(transformation)
sample = [by_id[item["id"]] for item in read_lines(path["sample.jsonl"])]
old = load(path["stats.json"])
stats = {**old, "characters": sum(len(row["text"]) for row in rows), "tokens": sum(row["token_count"] for row in rows)}
md = path["md"].read_text(encoding="utf-8")
for label, key in (("Proposed tokens", "tokens"), ("Characters", "characters")):
# the lookahead keeps "1,234" from matching the start of "1,234,567"
md, found = re.subn(rf"^- {label}: {old[key]:,}(?![\d,])", f"- {label}: {stats[key]:,}", md, flags=re.MULTILINE)
if found != 1:
raise SystemExit(f"{path['md'].name}: expected one '- {label}: {old[key]:,}' line")
write_as_before(path["attribution.jsonl"], jsonl_text(attribution))
write_as_before(path["sample.jsonl"], jsonl_text(sample))
write_as_before(path["stats.json"], json_text(stats))
write_as_before(path["md"], md)
return old, stats
def refresh_checksums(checksums):
"""Recompute every entry of the shard's checksums.json from the files next to it."""
write_as_before(checksums, json_text({name: digest((checksums.parent / name).read_bytes()) for name in load(checksums)}))
def read_cache(cache, rows):
"""Finished G1 results by id; a partial last line (an interrupted run) is dropped, and a result for a different
input text stops the run."""
if not cache.exists():
return {}
content = cache.read_text(encoding="utf-8")
lines = content.split("\n")[:-1]
if not content.endswith("\n"):
cache.write_text("".join(line + "\n" for line in lines), encoding="utf-8")
done = {item["id"]: item for item in map(json.loads, lines)}
source = {row["id"]: digest(row["text"].encode("utf-8")) for row in rows}
stale = [key for key, item in done.items() if source.get(key) != item["source_sha256"]]
if stale:
raise SystemExit(f"{cache} holds results for other texts, e.g. {stale[0]}; use a new --cache")
return done
def g1(out, nergal_path, cache, device=None, dtype="float32", batch=G1_BATCH, load=load_nergal):
"""Apply G1 in place to the committed shard directory `out` (data/uzp_orzeczenia_pl) and refresh every sidecar
that depends on the text. Results go to `cache` as they are made, so an interrupted run resumes."""
import pyarrow as pa
import pyarrow.parquet as pq
import tiktoken
path = shard_paths(out)
qa = json.loads(path["qa.json"].read_text(encoding="utf-8"))
if "g1" in qa:
raise SystemExit(f"G1 already applied at {qa['g1']['ran_at']}")
table = pq.read_table(path["parquet"])
rows = table.to_pylist()
done = read_cache(cache, rows)
todo = [row for row in rows if row["id"] not in done]
if todo:
module, nergal = load(nergal_path, device, dtype)
with cache.open("a", encoding="utf-8") as handle:
for i in range(0, len(todo), batch):
part = todo[i:i + batch]
for row, (text, counts) in zip(part, g1_batch(module, nergal, [r["text"] for r in part]), strict=True):
done[row["id"]] = {"id": row["id"], "source_sha256": digest(row["text"].encode("utf-8")),
"text": text, "counts": counts}
handle.write(json.dumps(done[row["id"]], ensure_ascii=False) + "\n")
handle.flush()
print(f"g1 {len(done)}/{len(rows)}", flush=True)
encoder = tiktoken.get_encoding("cl100k_base")
totals, changed = Counter(), 0
for row in rows:
result = done[row["id"]]
changed += result["text"] != row["text"]
row["text"], row["token_count"] = result["text"], len(encoder.encode_ordinary(result["text"]))
totals.update(result["counts"])
pq.write_table(pa.Table.from_pylist(rows, schema=table.schema), path["parquet"], compression="zstd")
refresh_sidecars(path, rows, G1_TRANSFORMATION)
qa["g1"] = {"nergal": NERGAL_VERSION, "nergal_revision": NERGAL_REVISION, "device": device or "auto",
"dtype": dtype, "ran_at": now(), "documents_changed": changed, "counts": dict(sorted(totals.items()))}
write_as_before(path["qa.json"], json_text(qa))
refresh_checksums(path["checksums.json"])
print(json.dumps(qa["g1"], ensure_ascii=False, indent=2))
SLICE_OBJECT = "object:dataset:uzp-orzeczenia-pl-dynaword-slice"
REBUILD_PROTOCOL = {
"id": "protocol:uzp-orzeczenia-rebuild-v1",
"procedure": "src/build_uzp_orzeczenia_pl.py rebuild: the shipped documents downloaded again (retained PDFs "
"restored to their recorded pdf_sha256), built with the current redact_pii and installed over the "
"shipped slice with the document set, decisions and metadata unchanged",
}
def install(out, data):
"""Replace the parquet and sidecars in `data` with the rebuild in `out` and record it in the ontology manifest.
The rebuild may change texts and what follows from them (token counts, text hashes, decision character
counts) only: the document set, row metadata, decisions and PDF hashes must be the shipped ones. Every check
runs before the first write."""
import pyarrow.parquet as pq
built, path = out / "hf_repo", shard_paths(data)
built_parquet = built / "data/train-00000-of-00001.parquet"
manifest_path = data.parents[1] / "artifacts" / f"{SOURCE}_ontology_manifest.json"
old_rows, rows = pq.read_table(path["parquet"]).to_pylist(), pq.read_table(built_parquet).to_pylist()
if [row["id"] for row in rows] != [row["id"] for row in old_rows]:
raise ValueError("rebuilt document set differs from the shipped one")
fixed = [field for field in FIELDS if field not in ("text", "token_count")]
for new, old in zip(rows, old_rows):
if any(new[field] != old[field] for field in fixed):
raise ValueError("metadata changed for " + new["id"])
decisions = read_lines(built / "artifacts/decisions.jsonl")
for new, old in zip(decisions, read_lines(path["decisions.jsonl"]), strict=True):
if any(new.get(key) != old.get(key) for key in ("id", "selected", "reason", "duplicate_of")):
raise ValueError("decision changed for " + old["id"])
attribution = read_lines(built / "artifacts/attribution.jsonl")
old_attribution = read_lines(path["attribution.jsonl"])
if [{**item, "text_sha256": ""} for item in attribution] != [{**item, "text_sha256": ""} for item in old_attribution]:
raise ValueError("attribution metadata or PDF hashes changed since the shipped build")
old_sha, new_sha = digest(path["parquet"].read_bytes()), digest(built_parquet.read_bytes())
if new_sha == old_sha:
raise ValueError("the rebuild reproduces the shipped parquet; nothing to install")
manifest = load(manifest_path)
cited = {item for claim in manifest["claims"] for item in claim["supported_by"]}
old_version = next((item["id"] for item in manifest["versions"]
if item["object"] == SLICE_OBJECT and item["content_address"] == old_sha), None)
old_stats_evidence = next((item["id"] for item in manifest["evidence"]
if item["observation_type"] == "target_slice_counts" and item["id"] in cited), None)
if not (old_version and old_stats_evidence):
raise ValueError(f"{manifest_path.name} has no version for the shipped parquet or no cited slice counts")
validated = [relation["target"] for relation in manifest["relations"]
if relation["source"] == old_version and relation["predicate"] == "VALIDATED_AGAINST"]
shutil.copy2(built_parquet, path["parquet"])
write_as_before(path["decisions.jsonl"], jsonl_text(decisions))
old_stats, stats = refresh_sidecars(path, rows)
version = f"version:dataset:uzp-orzeczenia-pl-dynaword:{new_sha}"
run = {"id": "run:uzp-orzeczenia-rebuild:" + digest({"script": digest(Path(__file__).read_bytes()), "parquet": new_sha}),
"protocol": REBUILD_PROTOCOL["id"], "started_at": load(out / "acquisition.json")["observed_at"],
"finished_at": now(), "success": True, "stats": stats}
stats_evidence = f"evidence:uzp-target-stats:{digest(stats)}"
manifest.update(
protocols=manifest["protocols"] + [REBUILD_PROTOCOL],
runs=manifest["runs"] + [run],
versions=manifest["versions"] + [{"id": version, "object": SLICE_OBJECT, "content_address": new_sha}],
evidence=manifest["evidence"] + [{"id": stats_evidence, "observation_type": "target_slice_counts",
"artifact": f"data/{SOURCE}/{SOURCE}.stats.json",
"content_address": digest(stats), "produced_by": run["id"]}],
claims=[{**claim, "supported_by": [stats_evidence if item == old_stats_evidence else item
for item in claim["supported_by"]]} for claim in manifest["claims"]],
relations=manifest["relations"] + [
{"source": version, "predicate": "DERIVED_FROM", "target": old_version},
{"source": version, "predicate": "GENERATED_BY", "target": run["id"]},
# signatures are unchanged, so the metadata overlap audit against the target still holds
*({"source": version, "predicate": "VALIDATED_AGAINST", "target": target} for target in validated)])
write_as_before(manifest_path, json_text(manifest))
refresh_checksums(path["checksums.json"])
report = {"documents_changed": sum(new["text"] != old["text"] for new, old in zip(rows, old_rows)),
"ip_tags_before": sum(row["text"].count("[REDACTED:IP]") for row in old_rows),
"ip_tags_after": sum(row["text"].count("[REDACTED:IP]") for row in rows),
"tokens_before": old_stats["tokens"], "tokens_after": stats["tokens"],
"characters_before": old_stats["characters"], "characters_after": stats["characters"]}
print(json.dumps(report, ensure_ascii=False, indent=2), flush=True)
return report
def rebuild(out, data, workers):
"""Re-acquire the shipped documents, build them with the current redact_pii, verify, and install in `data`."""
reacquire(out, data, workers)
build(out, added=load(data / f"{SOURCE}.stats.json")["added"])
verify(out)
return install(out, data)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--nergal", type=Path, help="g1: local SlayerLab/NERGAL snapshot directory")
parser.add_argument("--cache", type=Path, help="g1: JSONL of finished documents; an interrupted run resumes")
parser.add_argument("--device", help="g1: torch device (default: NERGAL's choice)")
parser.add_argument("--dtype", default="float32", choices=["float32", "float16"])
parser.add_argument("--data", type=Path, default=Path(__file__).resolve().parents[1] / "data" / SOURCE,
help="shipped shard for reacquire/install/rebuild")
parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap",
"build", "verify", "g1", "reacquire", "install", "rebuild"])
args = parser.parse_args()
if args.command == "g1" and not (args.nergal and args.cache):
parser.error("g1 needs --nergal and --cache; --output is the shard directory data/uzp_orzeczenia_pl")
if args.command == "reacquire":
return reacquire(args.output, args.data, args.workers)
if args.command == "install":
return install(args.output, args.data)
if args.command == "rebuild":
return rebuild(args.output, args.data, args.workers)
if args.command == "discover":
discover(args.output, args.workers)
elif args.command == "acquire":
acquire(args.output, args.workers)
elif args.command == "audit_target":
audit_target(args.output)
elif args.command == "audit_overlap":
audit_overlap(args.output)
elif args.command == "build":
build(args.output)
elif args.command == "g1":
g1(args.output, args.nergal, args.cache, args.device, args.dtype)
else:
verify(args.output)
if __name__ == "__main__":
main()