#!/usr/bin/env python3 """Convert dawidmajewski/samorzad-gov-pl-articles to DynaWord. The input is the published source dataset. Institution names are frozen in a committed publisher manifest generated from each tenant homepage's ``og:site_name`` metadata. The output uses DynaWord's canonical eight columns and writes a URL-bearing attribution sidecar for CC-BY-SA compliance. """ from __future__ import annotations import argparse import hashlib import html as html_module import http.client import json import os import re import shutil import tempfile import time import urllib.request from pathlib import Path import pyarrow as pa import pyarrow.dataset as ds import pyarrow.parquet as pq SOURCE = "samorzad_gov_pl" LICENSE = "CC-BY-SA-4.0" LICENSE_URL = "https://creativecommons.org/licenses/by-sa/4.0/" UPSTREAM_DATASET = "dawidmajewski/samorzad-gov-pl-articles" UPSTREAM_REVISION = "a998efea84bb0a62d94effc0b54f88b422d9898f" UPSTREAM_TEXT_SHA256 = "9378f130ce26fc95015f661910e660f8bbe6442e75640089185f78052533377d" UPSTREAM_MANIFEST_SHA256 = "9d349bb271033fef62a051e311115460e030740f9593bb7f3158cb1437f87639" UPSTREAM_EXPECTED = { "manifest_sha256": UPSTREAM_MANIFEST_SHA256, "dataset_id": UPSTREAM_DATASET, "schema_version": "1.0.0", "record_count": 81_418, "record_text_sha256": UPSTREAM_TEXT_SHA256, } MIN_CHARS = 200 MIN_POLISH_RATIO = 0.005 POLISH_RE = re.compile(r"[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]") ALPHA_RE = re.compile(r"[^\W\d_]", re.UNICODE) _SITE_NAME_RE = re.compile( r"]*\bproperty\s*=\s*['\"]og:site_name['\"])(?=[^>]*\bcontent\s*=\s*(['\"])(.*?)\1)[^>]*>", re.IGNORECASE | re.DOTALL, ) _TITLE_RE = re.compile(r"]*>(.*?)", re.IGNORECASE | re.DOTALL) # Third-party carve-out (slayerlabs/polish-dynaword-v2#49). gov.pl's copyright # page says the service also carries works whose rights belong to third parties # and whose use needs the owners' consent, so the operator-declared platform # licence does not reach them. Each rule below is one hand-checked slice. THIRD_PARTY_DROPS = ("poetry_friday", "imgw_notice", "nongov_source") # Powiat Sokołowski's "Piątek z poezją" series reprints poems by named authors. _POETRY_FRIDAY_TITLE_RE = re.compile(r"piątek z poezją", re.IGNORECASE) # IMGW-PIB warnings carry a notice allowing reuse only in verbatim form. _IMGW_NOTICE = "Opracowanie niniejsze i jego format" # First "Źródło:" on a line: the text before it and up to 200 credited chars. _SOURCE_LINE_RE = re.compile( r"^(?P[^\n]*?)\bźr[óo]d[łl]o\s*:\s*(?P[^\n]{0,200})", re.IGNORECASE | re.MULTILINE, ) # "Fot. X, źródło: Y" credits a photo, illustration or film, not the text. _MEDIA_CREDIT_RE = re.compile( r"^\W*(?:fot|ilustracj|film)|\b(?:fot|ilustracj|film)\w*[^\n]{0,20}$", re.IGNORECASE, ) # Credits naming a non-governmental author: media, encyclopedias, NGOs (OSP # units are associations), companies, and authored works. Associations of # local governments (Stowarzyszenie Łódzki Obszar Metropolitalny) are public. _NONGOV_CREDIT_RE = re.compile( r""" wikipedi | wikimedia | telewizja | \btvp\b | \bradio\s | serwis\s+samorządowy\s+pap | redakcj[ai]\s+(?:życia|tygodnika) | podlasie\s?24 | jasło112 | tymbark\.in | polskiobserwator | it\s+w\s+administracji | stowarzyszeni[ea](?!\s+łódzki\s+obszar) | fundacj[ia] | \bkgw\b | \bskgw\b | ^koło\s+gospodyń | \bklub\b | \bmlks\b | junis | amazonki | izba\s+(?:lotnicza|gospodarcza) | \bosp\b | \bzosp\b | związku\s+ochotniczych\s+straży | polskiego\s+związku\s+łowieckiego | lokalna\s+grupa\s+działania | sp\.\s*z\s*o\.\s*o | \bpge\b | edp\s+renewables | grupa\s+nowy\s+szpital | carrefour | \bautor(?:\s+tekstu)?\s*: | broszura | wspomnienia | monografia | rodzinne\s+gniazdo | historia\s+i\s+teraźniejszość | historia\s+włókniarza | jubiläumsschrift | bio\s+artystki | domowe\s+historie """, re.IGNORECASE | re.VERBOSE, ) MODIFICATION_NOTICE = ( "Article text was extracted from the source HTML and de-identified " "upstream. This DynaWord release normalizes metadata and may exclude " "short, non-Polish, duplicate or third-party records; retained text is " "otherwise unchanged after upstream de-identification." ) # The release on main 92b36dc before the third-party drops. refilter_release() # starts from it because a full build() also needs every other source's # Parquet for cross-source dedup. PRE_CARVE_OUT_SHA256 = { f"{SOURCE}.parquet": "3a683b4220b9b70698d7c524637d9ea5c1d72630b8f92ea7a871642a719cf2c0", f"{SOURCE}.attribution.jsonl": "2def7488c34e749204842bcf21d33149738b34de2515115e3f79401f7eb271c4", } DYNAWORD_SCHEMA = pa.schema( [ ("id", pa.string()), ("text", pa.string()), ("source", pa.string()), ("added", pa.string()), ("created", pa.string()), ("token_count", pa.int64()), ("license", pa.string()), ("author", pa.string()), ] ) def _clean_html_text(value: str) -> str: value = re.sub(r"<[^>]+>", " ", value) return " ".join(html_module.unescape(value).split()) def publisher_name_from_html(html: str) -> str: """Extract the human-readable institution name from a tenant homepage.""" match = _SITE_NAME_RE.search(html) if match: return _clean_html_text(match.group(2)) match = _TITLE_RE.search(html) if not match: return "" title = _clean_html_text(match.group(1)) prefix, suffix = "Strona główna - ", " - Portal gov.pl" if title.startswith(prefix) and title.endswith(suffix): return title[len(prefix) : -len(suffix)].strip() return "" def _fetch(url: str, attempts: int = 5) -> str: last_error: Exception | None = None for attempt in range(attempts): try: request = urllib.request.Request( url, headers={"User-Agent": "Polish-DynaWord-source-builder/1.0"}, ) with urllib.request.urlopen(request, timeout=45) as response: return response.read().decode("utf-8", "replace") except (OSError, TimeoutError, http.client.HTTPException) as error: last_error = error time.sleep(2**attempt) raise RuntimeError(f"Could not fetch {url}: {last_error}") def refresh_publishers(tenants: list[str], output: Path) -> dict[str, str]: """Fetch and freeze one verified display name for every source tenant.""" publishers: dict[str, str] = {} failures: list[str] = [] for index, tenant in enumerate(sorted(set(tenants)), 1): url = f"https://samorzad.gov.pl/web/{tenant}" try: name = publisher_name_from_html(_fetch(url)) except RuntimeError: name = "" if not name: failures.append(tenant) else: publishers[tenant] = name print(f"publishers {index}/{len(set(tenants))}: {tenant} -> {name or 'FAILED'}") if failures: raise RuntimeError( "Publisher-name refresh incomplete; retry before release: " + ", ".join(failures) ) output.parent.mkdir(parents=True, exist_ok=True) output.write_text( json.dumps( { "schema_version": "1.0.0", "source": "tenant homepage og:site_name", "publishers": publishers, }, ensure_ascii=False, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) return publishers def load_publishers(path: Path) -> dict[str, str]: data = json.loads(path.read_text(encoding="utf-8")) publishers = data.get("publishers") if data.get("schema_version") != "1.0.0" or not isinstance(publishers, dict): raise ValueError(f"Invalid publisher manifest: {path}") if not all(isinstance(k, str) and isinstance(v, str) and v.strip() for k, v in publishers.items()): raise ValueError(f"Empty or invalid publisher in {path}") return publishers def _file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def verify_upstream_release( input_path: Path, manifest_path: Path, expected: dict[str, object] = UPSTREAM_EXPECTED, ) -> dict: """Fail closed unless input exactly matches the pinned published release.""" input_path = input_path.resolve() manifest_path = manifest_path.resolve() raw_manifest = manifest_path.read_bytes() if hashlib.sha256(raw_manifest).hexdigest() != expected["manifest_sha256"]: raise ValueError("Upstream manifest hash mismatch") manifest = json.loads(raw_manifest) for key in ("dataset_id", "schema_version", "record_count", "record_text_sha256"): if manifest.get(key) != expected[key]: raise ValueError(f"Upstream manifest {key} mismatch") artifact_paths: list[Path] = [] artifact_records = 0 for artifact in manifest.get("artifacts", []): path = (manifest_path.parent / artifact["path"]).resolve() if path.parent != input_path: raise ValueError(f"Upstream artifact outside input directory: {path}") if not path.is_file(): raise ValueError(f"Missing upstream artifact: {path}") if path.stat().st_size != artifact["bytes"]: raise ValueError(f"Upstream artifact size mismatch: {path.name}") if _file_sha256(path) != artifact["sha256"]: raise ValueError(f"Upstream artifact hash mismatch: {path.name}") if pq.ParquetFile(path).metadata.num_rows != artifact["records"]: raise ValueError(f"Upstream artifact row-count mismatch: {path.name}") artifact_paths.append(path) artifact_records += artifact["records"] actual_paths = sorted(path.resolve() for path in input_path.glob("*.parquet")) if sorted(artifact_paths) != actual_paths: raise ValueError("Upstream artifact set differs from manifest") if artifact_records != expected["record_count"]: raise ValueError("Upstream artifact record total mismatch") source_dataset = ds.dataset([str(path) for path in actual_paths], format="parquet") if source_dataset.schema.names != manifest["record_fields"]: raise ValueError("Upstream Parquet schema differs from manifest") source_rows = source_dataset.to_table(columns=["record_id", "text"]).to_pylist() if len(source_rows) != expected["record_count"]: raise ValueError("Upstream dataset record count mismatch") source_rows.sort(key=lambda row: row["record_id"]) if len({row["record_id"] for row in source_rows}) != len(source_rows): raise ValueError("Upstream record IDs are not unique") text_digest = hashlib.sha256() for row in source_rows: text_digest.update(row["record_id"].encode()) text_digest.update(b"\0") text_digest.update(row["text"].encode()) text_digest.update(b"\n") if text_digest.hexdigest() != expected["record_text_sha256"]: raise ValueError("Upstream record-text digest mismatch") return manifest def normalize_record( source: dict, publishers: dict[str, str], token_count: int, added: str, ) -> tuple[dict, dict]: tenant = str(source["tenant"]) try: publisher = publishers[tenant] except KeyError as error: raise KeyError(f"No publisher name for tenant {tenant}") from error record_id = f"{SOURCE}_{source['record_id']}" created = source.get("published_date") or "" source_url = str(source["source_url"]) final_url = str(source.get("final_url") or source_url) row = { "id": record_id, "text": str(source["text"]), "source": SOURCE, "added": added, "created": str(created), "token_count": int(token_count), "license": LICENSE, "author": publisher, } attribution = { "id": record_id, "title": str(source.get("title") or ""), "source_url": source_url, "final_url": final_url, "attribution_url": final_url, "publisher": publisher, "tenant": tenant, "publisher_type": str(source.get("publisher_type") or ""), "license": LICENSE, "license_url": LICENSE_URL, "modified": True, "modification_notice": MODIFICATION_NOTICE, } return row, attribution def third_party_drop(title: str, text: str) -> str | None: """Return the THIRD_PARTY_DROPS slice a record belongs to, or None.""" if _POETRY_FRIDAY_TITLE_RE.search(title): return "poetry_friday" if _IMGW_NOTICE in text: return "imgw_notice" for line in _SOURCE_LINE_RE.finditer(text): if _NONGOV_CREDIT_RE.search(line["credit"]) and not _MEDIA_CREDIT_RE.search( line["before"] ): return "nongov_source" return None def _polish_ratio(text: str) -> float: letters = ALPHA_RE.findall(text) return len(POLISH_RE.findall(text)) / len(letters) if letters else 0.0 def _text_hash(text: str) -> bytes: return hashlib.sha256(text.encode("utf-8")).digest() def existing_text_hashes(repo_root: Path, output_path: Path) -> set[bytes]: """Load exact-text hashes from all existing DynaWord source Parquets.""" hashes: set[bytes] = set() output_resolved = output_path.resolve() for path in sorted((repo_root / "data").glob("*/*.parquet")): if path.resolve() == output_resolved or path.parent.name == SOURCE: continue for batch in pq.ParquetFile(path).iter_batches(columns=["text"], batch_size=4096): hashes.update(_text_hash(text) for text in batch.column(0).to_pylist() if text) return hashes def _fsync_path(path: Path) -> None: with path.open("rb+") as handle: os.fsync(handle.fileno()) def _write_text_synced(path: Path, content: str) -> None: with path.open("w", encoding="utf-8") as handle: handle.write(content) handle.flush() os.fsync(handle.fileno()) def _validate_staged_release(staged_dir: Path) -> None: parquet_path = staged_dir / f"{SOURCE}.parquet" sidecar_path = staged_dir / f"{SOURCE}.attribution.jsonl" stats = json.loads((staged_dir / f"{SOURCE}.stats.json").read_text()) table = pq.read_table(parquet_path) if table.schema != DYNAWORD_SCHEMA or table.num_rows != stats["kept"]: raise ValueError("Staged Parquet does not match canonical schema or stats") ids = table["id"].to_pylist() authors = table["author"].to_pylist() if len(ids) != len(set(ids)): raise ValueError("Staged IDs are not unique") sidecar_count = 0 with sidecar_path.open(encoding="utf-8") as handle: for sidecar_count, (line, record_id, author) in enumerate( zip(handle, ids, authors, strict=True), 1, ): attribution = json.loads(line) if attribution["id"] != record_id or attribution["publisher"] != author: raise ValueError("Staged sidecar does not match Parquet order") if attribution["attribution_url"] != attribution["final_url"]: raise ValueError("Staged attribution URL is not the fetched final URL") if sidecar_count != stats["kept"]: raise ValueError("Staged sidecar count does not match stats") def _replace_release(staged_dir: Path, output_dir: Path) -> None: """Replace a validated artifact set, restoring the previous set on error.""" names = ( f"{SOURCE}.parquet", f"{SOURCE}.attribution.jsonl", f"{SOURCE}.stats.json", ) backup_dir = staged_dir / "backup" backup_dir.mkdir() had_previous: set[str] = set() for name in names: destination = output_dir / name if destination.exists(): shutil.copy2(destination, backup_dir / name) _fsync_path(backup_dir / name) had_previous.add(name) try: for name in names: os.replace(staged_dir / name, output_dir / name) directory_fd = os.open(output_dir, os.O_RDONLY) try: os.fsync(directory_fd) finally: os.close(directory_fd) except BaseException: for name in names: destination = output_dir / name backup = backup_dir / name if name in had_previous: os.replace(backup, destination) elif destination.exists(): destination.unlink() raise def build( input_path: Path, manifest_path: Path, repo_root: Path, publishers_path: Path, added: str, refresh: bool, ) -> dict: manifest = verify_upstream_release(input_path, manifest_path) source_dataset = ds.dataset(str(input_path), format="parquet") source_table = source_dataset.to_table( columns=[ "record_id", "source_url", "final_url", "tenant", "publisher_type", "title", "text", "published_date", ] ) records = sorted(source_table.to_pylist(), key=lambda row: row["record_id"]) tenants = sorted({row["tenant"] for row in records}) tenant_types = {row["tenant"]: row["publisher_type"] for row in records} publishers = ( refresh_publishers(tenants, publishers_path) if refresh else load_publishers(publishers_path) ) missing = sorted(set(tenants) - set(publishers)) if missing: raise RuntimeError(f"Publisher manifest misses {len(missing)} tenants: {missing}") output_dir = repo_root / "data" / SOURCE output_dir.mkdir(parents=True, exist_ok=True) parquet_path = output_dir / f"{SOURCE}.parquet" prior_hashes = existing_text_hashes(repo_root, parquet_path) seen = set(prior_hashes) candidates: list[dict] = [] metadata = manifest["dataset_metadata"] stats = { "read": len(records), "kept": 0, "drop_short": 0, "drop_lang": 0, "drop_dup": 0, "drop_ocr": 0, "drop_third_party": dict.fromkeys(THIRD_PARTY_DROPS, 0), "publisher_count": len(publishers), "local_public_tenant_count": sum( publisher_type != "central" for publisher_type in tenant_types.values() ), "central_tenant_count": sum( publisher_type == "central" for publisher_type in tenant_types.values() ), "cross_source_hashes_loaded": len(prior_hashes), "license": LICENSE, "upstream_dataset": UPSTREAM_DATASET, "upstream_revision": UPSTREAM_REVISION, "upstream_record_text_sha256": UPSTREAM_TEXT_SHA256, "upstream_manifest_sha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(), "upstream_artifact_count": len(manifest["artifacts"]), "upstream_deidentification_model": metadata["deidentification_model"], "upstream_deidentification_model_revision": metadata[ "deidentification_model_revision" ], "upstream_deidentification_policy": metadata["deidentification_policy"], "upstream_source_quality_excluded_records": metadata[ "source_quality_excluded_records" ], } for record in records: text = str(record.get("text") or "").strip() if len(text) < MIN_CHARS: stats["drop_short"] += 1 continue if _polish_ratio(text) < MIN_POLISH_RATIO: stats["drop_lang"] += 1 continue digest = _text_hash(text) if digest in seen: stats["drop_dup"] += 1 continue seen.add(digest) # After dedup, so the dup set matches the pre-carve-out release and # refilter_release() gives the same rows as a full build. reason = third_party_drop(str(record.get("title") or ""), text) if reason: stats["drop_third_party"][reason] += 1 continue record["text"] = text candidates.append(record) import tiktoken encoder = tiktoken.get_encoding("cl100k_base") token_counts = [ len(tokens) for tokens in encoder.encode_ordinary_batch( [record["text"] for record in candidates], num_threads=8 ) ] rows: list[dict] = [] attribution_rows: list[dict] = [] for source_row, token_count in zip(candidates, token_counts, strict=True): row, attribution = normalize_record(source_row, publishers, token_count, added) rows.append(row) attribution_rows.append(attribution) table = pa.Table.from_pylist(rows, schema=DYNAWORD_SCHEMA) _write_release(output_dir, table, attribution_rows, stats) return stats def _write_release( output_dir: Path, table: pa.Table, attribution_rows: list[dict], stats: dict ) -> None: """Fill the row-derived stats, then stage, validate and swap in the release.""" stats.update( kept=table.num_rows, chars=sum(map(len, table["text"].to_pylist())), tokens=sum(table["token_count"].to_pylist()), licenses={LICENSE: table.num_rows}, authors_with_value=sum(map(bool, table["author"].to_pylist())), redirected_urls=sum( row["source_url"] != row["final_url"] for row in attribution_rows ), ) with tempfile.TemporaryDirectory(prefix=f".{SOURCE}-", dir=output_dir) as temp: staged_dir = Path(temp) staged_parquet = staged_dir / f"{SOURCE}.parquet" staged_sidecar = staged_dir / f"{SOURCE}.attribution.jsonl" staged_stats = staged_dir / f"{SOURCE}.stats.json" pq.write_table(table, staged_parquet, compression="zstd", row_group_size=4096) _fsync_path(staged_parquet) _write_text_synced( staged_sidecar, "".join( json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in attribution_rows ), ) _write_text_synced( staged_stats, json.dumps(stats, ensure_ascii=False, indent=2, sort_keys=True) + "\n", ) _validate_staged_release(staged_dir) _replace_release(staged_dir, output_dir) def refilter_release( output_dir: Path, expected: dict[str, str] = PRE_CARVE_OUT_SHA256 ) -> dict: """Apply third_party_drop() to the pinned pre-carve-out release in place.""" for name, digest in expected.items(): if _file_sha256(output_dir / name) != digest: raise ValueError(f"{name} is not the pinned pre-carve-out release") table = pq.read_table(output_dir / f"{SOURCE}.parquet") with (output_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as handle: attributions = [json.loads(line) for line in handle] stats = json.loads((output_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8")) stats["drop_third_party"] = dict.fromkeys(THIRD_PARTY_DROPS, 0) keep: list[bool] = [] for attribution, text in zip(attributions, table["text"].to_pylist(), strict=True): reason = third_party_drop(attribution["title"], text) if reason: stats["drop_third_party"][reason] += 1 keep.append(reason is None) kept_attributions = [ {**attribution, "modification_notice": MODIFICATION_NOTICE} for attribution, kept in zip(attributions, keep) if kept ] _write_release(output_dir, table.filter(pa.array(keep)), kept_attributions, stats) return stats def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--input", type=Path, help="directory containing source Parquet shards") parser.add_argument( "--manifest", type=Path, help="pinned source manifest (default: MANIFEST next to the input directory)", ) parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--publishers", type=Path, default=Path(__file__).with_name("samorzad_gov_pl_publishers.json")) parser.add_argument("--added") parser.add_argument("--refresh-publishers", action="store_true") parser.add_argument( "--refilter-release", action="store_true", help="apply the third-party drops to the pinned pre-carve-out release in data/", ) args = parser.parse_args() if args.refilter_release: stats = refilter_release(args.repo_root.resolve() / "data" / SOURCE) elif args.input is None or args.added is None: parser.error("--input and --added are required unless --refilter-release") else: stats = build( input_path=args.input, manifest_path=args.manifest or args.input.parent / "manifest.json", repo_root=args.repo_root.resolve(), publishers_path=args.publishers, added=args.added, refresh=args.refresh_publishers, ) print(json.dumps(stats, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()