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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
"""Cross-language article overlap for the FineWiki translation-resource audit.

Every FineWiki row carries a ``wikidata_id``. Two articles in different Wikipedias that
share a Wikidata item describe the same concept, so the size of the shared item set bounds
how many concept-aligned (comparable) article pairs a language pair can supply.

Only the ``wikidata_id`` column is ever needed. Small Parquet files are pulled whole because
a single sequential download beats hundreds of per-row-group range requests; large files use
column-projected range reads. Work is scheduled per Parquet file so that English, German and
French do not become one long serial task, and every file's parsed ids are cached so the run
is resumable.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import tempfile
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
CACHE = ROOT / "cache" / "lang_audit"
PART_DIR = CACHE / "qid_parts"
QID_DIR = CACHE / "qids"
DATASET = "HuggingFaceFW/finewiki"
PARQUET_REF = "refs/convert/parquet"
USER_AGENT = "gilaki-lang-audit/1.0"
# Deep enough that a language's best well-resourced pivot is in the list even when its
# nearest neighbours are all small wikis.
TOP_PARTNERS = 25
# Below this size a whole-file download is faster than range-reading every row group.
WHOLE_FILE_BYTES = 300_000_000
# Range reads cost one round trip per row group (~0.2 s), so large files are split into
# contiguous row-group slices read concurrently. Purely a latency workaround.
ROW_GROUPS_PER_SLICE = 120
SLICE_THREADS = 6


def _get_json(url: str, timeout: int = 180, token: str | None = None) -> dict:
    headers = {"User-Agent": USER_AGENT}
    if token:
        headers["Authorization"] = "Bearer " + token
    request = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.load(response)


def _token() -> str:
    sys.path.insert(0, str(ROOT / "scripts"))
    from hf_publishing_auth import publishing_token

    return publishing_token()


def finewiki_sizes() -> dict:
    url = (
        "https://datasets-server.huggingface.co/size?dataset="
        + urllib.parse.quote(DATASET, safe="")
    )
    payload = _get_json(url)
    if payload.get("partial"):
        raise RuntimeError("FineWiki size report is partial; refusing to build an audit from it")
    configs = {}
    for entry in payload["size"]["configs"]:
        if entry["config"] == "default":
            continue
        configs[entry["config"]] = {
            "articles": int(entry["num_rows"]),
            "bytes_original": int(entry.get("num_bytes_original_files") or 0),
            "bytes_parquet": int(entry.get("num_bytes_parquet_files") or 0),
        }
    if not configs:
        raise RuntimeError("FineWiki size report listed no language configs")
    return configs


def _retry(call, attempts: int = 5, delay: float = 3.0):
    last = None
    for attempt in range(attempts):
        try:
            return call()
        except Exception as error:  # noqa: BLE001 - network timeouts are expected here
            last = error
            if attempt + 1 < attempts:
                time.sleep(delay * (attempt + 1))
    raise last


def _descriptor(config: str, entry: dict) -> dict:
    return {
        "filename": entry["filename"],
        "path": f"{config}/{entry['split']}/{entry['filename']}",
        "size": int(entry.get("size") or 0),
        "url": entry["url"],
    }


def parquet_layout(configs) -> dict:
    """Parquet file descriptors for every config, from one bulk listing where possible."""
    base = "https://datasets-server.huggingface.co/parquet?dataset=" + urllib.parse.quote(
        DATASET, safe=""
    )
    layout: dict[str, list[dict]] = {}
    try:
        payload = _retry(lambda: _get_json(base, timeout=300))
        for entry in payload["parquet_files"]:
            if entry.get("split") != "train":
                continue
            layout.setdefault(entry["config"], []).append(_descriptor(entry["config"], entry))
    except Exception as error:  # noqa: BLE001 - fall back to per-config listing
        print(f"bulk Parquet listing failed ({error}); listing per config", flush=True)

    for config in configs:
        if config in layout:
            continue
        url = base + "&config=" + urllib.parse.quote(config, safe="")
        payload = _retry(lambda u=url: _get_json(u, timeout=180))
        files = [
            _descriptor(config, entry)
            for entry in payload["parquet_files"]
            if entry.get("split") == "train"
        ]
        if not files:
            raise RuntimeError(f"no train Parquet files listed for config {config!r}")
        layout[config] = files

    missing = [c for c in configs if c not in layout]
    if missing:
        raise RuntimeError(f"no Parquet layout for configs: {missing[:10]}")
    for config in layout:
        layout[config].sort(key=lambda f: f["filename"])
    return layout


def _parse_qids(values):
    """Parse a ``wikidata_id`` string array into a sorted unique int64 array."""
    import numpy as np

    raw = values.to_pylist()
    out = np.empty(len(raw), dtype=np.int64)
    kept = 0
    for value in raw:
        if not value or value[0] not in "Qq":
            continue
        digits = value[1:]
        if not digits.isdigit():
            continue
        out[kept] = int(digits)
        kept += 1
    return np.unique(out[:kept])


def _read_column_in_slices(repo_path: str, token: str):
    """Read ``wikidata_id`` from a large remote Parquet file with concurrent slice reads."""
    import pyarrow as pa
    import pyarrow.parquet as pq
    from huggingface_hub import HfFileSystem

    filesystem = HfFileSystem(token=token)
    with filesystem.open(repo_path, cache_type="none") as handle:
        groups = pq.ParquetFile(handle).num_row_groups
    if groups <= ROW_GROUPS_PER_SLICE:
        return pq.read_table(
            repo_path, columns=["wikidata_id"], filesystem=filesystem, pre_buffer=True
        )

    slices = [
        list(range(start, min(start + ROW_GROUPS_PER_SLICE, groups)))
        for start in range(0, groups, ROW_GROUPS_PER_SLICE)
    ]

    def one(row_groups):
        local = HfFileSystem(token=token)
        with local.open(repo_path, cache_type="none") as handle:
            return pq.ParquetFile(handle).read_row_groups(row_groups, columns=["wikidata_id"])

    with ThreadPoolExecutor(max_workers=min(SLICE_THREADS, len(slices))) as pool:
        tables = list(pool.map(one, slices))
    return pa.concat_tables(tables)


def read_part(config: str, descriptor: dict, token: str, force: bool = False) -> dict:
    """Cache the unique Wikidata ids found in one Parquet file."""
    import numpy as np
    import pyarrow.parquet as pq

    PART_DIR.mkdir(parents=True, exist_ok=True)
    stem = PART_DIR / f"{config}__{descriptor['filename']}"
    array_path = stem.with_suffix(".npy")
    meta_path = stem.with_suffix(".json")
    if not force and array_path.exists() and meta_path.exists():
        return json.loads(meta_path.read_text(encoding="utf-8"))

    started = time.time()
    repo_path = f"datasets/{DATASET}@{urllib.parse.quote(PARQUET_REF, safe='')}/{descriptor['path']}"
    if descriptor["size"] and descriptor["size"] < WHOLE_FILE_BYTES:
        mode = "download"
        handle, temp = tempfile.mkstemp(suffix=".parquet")
        os.close(handle)
        try:
            request = urllib.request.Request(
                descriptor["url"], headers={"User-Agent": USER_AGENT,
                                            "Authorization": "Bearer " + token}
            )
            with urllib.request.urlopen(request, timeout=900) as response, open(temp, "wb") as sink:
                while True:
                    chunk = response.read(4 << 20)
                    if not chunk:
                        break
                    sink.write(chunk)
            table = pq.read_table(temp, columns=["wikidata_id"])
        finally:
            os.unlink(temp)
    else:
        mode = "range"
        table = _read_column_in_slices(repo_path, token)

    unique = _parse_qids(table.column("wikidata_id").combine_chunks())
    np.save(array_path, unique)
    meta = {
        "config": config,
        "filename": descriptor["filename"],
        "mode": mode,
        "bytes": descriptor["size"],
        "rows": int(table.num_rows),
        "unique_wikidata_items": int(unique.size),
        "seconds": round(time.time() - started, 1),
    }
    meta_path.write_text(json.dumps(meta, ensure_ascii=False) + "\n", encoding="utf-8")
    return meta


def merge_config(config: str, descriptors: list[dict]) -> dict:
    """Combine a config's per-file id caches into one sorted unique array."""
    import numpy as np

    QID_DIR.mkdir(parents=True, exist_ok=True)
    parts = []
    rows = 0
    for descriptor in descriptors:
        stem = PART_DIR / f"{config}__{descriptor['filename']}"
        parts.append(np.load(stem.with_suffix(".npy")))
        rows += json.loads(stem.with_suffix(".json").read_text(encoding="utf-8"))["rows"]
    unique = np.unique(np.concatenate(parts)) if len(parts) > 1 else parts[0]
    np.save(QID_DIR / f"{config}.npy", unique)
    meta = {
        "config": config,
        "parquet_files": len(descriptors),
        "rows": rows,
        "unique_wikidata_items": int(unique.size),
    }
    (QID_DIR / f"{config}.json").write_text(
        json.dumps(meta, ensure_ascii=False) + "\n", encoding="utf-8"
    )
    return meta


