#!/usr/bin/env python3 """Drop Global Voices posts republished from partner outlets (slayerlabs/polish-dynaword-v2#50). Global Voices licenses "content created by Global Voices" under CC BY 3.0. Posts it republished from partner outlets (PRI's The World, Hong Kong Free Press, The Stand News, Meta.mk, 350.org, The Irrawaddy, ...) under content-sharing agreements or with permission stay the partner's work, so the CC BY grant does not demonstrably cover them. Each such post carries an editorial note in its first or last lines, e.g. "Ten artykuł ... pierwotnie ukazał się na portalu PRI.org ... i jest publikowany ponownie w ramach umowy o wymianie treści". `note_rules()` finds those notes. Kept on purpose: posts that GV contributors cross-posted from their own blogs, posts GV wrote for the ISN partnership, partner organisations writing directly for GV with no republication note, and photo-only permission credits ("Zdjęcie ..., użyte za pozwoleniem"). The input is the Parquet and sidecar as of v0.2.5 (the Parquet is unchanged since), pinned by SHA-256. Restore them before a rerun: git checkout 92b36dc -- data/global_voices/global_voices.parquet data/global_voices/global_voices.attribution.jsonl python3 src/clean_global_voices.py """ from __future__ import annotations import argparse import hashlib import json import os import re from collections import Counter from pathlib import Path import pyarrow.parquet as pq SOURCE = "global_voices" ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "data" / SOURCE INPUT_SHA256 = { f"{SOURCE}.parquet": "1ca02fdb6bad32b20757ddcd9b9f072056ff35b68c487143138cc7912b3a45c3", f"{SOURCE}.attribution.jsonl": "ab8ad393c4453524c4f3d7fe89157bfca1d9f66f2a735815f3b1ebd405c8fa13", } # The contributed release (PR #7) read 2,044 records and dropped 4 short ones before the v0.2.5 input. READ, DROP_SHORT = 2044, 4 # Editorial notes sit in the lede or the closing lines; the body quotes and reports on # agreements, first publications and permissions far too often to search it. HEAD, TAIL = 700, 350 # Sentence ends before an upper-case start or at a paragraph break, so "umowy dot. współdzielenia" holds. SENTENCE = re.compile(r"(?<=[.!?])\s+(?=[^\sa-ząćęłńóśźż])|\s*\n+\s*") PUB = r"(?:opublik|publik|ukaza|ukazuj|pojawi|przedruk|zamieszcz|udostępni|reprodukow|wydan)\w*" FIRST = r"(?:pierwotnie|oryginalnie|orginalnie|po\s+raz\s+pierwszy|pierwszy\s+raz|początkowo|uprzednio|wcześniej|najpierw|w\s+oryginale)" NOT_GV = r"(?!Global\s*Voices|GV\b|globalvoices|ramach|naszym|niniejszym|tym\b)" # A note speaks about the post itself: "Ten artykuł ...", "Poniżej publikujemy zredagowaną wersję artykułu ...", # "Jest to trzecia odsłona historii ...", "Opublikowano za zgodą PRI". SELF = re.compile( r"^\W*(?:\S+\s+){0,2}?(?:artykuł|tekst|post|wpis|histori|reportaż|wywiad|wiadomoś|wersj|seri|częś|materiał|opowieś|esej|treś)\w{0,3}\b" rf"|^\W*(?:Jest|Są)\s+to\b|^\W*(?:\S+\s+)?{PUB}", re.I) GV = re.compile(r"\bGV\b|Global\s*Voices|Rising\s*Voices", re.I) # Photo, art and video credits ("Zdjęcie: ... Opublikowano za zgodą.") are not text republications; # their sentences do not open with a text noun, and a bare permission line right after one belongs to it. IMAGE = r"zdj[eę]ci|zdjęć|fotograf|\bfot\.|ilustracj|obraz|grafik|wideo|\bfilm|nagrani|plakat|rysun|karykatur|okład|zrzut|\bmap" CREDIT = re.compile(rf"^\W*(?:\S+\s+)?\S*?(?:{IMAGE})", re.I) # an image is the subject RULES = { # "w ramach umowy o wymianie treści", "na mocy porozumienia o dzieleniu się treściami", # "umowy partnerskiej", "porozumienie z Global Voices" "agreement": re.compile( r"\b(?:umow|porozumie)\w*\s+(?:\w+\s+){0,3}?(?:o\s+|dot\.\s*|dotycząc\w*\s+|w\s+sprawie\s+)?" r"(?:wymian|udostępn|dzieleni|współdziel|podzia|rozpowszechn|partnersk|partnerstw)\w*" r"|\bporozumieni\w*\s+z\s+Global\s+Voices", re.I), # "w ramach partnerstwa pomiędzy PRI i Global Voices", "w ramach naszej współpracy z Syria Deeply", # "post partnerski ze strony EurasiaNet.org" "partnership": re.compile( r"(?:w\s+ramach|na\s+mocy|na\s+podstawie|jako\s+część)\s+(?:\w+\s+){0,2}?(?:partnerstw|współprac)\w*\s+" r"(?:\w+\s+){0,3}?(?:z|pomiędzy|między)\s" r"|\bpost\w*\s+partnersk\w*|\bpartnersk\w*\s+post\w*", re.I), # "pierwotnie ukazał się na portalu PRI.org", "pojawił się po raz pierwszy na stronie CHRI", # "Oryginalny tekst [ru] dostępny na stronie Teplicy" "originally": re.compile( rf"{FIRST}\s+(?:\S+\s+){{0,6}}?(?:{PUB}|ujrzał\w*)|{PUB}\s+(?:\S+\s+){{0,2}}?{FIRST}" r"|oryginaln\w*\s+(?:\[\w+\]\s+)?(?:wersj|tekst|artykuł|publikacj)\w*", re.I), # "Ta republikacja", "jest tutaj reprodukowany", "poniższa reedycja" "republished": re.compile(r"\brepublikacj\w*|reprodukowan\w*|przedrukowan\w*|reedycj\w*", re.I), # "napisany przez Fentona Lutunatabua dla 350.org", "artykułu napisanego przez Irinę Illa Pueyo dla Afroféminas" "written_for": re.compile(rf"napisan\w*\s+(?:\S+\s+){{0,6}}?dla\s+{NOT_GV}", re.I), # "Artykuł został opublikowany na stronie internetowej Agência Pública", "część artykułu opublikowanego na łamach The Stand News" "published_by": re.compile( rf"(?:artykuł|tekst|post|wpis|histori|reportaż|wywiad|wiadomoś|wersj|seri)\w*\s+(?:\S+\s+){{0,8}}?" rf"(?:opublikowan|publikowan|ukazał|pojawił)\w*\s+(?:\S+\s+){{0,3}}?" rf"(?:na\s+stronie|na\s+łamach|na\s+portalu|w\s+serwisie|na\s+blogu|przez|w)\s+{NOT_GV}", re.I), # "Opublikowano za zgodą PRI", "Opublikowany za pozwoleniem." (the author's or artist's own consent is not a partner's) "permission": re.compile( rf"{PUB}\s+(?:\S+\s+){{0,6}}?(?:za|ze|z)\s+(?:\S+\s+)?(?:zgodą|pozwoleniem|przyzwoleniem)(?!\s+(?:autor|artyst))", re.I), # Freemuse co-commissions: "may be republished by non-commercial media" conflicts with CC BY "non_commercial": re.compile(r"niekomercyjn\w*\s+medi|non-commercial\s+media", re.I), } # Rules that fire only on a sentence about the post itself that does not name Global Voices, # so news reporting ("raport opublikowany przez UNESCO") and GV's own projects do not count. SELF_RULES = {"originally", "republished", "written_for", "published_by", "permission"} # Notes a rule matches that are not partner republications, checked by hand against the text # and, where unclear, the English original on globalvoices.org. OWN_BLOG = "the GV author's cross-post from their own blog" ISN = "written by GV for the ISN blog under the GV-ISN partnership" KEEP = { **{f"global_voices_{n}": OWN_BLOG + " (Juan Arellano, Globalizado)" for n in (7749, 11971, 18309, 20340, 21612, 22399, 25101)}, "global_voices_1420": OWN_BLOG + " (Georgia Popplewell, Caribbean Free Radio)", "global_voices_23554": OWN_BLOG + " (Elia Ayoub, Hummus For Thought)", "global_voices_28150": OWN_BLOG + " (Jillian C. York)", "global_voices_28814": OWN_BLOG + " (Anca Matioc, Medium)", "global_voices_29905": OWN_BLOG + " (Derek Lackaff, r12n)", **{f"global_voices_{n}": ISN for n in (13370, 14712, 14881, 14946, 15662, 17435, 18724)}, "global_voices_3210": "a GV post that Ezhednevny Zhurnal republished, not the reverse", "global_voices_15986": "dates GV's own English original", "global_voices_22228": "dates GV's own English original", "global_voices_8": "news about an AOL partnership deal", "global_voices_14503": "news: a quoted blogger's posts also ran in The Guardian", "global_voices_15837": "news: interviews published on the Mujeres Mundi blog", } # Partner republications whose note no rule matches. DROP = { "global_voices_21466": "Agência Pública; a long quoted title splits the note", "global_voices_27005": "inmediahk.net; the note follows a 1,000-character lede", "global_voices_32352": "based on two Meta.mk / CriThink.mk (Metamorphosis Foundation) texts", } def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest() def note_zone(text: str) -> str: return text if len(text) <= HEAD + TAIL else text[:HEAD] + "\n" + text[-TAIL:] def note_rules(text: str) -> list[str]: """Names of the rules whose pattern matches a sentence in the post's opening or closing lines.""" hits = [] previous = "" for sentence in SENTENCE.split(note_zone(text)): about_post = SELF.search(sentence) and not GV.search(sentence) and not CREDIT.search(sentence) for name, rule in RULES.items(): if name in hits or (name in SELF_RULES and not about_post): continue if name == "permission" and re.search(IMAGE, previous, re.I): continue if rule.search(sentence): hits.append(name) previous = sentence return hits def reason(doc_id: str, text: str) -> str | None: """Why a row is dropped (rule names, or the DROP note), or None to keep it.""" if doc_id in DROP: return "listed: " + DROP[doc_id] if doc_id in KEEP: return None hits = note_rules(text) return "+".join(hits) if hits else None def build(input_dir: Path, out_dir: Path) -> dict: parquet, sidecar = (input_dir / name for name in INPUT_SHA256) for path, expected in zip((parquet, sidecar), INPUT_SHA256.values()): if sha256(path) != expected: raise SystemExit(f"{path} is not the v0.2.5 input; restore it with the command in this script's docstring") table = pq.read_table(parquet) lines = sidecar.read_text(encoding="utf-8").splitlines(keepends=True) ids = table.column("id").to_pylist() sidecar_ids = [json.loads(line)["id"] for line in lines] if len(set(ids)) != len(ids) or set(ids) != set(sidecar_ids) or len(sidecar_ids) != len(ids): raise SystemExit("Parquet and attribution sidecar do not cover the same ids") if stale := (KEEP.keys() | DROP.keys()) - set(ids): raise SystemExit(f"KEEP/DROP name ids that are not in the input: {sorted(stale)}") rows = table.to_pylist() dropped = {row["id"]: why for row in rows if (why := reason(row["id"], row["text"]))} kept = [row for row in rows if row["id"] not in dropped] rules = Counter(name for why in dropped.values() if not why.startswith("listed: ") for name in why.split("+")) stats = { "read": READ, "kept": len(kept), "drop_short": DROP_SHORT, "drop_lang": 0, "drop_dup": 0, "drop_ocr": 0, "drop_partner_republication": len(dropped), "chars": sum(len(r["text"]) for r in kept), "tokens": sum(r["token_count"] for r in kept), "licenses": dict(Counter(r["license"] for r in kept)), "authors_with_value": sum(bool(r["author"]) for r in kept), "stats_recomputed_from_parquet": True, "partner_republication": { "by_rule": dict(sorted(rules.items())), "listed": sum(why.startswith("listed: ") for why in dropped.values()), "kept_by_hand": len(KEEP), }, "input_sha256": INPUT_SHA256, } staged = { out_dir / f"{SOURCE}.parquet.tmp": lambda p: pq.write_table( table.from_pylist(kept, schema=table.schema), p, compression="zstd"), out_dir / f"{SOURCE}.attribution.jsonl.tmp": lambda p: p.write_text( "".join(line for line, i in zip(lines, sidecar_ids) if i not in dropped), encoding="utf-8"), out_dir / f"{SOURCE}.stats.json.tmp": lambda p: p.write_text( json.dumps(stats, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"), } for path, write in staged.items(): write(path) for path in staged: os.replace(path, path.with_suffix("")) return {**stats, "dropped": dropped} def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--input", type=Path, default=DATA, help="directory holding the v0.2.5 Parquet and sidecar") parser.add_argument("--out", type=Path, default=DATA) args = parser.parse_args() print(json.dumps(build(args.input, args.out), indent=2, ensure_ascii=False)) if __name__ == "__main__": main()