File size: 7,345 Bytes
aae3233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Document-level curation; no language-model inference or invented OCR corrections."""
from __future__ import annotations

from collections import defaultdict, deque
import hashlib
import json
from pathlib import Path
import re
from urllib.parse import urlparse

POLICY = Path(__file__).with_name("technical_mega_curation_policy.json")


def load_metadata(root: Path) -> dict[str, list[dict]]:
    paths = [root / "polish_cnc_technical_dynaword/provenance" / name for name in (
        "full_source_records.jsonl", "augmentation_bcpw_records.jsonl",
        "augmentation_zpe_records.jsonl", "augmentation_rock_records.jsonl",
    )]
    paths += [root / folder / "provenance/articles.jsonl" for folder in (
        "polish_industrial_maintenance_dynaword", "polish_automation_control_dynaword",
        "polish_engineering_new_dynaword",
    )]
    paths.append(root / "zpe_cnc_pl_dynaword/provenance/records.jsonl")
    paths += sorted((root / "polish_source_subset/data").glob("*/*.attribution.jsonl"))
    result: dict[str, list[dict]] = defaultdict(list)
    for path in paths:
        for line in path.read_text(encoding="utf-8-sig").splitlines():
            if line.strip():
                metadata = json.loads(line)
                if metadata not in result[metadata["id"]]:
                    result[metadata["id"]].append(metadata)
    return dict(result)


def group_keys(record: dict, metadata: list[dict]) -> list[str]:
    """Aliases join shared PDFs, book chapters and alternate source namespaces."""
    source, identity = record["source"], record["id"]
    keys = set()
    for item in metadata:
        if source.startswith("bibliotekanauki-"):
            article = str(item["article_id"])
            keys.add("bibliotekanauki:" + article)
        elif source == "wikibooks":
            keys.add("wikibooks:" + item["title"].split("/", 1)[0])
        elif source == "open_agh_chemistry_pl":
            keys.update("agh-book:" + str(book["book_id"]) for book in item["memberships"])
        elif source in ("rock_pollub_pl", "rock-pollub-open"):
            handle = item["handle"].removeprefix("https://hdl.handle.net/").strip("/")
            keys.add("rock-book:" + handle)
        elif source == "open_icm_pl":
            keys.add("icm-book:" + item["handle"].removeprefix("https://hdl.handle.net/").strip("/"))
        elif source == "bcpw-public-domain":
            keys.add("bcpw-book:" + " ".join(item["title"].split()).casefold())
        elif source == "wikisource-maszynisci-1873":
            keys.add("wikisource-book:maszynisci-1873")
        elif source == "zpe-cnc-pl":
            page = urlparse(item["url"]).path.rstrip("/").rsplit("/", 1)[-1]
            if not re.fullmatch(r"D[A-Za-z0-9]+", page):
                raise ValueError(f"Unreviewed ZPE page identity: {identity}: {page}")
            keys.add("zpe-page:" + page)
        else:
            raise ValueError(f"Unreviewed source family: {source}")
        for digest in (item.get("pdf_sha256"), item.get("payload_sha256"), (item.get("pdf") or {}).get("sha256")):
            if digest:
                if not re.fullmatch(r"[0-9a-f]{64}", digest):
                    raise ValueError(f"Invalid PDF checksum: {identity}")
                keys.add("pdf:" + digest)
    if not keys:
        raise ValueError(f"Missing document/book attribution: {identity}")
    return sorted(keys)


def exclusion_reasons(record: dict, metadata: list[dict], policy: dict) -> list[str]:
    source = record["source"]
    reasons = set()
    if source == "wikibooks":
        for item in metadata:
            book = item["title"].split("/", 1)[0]
            decision = policy["wikibooks_books"][book]  # Unknown books require review.
            if not decision["include"]:
                reasons.add("outside_selected_book_scope")
    if source == "open_icm_pl" and record["id"] not in policy["open_icm_include_ids"]:
        reasons.add("outside_selected_book_scope")
    if source in ("bcpw-public-domain", "wikisource-maszynisci-1873"):
        reasons.add("historical_technical_archive_not_current_training")
    if source.startswith("bibliotekanauki-"):
        for item in metadata:
            reviewed = policy["reviewed_damaged_articles"].get(str(item["article_id"]))
            if reviewed:
                if item["pdf_sha256"] != reviewed["pdf_sha256"]:
                    raise ValueError("Reviewed damaged PDF changed; a new review is required")
                reasons.add("verified_unreliable_pdf_text_layout")
    return sorted(reasons)


def assign_groups(records: list[dict], metadata: dict[str, list[dict]], policy: dict) -> None:
    parents: dict[str, str] = {}

    def find(key: str) -> str:
        parents.setdefault(key, key)
        root = key
        while parents[root] != root:
            root = parents[root]
        while parents[key] != key:
            next_key = parents[key]
            parents[key] = root
            key = next_key
        return root

    for record in records:
        identities = [record, *record.get("_aliases", [])]
        keys = sorted({key for identity in identities for key in group_keys(identity, metadata[identity["id"]])})
        root = find(keys[0])
        for key in keys[1:]:
            other = find(key)
            if other != root:
                low, high = sorted((root, other))
                parents[high] = low
                root = low
        record["_group_keys"] = keys
        record["_exclusion_reasons"] = sorted({
            reason for identity in identities
            for reason in exclusion_reasons(identity, metadata[identity["id"]], policy)
        })
    group_reasons: dict[str, set[str]] = defaultdict(set)
    for record in records:
        record["_group_id"] = find(record["_group_keys"][0])
        group_reasons[record["_group_id"]].update(record["_exclusion_reasons"])
    for record in records:
        record["_exclusion_reasons"] = sorted(group_reasons[record["_group_id"]])
        record["_split"] = "quarantine" if record["_exclusion_reasons"] else split_for(record["_group_id"])


def split_for(group: str) -> str:
    # Preserve the original article-ID split algorithm for unaliased Biblioteka articles.
    seed = group.removeprefix("bibliotekanauki:") if group.startswith("bibliotekanauki:") else group
    bucket = int(hashlib.sha256(seed.encode("utf-8")).hexdigest()[:8], 16) % 100
    return "test" if bucket < 5 else "valid" if bucket < 10 else "train"


def balanced_samples(records: list[dict], limit: int = 32) -> list[dict]:
    """Round robin across source families; distinct books/documents first."""
    buckets: dict[str, list[dict]] = defaultdict(list)
    for record in sorted(records, key=lambda row: hashlib.sha256(row["id"].encode()).hexdigest()):
        buckets[record["source"]].append(record)
    queues = {}
    for source, rows in sorted(buckets.items()):
        seen = set()
        first, rest = [], []
        for row in rows:
            (rest if row["_group_id"] in seen else first).append(row)
            seen.add(row["_group_id"])
        queues[source] = deque(first + rest)
    sample = []
    while len(sample) < limit and any(queues.values()):
        for queue in queues.values():
            if queue and len(sample) < limit:
                sample.append(queue.popleft())
    return sample