File size: 25,751 Bytes
c963be6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
"""Corpus construction for the bilingual English/Russian pretraining set.



This module implements the pipeline described in ``docs/data_plan.md``:



    fetch -> normalise -> quality filter -> deduplicate -> mix -> split



It deliberately has no third-party dependencies beyond the standard library so

that the corpus can be rebuilt on a bare machine.  The three things it is

careful about are:



* **licences** -- every shard is recorded with ``source``, ``licence``,

  ``url`` and ``sha256``; a shard without a known licence is rejected by

  :func:`record_shard`;

* **language** -- a fast heuristic (script shares) instead of a model, so the

  filter is explainable and reproducible;

* **boilerplate** -- MediaWiki pages are cleaned of templates, references,

  tables and image links before they are counted as text.



The module is used by ``scripts/build_bilingual.py``.

"""
from __future__ import annotations

import gzip
import hashlib
import json
import re
import unicodedata
import zlib
from dataclasses import dataclass, field, asdict
from pathlib import Path
from typing import Iterable, Iterator, Optional, Sequence

# ---------------------------------------------------------------------------
# Normalisation and MediaWiki cleaning
# ---------------------------------------------------------------------------

#: Sections that carry references or navigation rather than prose.
BOILERPLATE_SECTIONS = {
    # Russian
    "примечания", "литература", "ссылки", "источники", "см. также",
    "библиография", "комментарии", "сноски", "внешние ссылки",
    # English
    "references", "external links", "see also", "further reading",
    "notes", "bibliography", "citations", "sources", "footnotes",
}

_RE_COMMENT = re.compile(r"<!--.*?-->", re.S)
_RE_REF = re.compile(r"<ref[^>]*?/>|<ref[^>]*?>.*?</ref>", re.S | re.I)
_RE_TAG = re.compile(r"</?[a-zA-Z][^>]{0,200}>")
_RE_TABLE = re.compile(r"\{\|.*?\|\}", re.S)
_RE_MATH = re.compile(r"<math>(.*?)</math>", re.S | re.I)
_RE_HEADING = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M)
_RE_FILE = re.compile(
    r"\[\[(?:Файл|File|Изображение|Image|Медиа|Media):[^\[\]]*?(?:\[\[[^\]]*\]\][^\[\]]*?)*\]\]",
    re.I)
_RE_CATEGORY = re.compile(
    r"\[\[(?:Категория|Category):[^\[\]]*\]\]", re.I)
_RE_INTERWIKI = re.compile(r"\[\[[a-z]{2,3}:[^\[\]]*\]\]")
_RE_LINK = re.compile(r"\[\[([^\[\]|]+)(?:\|([^\[\]]*))?\]\]")
_RE_EXTLINK = re.compile(r"\[(?:https?|ftp)://[^\s\]]+\s*([^\]]*)\]")
_RE_BOLD = re.compile(r"'{2,5}")
_RE_LIST = re.compile(r"^[ \t]*[*#:;]+[ \t]*", re.M)
_RE_WS = re.compile(r"[ \t]+")
_RE_BLANKLINES = re.compile(r"\n{3,}")


def _strip_templates(text: str) -> str:
    """Remove ``{{...}}`` blocks, handling nesting.



    MediaWiki templates are balanced but not regular, so this walks the string

    once with a depth counter instead of using a regex.

    """
    out: list[str] = []
    depth = 0
    i = 0
    n = len(text)
    while i < n:
        if text.startswith("{{", i):
            depth += 1
            i += 2
            continue
        if text.startswith("}}", i) and depth:
            depth -= 1
            i += 2
            continue
        if depth == 0:
            out.append(text[i])
        i += 1
    return "".join(out)


def _drop_sections(text: str) -> str:
    """Drop whole sections whose heading is boilerplate (references, links)."""
    lines = text.split("\n")
    kept: list[str] = []
    skip_level: Optional[int] = None
    for line in lines:
        m = _RE_HEADING.match(line)
        if m:
            level = len(m.group(1))
            title = m.group(2).strip().lower().rstrip(":")
            if skip_level is not None and level <= skip_level:
                skip_level = None
            if skip_level is None and title in BOILERPLATE_SECTIONS:
                skip_level = level
                continue
        if skip_level is None:
            kept.append(line)
    return "\n".join(kept)


