File size: 5,456 Bytes
24aaa76 | 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 | #!/usr/bin/env python3
"""R5 PRINT stage A1b (second pass for thin languages): like r5_print_select.py, but keeps only documents where at least
60% of the pages carry the language label (per_page_languages) and ranks by that share, host cap 4.
R5 PRINT stage A1: pick candidate PDF URLs from HuggingFaceFW/finepdfs.
Reads ONLY metadata columns (never the text column) through range requests, keeps documents whose
`extractor` field is "docling" (finepdfs: text taken from the PDF's own text layer; the field is a
classifier guess from PDF metadata, so the text-layer check on the fetched PDF still decides later),
caps the number of documents per host, and writes candidates_<config>.jsonl.
No credentials are used (anonymous access). Run: python -I r5_print_select.py OUTDIR config1 config2 ...
"""
import json
import os
import random
import sys
import time
from urllib.parse import urlparse
import pyarrow.parquet as pq
from huggingface_hub import HfFileSystem
SEED = 20261121
REPO = "datasets/HuggingFaceFW/finepdfs/data"
COLS = ["id", "url", "extractor", "is_truncated", "language", "full_doc_lid",
"per_page_languages", "page_ends", "token_count", "dump"]
# hosts whose terms forbid reuse or that are known to be out of bounds
BLOCK_HOSTS = ("adebiportal.kz",)
# config -> (lang code of this project, shard list, max candidates, host cap)
CONF = {
"tuk_Latn": ("tk", ["000_00000.parquet"], 600, 4),
"bak_Cyrl": ("ba", ["000_00000.parquet"], 600, 4),
"sah_Cyrl": ("sah", ["000_00000.parquet"], 600, 4),
"tat_Cyrl": ("tt", ["000_00000.parquet"], 600, 4),
"kir_Cyrl": ("ky", ["000_00000.parquet"], 500, 4),
}
def host_of(url):
try:
h = urlparse(url).netloc.lower()
except Exception:
return ""
if h.startswith("www."):
h = h[4:]
return h
def main():
outdir = sys.argv[1]
configs = sys.argv[2:] or list(CONF)
os.makedirs(outdir, exist_ok=True)
fs = HfFileSystem()
rng = random.Random(SEED)
summary = {}
for cfg in configs:
lang, shards, maxc, hostcap = CONF[cfg]
t0 = time.time()
rows = []
n_all = 0
n_dock = 0
for sh in shards:
path = f"{REPO}/{cfg}/train/{sh}"
with fs.open(path, "rb") as f:
pf = pq.ParquetFile(f, pre_buffer=True)
nrg = pf.num_row_groups
for rg in range(nrg):
tb = pf.read_row_group(rg, columns=COLS)
d = tb.to_pydict()
for i in range(tb.num_rows):
n_all += 1
if d["extractor"][i] != "docling":
continue
n_dock += 1
pe = d["page_ends"][i] or []
npg = len(pe)
if npg < 1 or npg > 1500:
continue
ppl = d["per_page_languages"][i] or []
n_lang_pages = sum(1 for x in ppl if x == cfg)
if d["full_doc_lid"][i] != cfg and d["language"][i] != cfg:
continue
if n_lang_pages < min(2, npg) or n_lang_pages < 0.6 * npg:
continue
url = d["url"][i]
h = host_of(url)
if not h or any(h.endswith(b) for b in BLOCK_HOSTS):
continue
if not url.lower().startswith(("http://", "https://")):
continue
rows.append({"id": d["id"][i], "url": url, "host": h, "dump": d["dump"][i],
"pages": npg, "lang_pages": n_lang_pages,
"tokens": d["token_count"][i], "cfg": cfg, "lang": lang,
"lang_frac": round(n_lang_pages / npg, 3)})
# dedupe by url, cap per host, shuffle
seen = set()
uniq = []
for r in rows:
if r["url"] in seen:
continue
seen.add(r["url"])
uniq.append(r)
rng.shuffle(uniq)
uniq.sort(key=lambda r: 0 if r["lang_frac"] >= 0.9 else (1 if r["lang_frac"] >= 0.75 else 2))
per_host = {}
picked = []
for r in uniq:
c = per_host.get(r["host"], 0)
if c >= hostcap:
continue
per_host[r["host"]] = c + 1
picked.append(r)
if len(picked) >= maxc:
break
with open(os.path.join(outdir, f"candidates_{cfg}.jsonl"), "w", encoding="utf-8") as fo:
for r in picked:
fo.write(json.dumps(r, ensure_ascii=False) + "\n")
hosts_total = len({r["host"] for r in uniq})
summary[cfg] = {"lang": lang, "rows_read": n_all, "docling_rows": n_dock,
"after_filters_unique_urls": len(uniq), "hosts_after_filters": hosts_total,
"picked": len(picked), "picked_hosts": len(per_host and {r['host'] for r in picked}),
"host_cap": hostcap, "seconds": round(time.time() - t0, 1)}
print(cfg, json.dumps(summary[cfg]), flush=True)
with open(os.path.join(outdir, "select_summary_" + "_".join(configs)[:80] + ".json"), "w") as fs_:
json.dump(summary, fs_, indent=1)
if __name__ == "__main__":
main()
|