Download scripts/r5_print/r5_print_select.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 5.31 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_print/r5_print_select.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_print/r5_print_select.py
-
curl -L -o r5_print_select.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_print/r5_print_select.py
5.31 kB
| #!/usr/bin/env python3 | |
| """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 = { | |
| "kaz_Cyrl": ("kk", ["000_00000.parquet"], 320, 5), | |
| "kir_Cyrl": ("ky", ["000_00000.parquet"], 320, 6), | |
| "uzn_Cyrl": ("uz_cyrl", ["000_00000.parquet"], 320, 6), | |
| "uzn_Latn": ("uz_latn", ["000_00000.parquet"], 320, 6), | |
| "tur_Latn": ("tr", ["000_00000.parquet"], 360, 3), | |
| "azj_Latn": ("az", ["000_00000.parquet"], 320, 6), | |
| "tat_Cyrl": ("tt", ["000_00000.parquet"], 400, 10), | |
| "bak_Cyrl": ("ba", ["000_00000.parquet"], 400, 10), | |
| "tuk_Latn": ("tk", ["000_00000.parquet"], 400, 10), | |
| "sah_Cyrl": ("sah", ["000_00000.parquet"], 400, 10), | |
| } | |
| 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 < 1: | |
| 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}) | |
| # 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) | |
| 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() | |