File size: 4,885 Bytes
8032ef4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/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 <front> or <back> kept in the text of a novel, by the xml:id of its <TEI> element: POL0100 (Makuszyński,
# "Po mlecznej drodze") opens with the author's address to the reader in <front>; POL0091 (Żeromski, "Dzieje
# grzechu") ends with the author's draft passages (Dodatek) in <back>. The title pages and the other <front>
# and <back> 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 <p> under `parent`, nested ones too, and every <head> that is not
    inside a <p> or a <head> and holds no <p> (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 <p> of <body>, "head" for a <head> of <body> (a chapter title, in its place among the
    paragraphs), and "front" or "back" for each <p> and <head> of the one <front> or <back> 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()