#!/usr/bin/env python3 """Fetch the Polish ELTeC corpus (European Literary Text Collection, COST Action 'Distant Reading') into a SpeakLeash-style .jsonl.zst. ~100 Polish novels (1840-1920), level-1 TEI XML, released CC-BY. Directly sourced from GitHub. Usage: python3 src/fetch_eltec.py --out ~/Local/Ventures/Slayer/data/speakleash """ from __future__ import annotations import argparse, json, re, subprocess, time from pathlib import Path from urllib.request import urlopen, Request API = "https://api.github.com/repos/COST-ELTeC/ELTeC-pol/contents/level1" TEI = "{http://www.tei-c.org/ns/1.0}" XML_ID = "{http://www.w3.org/XML/1998/namespace}id" SEPARATOR = "\n\n" # between paragraphs # The one or kept in the text of a novel, by the xml:id of its element: POL0100 (MakuszyƄski, # "Po mlecznej drodze") opens with the author's address to the reader in ; POL0091 (Ć»eromski, "Dzieje # grzechu") ends with the author's draft passages (Dodatek) in . The title pages and the other # and parts stay out. RESTORED_PARTS = {"POL0100": "front", "POL0091": "back"} UA = {"User-Agent": "polish-dynaword/0.1 (+research; openly-licensed corpus)"} KEY = "eltec_pol" MIN_CHARS = 200 def _get(url, raw=False, tries=4): for i in range(tries): try: with urlopen(Request(url, headers=UA), timeout=60) as r: data = r.read() return data if raw else json.loads(data) except Exception: time.sleep(1.5 * (i + 1)) return None def _paragraph_elements(parent, inside_text=False): """(kind, element) in document order for every

under `parent`, nested ones too, and every that is not inside a

or a and holds no

(its text is in that paragraph already).""" for child in parent: if child.tag == f"{TEI}p": yield "p", child elif child.tag == f"{TEI}head" and not inside_text and child.find(f".//{TEI}p") is None: yield "head", child yield from _paragraph_elements(child, inside_text or child.tag in (f"{TEI}p", f"{TEI}head")) def tei_paragraphs(root): """The non-empty paragraphs of the reading text of a parsed TEI file as (kind, text), in reading order. kind is "p" for a

of , "head" for a of (a chapter title, in its place among the paragraphs), and "front" or "back" for each

and of the one or RESTORED_PARTS names for the file. Whitespace inside a paragraph is collapsed.""" restored = RESTORED_PARTS.get(root.get(XML_ID)) paragraphs = [] for section in ("front", "body", "back"): part = root.find(f".//{TEI}text/{TEI}{section}") if part is not None and section in ("body", restored): paragraphs += [(kind if section == "body" else section, re.sub(r"\s+", " ", " ".join(el.itertext())).strip()) for kind, el in _paragraph_elements(part)] return [(kind, text) for kind, text in paragraphs if text] def tei_to_text(xml_bytes): """Extract reading text (title + paragraphs, see tei_paragraphs) from a TEI file.""" from xml.etree.ElementTree import fromstring root = fromstring(xml_bytes) title_el = root.find(f".//{TEI}titleStmt/{TEI}title") title = (title_el.text or "").strip() if title_el is not None else "" return title, SEPARATOR.join(text for _, text in tei_paragraphs(root)) def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="~/Local/Ventures/Slayer/data/speakleash") args = ap.parse_args() out_dir = Path(args.out).expanduser(); out_dir.mkdir(parents=True, exist_ok=True) listing = _get(API) or [] files = [f for f in listing if f["name"].endswith(".xml")] print(f"ELTeC-pol: {len(files)} TEI files", flush=True) jsonl = out_dir / f"{KEY}.jsonl"; kept = 0; t0 = time.time() with jsonl.open("w", encoding="utf-8") as fo: for i, f in enumerate(files, 1): xml = _get(f["download_url"], raw=True) if not xml: print(f" ! skip {f['name']}"); continue title, text = tei_to_text(xml) if len(text) < MIN_CHARS: continue fo.write(json.dumps({ "text": text, "meta": {"url": f["html_url"], "title": title, "file": f["name"], "domain": "literature"}, }, ensure_ascii=False) + "\n") kept += 1 if i % 20 == 0: print(f" {i}/{len(files)} | kept {kept}", flush=True) subprocess.run(["zstd", "-19", "-f", "--rm", str(jsonl), "-o", str(out_dir / f"{KEY}.jsonl.zst")], check=True) print(f"{KEY}: {kept} novels in {round(time.time()-t0)}s -> {KEY}.jsonl.zst") if __name__ == "__main__": main()