def clean_wikitext(text: str) -> str:
    """Convert MediaWiki wikitext to plain prose.



    The cleaner is intentionally conservative: it removes markup that never

    contains prose (templates, references, tables, files, categories) and

    unwraps markup that wraps prose (links, bold, headings).  It does not try

    to be a full parser; residual markup is filtered later by the symbol-ratio

    check.



    Args:

        text: raw wikitext of one article.



    Returns:

        Plain text with paragraphs separated by a single blank line.

    """
    text = _RE_COMMENT.sub(" ", text)
    text = _RE_REF.sub(" ", text)
    text = _RE_TABLE.sub(" ", text)
    text = _strip_templates(text)
    text = _RE_MATH.sub(lambda m: " " + m.group(1).strip() + " ", text)
    text = _drop_sections(text)
    text = _RE_FILE.sub(" ", text)
    text = _RE_CATEGORY.sub(" ", text)
    text = _RE_INTERWIKI.sub(" ", text)
    # headings -> sentences on their own line, then unwrapped
    text = _RE_HEADING.sub(lambda m: "\n\n" + m.group(2).strip() + "\n\n", text)
    text = _RE_LINK.sub(lambda m: (m.group(2) or m.group(1)).strip(), text)
    text = _RE_EXTLINK.sub(lambda m: (m.group(1) or "").strip(), text)
    text = _RE_BOLD.sub("", text)
    text = _RE_LIST.sub("", text)
    text = _RE_TAG.sub(" ", text)
    text = text.replace("&nbsp;", " ").replace("&amp;", "&")
    text = text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
    return normalize(text)


def normalize(text: str, keep_indent: bool = False) -> str:
    """Unicode-normalise and clean whitespace.



    Args:

        text: input text.

        keep_indent: keep leading indentation and blank lines (used for code,

            where indentation carries meaning).



    Returns:

        Normalised text, paragraphs separated by ``\\n\\n``.

    """
    text = unicodedata.normalize("NFKC", text)
    text = text.replace("\r\n", "\n").replace("\r", "\n")
    text = text.replace("\u00ad", "")          # soft hyphen
    text = text.replace("\ufeff", "")
    for space in ("\u00a0", "\u2009", "\u202f", "\u2007"):
        text = text.replace(space, " ")
    if keep_indent:
        lines = [ln.rstrip() for ln in text.split("\n")]
        out: list[str] = []
        for ln in lines:
            out.append(ln)
        return _RE_BLANKLINES.sub("\n\n\n", "\n".join(out)).strip("\n")
    lines = []
    for ln in text.split("\n"):
        ln = _RE_WS.sub(" ", ln).strip()
        lines.append(ln)
    text = "\n".join(lines)
    text = _RE_BLANKLINES.sub("\n\n", text)
    return text.strip()


# ---------------------------------------------------------------------------
# Language and quality filters
# ---------------------------------------------------------------------------

_CYRILLIC = re.compile(r"[\u0400-\u04FF]")
_LATIN = re.compile(r"[A-Za-z]")
_LETTER = re.compile(r"[^\W\d_]", re.UNICODE)
_DIGIT = re.compile(r"\d")
_SYMBOL = re.compile(r"[^\w\s]", re.UNICODE)


@dataclass
class QualityStats:
    """Measured properties of one document."""

    chars: int
    words: int
    letters: int
    digits: int
    symbols: int
    cyrillic: int
    latin: int
    repeat_ratio: float
    compression: float
    ok: bool
    reasons: list[str] = field(default_factory=list)


def _repeat_ratio(words: Sequence[str], n: int = 5) -> float:
    """Fraction of ``n``-grams that occur more than once."""
    if len(words) < n:
        return 0.0
    grams = [tuple(words[i:i + n]) for i in range(len(words) - n + 1)]
    if not grams:
        return 0.0
    unique = len(set(grams))
    return 1.0 - unique / len(grams)


