File size: 3,068 Bytes
cfe406c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/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}"
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 tei_to_text(xml_bytes):
    """Extract reading text (title + body 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 ""
    body = root.find(f".//{TEI}text/{TEI}body")
    if body is None:
        return title, ""
    parts = []
    for p in body.iter(f"{TEI}p"):
        txt = " ".join(p.itertext())
        txt = re.sub(r"\s+", " ", txt).strip()
        if txt:
            parts.append(txt)
    return title, "\n\n".join(parts)


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()