#!/usr/bin/env python3 """Build an auditable slice of CC BY-SA 4.0 Polish Wiadomosci Statystyczne articles.""" from __future__ import annotations import argparse from collections import Counter from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from difflib import SequenceMatcher, get_close_matches import gzip import hashlib import html as html_module import json from pathlib import Path import re import time import unicodedata from urllib.parse import quote, urlsplit, urlunsplit import requests from language_gate import language_vote SOURCE = "wiadomosci_statystyczne_pl" OWN_REPO = "PiotrSty/wiadomosci-statystyczne-pl-articles" TARGET = "SlayerLab/polish-dynaword" BASE = "https://ws.stat.gov.pl" ARCHIVES_URL = BASE + "/Archives" POLICY_URL = "https://nauka.stat.gov.pl/News/Info/60" SOURCE_URL = BASE + "/" FIELDS = ["id", "text", "source", "added", "created", "token_count", "license", "author"] UA = "WiadomosciStatystyczneCorpusResearch/0.1 (PiotrSty; open research slice)" MIN_YEAR = 2022 LICENSE_SPDX = "CC-BY-SA-4.0" MIN_TEXT_CHARS = 3_000 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") ARTICLE_RE = re.compile(r"^/Article/(\d{4})/(\d+)/(\d{2,4}-\d{2,4})$") PER_ARTICLE_LICENSE_RE = re.compile(r"udost\w*pnion\w*\s+na\s+licencji\s+CC\s+BY-SA\s+4\.0", re.I) BY_SA_URL_RE = re.compile(r"creativecommons\.org/licenses/by-sa/4\.0", re.I) MONTHS = { "stycznia": 1, "lutego": 2, "marca": 3, "kwietnia": 4, "maja": 5, "czerwca": 6, "lipca": 7, "sierpnia": 8, "września": 9, "października": 10, "listopada": 11, "grudnia": 12, } 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 request(url, attempts=5, timeout=(15, 90), binary=False): response = None for attempt in range(attempts): response = requests.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, params=None): response = request(url + ("?" + "&".join(f"{k}={v}" for k, v in params.items()) if params else "")) return json.loads(response) def safe_url(url): parts = urlsplit(url.replace("http://", "https://")) return urlunsplit((parts.scheme, parts.netloc, quote(parts.path), parts.query, parts.fragment)) def article_id(path): match = ARTICLE_RE.match(path) year, issue, pages = match.groups() return f"{year}_{int(issue)}_{pages}" def meta_content(page, name): match = re.search(r'citation_' + name + r'" content="([^"]*)"', page) return html_module.unescape(match.group(1)).strip() if match else "" def per_article_license(page): match = PER_ARTICLE_LICENSE_RE.search(page) if not match: return None window = page[match.start():match.end() + 400] if not BY_SA_URL_RE.search(window): return None return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", match.group(0))).strip() def parse_article(path, page): license_line = per_article_license(page) langs = sorted(set(re.findall(r"\((Polski|Angielski)\)", page))) pdf = meta_content(page, "pdf_url") return { "article_id": article_id(path), "landing_url": BASE + path, "title": meta_content(page, "title"), "authors": [html_module.unescape(a).strip() for a in re.findall(r'citation_author" content="([^"]*)"', page)], "doi": meta_content(page, "doi"), "pdf_url": safe_url(pdf) if pdf else "", "online_date": meta_content(page, "online_date"), "volume": meta_content(page, "volume"), "issue": meta_content(page, "issue"), "issn": meta_content(page, "issn"), "keywords": meta_content(page, "keywords"), "languages": langs, "has_polish_pdf": "Polski" in langs, "per_article_license": bool(license_line), "license_line": license_line or "", } def iso_date(text, fallback_year): match = re.search(r"(\d{1,2})\s+([a-ząćęłńóśźż]+)\s+(\d{4})", (text or "").casefold()) if match and match.group(2) in MONTHS: return f"{match.group(3)}-{MONTHS[match.group(2)]:02d}-{int(match.group(1)):02d}" return str(fallback_year) def discover(out, workers): page = request(ARCHIVES_URL) (out / "raw_pages").mkdir(parents=True, exist_ok=True) (out / "raw_pages/_archives.html.gz").write_bytes(gzip.compress(page.encode("utf-8"))) paths = sorted(set( href.strip() for href in re.findall(r'href="([^"]+)"', page) if ARTICLE_RE.match(href.strip()) and int(ARTICLE_RE.match(href.strip()).group(1)) >= MIN_YEAR )) records = [] def fetch(path): body = request(BASE + path) return path, body with ThreadPoolExecutor(max_workers=workers) as pool: futures = {pool.submit(fetch, path): path for path in paths} for index, future in enumerate(as_completed(futures), 1): path, body = future.result() (out / "raw_pages" / (article_id(path) + ".html.gz")).write_bytes(gzip.compress(body.encode("utf-8"))) records.append(parse_article(path, body)) if index % 50 == 0: print(f" {index}/{len(paths)}", flush=True) records.sort(key=lambda record: record["article_id"]) write_lines(out / "source_manifest.jsonl", records) selected = [record for record in records if record["per_article_license"] and record["has_polish_pdf"] and record["pdf_url"]] selection = { "observed_at": now(), "archives_url": ARCHIVES_URL, "policy_url": POLICY_URL, "min_year": MIN_YEAR, "article_urls_min_year": len(paths), "enumerated": len(records), "with_per_article_cc_by_sa": sum(record["per_article_license"] for record in records), "polish_marker": sum(record["has_polish_pdf"] for record in records), "selected": len(selected), "selected_ids": [record["article_id"] for record in selected], "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["article_id"]: record for record in read_lines(out / "source_manifest.jsonl")} selected = [manifest[article] for article in selection["selected_ids"]] (out / "raw_pdf").mkdir(parents=True, exist_ok=True) (out / "raw_text").mkdir(parents=True, exist_ok=True) results = [] def fetch_pdf(record): aid = record["article_id"] pdf_path = out / "raw_pdf" / (aid + ".pdf") text_path = out / "raw_text" / (aid + ".txt") if pdf_path.is_file() and text_path.is_file(): return aid, digest(pdf_path.read_bytes()), pdf_path.stat().st_size, digest(text_path.read_bytes()), "cached" payload = request(record["pdf_url"], binary=True) if not payload.startswith(b"%PDF"): raise ValueError("not a PDF: " + aid) pdf_path.write_bytes(payload) from pypdf import PdfReader import io 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 aid, digest(payload), len(payload), digest(text.encode("utf-8")), str(len(reader.pages)) with ThreadPoolExecutor(max_workers=workers) as pool: futures = {pool.submit(fetch_pdf, record): record for record in selected} for index, future in enumerate(as_completed(futures), 1): record = futures[future] try: aid, pdf_sha, pdf_bytes, text_sha, pages = future.result() results.append({**record, "pdf_sha256": pdf_sha, "pdf_bytes": pdf_bytes, "text_sha256": text_sha, "pdf_pages": pages, "pdf_path": f"raw_pdf/{aid}.pdf", "text_path": f"raw_text/{aid}.txt"}) except Exception as error: results.append({**record, "error": f"{type(error).__name__}: {error}"}) if index % 25 == 0: print(f" {index}/{len(selected)}", flush=True) results.sort(key=lambda record: record["article_id"]) acquisition = { "observed_at": now(), "target": selection["selected"], "acquired": sum("pdf_sha256" in record for record in results), "failed": [record["article_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 strip_running_heads(text): lines = text.splitlines() counts = Counter(re.sub(r"\d+", "", line).strip() for line in lines if line.strip()) kept = [] for line in lines: stripped = line.strip() if not stripped: kept.append("") continue norm = re.sub(r"\d+", "", stripped).strip() if "wiadomo" in stripped.casefold() and "polish statistician" in stripped.casefold(): continue if counts[norm] >= 3 and len(norm) >= 8 and ( re.match(r"^\d{1,4}\s", stripped) or re.search(r"\s{2,}\d{1,4}\s*$", stripped) ): continue kept.append(line) return "\n".join(kept) def normalize(text): text = unicodedata.normalize("NFKC", text or "").replace("\u00ad", "").replace("\u200b", "") text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text) text = strip_running_heads(text) lines = [re.sub(r"[ \t ]+", " ", line).strip() for line in text.splitlines()] lines = [line for line in lines if not re.fullmatch(r"\d{1,4}", line)] text = "\n".join(lines) text = re.sub(r"(?<=\w)-\n(?=[a-ząćęłńóśźż])", "", text) text = re.sub(r"(? limit: return set(sorted(hashes)[:limit]) return hashes 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 = ("wiadomosci", "stat.gov", "gus", "polish_statistician", "statystyczne") 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): import pyarrow.parquet as pq from huggingface_hub import HfApi, HfFileSystem acquisition = load(out / "acquisition.json") revision = HfApi().dataset_info(TARGET).sha remote = f"datasets/{TARGET}@{revision}/data/biblioteka_nauki/biblioteka_nauki.parquet" with HfFileSystem().open(remote, "rb") as handle: table = pq.read_table(handle, columns=["id", "attribution"]) target = [] for row in table.to_pylist(): attribution = row.get("attribution") or "" parts = attribution.split(" | ") title = parts[2] if len(parts) >= 4 else attribution target.append((row["id"], attribution, normalize_title(title))) target_by_title = {} for row_id, attribution, normalized in target: if normalized: target_by_title.setdefault(normalized, []).append((row_id, attribution)) target_titles = list(target_by_title) results = [] for record in acquisition["selected"]: title = normalize_title(record["title"]) dois = [record["doi"].casefold()] if record.get("doi") else [] exact = [{"id": row_id, "attribution": attribution} for row_id, attribution, normalized in target if (title and title in normalized) or any(doi in attribution.casefold() for doi in dois)] fuzzy = [] if not exact and title: matches = get_close_matches(title, target_titles, n=3, cutoff=0.90) for normalized in matches: score = SequenceMatcher(None, title, normalized).ratio() fuzzy.extend({"score": score, "id": row_id, "attribution": attribution} for row_id, attribution in target_by_title[normalized]) fuzzy = fuzzy[:3] results.append({"article_id": record["article_id"], "title": record["title"], "doi": dois, "exact_title_or_doi_matches": exact, "fuzzy_title_matches": fuzzy}) report = { "target": f"{TARGET}:data/biblioteka_nauki", "target_revision": revision, "method": "DOI or normalized title substring; fallback SequenceMatcher >= 0.90 over attribution titles", "target_rows": table.num_rows, "candidate_records": len(results), "records_with_exact_match": sum(bool(row["exact_title_or_doi_matches"]) for row in results), "records_with_fuzzy_match": sum(bool(row["fuzzy_title_matches"]) for row in results), "text_overlap": "not tested; target-wide text dedup remains an integration gate", "observed_at": now(), "results": results, } save(out / "overlap_audit.json", report) print(json.dumps({key: report[key] for key in ("target_revision", "target_rows", "candidate_records", "records_with_exact_match", "records_with_fuzzy_match")}, 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, sketches = [], [], [], {}, {} pii = Counter() added = acquisition["observed_at"][:10] for record in acquisition["selected"]: if "error" in record: decisions.append({"id": f"{SOURCE}_{record['article_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: " + record["article_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, emails = EMAIL_RE.subn("[REDACTED:EMAIL]", text) text, phones = PHONE_RE.subn("[REDACTED:PHONE]", text) pii.update(email=emails, labelled_phone=phones) 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 sketch = shingle_sketch(text) if not reason: for other_id, other_sketch in sketches.items(): score = len(sketch & other_sketch) / max(len(sketch | other_sketch), 1) if score >= 0.90: reason, duplicate_of, duplicate_score = "near_duplicate", other_id, score break row_id = f"{SOURCE}_{record['article_id']}" 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 sketches[row_id] = sketch author = "; ".join(record["authors"]) if record["authors"] else "Unknown" created = iso_date(record.get("online_date"), record["article_id"].split("_")[0]) row = { "id": row_id, "text": text, "source": SOURCE, "added": added, "created": created, "token_count": len(encoder.encode_ordinary(text)), "license": LICENSE_SPDX, "author": author, } rows.append(row) attribution.append({ "id": row_id, "article_id": record["article_id"], "title": record["title"], "authors": record["authors"], "doi": record["doi"], "issn": record["issn"], "volume": record["volume"], "issue": record["issue"], "online_date": record["online_date"], "keywords": record["keywords"], "landing_url": record["landing_url"], "pdf_url": record["pdf_url"], "pdf_sha256": record["pdf_sha256"], "pdf_bytes": record["pdf_bytes"], "license": LICENSE_SPDX, "license_line": record["license_line"], "license_policy_url": POLICY_URL, "text_sha256": digest(text.encode("utf-8")), "transformations": ["per-article PDF", "pypdf text extraction", "running-head removal (journal name and repeated page-numbered lines)", "Unicode/whitespace normalization", "page-number-only removal", "line-wrap repair", "email and labelled-phone pattern redaction"], }) root = out / "hf_repo" (root / "data").mkdir(parents=True, exist_ok=True) (root / "artifacts" / "article_pages").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) for source_page in sorted((out / "raw_pages").rglob("*.html.gz")): destination = root / "artifacts" / "article_pages" / source_page.relative_to(out / "raw_pages") destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(source_page.read_bytes()) 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 = { "enumerated_min_year": selection["enumerated"], "with_per_article_cc_by_sa": selection["with_per_article_cc_by_sa"], "selected_polish": selection["selected"], "acquired": acquisition["acquired"], "kept": len(rows), "rejected": len(decisions) - len(rows), "tokens": sum(row["token_count"] for row in rows), "characters": sum(len(row["text"]) for row in rows), "author_coverage": sum(row["author"] != "Unknown" for row in rows) / len(rows) if rows else 0, "license_counts": dict(Counter(row["license"] for row in rows)), "sample_count": len(sample), "added": added, } qa = { "scope": "all Wiadomosci Statystyczne articles from 2022 onward carrying an explicit per-article CC BY-SA 4.0 line and a Polish-language PDF marker", "license_gate": "article page must contain 'udostepniony na licencji CC ... creativecommons.org/licenses/by-sa/4.0'; GUS policy statement applies from 2022-01-01", "language_gate": "site '(Polski)' PDF marker plus independent three-window langid vote", "glyph_gate": "reject when replacement characters exceed 100 or 0.2% of text; scattered TeX-math glyph loss is tolerated and marked", "pii_pattern_matches": dict(pii), "exact_dedup": True, "near_dedup": "deterministic capped 5-word-shingle hash Jaccard >= 0.90 within source", "biblioteka_nauki_overlap": overlap or "pending", "cross_source_text_dedup": "pending target integration", "benchmark_overlap": "pending", "limitations": [ "pypdf extraction may retain layout artifacts; formulas use math-alphanumeric glyphs and isolated unmapped math glyphs are marked [UNREADABLE_GLYPH] (tolerated below 100 chars or 0.2%)", "figures are omitted and tables may be flattened", "per-article license does not prove every quoted third-party passage is reusable", "pattern checks are not comprehensive de-identification", "articles published before 2022 and English-language articles are out of scope", ], } save(root / "artifacts/stats.json", stats) save(root / "artifacts/qa.json", qa) protocol_id = "protocol:wiadomosci-statystyczne-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:codex", "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:wiadomosci-statystyczne", "type": "Source"}, {"id": "object:dataset:wiadomosci-statystyczne-pl", "type": "Dataset"}], "versions": [{"id": source_version, "object": "object:source:wiadomosci-statystyczne", "content_address": source_version.rsplit(":", 1)[-1]}, {"id": dataset_version, "object": "object:dataset:wiadomosci-statystyczne-pl", "content_address": dataset_version.rsplit(":", 1)[-1]}], "protocols": [{"id": protocol_id, "procedure": "enumerate /Archives; require explicit per-article CC BY-SA 4.0 line and Polish PDF marker; pypdf extraction; running-head removal; normalization; PII patterns; exact and near dedup"}], "runs": [run], "evidence": evidence, "claims": [ {"id": "claim:per-article-license-observed", "statement": f"The enumeration observed {selection['with_per_article_cc_by_sa']} articles from {MIN_YEAR} onward carrying an explicit per-article CC BY-SA 4.0 statement; {selection['selected']} also carried a Polish-language PDF marker.", "supported_by": [selection_evidence], "falsification_condition": "The preserved article pages and manifest do not reproduce the count and filters."}, {"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:source-absence-at-audit", "statement": "Wiadomosci Statystyczne was not registered as a source in the pinned DynaWord data tree or open pull-request list at audit time.", "supported_by": [target_evidence] if target_evidence else [qa_evidence], "falsification_condition": "The pinned target evidence contains a matching source or proposal."}, {"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:gus", "type": "Organization"}, {"id": "actor:codex", "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": ["pre-2022 archive review (license status unresolved)", "cross-source text deduplication", "benchmark contamination check", "review of third-party quoted text", "controlled training ablation"], } save(root / "artifacts/ontology.json", ontology) card = f"""--- license: cc-by-sa-4.0 language: - pl task_categories: - text-generation configs: - config_name: default data_files: - split: train path: data/train-00000-of-00001.parquet --- # Wiadomosci Statystyczne (The Polish Statistician) - Polish articles, CC BY-SA 4.0 Polish-language articles from *Wiadomosci Statystyczne. The Polish Statistician* (https://ws.stat.gov.pl/), the peer-reviewed statistical journal published by Statistics Poland (GUS). Scope: articles published from 2022 onward whose article page carries an explicit per-article "udostepniony na licencji CC BY-SA 4.0" statement and a Polish-language PDF marker. - Enumerated articles ({MIN_YEAR}+): {stats['enumerated_min_year']} - With explicit per-article CC BY-SA 4.0 line: {stats['with_per_article_cc_by_sa']} - Selected (Polish PDF marker): {stats['selected_polish']} - Acquired PDFs: {stats['acquired']} - Retained after text QA and within-source deduplication: {stats['kept']} - Characters: {stats['characters']:,} - Tokens: {stats['tokens']:,} (`cl100k_base` proxy) - Author coverage: {stats['author_coverage']:.1%} - License: CC BY-SA 4.0 per record ## Provenance and rights GUS policy (https://nauka.stat.gov.pl/News/Info/60) states that from 1 January 2022 journals and monographs published or co-published by GUS are released under CC BY-SA 4.0. Every retained article additionally carries the per-article license line on its landing page; the preserved page snapshots in `artifacts/article_pages/` let a reviewer re-check that statement. Each row is linked to its landing URL, DOI, authors, volume/issue, PDF URL and checksum. Articles from before 2022 show only the site-wide footer license and are excluded. ## Processing and limitations Text was extracted from publisher PDFs with pypdf, then normalized: running heads (journal name; repeated page-numbered lines), Unicode/whitespace normalization, page-number-only line removal, line-wrap repair, and limited email/phone pattern redaction. Language is checked independently across three text windows; exact and deterministic near deduplication run within the source. PDF-derived text may retain layout artifacts; formulas use math-alphanumeric glyphs, figures are omitted and tables may be flattened. Pattern checks are not comprehensive de-identification. Per-article licensing does not establish the status of every quoted third-party passage. ## 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`. The ontology separates content-addressed Objects and Versions, Protocols, actual Runs, Evidence, falsifiable Claims, Actors and typed lineage. """ (root / "README.md").write_text(card, encoding="utf-8") (root / "NOTICE.md").write_text( "# Attribution and license notice\n\n" "Source: Wiadomosci Statystyczne. The Polish Statistician, https://ws.stat.gov.pl/ " "(Statistics Poland / Glowny Urzad Statystyczny).\n\n" "Each record retains its landing URL, DOI, authorship, volume/issue, PDF checksum and the " "per-article CC BY-SA 4.0 license statement; consult `artifacts/attribution.jsonl`. The CC BY-SA 4.0 " "terms (attribution, link to the license, indication of changes, share-alike) apply per record.\n\n" "Preparation: Piotr Styla with OpenAI Codex. Changes: publisher-PDF text extraction, running-head " "removal, Unicode and whitespace normalization, page-number-only removal, line-wrap repair, limited " "email and labelled-phone redaction, language/quality filtering and within-source deduplication. " "No endorsement by GUS or credited authors is implied.\n", encoding="utf-8", ) print(json.dumps(stats, ensure_ascii=False, indent=2)) def verify(out): import pyarrow.parquet as pq 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) assert sum(row["token_count"] for row in rows) == stats["tokens"] assert all(row["source"] == SOURCE and row["license"] == LICENSE_SPDX for row in rows) assert all(EMAIL_RE.search(row["text"]) is None 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) 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"] print(json.dumps({"verified": True, **stats}, 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()