polish-dynaword / src /clean_plwiki_talk.py
ppuzio's picture
v0.2.6 errata: corrections to the notes, cards and scripts (no data change) (#219)
44a5f97
Raw History Blame Contribute Delete
14.6 kB
#!/usr/bin/env python3
"""Clean and relabel the committed plwiki talk releases in place, without re-reading the dump.
retext: applies fetch_wikimedia.drop_residue to the text as the builders now do, keeping
the category lines, which the talk pages discuss. A changed row gets its tokens recounted; one that
falls under MIN_TEXT_CHARS is dropped as `too_little_text_after_residue_cleanup`, and one whose
cleaned text repeats an earlier kept row's (the builders' candidate order and key) as
`normalized_duplicate`, as a rebuild would. Rewrites the parquet, the decisions (the changed rows'
`characters` and `letter_ratio`, the dropped rows' reason), the attribution (dropped rows out,
`text_sha256`, the residue step in `transformations`), the sample rows that remain, stats and qa
(`source_text_qa_rejected`, `residue_cleanup`). Near-duplicates are not re-traced: the rejected
rows' decisions stay the build's.
relabel: labels each row by contribution from wiki_history.py compare's labels, as the
wikipedia shard is: text added before 2023-06-07 keeps CC-BY-SA-3.0, a page created from that day
is CC-BY-SA-4.0, a page with text from both sides carries both ("CC-BY-SA-3.0 AND CC-BY-SA-4.0").
Rewrites the parquet `license` column, the attribution (wiki_history.apply_labels and
`license_evidence`), the sample `license`, stats `license_counts` and qa `licence_labels` (the stub
dump and the cases). A rebuild labels by last revision, so relabel follows it.
provenance: adds each record's `citations` (fetch_wikimedia.page_sources: the <ref> bodies and
Cytuj*/Cite* templates of the page's wikitext, each through the builders' redact_pii) and `source_notes` (empty: no
talk-page template says where text came from), read again from the build's pages-meta-current dump, whose shards
must be in --dumps. A record whose page is missing from the dump, or whose revision there is not the shipped one
(revision id, timestamp, wikitext length), stops it. qa.json `citations` records the counts and redactions.
It does both sources in one pass over the dump.
All write <source>.checksums.json last, so edit NOTICE.md and the card first (rerunning refreshes
it). Each JSON file keeps its line ending (the committed ones use CRLF); rerunning changes nothing.
python3 src/clean_plwiki_talk.py retext plwiki_talk
python3 src/wiki_history.py compare --source plwiki_talk ... --out OUT/plwiki_talk.labels.jsonl
python3 src/clean_plwiki_talk.py relabel plwiki_talk --labels OUT/plwiki_talk.labels.jsonl \\
--stub OUT/plwiki-20261001-stub-meta-history.xml.gz.json
python3 src/clean_plwiki_talk.py provenance --dumps DUMPS/plwiki-20260901
"""
from __future__ import annotations
import argparse
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import sys
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_plwiki_talk_pl import ( # noqa: E402
LICENSE_EVIDENCE, MIN_TEXT_CHARS, digest, exact_key, iter_pages, load, read_lines, redact_pii, save, write_lines)
from fetch_wikimedia import drop_residue, page_sources # noqa: E402
from wiki_history import WIKIS, apply_labels # noqa: E402
DATA = Path(__file__).resolve().parents[1] / "data"
SOURCES = ("plwiki_talk", "plwiki_user_talk") # both builders keep MIN_TEXT_CHARS = 500
STEP = "file-link residue removal" # the builders' `transformations` entry
def keep_line_ending(write, path: Path, value) -> None:
"""write(path, value), then restore CRLF if the file used it before (JSON escapes newlines in values)."""
crlf = b"\r\n" in path.read_bytes()
write(path, value)
if crlf:
path.write_bytes(path.read_bytes().replace(b"\n", b"\r\n"))
def write_parquet(table: pa.Table, path: Path) -> None:
groups = pq.ParquetFile(path).metadata.row_group(0).num_rows # the release's row groups, kept
pq.write_table(table, path, compression="zstd", row_group_size=groups)
def retext(folder: Path, source: str) -> None:
import tiktoken
def path(suffix):
return folder / f"{source}.{suffix}"
table = pq.read_table(path("parquet"))
ids, old = table["id"].to_pylist(), table["text"].to_pylist()
new = [drop_residue(text, categories=False) for text in old]
changed = [n for n, (a, b) in enumerate(zip(old, new)) if a != b]
if not changed:
print(f"{source}: text already clean")
return
decisions = read_lines(path("decisions.jsonl"))
attribution = read_lines(path("attribution.jsonl"))
if [d["id"] for d in decisions if d["selected"]] != ids or [a["id"] for a in attribution] != ids:
raise ValueError("the selected decisions and the attribution are not the parquet rows in order")
enc = tiktoken.get_encoding("cl100k_base")
tokens = table["token_count"].to_pylist()
for n in changed:
tokens[n] = len(enc.encode_ordinary(new[n]))
short = {ids[n]: len(new[n]) for n in changed if len(new[n]) < MIN_TEXT_CHARS}
first, dup_of = {}, {} # equal cleaned texts: the first in candidate (= parquet) order stays, as in the build
for i, text in zip(ids, new):
if i not in short:
if (key := exact_key(text)) in first:
dup_of[i] = first[key]
else:
first[key] = i
gone = short.keys() | dup_of.keys()
before = {"docs": len(ids), "chars": sum(map(len, old)), "tokens": sum(table["token_count"].to_pylist())}
table = table.set_column(table.column_names.index("text"), "text", pa.array(new, pa.string()))
table = table.set_column(table.column_names.index("token_count"), "token_count", pa.array(tokens, pa.int64()))
table = table.filter(pa.array([i not in gone for i in ids]))
write_parquet(table, path("parquet"))
after = {"docs": table.num_rows, "chars": sum(len(new[n]) for n, i in enumerate(ids) if i not in gone),
"tokens": pc.sum(table["token_count"]).as_py()}
by_id = {d["id"]: d for d in decisions}
for n in changed:
d = by_id[ids[n]]
letters = round(d["letter_ratio"] * d["characters"]) # the builders count letters before the cleanup
d.update(characters=len(new[n]), letter_ratio=letters / max(len(new[n]), 1))
for i in short:
by_id[i].update(selected=False, reason="too_little_text_after_residue_cleanup")
for i, of in dup_of.items():
by_id[i].update(selected=False, reason="normalized_duplicate", duplicate_of=of, jaccard=1.0)
keep_line_ending(write_lines, path("decisions.jsonl"), decisions)
text_of = {i: t for i, t in zip(ids, new) if i not in gone}
attribution = [a for a in attribution if a["id"] in text_of]
for a in attribution:
a["text_sha256"] = digest(text_of[a["id"]].encode("utf-8"))
if STEP not in a["transformations"]:
a["transformations"].append(STEP)
keep_line_ending(write_lines, path("attribution.jsonl"), attribution)
sample_ids = [row["id"] for row in read_lines(path("sample.jsonl")) if row["id"] in text_of]
rows = {row["id"]: row for row in table.filter(pc.is_in(table["id"], pa.array(sample_ids, pa.string()))).to_pylist()}
keep_line_ending(write_lines, path("sample.jsonl"), [rows[i] for i in sample_ids])
stats = load(path("stats.json"))
stats.update(kept=after["docs"], source_slice_kept=after["docs"], characters=after["chars"], tokens=after["tokens"],
license_counts=dict(Counter(table["license"].to_pylist())), sample_count=len(sample_ids))
keep_line_ending(save, path("stats.json"), stats)
qa = load(path("qa.json"))
qa["source_text_qa_rejected"] += len(gone)
qa["residue_cleanup"] = {
"step": "clean_plwiki_talk.py retext: fetch_wikimedia.drop_residue, category lines kept",
"rows_changed": len(changed), "before": before, "after": after,
"dropped_short": [{"id": i, "chars": chars} for i, chars in short.items()],
"dropped_duplicate": [{"id": i, "duplicate_of": of} for i, of in dup_of.items()],
# ponytail: a rebuild re-runs near-dedup on the cleaned text; only these counts say how far it could move
"not_retraced": {
"note": "near-duplicate decisions and rejected rows' characters are the build's",
"rejected_as_copies_of_dropped_rows": sum(d.get("duplicate_of") in gone for d in decisions
if not d["selected"] and d["id"] not in gone),
},
}
keep_line_ending(save, path("qa.json"), qa)
print(f"{source}: {len(changed)} rows cleaned, {len(short)} dropped under {MIN_TEXT_CHARS} chars, "
f"{len(dup_of)} as duplicates, {before} -> {after}")
def relabel(folder: Path, source: str, labels_path: Path, stub_path: Path) -> None:
def path(suffix):
return folder / f"{source}.{suffix}"
attribution = read_lines(path("attribution.jsonl"))
labels = read_lines(labels_path)
table = apply_labels(pq.read_table(path("parquet")), attribution, labels, source)
write_parquet(table, path("parquet"))
for a in attribution:
a["license_evidence"] = LICENSE_EVIDENCE[a["license"]]
keep_line_ending(write_lines, path("attribution.jsonl"), attribution)
label_of = {a["id"]: a["license"] for a in attribution}
sample = read_lines(path("sample.jsonl"))
for row in sample:
row["license"] = label_of[row["id"]]
keep_line_ending(write_lines, path("sample.jsonl"), sample)
stats = load(path("stats.json"))
stats["license_counts"] = dict(Counter(label_of.values()))
keep_line_ending(save, path("stats.json"), stats)
day = WIKIS[source]["cutoff"][:10]
qa = load(path("qa.json"))
qa["licence_labels"] = {
"stub": load(stub_path),
"cases": dict(Counter(lab["case"] for lab in labels)),
"created_on_cutoff_day": sum(lab["case"] == "created_after_cutoff" and lab["first_at"].startswith(day) for lab in labels),
}
keep_line_ending(save, path("qa.json"), qa)
print(source, stats["license_counts"])
def _shard_citations(job: tuple[Path, dict[str, str]]) -> dict[str, tuple]:
"""provenance's work on one dump shard: {pageid: (revid, timestamp, wikitext length, citations, redactions)}
for the pages in `wanted` (pageid: source)."""
path, wanted = job
found = {}
for pageid, _, _, revid, timestamp, _, text in iter_pages(path):
if (source := wanted.get(pageid)) is None:
continue
if pageid in found:
raise ValueError(f"page {pageid} twice in {path.name}")
cites, counts = [], Counter()
for cite in page_sources(source, text or "")[0]:
clean, redacted = redact_pii(cite) # the build redacts the text; the citations come from the raw wikitext
cites.append(clean)
counts.update(redacted)
found[pageid] = (revid, timestamp, len(text or ""), list(dict.fromkeys(cites)), counts)
return found
def provenance(data: Path, dumps: Path, sources=SOURCES, workers: int = 7) -> None:
sides = {source: read_lines(data / source / f"{source}.attribution.jsonl") for source in sources}
wanted = {rec["pageid"]: source for source, side in sides.items() for rec in side}
if len(wanted) != sum(map(len, sides.values())):
raise ValueError("a page id is on two rows")
shards = sorted({name for side in sides.values() for rec in side for name in rec["dump"]["files"]})
found = {}
with ProcessPoolExecutor(workers) as pool:
for part in pool.map(_shard_citations, [(dumps / name, wanted) for name in shards]):
if twice := found.keys() & part.keys():
raise ValueError(f"pages in two shards: {sorted(twice)[:5]}")
found.update(part)
for source, side in sides.items():
bad, redactions = [], Counter()
for rec in side:
if (page := found.get(rec["pageid"])) is None:
bad.append(f"{rec['id']}: not in the dump")
continue
revid, timestamp, chars, cites, counts = page
shipped = rec["permalink"] and rec["permalink"].rsplit("=", 1)[1] # null for a page deleted since
if shipped not in (None, revid) or (timestamp, chars) != (rec["last_revision_at"], rec["wikitext_chars"]):
bad.append(f"{rec['id']}: the dump has revision {revid} at {timestamp}, {chars} characters")
rec["citations"], rec["source_notes"] = cites, []
redactions.update(counts)
if bad:
raise ValueError(f"{source}: {len(bad)} rows do not match the dump: {bad[:5]}")
folder = data / source
keep_line_ending(write_lines, folder / f"{source}.attribution.jsonl", side)
qa = load(folder / f"{source}.qa.json")
qa["citations"] = {"shards": shards,
"rows_with_citations": sum(bool(rec["citations"]) for rec in side),
"citations": sum(len(rec["citations"]) for rec in side),
"redacted": {k: v for k, v in sorted(redactions.items()) if v}}
keep_line_ending(save, folder / f"{source}.qa.json", qa)
print(source, qa["citations"]["rows_with_citations"], qa["citations"]["citations"], qa["citations"]["redacted"])
def write_checksums(folder: Path, source: str) -> None:
path = folder / f"{source}.checksums.json"
keep_line_ending(save, path, {name: digest((folder / name).read_bytes()) for name in load(path)})
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
sub = parser.add_subparsers(dest="step", required=True)
sub.add_parser("retext").add_argument("source", choices=SOURCES)
rel = sub.add_parser("relabel")
rel.add_argument("source", choices=SOURCES)
rel.add_argument("--labels", type=Path, required=True, help="wiki_history.py compare's output")
rel.add_argument("--stub", type=Path, required=True, help="the stub dump's record (wiki_history.py download)")
sub.add_parser("provenance").add_argument("--dumps", type=Path, required=True, help="the build's dump shards")
args = parser.parse_args()
if args.step == "provenance":
provenance(DATA, args.dumps)
elif args.step == "retext":
retext(DATA / args.source, args.source)
else:
relabel(DATA / args.source, args.source, args.labels, args.stub)
for source in SOURCES if args.step == "provenance" else (args.source,):
write_checksums(DATA / source, source)
if __name__ == "__main__":
main()