polish-dynaword / src /clean_plwiki_talk.py
ppuzio's picture
plwiki_user_talk: label each record CC-BY-SA-3.0 or 4.0 by last revision (v2#57) (#93)
6fce4bd
Raw History Blame Contribute Delete
4.45 kB
#!/usr/bin/env python3
"""Label the committed plwiki talk releases per record: CC-BY-SA-3.0 or CC-BY-SA-4.0 by last revision.
v0.2.5 labelled every row CC-BY-SA-4.0. Text contributed under the 2014 Wikimedia Terms of Use is
CC BY-SA 3.0, so a page whose last revision predates 2023-06-07 is now labelled CC-BY-SA-3.0, by the
rule the wikipedia shard uses (rights.license_for_revision; v0.2.6 rights audit,
slayerlabs/polish-dynaword-v2#57). The dump is not re-read: each row's label comes from
`last_revision_at` in <source>.attribution.jsonl, the timestamp the build read from the dump.
Rewritten in place: the Parquet `license` column, the attribution `license` and `license_evidence`,
the sample `license`, stats `license_counts`, and every entry of <source>.checksums.json (computed
last, so edit NOTICE.md and the card first). Text, ids and every other column are unchanged; each
JSON file keeps its line ending (the committed ones use CRLF).
Fails if the attribution rows are not the Parquet rows in order, if a row's `created` is not its
last-revision date, or if a row already carries a label other than CC-BY-SA-4.0 or its new one.
Rerunning on relabelled data changes nothing.
python3 src/clean_plwiki_talk.py plwiki_talk
python3 src/clean_plwiki_talk.py plwiki_user_talk
"""
from __future__ import annotations
import argparse
from collections import Counter
from pathlib import Path
import sys
import pyarrow as pa
import pyarrow.parquet as pq
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_plwiki_talk_pl import LICENSE_EVIDENCE, digest, load, read_lines, save, write_lines # noqa: E402
from rights import license_for_revision # noqa: E402
DATA = Path(__file__).resolve().parents[1] / "data"
SOURCES = ("plwiki_talk", "plwiki_user_talk")
OLD_LABEL = "CC-BY-SA-4.0" # v0.2.5: one label for every row
def relabel(table: pa.Table, attribution: list[dict]) -> pa.Table:
"""`table` with each row's `license` set from its attribution record's last revision."""
if table["id"].to_pylist() != [item["id"] for item in attribution]:
raise ValueError("attribution rows are not the Parquet rows in order")
labels = []
for created, current, item in zip(table["created"].to_pylist(), table["license"].to_pylist(), attribution):
if created != item["last_revision_at"][:10]:
raise ValueError(f"{item['id']}: created {created!r} is not the last revision {item['last_revision_at']!r}")
label = license_for_revision(item["last_revision_at"])
if current not in (OLD_LABEL, label):
raise ValueError(f"{item['id']}: unexpected label {current!r} (new label {label!r})")
labels.append(label)
return table.set_column(table.column_names.index("license"), "license", pa.array(labels, pa.string()))
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 main(source: str) -> None:
folder = DATA / source
def path(suffix):
return folder / f"{source}.{suffix}"
attribution = read_lines(path("attribution.jsonl"))
table = relabel(pq.read_table(path("parquet")), attribution)
pq.write_table(table, path("parquet"), compression="zstd")
labels = dict(zip(table["id"].to_pylist(), table["license"].to_pylist()))
for item in attribution:
item["license"] = labels[item["id"]]
item["license_evidence"] = LICENSE_EVIDENCE[item["license"]]
keep_line_ending(write_lines, path("attribution.jsonl"), attribution)
sample = read_lines(path("sample.jsonl"))
for row in sample:
row["license"] = labels[row["id"]]
keep_line_ending(write_lines, path("sample.jsonl"), sample)
stats = load(path("stats.json"))
stats["license_counts"] = dict(Counter(labels.values()))
keep_line_ending(save, path("stats.json"), stats)
checksums = load(path("checksums.json"))
keep_line_ending(save, path("checksums.json"), {name: digest((folder / name).read_bytes()) for name in checksums})
print(source, stats["license_counts"])
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("source", choices=SOURCES)
main(parser.parse_args().source)