Datasets:
Download src/build_uzp_orzeczenia_pl.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 42.3 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/src/build_uzp_orzeczenia_pl.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword/src/build_uzp_orzeczenia_pl.py
-
curl -L -o build_uzp_orzeczenia_pl.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/main/src/build_uzp_orzeczenia_pl.py
42.3 kB
| #!/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, timezone | |
| import gzip | |
| import hashlib | |
| import html as html_module | |
| import io | |
| import ipaddress | |
| import json | |
| from pathlib import Path | |
| import re | |
| import time | |
| import requests | |
| 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") | |
| IPV4_RE = re.compile(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b") | |
| IPV6_RE = re.compile(r"(?i)\b(?:[0-9a-f]{1,4}:){3,}[0-9a-f]{1,4}\b") | |
| IPV6_CANDIDATE_RE = re.compile(r"(?<![\w:])(?:[0-9a-fA-F]{0,4}:){2,}[0-9a-fA-F:.]*(?![\w:])") | |
| NATIONAL_ID_RE = re.compile(r"(?i)\b(PESEL|NIP|REGON)\s*[:=]?\s*\d(?:[ -]?\d){8,13}\b") | |
| BANK_ACCOUNT_RE = re.compile(r"(?<!\d)(?:PL\s*)?\d{2}(?:[ -]?\d){24}(?!\d)") | |
| DETAILS_LINK_RE = re.compile(r'href="/Home/Details/(\d+)"') | |
| RESULT_COUNTS_RE = re.compile(r'value="([\d,]+)"\s+id="resultCounts"') | |
| PDF_LINK_RE = re.compile(r'href="(/Home/PdfContent/(\d+)\?Kind=([A-Z]+))"') | |
| SYGN_RE = re.compile(r"^Sygn\.\s*akt\b", re.I) | |
| PAGE_NUM_RE = re.compile(r"^\d{1,4}$") | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def digest(value): | |
| if not isinstance(value, bytes): | |
| value = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") | |
| return hashlib.sha256(value).hexdigest() | |
| def save(path, value): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8") | |
| def write_lines(path, rows): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text("".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows), encoding="utf-8") | |
| def read_lines(path): | |
| return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line] | |
| def load(path): | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def is_ipv6(value): | |
| try: | |
| return ipaddress.ip_address(value.rstrip(".")).version == 6 | |
| except ValueError: | |
| return False | |
| def redact_pii(text): | |
| counts = Counter() | |
| def replace_ipv6(match): | |
| value = match.group().rstrip(".") | |
| if not is_ipv6(value): | |
| return match.group() | |
| counts["ipv6"] += 1 | |
| return "[REDACTED:IP]" + match.group()[len(value):] | |
| text = IPV6_CANDIDATE_RE.sub(replace_ipv6, text) | |
| for name, pattern, replacement in ( | |
| ("email", EMAIL_RE, "[REDACTED:EMAIL]"), | |
| ("labelled_phone", PHONE_RE, "[REDACTED:PHONE]"), | |
| ("ipv4", IPV4_RE, "[REDACTED:IP]"), | |
| ("ipv6_legacy_pattern", IPV6_RE, "[REDACTED:IP]"), | |
| ("national_identifier", NATIONAL_ID_RE, lambda match: match.group(1) + " [REDACTED:ID]"), | |
| ("account_candidate", BANK_ACCOUNT_RE, "[REDACTED:ACCOUNT]"), | |
| ): | |
| text, count = pattern.subn(replacement, text) | |
| counts[name] += count | |
| return text, counts | |
| def iso_date(text): | |
| match = re.match(r"(\d{2})-(\d{2})-(\d{4})", (text or "").strip()) | |
| if match: | |
| day, month, year = match.groups() | |
| return f"{year}-{month}-{day}" | |
| return "" | |
| def strip_html(fragment): | |
| return html_module.unescape(re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", fragment))).strip() | |
| def parse_result_items(page_html): | |
| """Parse /Home/GetResults response into per-document records.""" | |
| records = [] | |
| for block in re.findall(r'<div class="search-list-item".*?(?=<div class="search-list-item"|$)', | |
| page_html, flags=re.S): | |
| link = DETAILS_LINK_RE.search(block) | |
| if not link: | |
| continue | |
| fields = dict() | |
| for label, value in re.findall(r"<label>([^<]+)</label>\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"<script.*?</script>", " ", page_html, flags=re.S) | |
| fields = {} | |
| for label, value in re.findall(r"<label>([^<]+)</label>\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 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) | |
| from pypdf import PdfReader | |
| reader = PdfReader(io.BytesIO(payload)) | |
| text = "\n".join(page.extract_text() or "" for page in reader.pages) | |
| text_path.write_text(text, encoding="utf-8") | |
| return record, digest(payload), len(payload), digest(text.encode("utf-8")), \ | |
| str(len(reader.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 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"(?<![.!?:;\n])\n(?!\n)(?=[a-ząćęłńóśźż])", " ", text) | |
| return re.sub(r"\n{3,}", "\n\n", text).strip() | |
| def shingle_sketch(text, limit=5_000): | |
| words = re.findall(r"\w+", text.casefold()) | |
| hashes = set() | |
| for index in range(max(0, len(words) - 4)): | |
| value = " ".join(words[index:index + 5]).encode("utf-8") | |
| hashes.add(int.from_bytes(hashlib.blake2b(value, digest_size=8).digest(), "big")) | |
| if len(hashes) > limit: | |
| return set(sorted(hashes)[:limit]) | |
| return hashes | |
| 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 | |
| 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 language_vote(identifier, text): | |
| chunks = [text[:30_000], text[max(0, len(text) // 2 - 15_000):len(text) // 2 + 15_000], text[-30_000:]] | |
| classified = {chunk: identifier.classify(chunk) for chunk in dict.fromkeys(chunks) if chunk.strip()} | |
| votes = [classified[chunk] for chunk in chunks if chunk in classified] | |
| languages = Counter(language for language, _ in votes) | |
| return (languages.most_common(1)[0][0] if languages else "unknown", votes) | |
| 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): | |
| 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 = 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": ["formal legal review of art. 4(2) application", "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. Formal legal review has not been performed. " | |
| "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(pattern.search(row["text"])) for row in rows) | |
| for name, pattern in {"email": EMAIL_RE, "labelled_phone": PHONE_RE, | |
| "ipv4": IPV4_RE, "ipv6": IPV6_RE}.items() | |
| } | |
| report = {"verified": True, "residual_patterns": residual, **stats} | |
| save(out / "validation_report.json", report) | |
| print(json.dumps(report, ensure_ascii=False, indent=2)) | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument("command", choices=["discover", "acquire", "audit_target", "audit_overlap", | |
| "build", "verify"]) | |
| args = parser.parse_args() | |
| 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) | |
| else: | |
| verify(args.output) | |
| if __name__ == "__main__": | |
| main() | |