Datasets:
File size: 25,191 Bytes
8cc48a3 19ed7f8 8cc48a3 19ed7f8 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 19ed7f8 8cc48a3 19ed7f8 8cc48a3 409b93e 8cc48a3 19ed7f8 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 409b93e 8cc48a3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | #!/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"<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)
# 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<before>[^\n]*?)\bźr[óo]d[łl]o\s*:\s*(?P<credit>[^\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()
|