Datasets:
Download src/clean_samorzad_gov_pl.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/503c9db5d79c4b2f7fb9ebbfb40bfd3b679e2526/src/clean_samorzad_gov_pl.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword@503c9db5d79c4b2f7fb9ebbfb40bfd3b679e2526/src/clean_samorzad_gov_pl.py
-
curl -L -o clean_samorzad_gov_pl.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/503c9db5d79c4b2f7fb9ebbfb40bfd3b679e2526/src/clean_samorzad_gov_pl.py
19.2 kB
| #!/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 = "d5eaefc32c3f17cfa5a01d14573f8e4ee7d43385" | |
| UPSTREAM_TEXT_SHA256 = "6c35e1dc0bd35863ddb2f4e43d5bd08264c1fc27affdd60684ab5ecbc5457f63" | |
| UPSTREAM_MANIFEST_SHA256 = "97b5a266b2fd4f043648b7d3c757721cd826c7ca1048301761084b0abdee5c48" | |
| UPSTREAM_EXPECTED = { | |
| "manifest_sha256": UPSTREAM_MANIFEST_SHA256, | |
| "dataset_id": UPSTREAM_DATASET, | |
| "schema_version": "1.0.0", | |
| "record_count": 81_422, | |
| "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"<meta\b(?=[^>]*\bproperty\s*=\s*['\"]og:site_name['\"])(?=[^>]*\bcontent\s*=\s*(['\"])(.*?)\1)[^>]*>", | |
| re.IGNORECASE | re.DOTALL, | |
| ) | |
| _TITLE_RE = re.compile(r"<title\b[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL) | |
| 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": ( | |
| "Article text was extracted from the source HTML. This DynaWord " | |
| "release normalizes metadata and may exclude short, non-Polish or " | |
| "duplicate records; the retained text is otherwise unchanged." | |
| ), | |
| } | |
| return row, attribution | |
| 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] = [] | |
| stats = { | |
| "read": len(records), | |
| "kept": 0, | |
| "drop_short": 0, | |
| "drop_lang": 0, | |
| "drop_dup": 0, | |
| "drop_ocr": 0, | |
| "chars": 0, | |
| "tokens": 0, | |
| "licenses": {LICENSE: 0}, | |
| "authors_with_value": 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() | |
| ), | |
| "redirected_urls": 0, | |
| "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"]), | |
| } | |
| 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) | |
| 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) | |
| stats["kept"] += 1 | |
| stats["chars"] += len(row["text"]) | |
| stats["tokens"] += token_count | |
| stats["licenses"][LICENSE] += 1 | |
| stats["authors_with_value"] += int(bool(row["author"])) | |
| stats["redirected_urls"] += int( | |
| attribution["source_url"] != attribution["final_url"] | |
| ) | |
| table = pa.Table.from_pylist(rows, schema=DYNAWORD_SCHEMA) | |
| 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) | |
| return stats | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--input", type=Path, required=True, 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", required=True) | |
| parser.add_argument("--refresh-publishers", action="store_true") | |
| args = parser.parse_args() | |
| 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() | |