def collect(configs, workers: int = 24, force: bool = False) -> tuple[dict, dict]:
    token = _token()
    layout_path = CACHE / "parquet_layout.json"
    if layout_path.exists() and not force:
        layout = json.loads(layout_path.read_text(encoding="utf-8"))
    else:
        print(f"listing Parquet files for {len(configs)} configs", flush=True)
        layout = parquet_layout(configs)
        layout_path.write_text(json.dumps(layout, ensure_ascii=False) + "\n", encoding="utf-8")

    tasks = [(c, d) for c in configs for d in layout[c]]
    whole = sum(d["size"] for _, d in tasks if d["size"] < WHOLE_FILE_BYTES)
    print(
        f"files: {len(tasks)}  whole-file download: {whole / 1e9:.1f} GB  "
        f"range-read files: {sum(1 for _, d in tasks if d['size'] >= WHOLE_FILE_BYTES)}",
        flush=True,
    )
    pending = [
        (c, d) for c, d in tasks
        if force or not (PART_DIR / f"{c}__{d['filename']}").with_suffix(".json").exists()
    ]
    # Largest first so the long tasks start immediately and short ones fill in behind them.
    pending.sort(key=lambda item: -item[1]["size"])
    print(f"cached files: {len(tasks) - len(pending)}  to fetch: {len(pending)}", flush=True)

    failures: dict[str, str] = {}
    done = 0
    if pending:
        with ThreadPoolExecutor(max_workers=workers) as pool:
            futures = {
                pool.submit(_retry, lambda c=c, d=d: read_part(c, d, token, force), 3, 5.0): (c, d)
                for c, d in pending
            }
            for future in as_completed(futures):
                config, descriptor = futures[future]
                try:
                    future.result()
                except Exception as error:  # noqa: BLE001 - retried on a later pass of the script
                    failures[f"{config}/{descriptor['filename']}"] = f"{type(error).__name__}: {error}"
                done += 1
                if done % 25 == 0 or done == len(pending):
                    print(f"  {done}/{len(pending)} files  failures={len(failures)}", flush=True)

    merged = {}
    for config in configs:
        if all(
            (PART_DIR / f"{config}__{d['filename']}").with_suffix(".json").exists()
            for d in layout[config]
        ):
            merged[config] = merge_config(config, layout[config])
    return merged, failures


