grundtvig-bot commited on
Commit
4ca878d
·
1 Parent(s): f34e983

cellar: parse in a forked child; gutenberg: licence section as H2

Browse files

Both converters are Rust and abort the worker on some files, which killed the
map with 'subprocess abruptly died' every few minutes; forking per document
turns that into a skipped document, with a timeout for the ones that parse for
minutes. The Gutenberg card's licence block sat under an H3, so the datasheet
test that requires licence_information for license: other could not find it.

Files changed (2) hide show
  1. data/cellar/create.py +367 -0
  2. data/gutenberg/gutenberg.md +139 -0
data/cellar/create.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "datasets>=3.0.0",
5
+ # "requests",
6
+ # "tenacity",
7
+ # "multiprocess",
8
+ # "liteparse",
9
+ # "html-to-markdown",
10
+ # "pyarrow>=17.0",
11
+ # "dynaword>=0.1",
12
+ # ]
13
+ # ///
14
+ """Fetch the German documents of the EU Publications Office (Cellar).
15
+
16
+ To run this script from the repository root:
17
+
18
+ uv run data/cellar/create.py
19
+
20
+ The pipeline is the one `danish-dynaword` and `swedish-dynaword` use for the same
21
+ collection, with the language code switched to `DEU`:
22
+
23
+ - the document list comes from `danish-foundation-models/cellar-metadata`, which
24
+ holds one row per (document, language, file type) with the download URL and the
25
+ document date;
26
+ - PDFs are converted with LiteParse (no OCR, 100-page cap) and markup files with
27
+ `html-to-markdown`; anything else is skipped;
28
+ - an item published in several manifestations is kept once, in the format that
29
+ sorts first — the same rule the Danish subset applies, so an act is one document
30
+ rather than one document per file format.
31
+
32
+ Cellar is published under CC-BY-SA 4.0; every document here is licensed that way,
33
+ which is why the subset card says so and the `license` column repeats it per row.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import logging
39
+ import os
40
+ import re
41
+ import select
42
+ import signal
43
+ import time
44
+ from datetime import date
45
+ from pathlib import Path
46
+
47
+ import multiprocess
48
+ import pyarrow as pa
49
+ import pyarrow.parquet as pq
50
+ import requests
51
+ from datasets import Dataset, load_dataset, load_from_disk
52
+ from html_to_markdown import ConversionOptions, convert
53
+ from liteparse import LiteParse
54
+ from tenacity import retry, stop_after_attempt, wait_exponential
55
+
56
+ from dynaword.dataset_structure import COLUMN_ORDER
57
+ from dynaword.process_dataset import (
58
+ add_token_count,
59
+ remove_duplicate_text,
60
+ remove_empty_texts,
61
+ )
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+ SOURCE = "cellar"
66
+ WORKERS = int(os.environ.get("CELLAR_WORKERS", 32))
67
+ LANGCODE = "DEU"
68
+ LICENSE = "CC-BY-SA-4.0"
69
+ METADATA_REPO = "danish-foundation-models/cellar-metadata"
70
+ METADATA_REVISION = "0601edf401679f30079c4df7fcf752602b4498fb"
71
+ # documents without a date in the metadata get the collection window, as in the
72
+ # Danish and Swedish subsets
73
+ FALLBACK_CREATED = "1950-01-01, 2026-12-31"
74
+ PDF_TYPES = {"pdf", "pdfa2a", "pdfa1a", "pdf1x", "pdfx4", "pdfx", "pdfa1b"}
75
+ MARKUP_TYPES = {"html", "xhtml", "xhtml5", "xml", "etsi_xml"}
76
+ # C0/C1 control characters and U+FFFD: what a binary blob turns into after a
77
+ # "successful" conversion
78
+ NON_TEXT = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\ufffd]")
79
+
80
+ ANNOTATION_COLUMNS = [
81
+ "content_integrity",
82
+ "content_ratio",
83
+ "content_length",
84
+ "one_sentence_description",
85
+ "content_type",
86
+ "business_sector",
87
+ "technical_content",
88
+ "information_density",
89
+ "content_quality",
90
+ "audience_level",
91
+ "commercial_bias",
92
+ "time_sensitivity",
93
+ "content_safety",
94
+ "educational_value",
95
+ "reasoning_indicators",
96
+ "pii_presence",
97
+ "regional_relevance",
98
+ "country_relevance",
99
+ ]
100
+
101
+ ROOT = Path(__file__).parent
102
+ CACHE = Path.home() / ".cache" / "dynaword" / SOURCE / METADATA_REVISION
103
+ EXTRACT_OUT = CACHE / "extracted"
104
+ DS_PATH = CACHE / f"german_metadata"
105
+
106
+ CRASHED_FILE = CACHE / "crashed.txt"
107
+
108
+
109
+ def load_crashed() -> set[int]:
110
+ """The indices whose conversion killed the worker process.
111
+
112
+ A parser abort inside liteparse (a Rust panic on a malformed file) kills the
113
+ worker without raising, so datasets only reports that a subprocess died. The
114
+ per-document cache makes a restart cheap, but the map reaches the same
115
+ document again and dies at the same place, so the build never gets past it.
116
+ Every parse attempt leaves an .inprogress marker; a marker without its .md
117
+ names a document that killed a worker. Record it once and skip it, so a
118
+ restart makes progress instead of repeating the same death.
119
+ """
120
+ crashed: set[int] = set()
121
+ if CRASHED_FILE.exists():
122
+ crashed |= {
123
+ int(line) for line in CRASHED_FILE.read_text().split() if line.strip()
124
+ }
125
+ for marker in sorted(EXTRACT_OUT.glob("*.inprogress")):
126
+ index = int(marker.stem)
127
+ if not (EXTRACT_OUT / f"{index}.md").exists():
128
+ crashed.add(index)
129
+ with CRASHED_FILE.open("a") as handle:
130
+ handle.write(f"{index}\n")
131
+ marker.unlink()
132
+ if crashed:
133
+ logger.info("cellar: %s documents known to abort the parser", len(crashed))
134
+ return crashed
135
+
136
+
137
+ CRASHED = load_crashed()
138
+
139
+ CONVERT_TIMEOUT = float(os.environ.get("CELLAR_CONVERT_TIMEOUT", 180))
140
+
141
+
142
+ def convert_isolated(parse, timeout: float = CONVERT_TIMEOUT) -> str | None:
143
+ """Run a parser in a forked child and never let it take the worker down.
144
+
145
+ Both converters are Rust extensions, and on a malformed file one of them
146
+ kills the process outright instead of raising: the dataset map then dies
147
+ with "one of the subprocesses has abruptly died", minutes of work are lost,
148
+ and the restart walks into the same file. Some files also parse for many
149
+ minutes. A fork per document turns both into a skipped document with a log
150
+ line, which is all a corpus wants from a file it cannot read.
151
+ """
152
+ read_fd, write_fd = os.pipe()
153
+ pid = os.fork()
154
+ if pid == 0:
155
+ os.close(read_fd)
156
+ try:
157
+ payload = (parse() or "").encode("utf-8", "replace")
158
+ except BaseException as error:
159
+ payload = b"\0" + str(error).encode("utf-8", "replace")[:500]
160
+ try:
161
+ with os.fdopen(write_fd, "wb") as handle:
162
+ handle.write(payload)
163
+ except BaseException:
164
+ os._exit(1)
165
+ os._exit(0)
166
+ os.close(write_fd)
167
+ chunks: list[bytes] = []
168
+ deadline = time.monotonic() + timeout
169
+ try:
170
+ while True:
171
+ remaining = deadline - time.monotonic()
172
+ if remaining <= 0:
173
+ os.kill(pid, signal.SIGKILL)
174
+ print("Parse timed out, skipping...")
175
+ return None
176
+ ready, _, _ = select.select([read_fd], [], [], min(remaining, 5.0))
177
+ if ready:
178
+ block = os.read(read_fd, 1 << 20)
179
+ if not block:
180
+ break
181
+ chunks.append(block)
182
+ finally:
183
+ os.close(read_fd)
184
+ _, status = os.waitpid(pid, 0)
185
+ if not (os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0):
186
+ print("Parser aborted, skipping...")
187
+ return None
188
+ payload = b"".join(chunks)
189
+ if payload.startswith(b"\0"):
190
+ raise RuntimeError(payload[1:].decode("utf-8", "replace"))
191
+ return payload.decode("utf-8", "replace")
192
+
193
+
194
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1))
195
+ def fetch(url: str):
196
+ with requests.get(url, timeout=30, stream=True) as response:
197
+ response.raise_for_status()
198
+ limit = 100 * 1024 * 1024
199
+ if int(response.headers.get("Content-Length", 0)) > limit:
200
+ return None
201
+ content = bytearray()
202
+ for block in response.iter_content(1024 * 1024):
203
+ content.extend(block)
204
+ if len(content) > limit:
205
+ return None
206
+ response._content = bytes(content)
207
+ return response
208
+
209
+
210
+ def parse_uri(uri: str) -> tuple[str, int]:
211
+ """The item id and manifestation number of a Cellar URI."""
212
+ item = uri.rsplit("/", 2)[1]
213
+ item_id, _expression, manifestation = item.rsplit(".", 2)
214
+ return item_id, int(manifestation)
215
+
216
+
217
+ def fetch_and_convert(example: dict) -> None:
218
+ file_type = example["type"]
219
+ url = example["item"]
220
+ index = example["global_index"]
221
+
222
+ if file_type not in PDF_TYPES | MARKUP_TYPES:
223
+ return
224
+ output = EXTRACT_OUT / f"{index}.md"
225
+ if output.exists() and output.stat().st_size:
226
+ return
227
+ if index in CRASHED:
228
+ return
229
+ mark = EXTRACT_OUT / f"{index}.inprogress"
230
+
231
+ try:
232
+ response = fetch(url)
233
+ if response is None:
234
+ return
235
+ except Exception as error: # noqa: BLE001 - one bad document must not stop the run
236
+ print(f"Fetch exception, skipping... {error}")
237
+ return
238
+
239
+ mark.write_text("")
240
+ try:
241
+ if file_type in PDF_TYPES:
242
+ text = convert_isolated(
243
+ lambda: LiteParse(
244
+ output_format="markdown",
245
+ image_mode="off",
246
+ extract_links=False,
247
+ quiet=True,
248
+ max_pages=100,
249
+ ocr_enabled=False,
250
+ ).parse(response.content).text
251
+ )
252
+ else:
253
+ text = convert_isolated(
254
+ lambda: convert(
255
+ response.text,
256
+ ConversionOptions(extract_metadata=False, skip_images=True),
257
+ ).content
258
+ )
259
+ if text and text.strip():
260
+ temporary = output.with_suffix(".tmp")
261
+ temporary.write_text(text, encoding="utf-8")
262
+ temporary.replace(output)
263
+ except Exception as error: # noqa: BLE001
264
+ print(f"Failed parsing {file_type} {url}: {error}")
265
+ finally:
266
+ mark.unlink(missing_ok=True)
267
+
268
+
269
+ def looks_like_text(text: str) -> bool:
270
+ """Reject the rows whose URL serves a scan or a JPEG instead of the document.
271
+
272
+ Cellar's metadata declares a file type, but a few items are served as binary
273
+ blobs (the markup converter happily turns a JPEG into 1.7M characters of
274
+ noise). Anything with more than 2% non-text characters, or shorter than a
275
+ short paragraph, is dropped.
276
+ """
277
+ sample = text[:200_000]
278
+ if len(sample) < 200:
279
+ return False
280
+ non_text = len(NON_TEXT.findall(sample))
281
+ return non_text / len(sample) < 0.02
282
+
283
+
284
+ def clean_samples(example: dict) -> dict:
285
+ example["text"] = re.sub(r"<\?xml.*?\?>", "", example["text"]).strip()
286
+ return example
287
+
288
+
289
+ def create_samples(metadata: Dataset):
290
+ date_map = dict(zip(metadata["global_index"], metadata["date"]))
291
+ item_map = dict(zip(metadata["global_index"], metadata["item"]))
292
+ scanned_items: dict[str, int] = {}
293
+
294
+ for file in sorted(EXTRACT_OUT.glob("*.md"), key=lambda path: int(path.stem)):
295
+ index = int(file.stem)
296
+ if index not in item_map:
297
+ continue
298
+ document = clean_samples({"text": file.read_text(encoding="utf-8")})["text"]
299
+ if not document or not looks_like_text(document):
300
+ continue
301
+ if document.count("\ufffd") > len(document) * 0.2:
302
+ continue
303
+ item_id, manifestation = parse_uri(item_map[index])
304
+ if scanned_items.setdefault(item_id, manifestation) != manifestation:
305
+ continue
306
+ written = date_map.get(index)
307
+ yield {
308
+ "id": f"{SOURCE}_{index}",
309
+ "text": document,
310
+ "source": SOURCE,
311
+ "license": LICENSE,
312
+ "added": date.today().isoformat(),
313
+ "created": f"{written}, {written}" if written else FALLBACK_CREATED,
314
+ }
315
+
316
+
317
+ def write_metadata(ids: list[str], path: Path) -> None:
318
+ table = pa.table(
319
+ {
320
+ "dataset": pa.array([SOURCE] * len(ids), type=pa.string()),
321
+ "id": pa.array(ids, type=pa.string()),
322
+ **{
323
+ column: pa.array([None] * len(ids), type=pa.string())
324
+ for column in ANNOTATION_COLUMNS
325
+ },
326
+ }
327
+ )
328
+ pq.write_table(table, path)
329
+
330
+
331
+ def main() -> None:
332
+ EXTRACT_OUT.mkdir(parents=True, exist_ok=True)
333
+ if DS_PATH.exists():
334
+ filtered = load_from_disk(DS_PATH)
335
+ else:
336
+ dataset = load_dataset(
337
+ METADATA_REPO, revision=METADATA_REVISION, split="train"
338
+ )
339
+ filtered = dataset.filter(lambda row: row["langCode"] == LANGCODE)
340
+ filtered = filtered.map(
341
+ lambda example, index: {"global_index": index}, with_indices=True
342
+ )
343
+ filtered.save_to_disk(DS_PATH)
344
+ logger.info("%s: %s documents in the metadata", SOURCE, len(filtered))
345
+
346
+ multiprocess.set_start_method("spawn", force=True)
347
+ filtered.map(
348
+ fetch_and_convert, desc="Fetching and converting...", num_proc=WORKERS
349
+ )
350
+
351
+ dataset = Dataset.from_generator(create_samples, gen_kwargs={"metadata": filtered})
352
+ dataset = remove_empty_texts(dataset)
353
+ dataset = remove_duplicate_text(dataset)
354
+ dataset = add_token_count(dataset)
355
+ dataset = dataset.select_columns([*COLUMN_ORDER, "license"])
356
+ dataset.to_parquet(ROOT / "data.parquet")
357
+ write_metadata(dataset["id"], ROOT / "metadata.parquet")
358
+ logger.info("%s: wrote %s documents", SOURCE, len(dataset))
359
+
360
+
361
+ if __name__ == "__main__":
362
+ started = time.strftime("%Y-%m-%d %H:%M:%S")
363
+ logging.basicConfig(
364
+ level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
365
+ )
366
+ logger.info("cellar build started %s", started)
367
+ main()
data/gutenberg/gutenberg.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Project Gutenberg (German)
3
+ language:
4
+ - de
5
+ license: other
6
+ license_name: Gutenberg
7
+ size_categories:
8
+ - 1K<n<10K
9
+ task_categories:
10
+ - text-generation
11
+ - fill-mask
12
+ task_ids:
13
+ - language-modeling
14
+ source_datasets:
15
+ - original
16
+ domains:
17
+ - Books
18
+ ---
19
+
20
+ # Dataset Card for Project Gutenberg (German)
21
+
22
+ <!-- START-SHORT DESCRIPTION -->
23
+ German-language books from [Project Gutenberg](https://www.gutenberg.org) whose authors died in 1955 or earlier
24
+ <!-- END-SHORT DESCRIPTION -->
25
+
26
+ Project Gutenberg is the oldest digital library of public-domain books. This
27
+ subset holds its German-language titles: prose, drama, poetry and non-fiction,
28
+ mostly 19th century, including the canonical authors (Goethe, Schiller, Kleist,
29
+ Rilke, Fontane) and many titles that are otherwise only available as scans.
30
+
31
+ ## Dataset Description
32
+
33
+ <!-- START-DESC-STATS -->
34
+ - **Number of samples**: 1.78K
35
+ - **Number of tokens (Llama 3)**: 198.60M
36
+ - **Average document length in tokens (min, max)**: 111.26K (69, 1.19M)
37
+ <!-- END-DESC-STATS -->
38
+
39
+ ## Dataset Structure
40
+
41
+ An example from the dataset looks as follows.
42
+
43
+ <!-- START-SAMPLE -->
44
+ ```py
45
+ {
46
+ "id": "gutenberg_2054",
47
+ "text": "Iphigenie auf Tauris.\n\nEin Schauspiel.\n\nJohann Wolfgang von Goethe\n\nPersonen:\n\nIphigenie.\nThoas, Kön[...]",
48
+ "source": "gutenberg",
49
+ "added": "2026-10-30",
50
+ "created": "1749-01-01, 1832-12-31",
51
+ "token_count": 30092,
52
+ "license": "public-domain"
53
+ }
54
+ ```
55
+
56
+ ### Data Fields
57
+
58
+ An entry in the dataset consists of the following fields:
59
+
60
+ - `id` (`str`): A unique identifier for each document.
61
+ - `text` (`str`): The content of the document.
62
+ - `source` (`str`): The source of the document (see [Source Data](#source-data)).
63
+ - `added` (`str`): The date when the document was added to this collection.
64
+ - `created` (`str`): The date range when the document was originally created.
65
+ - `token_count` (`int`): The number of tokens in the sample computed using the Llama 3 tokenizer.
66
+ <!-- END-SAMPLE -->
67
+
68
+ ### Data Fields
69
+
70
+ An entry in the dataset consists of the following fields:
71
+
72
+ - `id` (`str`): A unique identifier for each document.
73
+ - `text` (`str`): The content of the document.
74
+ - `source` (`str`): The source of the document.
75
+ - `license` (`str`): the licence of the document, `public-domain` for this subset.
76
+ - `added` (`str`): The date when the document was added to this collection.
77
+ - `created` (`str`): The date range when the document was originally created.
78
+ - `token_count` (`int`): The number of tokens in the sample computed using the Llama 3 tokenizer.
79
+
80
+ ### Dataset Statistics
81
+
82
+ <!-- START-DATASET PLOTS -->
83
+ <p align="center">
84
+ <img src="./images/dist_document_length.png" width="600" style="margin-right: 10px;" />
85
+ </p>
86
+ <!-- END-DATASET PLOTS -->
87
+
88
+ ### Annotation Overview
89
+
90
+ <!-- START-ANNOTATION PLOTS -->
91
+ <!-- END-ANNOTATION PLOTS -->
92
+
93
+ ## License Information
94
+
95
+ The books are in the public domain and Project Gutenberg publishes them under the
96
+ [Project Gutenberg License](https://www.gutenberg.org/policy/license.html), which
97
+ permits redistribution of the texts. This subset strips Gutenberg's header,
98
+ transcriber credit and licence block from every file — which is what those terms
99
+ ask of a redistributor — and keeps the work's own text alone.
100
+
101
+ Beyond the US public-domain determination Gutenberg applies, the build enforces
102
+ the German term as well: only books whose authors died in 1955 or earlier are
103
+ included, so copyright has expired under the 70-years-*post-mortem-auctoris*
104
+ rule too.
105
+
106
+ ## Additional Information
107
+
108
+ ### Source Data
109
+
110
+ The titles and their bibliographic metadata come from Gutenberg's catalogue
111
+ dump (`pg_catalog.csv`), filtered to `Language == de` and `Type == Text`. Each
112
+ book is downloaded as its UTF-8 plain-text file (`ebooks/<id>.txt.utf-8`) and
113
+ Gutenberg's own boilerplate — header, transcriber credit and licence — is
114
+ removed between its `START OF THE PROJECT GUTENBERG EBOOK` and `END OF …`
115
+ markers, which is also what its licence asks of a redistributor. A file without
116
+ both markers is refused rather than shipped with the licence text inside it.
117
+
118
+ ### Annotations
119
+
120
+ Not available: the propella annotation release does not cover Project Gutenberg,
121
+ so `metadata.parquet` carries nulls and every document keeps its text. The subset
122
+ can be annotated from its text in a later batch run.
123
+
124
+ ### Limitations
125
+
126
+ - **The `created` range is a bound, not a publication date.** Gutenberg does not
127
+ publish composition or edition dates (the dates it does carry are transcription
128
+ dates), so the range written for each document is the author's life span —
129
+ the interval in which the text must have been written. It is deliberately wider
130
+ than the true publication date.
131
+ - **Only books whose author died by 1955 are included**, so that German copyright
132
+ (70 years *post mortem auctoris*) has expired as well as the US term Gutenberg
133
+ works from. Books whose authors carry no dates are excluded entirely: the term
134
+ cannot be asserted for them. Of 2,415 German text entries in the catalogue,
135
+ 1,8xx survive that filter.
136
+ - The books are volunteer transcriptions, so the error rate varies by book;
137
+ `remove_duplicate_text` has already dropped duplicates created by re-releases.
138
+ - Translations are included when their translator's dates are known and expired,
139
+ so a small share of the text is translated rather than original German.