def quality(text: str, language: Optional[str] = None,

            min_chars: int = 400, max_symbol_ratio: float = 0.20,

            max_digit_ratio: float = 0.12,

            max_repeat_ratio: float = 0.30,

            min_compression: float = 0.22,

            max_compression: float = 0.80) -> QualityStats:
    """Score a document and decide whether it may enter the corpus.



    The thresholds are calibrated on the pilot, not on theory: they remove

    lists, tables, navigation residue and machine-generated text while keeping

    dense prose and formulas.



    Args:

        text: normalised document.

        language: ``"en"`` or ``"ru"``; ``None`` skips the script check.

        min_chars: minimum document length in characters.

        max_symbol_ratio: maximum share of non-alphanumeric characters.

        max_digit_ratio: maximum share of digits (filters data dumps).

        max_repeat_ratio: maximum share of repeated 5-grams.

        min_compression: minimum zlib ratio (too uniform text is suspicious).

        max_compression: maximum zlib ratio (too random text is suspicious).



    Returns:

        A :class:`QualityStats` with ``ok`` set to the verdict.

    """
    n = len(text)
    letters = len(_LETTER.findall(text))
    digits = len(_DIGIT.findall(text))
    symbols = len(_SYMBOL.findall(text))
    cyr = len(_CYRILLIC.findall(text))
    lat = len(_LATIN.findall(text))
    words = text.split()
    comp = len(zlib.compress(text.encode("utf-8"), 6)) / max(1, len(text.encode("utf-8")))
    rep = _repeat_ratio(words)

    reasons: list[str] = []
    if n < min_chars:
        reasons.append("short")
    if n and symbols / n > max_symbol_ratio:
        reasons.append("symbols")
    if n and digits / n > max_digit_ratio:
        reasons.append("digits")
    if rep > max_repeat_ratio:
        reasons.append("repetition")
    if not (min_compression <= comp <= max_compression):
        reasons.append("compression")
    if language == "ru" and (cyr + lat) and cyr / (cyr + lat) < 0.60:
        reasons.append("not_ru")
    if language == "en" and (cyr + lat) and lat / (cyr + lat) < 0.80:
        reasons.append("not_en")

    return QualityStats(chars=n, words=len(words), letters=letters,
                        digits=digits, symbols=symbols, cyrillic=cyr,
                        latin=lat, repeat_ratio=round(rep, 4),
                        compression=round(comp, 4), ok=not reasons,
                        reasons=reasons)


# ---------------------------------------------------------------------------
# Near-duplicate detection (MinHash + LSH)
# ---------------------------------------------------------------------------

def _shingles(text: str, k: int = 5) -> set[int]:
    """Hashed word shingles of a document."""
    words = text.lower().split()
    if len(words) < k:
        return {hash(tuple(words))}
    return {hash(tuple(words[i:i + k])) for i in range(len(words) - k + 1)}


def minhash(text: str, permutations: int = 64, k: int = 5,

            seed: int = 13) -> tuple[int, ...]:
    """MinHash signature used for near-duplicate detection."""
    import random

    rng = random.Random(seed)
    a = [rng.randrange(1, 2**61 - 1) for _ in range(permutations)]
    b = [rng.randrange(0, 2**61 - 1) for _ in range(permutations)]
    sig = []
    sh = _shingles(text, k)
    for i in range(permutations):
        sig.append(min(((a[i] * s + b[i]) % (2**61 - 1)) for s in sh))
    return tuple(sig)


def _bands(sig: Sequence[int], bands: int) -> Iterator[tuple]:
    step = max(1, len(sig) // bands)
    for i in range(0, len(sig), step):
        yield (i, tuple(sig[i:i + step]))


def dedup(docs: Iterable[dict], threshold: float = 0.8,

          text_key: str = "text") -> tuple[list[dict], int]:
    """Remove exact and near duplicates.



    Exact duplicates are dropped by SHA-256 of the normalised text, near

    duplicates by MinHash banding with a Jaccard cutoff.  The first document

    wins, so callers should feed sources in priority order.



    Args:

        docs: documents with at least ``text`` (and ``sha256`` optionally).

        threshold: Jaccard similarity above which two documents are duplicates.

        text_key: key holding the text.



    Returns:

        ``(kept, dropped)``.

    """
    seen_exact: set[str] = set()
    buckets: dict[tuple, list[tuple[int, ...]]] = {}
    kept: list[dict] = []
    dropped = 0
    for doc in docs:
        text = doc[text_key]
        h = doc.get("sha256") or hashlib.sha256(text.encode("utf-8")).hexdigest()
        if h in seen_exact:
            dropped += 1
            continue
        sig = minhash(text)
        is_dup = False
        for band in _bands(sig, 16):
            bucket = buckets.setdefault(band, [])
            for other in bucket:
                same = sum(1 for x, y in zip(sig, other) if x == y)
                if same / len(sig) >= threshold:
                    is_dup = True
                    break
            if is_dup:
                break
        if is_dup:
            dropped += 1
            continue
        for band in _bands(sig, 16):
            buckets.setdefault(band, []).append(sig)
        seen_exact.add(h)
        doc["sha256"] = h
        kept.append(doc)
    return kept, dropped


# ---------------------------------------------------------------------------
# Manifest
# ---------------------------------------------------------------------------

REQUIRED_FIELDS = ("source", "licence", "url", "language", "domain",
                   "sha256", "bytes")


@dataclass
class Shard:
    """One corpus shard and its provenance."""

    source: str
    licence: str
    url: str
    language: str
    domain: str
    sha256: str
    bytes: int
    docs: int = 0
    path: str = ""
    note: str = ""

    def as_dict(self) -> dict:
        return asdict(self)


def sha256_file(path: Path) -> str:
    """SHA-256 of a file, streamed."""
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def record_shard(path: Path, manifest: Path, source: str, licence: str,

                 url: str, language: str, domain: str, docs: int = 0,

                 note: str = "") -> Shard:
    """Append one shard to the JSONL manifest.



    Args:

        path: shard file on disk.

        manifest: JSONL manifest path.

        source: human-readable source name.

        licence: licence identifier; must be known.

        url: canonical source URL.

        language: ``en`` or ``ru``.

        domain: ``math``, ``science``, ``logic``, ``literature``, ``code``

            or ``encyclopedic``.

        docs: number of documents in the shard.

        note: free-form remark.



    Raises:

        ValueError: if the licence is unknown or a required field is empty.

    """
    if licence.strip().lower() in {"", "unknown", "n/a", "none"}:
        raise ValueError(f"shard {path} has no known licence")
    if language not in {"en", "ru"}:
        raise ValueError(f"unexpected language {language!r}")
    if domain not in {"math", "science", "logic", "literature", "code",
                      "encyclopedic", "ml", "cs", "humour", "identity"}:
        raise ValueError(f"unexpected domain {domain!r}")
    shard = Shard(source=source, licence=licence, url=url, language=language,
                  domain=domain, sha256=sha256_file(path),
                  bytes=path.stat().st_size, docs=docs, path=str(path),
                  note=note)
    manifest.parent.mkdir(parents=True, exist_ok=True)
    with open(manifest, "a", encoding="utf-8") as f:
        f.write(json.dumps(shard.as_dict(), ensure_ascii=False) + "\n")
    return shard


# ---------------------------------------------------------------------------
# Mixing and splitting
# ---------------------------------------------------------------------------

DOMAIN_QUOTAS = {
    "math": 0.25,
    "science": 0.14,
    "code": 0.15,
    "logic": 0.10,
    "literature": 0.11,
    "encyclopedic": 0.09,
    # Computer science, software engineering and engineering prose.  A small
    # slice: the code domain already teaches the syntax, this teaches the
    # discourse around it.
    "cs": 0.03,
    "ml": 0.12,
    # Humour, satire and jokes: short texts that teach tone rather than facts.
    "humour": 0.01,
    # Self-identity: synthetic first-person texts that teach the model its own
    # name.  The quota is an upper bound; the slice is sample-limited, so the
    # mixer reports it as a shortfall rather than duplicating text.
    "identity": 0.01,
}


def mix_corpus(shards: Sequence[Shard], total_bytes: int,

               language_ratio: float = 0.40,

               quotas: Optional[dict[str, float]] = None,

               ) -> dict[str, list[tuple[Shard, int]]]:
    """Allocate a byte budget per language and domain.



    English receives ``1 - language_ratio`` of the total and Russian

    ``language_ratio``.  Inside a language the domain quotas are applied to

    whatever is available; a starved domain is simply under-filled, which the

    caller can detect by comparing the allocation with the quota.



    Args:

        shards: available shards.

        total_bytes: budget for the whole corpus, both languages.

        language_ratio: share of Russian bytes (0.40 in the plan).

        quotas: domain shares; defaults to :data:`DOMAIN_QUOTAS`.



    Returns:

        Mapping ``language -> [(shard, allocated_bytes), ...]``.

    """
    quotas = quotas or DOMAIN_QUOTAS
    plan: dict[str, list[tuple[Shard, int]]] = {"en": [], "ru": []}
    for lang, share in (("en", 1.0 - language_ratio), ("ru", language_ratio)):
        lang_budget = int(total_bytes * share)
        by_domain: dict[str, list[Shard]] = {}
        for s in shards:
            if s.language == lang:
                by_domain.setdefault(s.domain, []).append(s)
        for domain, quota in quotas.items():
            want = int(lang_budget * quota)
            pool = by_domain.get(domain, [])
            have = sum(s.bytes for s in pool)
            take = min(want, have)
            if take <= 0:
                continue
            for s in pool:
                alloc = int(round(take * s.bytes / have))
                if alloc:
                    plan[lang].append((s, min(alloc, s.bytes)))
    return plan


def write_heldout(docs: Iterable[dict], out_dir: Path, per_language_bytes: int,

                  language: str) -> Path:
    """Write a deterministic held-out slice (first documents, fixed order)."""
    out_dir.mkdir(parents=True, exist_ok=True)
    path = out_dir / f"heldout_{language}.txt"
    written = 0
    with open(path, "w", encoding="utf-8") as f:
        for doc in docs:
            if written >= per_language_bytes:
                break
            text = doc["text"]
            f.write(text + "\n\n")
            written += len(text.encode("utf-8"))
    return path


def quota_mix(docs: Sequence[dict], budget_per_language: int,

              quotas: Optional[dict[str, float]] = None,

              heldout_bytes: int = 0,

              budgets: Optional[dict[str, int]] = None) -> dict:
    """Split a held-out slice and apply the domain quotas.



    Fetching is deliberately generous and uneven; this is where the plan is

    enforced.  Both the held-out reservation and the quota selection walk

    documents in SHA-256 order, so the same input always yields the same

    corpus.



    Args:

        docs: deduplicated documents with ``language``, ``domain``, ``sha256``

            and ``text``.

        budget_per_language: maximum training bytes per language.

        quotas: domain shares inside a language; defaults to

            :data:`DOMAIN_QUOTAS`.

        heldout_bytes: total held-out budget, split evenly across

            ``2 * len(quotas)`` buckets.

        budgets: per-language override of ``budget_per_language``; used to

            enforce the 60/40 byte ratio when the fetched volumes differ.



    Returns:

        ``{"train": {lang: {domain: [docs]}}, "heldout": {lang: [docs]},

        "shortfalls": [str], "bytes": {lang: {domain: int}}}``.

    """
    quotas = quotas or DOMAIN_QUOTAS
    ordered = sorted(docs, key=lambda d: d.get("sha256") or "")
    buckets: dict[tuple, list[dict]] = {}
    for doc in ordered:
        buckets.setdefault((doc["language"], doc["domain"]), []).append(doc)

    per_bucket = int(heldout_bytes / max(1, 2 * len(quotas)))
    heldout: dict[str, list[dict]] = {"en": [], "ru": []}
    pool: dict[tuple, list[dict]] = {}
    for key, items in buckets.items():
        bucket_bytes = sum(len(d["text"].encode("utf-8")) for d in items)
        # A bucket smaller than 5 MB is a deliberate small slice (identity,
        # rare domains).  Holding out a share of it would remove it from
        # training entirely, which is the opposite of the intent.
        budget = per_bucket if bucket_bytes >= 5_000_000 else 0
        taken = 0
        n = 0
        while n < len(items) and taken < budget:
            taken += len(items[n]["text"].encode("utf-8"))
            n += 1
        heldout.setdefault(key[0], []).extend(items[:n])
        pool[key] = items[n:]

    train: dict[str, dict[str, list[dict]]] = {"en": {}, "ru": {}}
    sizes: dict[str, dict[str, int]] = {"en": {}, "ru": {}}
    shortfalls: list[str] = []
    for lang in ("en", "ru"):
        available = sum(len(d["text"].encode("utf-8"))
                        for key, items in pool.items() if key[0] == lang
                        for d in items)
        lang_budget = int((budgets or {}).get(lang, budget_per_language))
        budget = min(available, lang_budget)
        for domain, quota in quotas.items():
            want = int(budget * quota)
            items = pool.get((lang, domain), [])
            chosen: list[dict] = []
            taken = 0
            for doc in items:
                if taken >= want:
                    break
                chosen.append(doc)
                taken += len(doc["text"].encode("utf-8"))
            if not chosen:
                shortfalls.append(f"{lang}/{domain}: empty")
                continue
            if taken < want * 0.8:
                shortfalls.append(f"{lang}/{domain}: "
                                  f"{taken/1e6:.1f} MB of {want/1e6:.1f} MB")
            train[lang][domain] = chosen
            sizes[lang][domain] = taken
    return {"train": train, "heldout": heldout, "shortfalls": shortfalls,
            "bytes": sizes}


def iter_jsonl(path: Path) -> Iterator[dict]:
    """Stream documents from a JSONL file."""
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                yield json.loads(line)


def append_jsonl(path: Path, docs: Iterable[dict]) -> int:
    """Append documents to a JSONL file and return how many were written."""
    path.parent.mkdir(parents=True, exist_ok=True)
    n = 0
    with open(path, "a", encoding="utf-8") as f:
        for doc in docs:
            f.write(json.dumps(doc, ensure_ascii=False) + "\n")
            n += 1
    return n


def corpus_report(shards: Sequence[Shard], out_path: Path) -> dict:
    """Summarise a manifest into a JSON report (bytes, docs, licences)."""
    report: dict = {"total_bytes": 0, "total_docs": 0, "by_language": {},
                    "by_domain": {}, "by_licence": {}, "shards": len(shards)}
    for s in shards:
        report["total_bytes"] += s.bytes
        report["total_docs"] += s.docs
        lang = report["by_language"].setdefault(
            s.language, {"bytes": 0, "docs": 0, "domains": {}})
        lang["bytes"] += s.bytes
        lang["docs"] += s.docs
        lang["domains"][s.domain] = lang["domains"].get(s.domain, 0) + s.bytes
        dom = report["by_domain"].setdefault(s.domain, {"bytes": 0, "docs": 0})
        dom["bytes"] += s.bytes
        dom["docs"] += s.docs
        report["by_licence"][s.licence] = (
            report["by_licence"].get(s.licence, 0) + s.bytes)
    total = max(1, report["total_bytes"])
    report["language_share"] = {
        k: round(v["bytes"] / total, 4)
        for k, v in report["by_language"].items()}
    report["domain_share"] = {
        k: round(v["bytes"] / total, 4)
        for k, v in report["by_domain"].items()}
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(report, indent=2, ensure_ascii=False),
                        encoding="utf-8")
    return report


def read_manifest(path: Path) -> list[Shard]:
    """Load a JSONL manifest into :class:`Shard` objects."""
    out = []
    if not path.exists():
        return out
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line:
            out.append(Shard(**json.loads(line)))
    return out


def pack_shard(docs: Iterable[dict], path: Path, compress: bool = True) -> int:
    """Write documents to one shard file, optionally gzip-compressed.



    Shards are newline-delimited JSON so that they can be streamed without

    loading the whole corpus into memory.



    Returns:

        Number of documents written.

    """
    path.parent.mkdir(parents=True, exist_ok=True)
    opener = gzip.open if compress else open
    n = 0
    with opener(path, "wt", encoding="utf-8") as f:
        for doc in docs:
            f.write(json.dumps(doc, ensure_ascii=False) + "\n")
            n += 1
    return n