def overlap_matrix(configs):
    """Return (ordered configs, shared-item matrix, per-language item counts, distinct items)."""
    import numpy as np
    from scipy.sparse import csr_matrix

    order = [c for c in configs if (QID_DIR / f"{c}.npy").exists()]
    arrays = [np.load(QID_DIR / f"{c}.npy") for c in order]
    sizes = np.array([a.size for a in arrays], dtype=np.int64)
    all_qids = np.concatenate(arrays)
    lang_index = np.repeat(np.arange(len(order), dtype=np.int32), sizes)
    del arrays
    unique, ranks = np.unique(all_qids, return_inverse=True)
    del all_qids
    membership = csr_matrix(
        (np.ones(ranks.size, dtype=np.int32), (ranks.astype(np.int64), lang_index)),
        shape=(unique.size, len(order)),
        dtype=np.int32,
    )
    del ranks, lang_index
    shared = (membership.T @ membership).toarray()
    return order, shared, sizes, int(unique.size)


def _entry(code, count, own):
    return {
        "language": code,
        "shared_items": int(count),
        "share_of_own_items": round(count / own, 4) if own else None,
    }


def partner_report(order, shared, sizes, top: int = TOP_PARTNERS) -> dict:
    index = {name: i for i, name in enumerate(order)}
    english = index.get("en")
    report = {}
    for i, name in enumerate(order):
        row = shared[i].copy()
        row[i] = 0
        own = int(sizes[i])
        ranked = sorted(
            ((order[j], int(row[j])) for j in range(len(order)) if row[j] > 0),
            key=lambda item: (-item[1], item[0]),
        )
        non_english = [item for item in ranked if item[0] != "en"]
        report[name] = {
            "unique_wikidata_items": own,
            "languages_sharing_any_item": len(ranked),
            "shared_with_en": int(shared[i][english]) if english is not None and english != i else None,
            "top_partners": [_entry(c, n, own) for c, n in ranked[:top]],
            "top_partners_excluding_en": [_entry(c, n, own) for c, n in non_english[:top]],
        }
    return report


def build(workers: int = 24, force: bool = False) -> dict:
    import numpy as np

    CACHE.mkdir(parents=True, exist_ok=True)
    configs = finewiki_sizes()
    names = sorted(configs)
    total = sum(c["articles"] for c in configs.values())
    print(f"FineWiki configs: {len(names)}  articles: {total:,}", flush=True)
    merged, failures = collect(names, workers=workers, force=force)
    if failures:
        print(f"file failures: {len(failures)} e.g. {sorted(failures)[:5]}", flush=True)
    order, shared, sizes, unique_total = overlap_matrix(names)
    np.savez_compressed(
        CACHE / "overlap_matrix.npz",
        order=np.array(order, dtype=object),
        shared=shared,
        sizes=sizes,
    )
    payload = {
        "source": f"https://huggingface.co/datasets/{DATASET}",
        "method": (
            "Shared Wikidata item ids between FineWiki language configs. Each count is the "
            "number of Wikidata items with an article in both Wikipedias, which bounds the "
            "number of concept-aligned (comparable) article pairs the pair can supply."
        ),
        "configs_requested": len(names),
        "configs_counted": len(order),
        "distinct_wikidata_items_total": unique_total,
        "per_language": partner_report(order, shared, sizes),
        "config_stats": merged,
        "file_failures": failures,
    }
    out = CACHE / "overlap.json"
    out.write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    print(
        f"wrote {out}  languages={len(order)}  distinct items={unique_total:,}",
        flush=True,
    )
    return payload


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--workers", type=int, default=24)
    parser.add_argument("--force", action="store_true", help="re-read cached id columns")
    args = parser.parse_args(argv)
    build(workers=args.workers, force=args.force)
    return 0


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