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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Gather the parallel training data that already exists for the shortlist languages.

This is the baseline a newly mined corpus has to beat. It covers the same languages and the
same pivot directions as the evaluation corpus, so the two are comparable.

Every record carries a ``corpus_type``, because the raw sentence totals are misleading on
their own. Bavarian looks well supplied at roughly 900,000 "sentences", but 86% of that is
XLEnt -- automatically extracted *named entity* pairs, not sentences -- and the remaining
14% is WikiMatrix and the wikimedia corpus, both automatically mined from the very
Wikipedia a new corpus would mine. Interlingua's 1.1M is 94% GNOME interface strings.
Classifying each corpus lets the baseline be split into data that genuinely competes with
human translation and data that does not:

    human_prose       professionally or community translated running text
    crowd_sentences   Tatoeba and similar volunteer sentence pairs
    religious         bible and similar translations
    subtitles         film and talk subtitles
    ui_strings        software interface messages
    auto_mined        sentence pairs aligned automatically from comparable text
    entity_list       automatically extracted named-entity or title pairs

Everything comes from OPUS, which publishes direct download links per corpus and language
pair under open terms, plus the Tatoeba Challenge training splits where they exist.
"""

from __future__ import annotations

import argparse
import hashlib
import io
import json
import re
import sys
import time
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

import shortlist_pivots as pivots  # noqa: E402
from build_eval_corpus import TATOEBA_REVISION, fetch, norm_key, _clean  # noqa: E402
from corpus_subsets import subset_name, write_subsets  # noqa: E402

CACHE = ROOT / "cache" / "baseline_corpus"
DIST = ROOT / "dist" / "baseline_corpus"
OPUS_API = "https://opus.nlpl.eu/opusapi/"

# How each OPUS corpus was produced. Unlisted corpora are reported as "unclassified" rather
# than guessed into a bucket, so an unexpected source cannot quietly count as human text.
CORPUS_TYPES = {
    "XLEnt": "entity_list",
    "LinguaTools-WikiTitles": "entity_list",
    "WikiMatrix": "auto_mined",
    "wikimedia": "auto_mined",
    "Wikipedia": "auto_mined",
    "CCMatrix": "auto_mined",
    "CCAligned": "auto_mined",
    "MultiCCAligned": "auto_mined",
    "ParaCrawl": "auto_mined",
    "NLLB": "auto_mined",
    "XLEnt-v1.2": "entity_list",
    "translatewiki": "ui_strings",
    "GNOME": "ui_strings",
    "KDE4": "ui_strings",
    "KDEdoc": "ui_strings",
    "Ubuntu": "ui_strings",
    "PHP": "ui_strings",
    "OpenOffice": "ui_strings",
    "LibreOffice": "ui_strings",
    "Mozilla-I10n": "ui_strings",
    "QED": "subtitles",
    "OpenSubtitles": "subtitles",
    "TED2020": "subtitles",
    "TED2013": "subtitles",
    "Tatoeba": "crowd_sentences",
    "tatoeba_challenge": "crowd_sentences",
    "bible-uedin": "religious",
    "JW300": "religious",
    "MultiParaCrawl": "auto_mined",
    "GlobalVoices": "human_prose",
    "News-Commentary": "human_prose",
    "infopankki": "human_prose",
    "ELRC": "human_prose",
    "WMT-News": "human_prose",
    "EUbookshop": "human_prose",
}

# Buckets that represent translation a human actually produced as running text. Used for the
# "does this language already have competing data" question the audit's saturation gate asks.
HUMAN_TYPES = ("human_prose", "crowd_sentences", "religious", "subtitles")


def corpus_type(name: str) -> str:
    if name in CORPUS_TYPES:
        return CORPUS_TYPES[name]
    base = name.split("-")[0].split("_")[0]
    return CORPUS_TYPES.get(base, "unclassified")


def opus_packages(source: str, target: str) -> list[dict]:
    """Downloadable OPUS moses packages for one language pair."""
    query = urllib.parse.urlencode({
        "source": source, "target": target, "preprocessing": "moses", "version": "latest",
    })
    payload = fetch(f"{OPUS_API}?{query}")
    if not payload:
        return []
    data = json.loads(payload)
    items = data.get("corpora", data) if isinstance(data, dict) else data
    return [item for item in items if item.get("url")]


def read_moses_zip(payload: bytes, source: str, target: str) -> list[tuple[str, str]]:
    """Sentence pairs from an OPUS moses zip: two line-aligned plain-text members."""
    try:
        archive = zipfile.ZipFile(io.BytesIO(payload))
    except zipfile.BadZipFile:
        return []
    members = [n for n in archive.namelist() if n.endswith((f".{source}", f".{target}"))]
    left = next((n for n in members if n.endswith(f".{source}")), None)
    right = next((n for n in members if n.endswith(f".{target}")), None)
    if not left or not right or left == right:
        # One member matching both suffixes means the codes are ambiguous for this archive,
        # and pairing a file with itself would manufacture identical "translations".
        return []
    src_lines = archive.read(left).decode("utf-8", "replace").splitlines()
    trg_lines = archive.read(right).decode("utf-8", "replace").splitlines()
    if len(src_lines) != len(trg_lines):
        # A length mismatch means the alignment cannot be trusted at all.
        return []
    return list(zip(src_lines, trg_lines))


def collect_opus(targets, rows, pivot_sets, workers: int = 6):
    """Every OPUS moses package for each target/pivot pair."""
    jobs = []
    for config in targets:
        iso = rows[config]["iso639_3"]
        for pivot in pivot_sets[config]:
            jobs.append((config, iso, pivot, rows[pivot]["iso639_3"]))

    records, notes = [], []

    def one(job):
        config, iso, pivot, pivot_iso = job
        got, local_notes = [], []
        # OPUS keys wiki-derived corpora by the Wikipedia prefix and others by ISO code, so
        # both spellings are tried for each side.
        tried = set()
        for left in dict.fromkeys([config, iso]):
            for right in dict.fromkeys([pivot, pivot_iso]):
                if not left or not right or (left, right) in tried:
                    continue
                tried.add((left, right))
                for package in opus_packages(left, right):
                    payload = fetch(package["url"])
                    if not payload:
                        local_notes.append({"target": config, "pivot": pivot,
                                            "corpus": package.get("corpus"),
                                            "reason": "package not fetchable"})
                        continue
                    # Pivot first: every record is (src = pivot text, trg = target text),
                    # matching ``sl``/``tl`` below and the orientation of the eval corpus.
                    # Passing the target first silently swapped the two columns against
                    # their own labels, which also defeated the contamination check.
                    pairs = read_moses_zip(payload, right, left)
                    if not pairs:
                        local_notes.append({"target": config, "pivot": pivot,
                                            "corpus": package.get("corpus"),
                                            "reason": "no usable aligned member in archive"})
                        continue
                    name = package.get("corpus") or "unknown"
                    for src, trg in pairs:
                        if not src.strip() or not trg.strip():
                            continue
                        got.append({
                            "sl": pivot, "tl": config, "id": None,
                            "src": _clean(src), "trg": _clean(trg),
                            "split": "train",
                            "source": f"opus/{name}",
                            "source_url": f"https://opus.nlpl.eu/{name}",
                            "source_revision": str(package.get("version") or "latest"),
                            "licence": package.get("license") or "see OPUS corpus page",
                            "corpus": name,
                            "corpus_type": corpus_type(name),
                        })
                if got:
                    break
            if got:
                break
        return got, local_notes

    with ThreadPoolExecutor(max_workers=workers) as pool:
        for index, (got, local_notes) in enumerate(pool.map(one, jobs), 1):
            records += got
            notes += local_notes
            if index % 20 == 0 or index == len(jobs):
                print(f"    opus {index}/{len(jobs)} pairs, {len(records):,} records",
                      flush=True)
    return records, notes


def collect_tatoeba_train(targets, rows, iso2cfg, pairs, pivot_sets):
    """Tatoeba Challenge training splits, where the release ships one."""
    records, notes = [], []
    for config in targets:
        iso = rows[config]["iso639_3"]
        if not iso:
            continue
        for pair in pairs:
            left, _, right = pair.partition("-")
            if iso not in (left, right):
                continue
            other = right if left == iso else left
            if other == iso:
                continue
            pivot = iso2cfg.get(other) or other
            if pivot not in pivot_sets[config]:
                continue
            # The repository ships only test.txt per pair; training data is distributed as
            # per-pair tar archives on CSC object storage
            # (https://object.pouta.csc.fi/Tatoeba-Challenge/<pair>.tar), and only for pairs
            # large enough to have a training release. This path therefore finds nothing.
            # It is kept, and now records why, because the earlier version failed silently
            # and the resulting zero contribution looked deliberate. Tatoeba training text
            # still reaches the baseline through OPUS's Tatoeba corpus.
            url = ("https://raw.githubusercontent.com/Helsinki-NLP/Tatoeba-Challenge/"
                   f"{TATOEBA_REVISION}/data/test/{pair}/train.txt")
            payload = fetch(url)
            if not payload:
                notes.append({"target": config, "pivot": pivot, "corpus": "Tatoeba-Challenge",
                              "reason": "no train.txt in the repository for this pair",
                              "pair": pair})
                continue
            for line in payload.decode("utf-8", "replace").splitlines():
                parts = line.split("\t")
                if len(parts) < 4:
                    continue
                if parts[1].split("_")[0] == iso:
                    src, trg = parts[2], parts[3]
                elif parts[0].split("_")[0] == iso:
                    src, trg = parts[3], parts[2]
                else:
                    continue
                if not src.strip() or not trg.strip():
                    continue
                records.append({
                    "sl": pivot, "tl": config, "id": None,
                    "src": _clean(src), "trg": _clean(trg), "split": "train",
                    "source": "tatoeba_challenge",
                    "source_url": "https://github.com/Helsinki-NLP/Tatoeba-Challenge",
                    "source_revision": TATOEBA_REVISION,
                    "licence": "CC-BY-2.0-FR",
                    "corpus": "Tatoeba-Challenge",
                    "corpus_type": "crowd_sentences",
                })
    return records, notes


# ------------------------------------------------------------------- contamination & output


def eval_keys(eval_release: Path) -> dict:
    """Target-side keys of every evaluation record, for the contamination check.

    Keyed on the target sentence alone, not on the (source, target) pair. A pair key is far
    too weak: the same reference sentence is routinely paired with a different source -- a
    paraphrase, or the same sentence in another pivot language -- and a model that has
    memorised the reference scores just as highly either way. Keying on pairs let 24,110 of
    37,386 evaluation sentences through on the first build.
    """
    keys: dict[str, set] = {}
    for path in sorted((eval_release / "languages").glob("*.jsonl")):
        with path.open(encoding="utf-8") as handle:
            for line in handle:
                record = json.loads(line)
                if not record.get("trg"):
                    continue
                keys.setdefault(record["tl"], set()).add(norm_key(record["trg"]))
    return keys


def drop_contamination(records, keys):
    """Remove training records whose target side appears in the evaluation set.

    Tatoeba is the expected offender: its Challenge test and training splits are drawn from
    the same pool, and OPUS ships the whole Tatoeba corpus including the held-out sentences.
    Leaving them in would let a baseline train on its own test set.

    This compares ``record["trg"]`` against evaluation target text, so it only works if the
    two corpora agree on orientation. They now do -- see the note in ``collect_opus``.
    """
    kept, removed = [], []
    for record in records:
        if norm_key(record["trg"]) in keys.get(record["tl"], ()):
            removed.append(record)
            continue
        kept.append(record)
    return kept, removed


def deduplicate(records):
    seen, out = set(), []
    for record in records:
        key = (record["tl"], record["sl"], norm_key(record["src"]), norm_key(record["trg"]))
        if key in seen:
            continue
        seen.add(key)
        out.append(record)
    return out


def write_release(records, notes, removed, selection, rows, eval_release, release_id=None):
    import pyarrow as pa
    import pyarrow.parquet as pq

    release_id = release_id or time.strftime("baseline_%Y%m%dT%H%M%SZ", time.gmtime())
    output = DIST / release_id
    (output / "languages").mkdir(parents=True, exist_ok=True)

    by_language: dict[str, list[dict]] = {}
    for record in records:
        by_language.setdefault(record["tl"], []).append(record)

    columns = ["sl", "tl", "id", "src", "trg", "split", "source", "source_url",
               "source_revision", "licence", "corpus", "corpus_type"]
    schema = pa.schema([(name, pa.int64() if name == "id" else pa.string())
                        for name in columns])

    summary, flat = {}, []
    for config in sorted(by_language):
        items = by_language[config]
        items.sort(key=lambda r: (r["corpus_type"], r["corpus"], r["sl"], r["src"]))
        for index, record in enumerate(items):
            record["id"] = index
        with (output / "languages" / f"{config}.jsonl").open("w", encoding="utf-8") as handle:
            for record in items:
                handle.write(json.dumps(record, ensure_ascii=False) + "\n")
        flat += items
        by_type: dict[str, int] = {}
        for record in items:
            by_type[record["corpus_type"]] = by_type.get(record["corpus_type"], 0) + 1
        human = sum(count for kind, count in by_type.items() if kind in HUMAN_TYPES)
        summary[config] = {
            "language_name": rows[config]["language_name"],
            "opportunity_rank": rows[config]["opportunity_rank"],
            "records": len(items),
            "human_records": human,
            "human_share": round(human / len(items), 4) if items else 0.0,
            "pivots": sorted({r["sl"] for r in items}),
            "corpora": sorted({r["corpus"] for r in items}),
            "by_corpus_type": dict(sorted(by_type.items(), key=lambda kv: -kv[1])),
        }

    def as_table(items):
        return pa.Table.from_pylist(
            [{column: record.get(column) for column in columns} for record in items],
            schema=schema,
        )

    pq.write_table(as_table(flat), output / "baseline.parquet", compression="zstd")

    # One subset per corpus and language: "<corpus>-<language>" says where the training
    # data came from and which language it is for -- wikimatrix-bar, xlent-bar, tatoeba-bar.
    # The evaluation corpus names its subsets the same way, so a name present in both
    # identifies one body of data with its training split here and its test split there.
    #
    # Alongside those: "all", and subsets by how the data was produced, because that is the
    # distinction the totals hide. "human" is the only part that genuinely competes with a
    # newly translated corpus.
    # Only "all" and the per-corpus subsets. ``corpus_type`` stays as a column, so the
    # human/automatic split is still one filter away without multiplying the subset list.
    subsets = {"all": list(flat)}
    for corpus, language in sorted({(r["corpus"], r["tl"]) for r in flat}):
        subsets[subset_name(corpus, language)] = [
            r for r in flat if r["corpus"] == corpus and r["tl"] == language
        ]

    subset_meta = write_subsets(output, subsets, as_table, split="train",
                               human_types=HUMAN_TYPES)

    total = sum(s["records"] for s in summary.values())
    total_human = sum(s["human_records"] for s in summary.values())
    manifest = {
        "release_id": release_id,
        "built_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "audit_release": selection["release"],
        "eval_release": eval_release.name,
        "shortlist_count": selection["count"],
        "languages_with_records": len(summary),
        "total_records": total,
        "human_records": total_human,
        "human_share": round(total_human / total, 4) if total else 0.0,
        "contaminated_records_removed": len(removed),
        "corpus_types": {
            "human_prose": "professionally or community translated running text",
            "crowd_sentences": "volunteer sentence pairs, chiefly Tatoeba",
            "religious": "bible and similar translations",
            "subtitles": "film and talk subtitles",
            "ui_strings": "software interface messages",
            "auto_mined": "sentence pairs aligned automatically from comparable text",
            "entity_list": "automatically extracted named-entity or title pairs",
            "unclassified": "corpus not in the classification table; not counted as human",
        },
        "human_types": list(HUMAN_TYPES),
        "subsets": subset_meta,
        "subset_note": (
            "'all' is every record. The rest are one per corpus and language, named "
            "'<corpus>-<language>', matching the evaluation corpus's naming. The "
            "human/automatic distinction is a 'corpus_type' column rather than a subset, so "
            "it can be filtered without multiplying the subset list."
        ),
        "licence": "CC-BY-SA-4.0",
        "licence_note": (
            "Mixed upstream licences; every record carries its own licence field and the "
            "OPUS corpus it came from. Consult the named OPUS corpus page before "
            "redistributing any single subset."
        ),
        "languages": summary,
        "notes": notes[:500],
        "note_count": len(notes),
        "columns": columns,
    }
    (output / "manifest.json").write_text(
        json.dumps(manifest, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
    )
    return output, manifest


def build(release_id=None, eval_release: Path | None = None, workers: int = 6):
    selection = pivots.selection()
    rows = pivots.load_rows(pivots.DIST / selection["release"])
    targets = list(selection["languages"])
    iso2cfg = pivots.iso_to_config(rows)

    eval_root = ROOT / "dist" / "eval_corpus"
    eval_release = eval_release or sorted(
        p for p in eval_root.glob("eval_*") if (p / "manifest.json").exists()
    )[-1]
    print(f"evaluation corpus: {eval_release.name}")

    # Same directions as the evaluation set: the structural pivots plus whatever the test
    # sets actually attested, so train and test cover the same pairs.
    with (eval_release / "manifest.json").open(encoding="utf-8") as handle:
        eval_manifest = json.load(handle)
    pivot_sets = {}
    for config in targets:
        structural = set(pivots.structural_pivots(config, rows))
        attested = set(eval_manifest["languages"].get(config, {}).get("pivots") or [])
        pivot_sets[config] = sorted(
            p for p in structural | attested
            if p in rows and pivots.acceptable_pivot(config, p, rows)[0]
        )
    print(f"pairs to query: {sum(len(v) for v in pivot_sets.values())}")

    with (ROOT / "cache" / "lang_audit" / "sources" / "tatoeba_challenge.json").open(
        encoding="utf-8"
    ) as handle:
        tatoeba_pairs = json.load(handle)["data"]["test_pairs"]["pairs"]

    records, notes = collect_opus(targets, rows, pivot_sets, workers=workers)
    print(f"  opus                 {len(records):>9,} records, {len(notes)} notes")
    extra, more = collect_tatoeba_train(targets, rows, iso2cfg, tatoeba_pairs, pivot_sets)
    print(f"  tatoeba train splits {len(extra):>9,} records")
    records += extra
    notes += more

    before = len(records)
    records = deduplicate(records)
    print(f"  deduplicated:        {before - len(records):>9,} collapsed")

    keys = eval_keys(eval_release)
    records, removed = drop_contamination(records, keys)
    print(f"  contamination:       {len(removed):>9,} training records matched an eval pair")

    output, manifest = write_release(
        records, notes, removed, selection, rows, eval_release, release_id
    )
    print(f"\nrelease: {output}")
    return output, manifest


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--release-id", default=None)
    parser.add_argument("--workers", type=int, default=6)
    args = parser.parse_args(argv)
    _output, manifest = build(args.release_id, workers=args.workers)
    print(f"languages: {manifest['languages_with_records']}/{manifest['shortlist_count']}")
    print(f"records: {manifest['total_records']:,}  "
          f"human: {manifest['human_records']:,} ({manifest['human_share']:.1%})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())