Datasets:
Download src/clean_1000_novels.py from SlayerLab/polish-dynaword: direct link, hf CLI and curl.
- Browser
- Download file 9.99 kB
-
https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/0783e5eb1e2eda3aab5edd4f76c7f85910e7ff3d/src/clean_1000_novels.py
- Command line
-
hf download hf://datasets/SlayerLab/polish-dynaword@0783e5eb1e2eda3aab5edd4f76c7f85910e7ff3d/src/clean_1000_novels.py
-
curl -L -o clean_1000_novels.py https://huggingface.co/datasets/SlayerLab/polish-dynaword/resolve/0783e5eb1e2eda3aab5edd4f76c7f85910e7ff3d/src/clean_1000_novels.py
9.99 kB
| #!/usr/bin/env python3 | |
| """Rebuild `1000_novels` as its public-domain subset with per-row attribution. | |
| CLARIN-PL replied (October 2026) that handle 11321/312 holds metadata only: CLARIN does not | |
| distribute the texts and holds no rights documentation, so no licence covers them. A row is | |
| kept only when the per-text rights screen finds it public domain in Poland: | |
| polish-dynaword-v2/evidence/1000_novels_rights_screen.csv | |
| (written by polish-dynaword-v2/scripts/novels_rights_screen.py) | |
| Kept rows are labelled `public-domain`, and `author` credits the author and any translator. | |
| Title, death year, screen basis and CLARIN file name go to `1000_novels.attribution.jsonl`. | |
| The input is the v0.2.5 Parquet and the screen CSV, both pinned by SHA-256. Restore the Parquet | |
| before a rerun: | |
| git checkout v0.2.5 -- data/1000_novels/1000_novels.parquet | |
| python3 src/clean_1000_novels.py --screen ../polish-dynaword-v2/evidence/1000_novels_rights_screen.csv | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import unicodedata | |
| from collections import Counter | |
| from pathlib import Path | |
| import pyarrow.parquet as pq | |
| SOURCE = "1000_novels" | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA = ROOT / "data" / SOURCE | |
| INPUT_SHA256 = "27be09e5e2347dcf1a83e94b6c210ca26bdd89365bc3563e88ea5af9846990ea" # v0.2.5 | |
| # polish-dynaword-v2 evidence/1000_novels_rights_screen.csv for v0.2.6; also in 1000_novels.license-evidence.json | |
| SCREEN_SHA256 = "7fefc75f8fcbd07e5ec98842276765ffef9520b6acb4e24b4751c67cc3d2081c" | |
| UPSTREAM = "https://clarin-pl.eu/dspace/handle/11321/312" | |
| LICENSE = "public-domain" | |
| KEEP = {"pd_by_term"} | |
| SCREENS = KEEP | {"in_copyright", "unresolved"} | |
| # Read off each text's header by hand where the rules below fail: no header, a dedication | |
| # ("H. K. T."), a series title (Proust), a title broken over lines, or a misspelt file name. | |
| TITLES = { | |
| "conrad_murzyn-z-zalogi-narcyza_1923.txt": "Murzyn z załogi „Narcyza”", | |
| "orzeszkowa_pan-graba_czesc1_1872.txt": "Pan Graba", | |
| "proust_w-cieniu-zakwitajacych-dziewczat_tom-I_1937.txt": "W cieniu zakwitających dziewcząt", | |
| "proust_w-cieniu-zakwitajacych-dziewczat_tom-II_1937.txt": "W cieniu zakwitających dziewcząt", | |
| "proust_w-cieniu-zakwitajacych-dziewczat_tom-III_1937.txt": "W cieniu zakwitających dziewcząt", | |
| "prus_co-sie-z-wielkiej-idei-zrobilo-w-malym-miasteczku.txt": "Co się z wielkiej idei zrobiło w małem miasteczku", | |
| "prus_piesn-swiata_1935.txt": "Pleśń świata", | |
| "puszkin_basn-o-krolu-saltanie_1924.txt": | |
| "Baśń o królu Sałtanie, o jego synu, słynnym i potężnym bohaterze Gwidonie, i o pięknej królewnie Łabędziu", | |
| "reymont_wampir.txt": "Wampir", | |
| "sienkiewicz_bajka1.txt": "Bajka", | |
| "sienkiewicz_bajka3.txt": "Bajka", | |
| "sienkiewicz_jako-sie-pan-lubomirski-nawrocil-kosciol-w-tarnowie-zbudowal_1931.txt": | |
| "Jako się pan Lubomirski nawrócił i kościół w Tarnawie zbudował", | |
| "verne_przygody-trzech-rosjan-i-trzech-anglikow-w-poludniowej-afryce_1883.txt": | |
| "Przygody trzech Rossyan i trzech Anglików w południowej Afryce", | |
| "zapolska_papuzia_1958.txt": "Papuzia", | |
| "zeromski_popioly.txt": "Popioły", | |
| "zulawski_list-senki-do-lucjusza_1914.txt": "List Seneki do Lucyljusza", | |
| "zulawski_z-domu-ojcow_1897.txt": "Z domu ojców", | |
| } | |
| NOT_A_TITLE = re.compile(r"^(tłum|tłumacz|przekład|rozdział|tom|księga|[IVXLC]+\.?$|\d+\.?$)", re.I) | |
| 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 fold(text: str) -> str: | |
| """ASCII slug as in CLARIN file names: `Śpiewak spod strzechy` -> `spiewak-spod-strzechy`.""" | |
| text = text.replace("ł", "l").replace("Ł", "L") | |
| text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower() | |
| return re.sub(r"[^a-z0-9]+", "-", text).strip("-") | |
| def file_slug(clarin_file: str) -> str: | |
| """`sienkiewicz_krzyzacy_tom-II_1900.txt` -> `krzyzacy_tom-II` folded.""" | |
| parts = clarin_file.removesuffix(".txt").split("_")[1:] | |
| if parts and re.fullmatch(r"\d{4}", parts[-1]): | |
| parts = parts[:-1] | |
| return fold(" ".join(parts)) | |
| def header_lines(text: str, limit: int = 8) -> list[str]: | |
| lines = [] | |
| for line in re.split(r"[\r\n]+", text[:3000]): | |
| line = line.strip().lstrip("<").strip() | |
| if line: | |
| lines.append(line) | |
| if len(lines) == limit: | |
| break | |
| return lines | |
| def tidy(title: str) -> str: | |
| return re.sub(r"\s+", " ", title).strip(" .\t") | |
| def title_of(text: str, clarin_file: str, author: str) -> tuple[str, str]: | |
| """(title, how): `manual` = TITLES; `file` = header words that fold to the file-name slug | |
| (V against the file name); `position` = the line next to the author line (I); `none`.""" | |
| if clarin_file in TITLES: | |
| return TITLES[clarin_file], "manual" | |
| slug = file_slug(clarin_file) | |
| lines = header_lines(text) | |
| for i in range(len(lines)): | |
| for span in (1, 2, 3): # titles broken over lines: "...kościół w Tarnawie" / "zbudował" | |
| if fold(" ".join(lines[i:i + span])) == slug: | |
| return tidy(" ".join(lines[i:i + span])), "file" | |
| words = lines[i].split() # "Kalosze szczęścia (tłum. Mirandola)/1. Początek" | |
| for n in range(1, len(words)): | |
| if fold(" ".join(words[:n])) == slug: | |
| return tidy(" ".join(words[:n])), "file" | |
| keys = {fold(clarin_file.split("_")[0]), fold(author.split()[-1])} | |
| def is_author(line: str) -> bool: | |
| return len(line.split()) <= 6 and any(k and k in fold(line) for k in keys) | |
| if len(lines) > 1: | |
| for author_at, title_at in ((0, 1), (1, 0)): | |
| candidate = lines[title_at] | |
| if is_author(lines[author_at]) and not is_author(candidate) and not NOT_A_TITLE.match(candidate): | |
| return tidy(candidate), "position" | |
| return "", "none" | |
| def credit(author: str, translator: str) -> str: | |
| return f"{author} (tłum. {translator})" if translator else author | |
| def build(input_path: Path, screen_path: Path, out_dir: Path) -> dict: | |
| if (found := sha256(screen_path)) != SCREEN_SHA256: | |
| raise SystemExit(f"{screen_path} is not the pinned rights screen: SHA-256 {found}, expected " | |
| f"{SCREEN_SHA256}; regenerate it with polish-dynaword-v2/scripts/novels_rights_screen.py " | |
| "or update SCREEN_SHA256 and 1000_novels.license-evidence.json together") | |
| if sha256(input_path) != INPUT_SHA256: | |
| raise SystemExit(f"{input_path} is not the v0.2.5 Parquet; restore it with " | |
| "`git checkout v0.2.5 -- data/1000_novels/1000_novels.parquet`") | |
| table = pq.read_table(input_path) | |
| with screen_path.open(encoding="utf-8", newline="") as stream: | |
| screen = {row["id"]: row for row in csv.DictReader(stream)} | |
| ids = table.column("id").to_pylist() | |
| if set(ids) != set(screen) or len(ids) != len(set(ids)): | |
| raise SystemExit("rights screen and Parquet do not cover the same ids") | |
| if unknown := {row["screen"] for row in screen.values()} - SCREENS: | |
| raise SystemExit(f"unknown screen values: {unknown}") | |
| kept, attribution = [], [] | |
| for row in table.to_pylist(): | |
| rights = screen[row["id"]] | |
| if rights["screen"] not in KEEP: | |
| continue | |
| title, how = title_of(row["text"], rights["clarin_file"], rights["author"]) | |
| kept.append({**row, "license": LICENSE, "author": credit(rights["author"], rights["translator"])}) | |
| attribution.append({ | |
| "id": row["id"], "author": rights["author"], "author_died": rights["author_died"], | |
| "translator": rights["translator"], "title": title, "title_from": how, | |
| "clarin_file": rights["clarin_file"], "upstream": UPSTREAM, | |
| "license": LICENSE, "screen": rights["screen"], "basis": rights["basis"], | |
| }) | |
| if stale := TITLES.keys() - {a["clarin_file"] for a in attribution}: | |
| raise SystemExit(f"TITLES names files that are not kept: {sorted(stale)}") | |
| stats = { | |
| "read": len(ids), "kept": len(kept), "drop_rights": len(ids) - len(kept), | |
| "drop_short": 0, "drop_lang": 0, "drop_dup": 0, "drop_ocr": 0, | |
| "chars": sum(len(r["text"]) for r in kept), "tokens": sum(r["token_count"] for r in kept), | |
| "licenses": {LICENSE: len(kept)}, "authors_with_value": sum(bool(r["author"]) for r in kept), | |
| "license": LICENSE, "screen": dict(Counter(r["screen"] for r in screen.values())), | |
| "titles": dict(Counter(a["title_from"] for a in attribution)), | |
| "input_sha256": INPUT_SHA256, "screen_sha256": SCREEN_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(json.dumps(a, ensure_ascii=False) + "\n" for a in attribution), 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 | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| parser.add_argument("--input", type=Path, default=DATA / f"{SOURCE}.parquet") | |
| parser.add_argument("--screen", type=Path, required=True, help="1000_novels_rights_screen.csv") | |
| parser.add_argument("--out", type=Path, default=DATA) | |
| args = parser.parse_args() | |
| print(json.dumps(build(args.input, args.screen, args.out), indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |