#!/usr/bin/env python3 """Drop sejm_api_2011_2022 speeches already contained in a pinned reference set (slayerlabs/polish-dynaword-v2#57). The rights audit found that sejm_api_2011_2022 overlaps `parliamentary` (Sejm sittings to the end of term 8, sejm_api_common.PARLIAMENTARY_SEJM_END) and the since-removed `parlamint_pl`. A speech is dropped when one document of the reference set holds at least DROP_AT of its shingles: containment(speech, ref) = |S(speech) & S(ref)| / |S(speech)| S() is the set of 5-word shingles over NFKC-casefolded \\w+ tokens (the tokenisation of the repo's near_dedup, src/shingle_containment.py). The "Przebieg posiedzenia" trailers that the snapshot appends to most speeches are cut first, and each appended statement becomes a row of its own (sejm_api_common.split_release_rows, as in src/clean_sejm_api.py), so a speech is scored on its own words and an appended statement on its own. Containment is one-directional because a reference document can be a whole sitting while a speech is a few paragraphs. It is measured against single reference documents, not a union of them. The reference set is REFERENCES: every Parquet whose registry `release` is not None, each pinned by SHA-256. `parliamentary` is the PPC TEI rebuild of slayerlabs/polish-dynaword-v2#54 (option C). When a reference changes, re-pin REFERENCES and rerun this script on the restored input; nothing here follows the registry silently. Exact search: the speeches are indexed, the references are streamed. A speech is found when a reference shares at least one of its rarest (1 - REPORT_AT) * n + 1 shingles (prefix filter, exact by pigeonhole), and every such candidate is then scored on its full shingle sets. No MinHash/LSH, so there is no sampling error. Speeches scoring from REPORT_AT up are written to sejm_api_2011_2022.decisions.jsonl with the best score against each reference group (`parliamentary:-` from the record id, or the source key). Speeches under five words have no shingles and are never dropped. The inputs are the pre-dedup release files, pinned by SHA-256. Restore them before a rerun: git checkout 3bab9f9 -- data/sejm_api_2011_2022/sejm_api_2011_2022.{parquet,attribution.jsonl,stats.json} python3 src/clean_sejm_api_2011_2022.py """ from __future__ import annotations import argparse import json import multiprocessing import os import re import tempfile from collections import Counter from concurrent.futures import ProcessPoolExecutor from pathlib import Path import numpy as np import pyarrow as pa import pyarrow.parquet as pq import tiktoken from sejm_api_common import check_pin, release_stats, replace_all, split_release_rows from shingle_containment import shingles from sources import SOURCES SOURCE = "sejm_api_2011_2022" ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE # Pre-dedup release files (main at 3bab9f9); the ontology manifest records the same three. INPUT_SHA256 = { f"{SOURCE}.parquet": "606d49ab55180341bffe5270e9c88797a95ff9f8441bf2de095d36f9d7a756c1", f"{SOURCE}.attribution.jsonl": "a1c1a309075b2fbc2a42f5313e22e93584434f4260e61d6e92d6cc488b0d9be5", f"{SOURCE}.stats.json": "398dbaff87ec8f1d8702fce347db65ae8a3e4cf69a90594a6c7998cc4441c356", } # Reference source -> (Parquet, SHA-256). Only sources with a registry release (checked in build()). # `parlamint_pl` left the registry in Hub PR 54 and never had data, so it cannot be pinned. REFERENCES = { "parliamentary": (ROOT / "data/parliamentary/parliamentary.parquet", "07903953faa3bb88bd5083500cc77e8d49aa505037f7420bab49f09b7bb4115b"), "sejm_api": (ROOT / "data/sejm_api/sejm_api.parquet", # after src/clean_sejm_api.py "ba2daa20d2d2753c09e8bdd477839f43c82170f44caeadc634cb2295362c9c3b"), } DECISIONS = f"{SOURCE}.decisions.jsonl" DROP_AT = 0.5 REPORT_AT = 0.3 ROW_GROUP_SIZE = 1024 # the layout of the released file SIZE_BUCKETS = (("<10", 0, 10), ("10-19", 10, 20), ("20-49", 20, 50), ("50-199", 50, 200), (">=200", 200, 10**9)) # `parliamentary` ids are parliamentary_---- (src/fetch_parliamentary.py), # being the dump's directory name padded with "x" to five letters. These codes are the plenary and # interpellation directories; every other code is a committee. Codes can be non-ASCII ("kśpxx"). PPC_ID = re.compile(r"parliamentary_\d+-(sjm|snt|krn)-(\w+)-\d+-\d+") PPC_KINDS = {"ppxxx": "plenary", "usxxx": "plenary", "uzxxx": "plenary", "wsxxx": "plenary", "znxxx": "plenary", "ipxxx": "interpellation", "zpxxx": "interpellation", "ioxxx": "reply", "zoxxx": "reply"} def group_of(source: str, ref_id: str) -> str: """Reference group a document is reported under: `parliamentary:-` or the source key.""" if source != "parliamentary": return source match = PPC_ID.fullmatch(ref_id) if not match: raise ValueError(f"{ref_id!r} is not a parliamentary record id") return f"parliamentary:{match[1]}-{PPC_KINDS.get(match[2], 'committee')}" def min_shared(sizes: np.ndarray, at: float) -> np.ndarray: """Fewest shared shingles that reach containment `at` (the epsilon guards 0.3 * 10 = 3.0000000000000004).""" return np.ceil(at * sizes - 1e-9).astype(np.int64) # --- exact containment search ------------------------------------------------------------------- _INDEX: dict[str, np.ndarray] = {} # per-process, memory-mapped from the work directory def _load_index(work: str) -> None: _INDEX.update({name: np.load(Path(work) / f"{name}.npy", mmap_mode="r") for name in ("prefix_hash", "prefix_doc", "flat", "offsets", "need")}) def _shingle_chunk(texts: list[str]) -> list[np.ndarray]: return [shingles(text) for text in texts] def prefix_index(offsets: np.ndarray, flat: np.ndarray, need: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Sorted (hash, doc) pairs of each speech's rarest n - need + 1 shingles. A reference sharing >= `need` of a speech's n shingles misses at most need - 1 of them, so it must hold one of the n - need + 1 chosen; rarity (the count among speeches) only keeps the posting lists short. """ unique, counts = np.unique(flat, return_counts=True) rarity = counts[np.searchsorted(unique, flat)] hashes, docs = [], [] for doc in range(len(offsets) - 1): lo, hi = offsets[doc], offsets[doc + 1] if lo == hi: continue chosen = np.lexsort((flat[lo:hi], rarity[lo:hi]))[: hi - lo - need[doc] + 1] hashes.append(flat[lo:hi][chosen]) docs.append(np.full(len(chosen), doc, np.int32)) hashes, docs = np.concatenate(hashes), np.concatenate(docs) order = np.argsort(hashes, kind="stable") return hashes[order], docs[order] def _keep_best(best: dict, key: tuple[int, str], shared: int, ref_id: str) -> None: """Most shared shingles wins; a tie goes to the smaller reference id, so the result is order-independent.""" if key not in best or shared > best[key][0] or (shared == best[key][0] and ref_id < best[key][1]): best[key] = (shared, ref_id) def _scan_row_group(task: tuple[str, str, int]) -> dict[tuple[int, str], tuple[int, str]]: """Best (shared shingles, reference id) per (speech, group) over one row group of a reference.""" path, source, row_group = task table = pq.ParquetFile(path).read_row_group(row_group, columns=["id", "text"]) prefix_hash, prefix_doc = _INDEX["prefix_hash"], _INDEX["prefix_doc"] flat, offsets, need = _INDEX["flat"], _INDEX["offsets"], _INDEX["need"] best: dict[tuple[int, str], tuple[int, str]] = {} for ref_id, text in zip(table.column("id").to_pylist(), table.column("text").to_pylist(), strict=True): ref = shingles(text) lo = np.searchsorted(prefix_hash, ref, "left") lens = np.searchsorted(prefix_hash, ref, "right") - lo hits = int(lens.sum()) if not hits: continue group = group_of(source, ref_id) for doc in np.unique(prefix_doc[np.repeat(lo - np.cumsum(lens) + lens, lens) + np.arange(hits)]): speech = flat[offsets[doc]:offsets[doc + 1]] at = np.minimum(np.searchsorted(ref, speech), len(ref) - 1) shared = int((ref[at] == speech).sum()) if shared >= need[doc]: _keep_best(best, (int(doc), group), shared, ref_id) return best def _map(fn, tasks: list, workers: int, work: str) -> list: if workers == 1: _load_index(work) if work else None return [fn(task) for task in tasks] context = multiprocessing.get_context("spawn") with ProcessPoolExecutor(workers, mp_context=context, initializer=_load_index if work else None, initargs=(work,) if work else ()) as pool: return list(pool.map(fn, tasks)) def find_contained(texts: list[str], references: dict[str, Path], work: Path, workers: int, at: float = REPORT_AT) -> tuple[np.ndarray, dict[tuple[int, str], tuple[int, str]]]: """Shingle-set sizes of `texts`, and for every (text, reference group) pair scoring >= `at` the best (shared shingles, reference id). `references` maps a source key to its Parquet.""" chunks = [texts[i:i + 2048] for i in range(0, len(texts), 2048)] sets = [s for chunk in _map(_shingle_chunk, chunks, workers, "") for s in chunk] sizes = np.array([len(s) for s in sets], np.int64) offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(np.int64) flat = np.concatenate(sets) if sets else np.empty(0, np.uint64) need = min_shared(sizes, at) prefix_hash, prefix_doc = prefix_index(offsets, flat, need) for name, array in (("prefix_hash", prefix_hash), ("prefix_doc", prefix_doc), ("flat", flat), ("offsets", offsets), ("need", need)): np.save(work / f"{name}.npy", array) del sets, flat, prefix_hash, prefix_doc tasks = [(str(path), source, row_group) for source, path in references.items() for row_group in range(pq.ParquetFile(path).num_row_groups)] merged: dict[tuple[int, str], tuple[int, str]] = {} for part in _map(_scan_row_group, tasks, workers, str(work)): for key, (shared, ref_id) in part.items(): _keep_best(merged, key, shared, ref_id) return sizes, merged # --- build --------------------------------------------------------------------------------------- def score_table(sizes: np.ndarray, best: dict[tuple[int, str], tuple[int, str]], groups: list[str]) -> np.ndarray: """(speeches x groups) containment matrix; 0 where a group scored below REPORT_AT.""" scores = np.zeros((len(sizes), len(groups))) for (doc, group), (shared, _) in best.items(): scores[doc, groups.index(group)] = shared / sizes[doc] return scores def outcomes(scores: np.ndarray, groups: list[str]) -> dict[str, int]: """Speeches dropped (best score >= DROP_AT) against each reference, and against each group alone.""" def dropped(wanted): cols = [i for i, g in enumerate(groups) if wanted(g)] return int((scores[:, cols].max(axis=1) >= DROP_AT).sum()) if cols else 0 return { "all_references": dropped(lambda g: True), "parliamentary_all": dropped(lambda g: g.startswith("parliamentary:")), **{f"only_{g.replace(':', '_')}": dropped(lambda x, g=g: x == g) for g in groups}, } def build(input_dir: Path, references: dict[str, tuple[Path, str]], out_dir: Path, workers: int, check_registry: bool = True) -> dict: for name, sha in INPUT_SHA256.items(): check_pin(input_dir / name, sha, f"restore it with `git checkout 3bab9f9 -- data/{SOURCE}/{name}`") for source, (path, sha) in references.items(): check_pin(path, sha, f"it is not the pinned {source} Parquet; re-pin REFERENCES (see the docstring)") if check_registry and SOURCES[source]["release"] is None: raise SystemExit(f"{source} has no release in src/sources.py; it cannot be a reference") table = pq.read_table(input_dir / f"{SOURCE}.parquet") with (input_dir / f"{SOURCE}.attribution.jsonl").open(encoding="utf-8") as stream: sidecar = [json.loads(line) for line in stream] stats = json.loads((input_dir / f"{SOURCE}.stats.json").read_text(encoding="utf-8")) rows = table.to_pylist() recomputed = release_stats(rows, sidecar) if recomputed != {key: stats.get(key) for key in recomputed}: raise SystemExit("the input stats.json does not describe the input Parquet") rows, sidecar, cut = split_release_rows(rows, sidecar, tiktoken.get_encoding("cl100k_base")) with tempfile.TemporaryDirectory() as work: sizes, best = find_contained([row["text"] for row in rows], {s: p for s, (p, _) in references.items()}, Path(work), workers) groups = sorted({group for _, group in best}) scores = score_table(sizes, best, groups) top = scores.max(axis=1) if groups else np.zeros(len(sizes)) drop = top >= DROP_AT decisions = [] for doc in np.flatnonzero(top >= REPORT_AT): group = groups[int(scores[doc].argmax())] decisions.append({ "id": rows[doc]["id"], "created": rows[doc]["created"], "action": "drop" if drop[doc] else "keep_partial", "containment": round(float(top[doc]), 4), "ref_group": group, "ref_id": best[(int(doc), group)][1], "shingles": int(sizes[doc]), "shared": best[(int(doc), group)][0], "by_group": {g: round(float(scores[doc, i]), 4) for i, g in enumerate(groups) if scores[doc, i]}}) decisions.sort(key=lambda d: (-d["containment"], d["id"])) kept_rows = [row for row, dropped in zip(rows, drop) if not dropped] kept_sidecar = [line for line, dropped in zip(sidecar, drop) if not dropped] stats.update(release_stats(kept_rows, kept_sidecar)) stats["split_rows"] = cut["split_rows"] stats["drop_short"] = cut["drop_short"] stats["drop_dup"] += cut["drop_dup"] stats["trailer_cut"] = dict(cut) stats["drop_cross_source_dup"] = int(drop.sum()) stats["cross_source_dedup"] = { "drop_at": DROP_AT, "report_at": REPORT_AT, "shingle_words": 5, "input_sha256": INPUT_SHA256, "reference_sha256": {source: sha for source, (_, sha) in references.items()}, "no_shingles": int((sizes == 0).sum()), "dropped_by_best_group": dict(sorted(Counter(d["ref_group"] for d in decisions if d["action"] == "drop").items())), "dropped_by_year": dict(sorted(Counter(d["created"][:4] for d in decisions if d["action"] == "drop").items())), "dropped_by_shingles": {label: sum(d["action"] == "drop" and lo <= d["shingles"] < hi for d in decisions) for label, lo, hi in SIZE_BUCKETS}, "kept_partial": sum(d["action"] == "keep_partial" for d in decisions), "outcomes": outcomes(scores, groups) if groups else {}, } drops = ("drop_after_end", "drop_before_start", "drop_dup", "drop_short", "drop_cross_source_dup") if stats["read"] + stats["split_rows"] - sum(stats[k] for k in drops) != stats["kept"]: raise SystemExit("stats drop counts do not add up to the kept rows") replace_all({ out_dir / f"{SOURCE}.parquet": lambda p: pq.write_table( pa.Table.from_pylist(kept_rows, schema=table.schema), p, compression="zstd", row_group_size=ROW_GROUP_SIZE), out_dir / f"{SOURCE}.attribution.jsonl": lambda p: p.write_text( "".join(json.dumps(line, ensure_ascii=False, sort_keys=True) + "\n" for line in kept_sidecar), encoding="utf-8"), out_dir / DECISIONS: lambda p: p.write_text( "".join(json.dumps(d, ensure_ascii=False) + "\n" for d in decisions), encoding="utf-8"), out_dir / f"{SOURCE}.stats.json": lambda p: p.write_text( json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"), }) return stats def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--data", type=Path, default=DATA, help="directory holding the (restored) input files; outputs are written there") parser.add_argument("--workers", type=int, default=os.cpu_count() or 1) args = parser.parse_args() print(json.dumps(build(args.data, REFERENCES, args.data, args.workers), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()