diff --git a/release/page-pipeline/infer.py b/release/page-pipeline/infer.py index 16be78b1d44c14b6f8955dad98eb3f9010c5553d..964d9dce7b47e6b2775fab220bc66c8eda87b279 100644 --- a/release/page-pipeline/infer.py +++ b/release/page-pipeline/infer.py @@ -27,16 +27,16 @@ import os os.environ.setdefault("HF_HUB_OFFLINE", "1") os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") -import argparse # noqa: E402 -import csv # noqa: E402 -import importlib.util # noqa: E402 -import json # noqa: E402 -import subprocess # noqa: E402 -import sys # noqa: E402 -import tempfile # noqa: E402 -import time # noqa: E402 - -from PIL import Image # noqa: E402 +import argparse +import csv +import importlib.util +import json +import subprocess +import sys +import tempfile +import time + +from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") diff --git a/release/turkic-line-detector-yolo11s/infer.py b/release/turkic-line-detector-yolo11s/infer.py index 523bf163ec88dd1a36eb167894b486829ad078a3..122b191f81f21eac4094c73c1ba21499808f7b1b 100644 --- a/release/turkic-line-detector-yolo11s/infer.py +++ b/release/turkic-line-detector-yolo11s/infer.py @@ -19,11 +19,11 @@ import tempfile os.environ.setdefault("YOLO_OFFLINE", "1") # no network access, no analytics, no font download os.environ.setdefault("YOLO_CONFIG_DIR", os.path.join(tempfile.gettempdir(), "ultralytics_cfg_turkic_ocr")) -import argparse # noqa: E402 -import csv # noqa: E402 -import json # noqa: E402 -import sys # noqa: E402 -import time # noqa: E402 +import argparse +import csv +import json +import sys +import time HERE = os.path.dirname(os.path.abspath(__file__)) IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") @@ -71,7 +71,7 @@ def main(): for rid, path in items: try: r = det.predict(path, imgsz=1280, conf=a.conf, iou=0.6, max_det=300, device=dev, verbose=False)[0] - except Exception as ex: # noqa: BLE001 + except Exception as ex: sys.stderr.write("cannot read %s: %s\n" % (path, repr(ex)[:120])) fo.write("%s\t0\t[]\t[]\n" % rid) continue diff --git a/release/turkic-ocr-paddleocr-vl-1.6/infer.py b/release/turkic-ocr-paddleocr-vl-1.6/infer.py index 1d80dce5e04cf10d5bf8e30647568528e213174e..587c271ef446b7527d9d4412d6b9d58e2170f03f 100644 --- a/release/turkic-ocr-paddleocr-vl-1.6/infer.py +++ b/release/turkic-ocr-paddleocr-vl-1.6/infer.py @@ -25,18 +25,18 @@ os.environ.setdefault("HF_HUB_OFFLINE", "1") os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") -import argparse # noqa: E402 -import copy # noqa: E402 -import csv # noqa: E402 -import json # noqa: E402 -import re # noqa: E402 -import sys # noqa: E402 -import time # noqa: E402 -import unicodedata # noqa: E402 +import argparse +import copy +import csv +import json +import re +import sys +import time +import unicodedata -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) INSTR = "Transcribe the text in this image exactly." @@ -50,7 +50,6 @@ def norm(text): return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip() -# ----------------------------------------------------------------------------------------- copied from vlm_common.py def template_kwargs(proc, tok): """enable_thinking=False for every model whose chat template uses that variable; others get no extra variable.""" texts = [] @@ -135,7 +134,6 @@ def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, return recs -# ----------------------------------------------------------------------------------------- the reader class Reader: """Loads the model of this package once; read() turns PIL images into texts.""" @@ -178,14 +176,14 @@ class Reader: try: recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set, self.dev, self.dtype) - except Exception as ex: # noqa: BLE001 (as in the evaluation: one at a time, an unreadable image gives an empty text) + except Exception as ex: sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150]) recs = [] for im in chunk: try: recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set, self.dev, self.dtype) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]}) for r in recs: r["text"] = norm(r["raw"]) @@ -193,7 +191,6 @@ class Reader: return out -# ----------------------------------------------------------------------------------------- input and output def collect_inputs(images=None, manifest=None): """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" if manifest: @@ -232,7 +229,7 @@ def main(): try: imgs.append(Image.open(p).convert("RGB")) keep.append(i) - except Exception as ex: # noqa: BLE001 + except Exception as ex: sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) t1 = time.time() recs = reader.read(imgs, a.unit, a.batch_size) diff --git a/release/turkic-ocr-ppocrv6-medium/infer.py b/release/turkic-ocr-ppocrv6-medium/infer.py index 5e70b80ad5db82eda759e281e9b3781baca9dc76..42d613c589b9fc10f775c9e29101c6315e9c408d 100644 --- a/release/turkic-ocr-ppocrv6-medium/infer.py +++ b/release/turkic-ocr-ppocrv6-medium/infer.py @@ -33,19 +33,19 @@ import os os.environ.setdefault("HF_HUB_OFFLINE", "1") -import argparse # noqa: E402 -import csv # noqa: E402 -import json # noqa: E402 -import math # noqa: E402 -import sys # noqa: E402 -import time # noqa: E402 -import unicodedata # noqa: E402 - -import numpy as np # noqa: E402 -import torch # noqa: E402 -import torch.nn.functional as F # noqa: E402 -from PIL import Image # noqa: E402 -from safetensors.torch import load_file # noqa: E402 +import argparse +import csv +import json +import math +import sys +import time +import unicodedata + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from safetensors.torch import load_file HERE = os.path.dirname(os.path.abspath(__file__)) IMG_EXT = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp") @@ -59,7 +59,6 @@ NEG = -1e30 LN10 = math.log(10.0) -# ----------------------------------------------------------------------------------------- images (data.py pil_tensor, collate) def pil_tensor(im, height): im = im.convert("RGB") w, h = im.size @@ -77,7 +76,6 @@ def collate(tensors): return torch.stack([F.pad(s, (0, wmax - s.shape[2])) for s in tensors]), seq_lens -# ----------------------------------------------------------------------------------------- network (models.py PPOCRArm.infer) class Recognizer: def __init__(self, model_dir=None, device="auto", threads=0): from kraken.lib.codec import PytorchCodec @@ -172,7 +170,6 @@ class Recognizer: return out -# ----------------------------------------------------------------------------------------- character language model (lm_decode.py) _LM = None _L2C = None @@ -292,7 +289,6 @@ class CharLM: return [_decode_one(j) for j in jobs] -# ----------------------------------------------------------------------------------------- input and output def collect_inputs(images=None, manifest=None): """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" if manifest: @@ -339,7 +335,7 @@ def main(): try: imgs.append(Image.open(p).convert("RGB")) keep.append(i) - except Exception as ex: # noqa: BLE001 + except Exception as ex: sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) t1 = time.time() outs = rec.read(imgs, a.batch_size, a.decode, lm, a.workers, a.sort, a.batch_pad) diff --git a/release/turkic-ocr-qwen3-vl-2b/infer.py b/release/turkic-ocr-qwen3-vl-2b/infer.py index 1d80dce5e04cf10d5bf8e30647568528e213174e..587c271ef446b7527d9d4412d6b9d58e2170f03f 100644 --- a/release/turkic-ocr-qwen3-vl-2b/infer.py +++ b/release/turkic-ocr-qwen3-vl-2b/infer.py @@ -25,18 +25,18 @@ os.environ.setdefault("HF_HUB_OFFLINE", "1") os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") -import argparse # noqa: E402 -import copy # noqa: E402 -import csv # noqa: E402 -import json # noqa: E402 -import re # noqa: E402 -import sys # noqa: E402 -import time # noqa: E402 -import unicodedata # noqa: E402 +import argparse +import copy +import csv +import json +import re +import sys +import time +import unicodedata -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image HERE = os.path.dirname(os.path.abspath(__file__)) INSTR = "Transcribe the text in this image exactly." @@ -50,7 +50,6 @@ def norm(text): return _WS.sub(" ", unicodedata.normalize("NFC", text or "")).strip() -# ----------------------------------------------------------------------------------------- copied from vlm_common.py def template_kwargs(proc, tok): """enable_thinking=False for every model whose chat template uses that variable; others get no extra variable.""" texts = [] @@ -135,7 +134,6 @@ def generate_batch(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, return recs -# ----------------------------------------------------------------------------------------- the reader class Reader: """Loads the model of this package once; read() turns PIL images into texts.""" @@ -178,14 +176,14 @@ class Reader: try: recs = generate_batch(self.model, self.proc, self.tok, chunk, max_new, self.tmpl_kw, self.gc, self.stop_set, self.dev, self.dtype) - except Exception as ex: # noqa: BLE001 (as in the evaluation: one at a time, an unreadable image gives an empty text) + except Exception as ex: sys.stderr.write("batch failed (%s); reading one image at a time\n" % repr(ex)[:150]) recs = [] for im in chunk: try: recs += generate_batch(self.model, self.proc, self.tok, [im], max_new, self.tmpl_kw, self.gc, self.stop_set, self.dev, self.dtype) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "conf": None, "conf_min": None, "error": repr(ex2)[:200]}) for r in recs: r["text"] = norm(r["raw"]) @@ -193,7 +191,6 @@ class Reader: return out -# ----------------------------------------------------------------------------------------- input and output def collect_inputs(images=None, manifest=None): """List of (id, path). A manifest is a TSV with a header and the columns id and image (other columns are ignored).""" if manifest: @@ -232,7 +229,7 @@ def main(): try: imgs.append(Image.open(p).convert("RGB")) keep.append(i) - except Exception as ex: # noqa: BLE001 + except Exception as ex: sys.stderr.write("cannot read %s: %s\n" % (p, repr(ex)[:120])) t1 = time.time() recs = reader.read(imgs, a.unit, a.batch_size) diff --git a/scripts/b1_page_check/b1_page_check.py b/scripts/b1_page_check/b1_page_check.py index ee48872a790ad052db186b4e67d7255940204ed7..29547f5640dbaa7e64d49f76ecf0d4122cfa800b 100644 --- a/scripts/b1_page_check/b1_page_check.py +++ b/scripts/b1_page_check/b1_page_check.py @@ -24,10 +24,10 @@ a = ap.parse_args() assert "test" not in os.path.basename(a.pages).lower(), "refusing a test page list" sys.path.insert(0, a.vlma) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image -import vlm_common as vc # noqa: E402 +import vlm_common as vc torch.set_num_threads(a.threads) PROMPTS = {"spot": "Spotting:", "ocr": "OCR:", "instr": vc.INSTR} diff --git a/scripts/b1_page_check/detb1_page_check.py b/scripts/b1_page_check/detb1_page_check.py index 3f534d370b58d1b34e41b04f1bf4ece2b0908047..150c0dc074a98ad7c4455611fd9c24d485ed93ac 100644 --- a/scripts/b1_page_check/detb1_page_check.py +++ b/scripts/b1_page_check/detb1_page_check.py @@ -21,10 +21,10 @@ a = ap.parse_args() assert "test" not in os.path.basename(a.pages).lower() sys.path.insert(0, a.vlma) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image -import vlm_common as vc # noqa: E402 +import vlm_common as vc torch.set_num_threads(a.threads) SCHOOL = "/path/to/TURKIC_OCR_DATA/data/raw/school_notebooks_ru" diff --git a/scripts/j2/collect.py b/scripts/j2/collect.py index 31180f69a8df73800d0aa17106aed1d798dd1cfe..097fea4b432e6fac110a82585ec8e6542ee20533 100644 --- a/scripts/j2/collect.py +++ b/scripts/j2/collect.py @@ -40,7 +40,7 @@ def read_jsonl(path): continue try: recs.append(json.loads(line)) - except Exception: # noqa: BLE001 (half-written line of a killed job) + except Exception: bad += 1 return recs, bad diff --git a/scripts/j2/control_report.py b/scripts/j2/control_report.py index 1f653387b5d4245e9036c2d33ae833316381ffed..3361b7306a04e393e837afff78906cfb15fa4b3d 100644 --- a/scripts/j2/control_report.py +++ b/scripts/j2/control_report.py @@ -29,7 +29,7 @@ for dev, root in roots: for line in open(pp, encoding="utf-8"): try: r = json.loads(line) - except Exception: # noqa: BLE001 + except Exception: continue preds[r["crop_file"]] = r for H in (40, 80): diff --git a/scripts/j2/controls2_report.py b/scripts/j2/controls2_report.py index b3b7239c095488e43d6f35f7899c0ac69e38213d..632b3fb2497876dc5cf2d22d4bf3f35211e12969 100644 --- a/scripts/j2/controls2_report.py +++ b/scripts/j2/controls2_report.py @@ -25,7 +25,7 @@ def read_preds(path): for line in open(path, encoding="utf-8"): try: r = json.loads(line) - except Exception: # noqa: BLE001 + except Exception: continue preds[r["crop_file"]] = r return preds @@ -51,7 +51,7 @@ def block(name, model, rows, preds, pick): ay = sl.aggregate(lang["ky"]) if lang["ky"] else {} lab = dict(rows) five = " | ".join(f"{lab[c]} => {preds[c]['raw']!r}" for c in pick if c in preds) - fmt = lambda d, k: f"{d[k]:.4f}" if k in d else "" # noqa: E731 + fmt = lambda d, k: f"{d[k]:.4f}" if k in d else "" return "\t".join([name, model, str(len(sc)), f"{a['cer_pooled']:.4f}", f"{a['cer_mean_cap1']:.4f}", f"{a['exact']:.4f}", fmt(ak, "cer_pooled"), fmt(ay, "cer_pooled"), f"{a['hr4_loop_share']:.4f}", f"{a['empty_share']:.4f}", f"{a['other_script_share']:.4f}", five]) @@ -70,7 +70,7 @@ stored, stretch, fonts = (read_list(os.path.join(c2, n)) for n in ("contrast_stored_screen_set_v1.tsv", "contrast_stretch_screen_set_v1.tsv", "fonts_screen_set_v1.tsv")) printed40 = [(c, l) for c, l in read_list(printed_list) if "_h40_" in c] for m in models: - first5 = lambda rows: [c for c, _ in rows[:5]] # noqa: E731 + first5 = lambda rows: [c for c, _ in rows[:5]] for name, rows, root in (("A1 KOHTD first 300 crops, as stored", stored, "out_stored"), ("A2 KOHTD first 300 crops, contrast stretch p1-p99", stretch, "out_stretch")): r = block(name, m, rows, read_preds(os.path.join(c2, root, m, "s1", "preds.jsonl")), first5(rows)) diff --git a/scripts/j2/eligibility.py b/scripts/j2/eligibility.py index eaa5998bafe79102576b0fe7d38e7c3489c604fa..a46bf32420f9cb0d9fbf06df624005eff65a29c0 100644 --- a/scripts/j2/eligibility.py +++ b/scripts/j2/eligibility.py @@ -120,7 +120,7 @@ for short, repo, design_params, size_class in rows: got.append(os.path.relpath(os.path.join(root, fn), local)) rec["downloaded_files"] = sorted(g for g in got if not g.startswith(".cache")) assert not any(g.endswith(".py") for g in got), "a .py file was downloaded" - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("fetch: " + repr(e)[:300]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1) print(short, "FETCH ERROR", repr(e)[:200], flush=True) @@ -135,7 +135,7 @@ for short, repo, design_params, size_class in rows: rec.update(native_info(cfg_dict)) archs = cfg_dict.get("architectures") or [] rec["arch_class_in_transformers"] = [bool(getattr(transformers, a, None)) for a in archs] - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("config read: " + repr(e)[:300]) cfg_dict = {} @@ -145,7 +145,7 @@ for short, repo, design_params, size_class in rows: cfg = transformers.AutoConfig.from_pretrained(local, trust_remote_code=False) rec["autoconfig_class"] = type(cfg).__module__ + "." + type(cfg).__name__ rec["autoconfig_native"] = type(cfg).__module__.startswith("transformers.") - except Exception as e: # noqa: BLE001 + except Exception as e: rec["autoconfig_native"] = False rec["errors"].append("AutoConfig: " + repr(e)[:300]) @@ -178,7 +178,7 @@ for short, repo, design_params, size_class in rows: rec["meta_params_unique"] = n rec["meta_construct_ok"] = True del m - except Exception as e: # noqa: BLE001 + except Exception as e: rec["meta_construct_ok"] = False rec["errors"].append("meta construct: " + repr(e)[:300]) @@ -189,7 +189,7 @@ for short, repo, design_params, size_class in rows: kind = "hf" rec["tokenizer_class"] = type(tok).__module__ + "." + type(tok).__name__ rec["tokenizer_native"] = type(tok).__module__.startswith("transformers.") - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("AutoTokenizer: " + repr(e)[:300]) tj = os.path.join(local, "tokenizer.json") if os.path.exists(tj): @@ -199,7 +199,7 @@ for short, repo, design_params, size_class in rows: kind = "raw" rec["tokenizer_class"] = "tokenizers.Tokenizer(from tokenizer.json, data only)" rec["tokenizer_native"] = True - except Exception as e2: # noqa: BLE001 + except Exception as e2: rec["errors"].append("tokenizers.from_file: " + repr(e2)[:300]) rec["tokenizer_kind"] = kind if tok is not None: @@ -221,7 +221,7 @@ for short, repo, design_params, size_class in rows: rec["e3_labels_bad_examples"] = [[a, b] for a, b in bad_l[:12]] rec["e3_labels_bad_strip_equal"] = sum(1 for a, b in bad_l if a.strip() == b.strip()) rec["e3_unk_ids_labels"] = unk_l - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("roundtrip: " + repr(e)[:300] + traceback.format_exc()[-300:]) # processor, trust_remote_code=False @@ -231,7 +231,7 @@ for short, repo, design_params, size_class in rows: rec["processor_native"] = type(proc).__module__.startswith("transformers.") tmpl = getattr(proc, "chat_template", None) rec["chat_template_present"] = bool(tmpl) or bool(getattr(getattr(proc, "tokenizer", None), "chat_template", None)) - except Exception as e: # noqa: BLE001 + except Exception as e: rec["processor_native"] = False rec["errors"].append("AutoProcessor: " + repr(e)[:300]) diff --git a/scripts/j2/fetch_weights_loadtest.py b/scripts/j2/fetch_weights_loadtest.py index 37ca0c7eb4dfb621ffccc56ed8194f3e0f748002..6f5c3f6ae97fab28ff963f69211325cc8f98a3a0 100644 --- a/scripts/j2/fetch_weights_loadtest.py +++ b/scripts/j2/fetch_weights_loadtest.py @@ -81,7 +81,7 @@ for short in shorts: rec["ckpt_params_header"] = ck_params rec["ckpt_tensors_header"] = ck_tensors rec["download_seconds"] = round(time.time() - t0, 1) - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("fetch: " + repr(e)[:400]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1) print(short, "FETCH ERROR", repr(e)[:300], flush=True) @@ -120,7 +120,7 @@ for short in shorts: else "FAIL") rec["load_seconds"] = round(time.time() - t1, 1) del model - except Exception as e: # noqa: BLE001 + except Exception as e: rec["load_gate"] = "FAIL" rec["errors"].append("load: " + repr(e)[:500]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str) diff --git a/scripts/j2/make_controls2_set.py b/scripts/j2/make_controls2_set.py index e3b131fb901befdba7e5908cd10381c6634bac69..3a191e57f5c8fd3e1ee3e10b7deeb8c89e8fa325 100644 --- a/scripts/j2/make_controls2_set.py +++ b/scripts/j2/make_controls2_set.py @@ -14,7 +14,6 @@ spec.loader.exec_module(cs) os.makedirs(os.path.join(out_dir, "img_stretch"), exist_ok=True) os.makedirs(os.path.join(out_dir, "img_fonts"), exist_ok=True) -# ---- A: contrast rows = [] with open(screen_set, encoding="utf-8", newline="") as f: f.readline() @@ -48,7 +47,6 @@ print("A: 300 crops; grey 1st/99th percentile mean before %.1f / %.1f, after %.1 print("A: crops whose 1st percentile was already below 30: %d; whose 99th was above 225: %d" % ( sum(1 for v in p1b if v < 30), sum(1 for v in p99b if v > 225))) -# ---- B: handwriting fonts words = [] with open(words_tsv, encoding="utf-8", newline="") as f: f.readline() diff --git a/scripts/j2/raw_samples.py b/scripts/j2/raw_samples.py index e35ba700638ac2050b2737d583817b9a7ec065a0..39bbf5e28fd87cdb58152377106a99d09cedc17f 100644 --- a/scripts/j2/raw_samples.py +++ b/scripts/j2/raw_samples.py @@ -26,7 +26,7 @@ for model in sorted(os.listdir(out_root)): for line in open(pp, encoding="utf-8"): try: r = json.loads(line) - except Exception: # noqa: BLE001 + except Exception: continue preds[r["crop_file"]] = r done = [c for c in sample if c in preds] diff --git a/scripts/j2/run_screen.py b/scripts/j2/run_screen.py index 45a66f182c7907a7f4519a9c03ab407968fdea58..0ddac0598ab90ebba4a955f5a79a5a8e2538b891 100644 --- a/scripts/j2/run_screen.py +++ b/scripts/j2/run_screen.py @@ -131,7 +131,7 @@ revision = None try: lt = json.load(open(os.path.join(os.path.dirname(os.path.abspath(args.out_root)), "j11_stage1_kohtd", "loadtest", args.short + ".json"))) revision = lt.get("revision") -except Exception: # noqa: BLE001 +except Exception: pass @@ -177,7 +177,7 @@ def generate_batch(imgs): new = out[:, in_len:] try: texts = processor.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) - except Exception: # noqa: BLE001 + except Exception: texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False) recs = [] for r in range(new.shape[0]): @@ -202,7 +202,7 @@ def run_scale(scale, out_dir, bs, list_crops): for line in open(pred_path, encoding="utf-8"): try: done.add(json.loads(line)["crop_file"]) - except Exception: # noqa: BLE001 + except Exception: pass todo = [c for c in list_crops if c not in done] print(f"[{args.short}] scale {scale}x: done {len(done)}, to do {len(todo)}", flush=True) @@ -222,7 +222,7 @@ def run_scale(scale, out_dir, bs, list_crops): imgs = [load_image(c, scale) for c in batch] t_img = time.time() - ti recs, t_pre, t_gen = generate_batch(imgs) - except Exception as e: # noqa: BLE001 + except Exception as e: print(f"[{args.short}] batch failed ({repr(e)[:200]}); one crop at a time", flush=True) if use_cuda: torch.cuda.empty_cache() @@ -233,7 +233,7 @@ def run_scale(scale, out_dir, bs, list_crops): recs.append(r1[0]) t_pre += a t_gen += g - except Exception as e2: # noqa: BLE001 + except Exception as e2: errors += 1 recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_img_tokens": -1, "in_len": -1, "error": repr(e2)[:300]}) diff --git a/scripts/k1_build_split.py b/scripts/k1_build_split.py index 4f0b3b23962e9bb1f4e8deee1796eff8e49b4777..9b6c2674a69a4d0c89c3afac14c86bd8d4838a11 100644 --- a/scripts/k1_build_split.py +++ b/scripts/k1_build_split.py @@ -1,7 +1,3 @@ -# K1 (runs on the cluster): build the KOHTD form-disjoint split exactly as OUT/split_spec_v1.txt says. -# usage: python k1_build_split.py -# scan_map.tsv: header, then "stemsheet" for scan-named crops shown to be cuts of a sheet (their split = that sheet's form's split) -# Text only: no image is read. import collections import hashlib import os diff --git a/scripts/k1_labels_all.py b/scripts/k1_labels_all.py index b33344334b1bb6bce5b9d0e46e0e4426e310459a..7db964e0615b9bae9e5c96e7037f718ebea6cbee 100644 --- a/scripts/k1_labels_all.py +++ b/scripts/k1_labels_all.py @@ -1,5 +1,3 @@ -# K1 (runs on the cluster, ZEN4): read every KOHTD ann file (JSON with the label) and write one TSV: file stem, label. -# Text only; no image is read. usage: python k1_labels_all.py import json import os import sys diff --git a/scripts/kohtd_leak_scan.py b/scripts/kohtd_leak_scan.py index 0d3392f917c25e09485e735d4f4e206fb28dad39..76fed31847485b793b2ad9a75bc3979dad910c56 100644 --- a/scripts/kohtd_leak_scan.py +++ b/scripts/kohtd_leak_scan.py @@ -21,7 +21,7 @@ OUT = sys.argv[1] WORKERS = int(sys.argv[2]) SEED = 20261125 PREFIX = "KOHTD-split-v1-2026-11-20:" -STD_MIN = 5.0 # near-blank filter, as in K1 +STD_MIN = 5.0 ASPECT_LOG = math.log(1.15) # aspect-ratio gate: within 15 percent EXPECT = {"train_numbered": 80513, "validation": 16238, "test": 18615, "scan": 24989} FONT = "/path/to/TURKIC_OCR_CODE/.venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf" diff --git a/scripts/r5/r5_build_real.py b/scripts/r5/r5_build_real.py index c8e4940b3f9016f72f45a12163a2d75a99367d9e..b3347b75aa1567aaa094bbf98508fef51bd7e2d2 100644 --- a/scripts/r5/r5_build_real.py +++ b/scripts/r5/r5_build_real.py @@ -116,7 +116,7 @@ def stage_kohtd(): altered[sp] += 1 if key_type == "numbered": grp = "kohtd_form_" + form_id - else: # scan-named crop: the unit is the scan file name (split_spec_v1, K1 report) + else: grp = "kohtd_scan_" + crop_file[:-4].replace("word_croped_", "", 1).rsplit("_", 2)[0] rows.append(row("kohtd:" + crop_file[:-4], KOHTD_IMG / crop_file, t, "kk", "Cyrl", "hand_real", "kohtd", "val" if sp == "val" else sp, grp, "word")) @@ -361,7 +361,7 @@ def school_page_job(args): if im.size != (W, H): return fn, [], {"error": "size_mismatch", "got": im.size, "want": (W, H)} page = cv2.cvtColor(np.array(im.convert("RGB")), cv2.COLOR_RGB2BGR) - except Exception as e: # noqa + except Exception as e: return fn, [], {"error": repr(e)} out_rows = [] skipped = collections.Counter() @@ -693,7 +693,6 @@ def stage_dedupe(): print(json.dumps(info, ensure_ascii=False)[:3500]) - # synthetic manifests: hash and report-only duplicate check def synth_manifest_names(): return sorted(q.stem for pat in ("synth_*.tsv", "az_localdoc_*.tsv") for q in MAN.glob(pat) if q.stem.rsplit("_", 1)[-1] in ("train", "val", "test")) diff --git a/scripts/r5/r5_registry.py b/scripts/r5/r5_registry.py index bdb4671e4b4359dbd83d31e17b6bc77d16cba7a8..9a90f52b1d5ad63245247afcdac60a31ae200375 100644 --- a/scripts/r5/r5_registry.py +++ b/scripts/r5/r5_registry.py @@ -66,7 +66,6 @@ p2info = json.load(open(R5 / "p2_slice_info.json")) if (R5 / "p2_slice_info.json p2_final = bool(p2info.get("final")) sets = [ - # ---- validation sets (selection only; never used for the final claim) entry("V1", "kohtd_screen_v1", "val", "KOHTD validation screen set of the zero-shot screen: at most 15 crops per validation form, 3,678 crops (screen rule v1). Selection of B1 and B2 by amendment 3.2 C6 uses CER on this set.", False, group_unit="KOHTD form", source_of_list="records/R4/J2_screen/screen_set_v1.tsv, sha256 aca23aed02629f884cd533761ca2553951eb91cc9b15120a25c88071f54198ec (matches the cluster copy), used unchanged", @@ -91,7 +90,6 @@ sets = [ entry("synth_typed_val", "synth_typed_val", "val", "Synthetic typed line crops (500 per language-script planned).", False, group_unit="source document", owner="GEN"), entry("synth_clutter_val", "synth_clutter_val", "val", "Clutter crops with no text; the target is the empty string (500 planned). Measures hallucination.", False, owner="GEN"), entry("synth_pages_val", "synth_pages_val", "val", "Composed pages with line boxes and polygons (300 planned), for detector validation.", False, owner="GEN"), - # ---- test sets (locked) entry("kohtd_test", "kohtd_test", "test", "Primary endpoint P1: CER on all 18,615 KOHTD test crops of 305 forms.", True, group_unit="KOHTD form", endpoint="P1", split_rule="K1 split v1, share 85..99 of the form hash", caution="form-disjoint, not writer-disjoint (writer ids do not exist); labels are crowd labels (two volunteers agreeing)"), @@ -138,7 +136,6 @@ reg = { } json.dump(reg, open(R5 / "evalsets.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) -# ---- effective mix_v1 shares n_train = {k: mstats[k]["rows"] for k in ("kohtd_train", "hkr_train", "chd_train", "school_train") if k in mstats} latin_items = 0 # no Turkish (or other Latin-script) handwriting word or line set is held: the Turkish sets are single characters latin_cap_share = min(0.05, 5 * latin_items / 1e6) diff --git a/scripts/r5_erran/erran_analysis.py b/scripts/r5_erran/erran_analysis.py index 2e6d3267ad54b65bfcb63bbf5636c47b6d9e1bf5..630f898fa76e269c98b99bcd371364550395c8c1 100644 --- a/scripts/r5_erran/erran_analysis.py +++ b/scripts/r5_erran/erran_analysis.py @@ -9,12 +9,12 @@ import unicodedata import numpy as np sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import stats # noqa: E402 -from r5eval.align import align_ops, lev_fast # noqa: E402 -from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket # noqa: E402 -from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic # noqa: E402 -from r5eval.lookalike import PARTNER, repair_label # noqa: E402 -from r5eval.textnorm import fold_lower, char_script_set, norm # noqa: E402 +from r5eval import stats +from r5eval.align import align_ops, lev_fast +from r5eval.analyse import COLLAPSE, LETTERS, LEN_EDGES, length_bucket +from r5eval.ioutil import read_manifest, read_preds, read_meta_tsv, sha256_file, write_json_atomic +from r5eval.lookalike import PARTNER, repair_label +from r5eval.textnorm import fold_lower, char_script_set, norm D = "/path/to/TURKIC_OCR_DATA" PREDS = D + "/outputs/r5/preds" diff --git a/scripts/r5_erran/erran_sample.py b/scripts/r5_erran/erran_sample.py index f2a020a06f67001b355d9adfacf66318565b621b..2347b4949fa541b401312863e988491b4d3961d3 100644 --- a/scripts/r5_erran/erran_sample.py +++ b/scripts/r5_erran/erran_sample.py @@ -7,7 +7,7 @@ import numpy as np from PIL import Image, ImageDraw, ImageFont sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval.ioutil import read_manifest # noqa: E402 +from r5eval.ioutil import read_manifest SEED = 20261122 N_PER_ARM = 120 diff --git a/scripts/r5_freeze/compare_parsers.py b/scripts/r5_freeze/compare_parsers.py index 21d072e893916386db69ef9d059d954e01ebb467..531fec1fb262e6ab7ed40a97e5aeb464721d2a4b 100644 --- a/scripts/r5_freeze/compare_parsers.py +++ b/scripts/r5_freeze/compare_parsers.py @@ -20,11 +20,11 @@ def key(manifest, flt): readers = {} -from linedet.data import load_mix as ld_load # noqa: E402 +from linedet.data import load_mix as ld_load readers["LINEDET linedet.data.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in ld_load(yml)} -import ref_make_mix_lists as REF # noqa: E402 +import ref_make_mix_lists as REF readers["REF ref_make_mix_lists.load_mix"] = {key(c["manifest"], c["filter"]): (c["share"], c["name"]) for c in REF.load_mix(yml)} -from r5eval.ktrain import read_mix_leaves # noqa: E402 +from r5eval.ktrain import read_mix_leaves kt = read_mix_leaves(yml) readers["EVALCODE r5eval.ktrain.read_mix_leaves (no shares)"] = {key(c["manifest"], c["filter"]): (None, c["name"]) for c in kt} s = json.load(open(vsum, encoding="utf-8")) diff --git a/scripts/r5_linedet/inspect_models.sbatch b/scripts/r5_linedet/inspect_models.sbatch index 7e8f66df7ba95bae3c36a2aee42c372c597d38cb..7d71adb1dee0af794d4dbdd853e4faa74a1d4949 100644 --- a/scripts/r5_linedet/inspect_models.sbatch +++ b/scripts/r5_linedet/inspect_models.sbatch @@ -16,7 +16,6 @@ $HOME/.local/bin/uv pip freeze --python $CODE/.venv_kraken/bin/python > $DATA/ou OUT=$DATA/outputs/r5/linedet/base_models mkdir -p $OUT SITE=$CODE/.venv_kraken/lib/python3.12/site-packages -# rule 0.11: sha256 of every .py file of the maker packages that can run find $SITE/kraken $SITE/ultralytics -name '*.py' | sort | xargs sha256sum > $DATA/outputs/r5/linedet/maker_py_sha256.txt wc -l $DATA/outputs/r5/linedet/maker_py_sha256.txt cd $CODE diff --git a/scripts/r5_loopguard/lg_a1_first_step.py b/scripts/r5_loopguard/lg_a1_first_step.py index a58890e421a4b88e18b6d81def6e4345cf4873ca..5d039cf715617b4b4f2dfe9d9707772a8a89c643 100644 --- a/scripts/r5_loopguard/lg_a1_first_step.py +++ b/scripts/r5_loopguard/lg_a1_first_step.py @@ -5,12 +5,12 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -from PIL import Image # noqa: E402 -from transformers import NoRepeatNGramLogitsProcessor # noqa: E402 +import torch +from PIL import Image +from transformers import NoRepeatNGramLogitsProcessor ap = argparse.ArgumentParser() ap.add_argument("--ids", required=True) diff --git a/scripts/r5_loopguard/lg_det_prep.py b/scripts/r5_loopguard/lg_det_prep.py index 04aeb47725aa466341f808d8177088e296aa972c..5ffd511ce44e210b7fa332742439d4386f9bce21 100644 --- a/scripts/r5_loopguard/lg_det_prep.py +++ b/scripts/r5_loopguard/lg_det_prep.py @@ -8,8 +8,8 @@ import zipfile CODE = "/path/to/TURKIC_OCR_CODE" sys.path.insert(0, CODE + "/src") -from linedet import det_prep as DP # noqa: E402 -from linedet.common import DATA, write_tsv # noqa: E402 +from linedet import det_prep as DP +from linedet.common import DATA, write_tsv csv.field_size_limit(10 ** 9) HEADER = ["id", "image", "width", "height", "scale", "n_lines", "boxes_json", "polys_json", "baselines_json", "ref_lines_json", "note"] diff --git a/scripts/r5_loopguard/lg_detect.py b/scripts/r5_loopguard/lg_detect.py index 9fcf1d7ce8f363e81c321b132587eaa7bfffea3a..ce6e25e2b2993a41eb31d486a6f57bf1f85203ba 100644 --- a/scripts/r5_loopguard/lg_detect.py +++ b/scripts/r5_loopguard/lg_detect.py @@ -7,7 +7,7 @@ import time os.environ.setdefault("YOLO_OFFLINE", "1") os.environ.setdefault("YOLO_CONFIG_DIR", "/path/to/TURKIC_OCR_DATA/tmp/ultralytics_cfg") -import torch # noqa: E402 +import torch csv.field_size_limit(10 ** 9) ap = argparse.ArgumentParser() @@ -21,7 +21,7 @@ ap.add_argument("--max-pages", type=int, default=0) ap.add_argument("--threads", type=int, default=16) a = ap.parse_args() torch.set_num_threads(a.threads) -from ultralytics import YOLO # noqa: E402 +from ultralytics import YOLO with open(a.pages, encoding="utf-8", newline="") as f: pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) @@ -33,7 +33,7 @@ if os.path.exists(a.out): for ln in open(a.out, encoding="utf-8"): try: done.add(json.loads(ln)["id"]) - except Exception: # noqa: BLE001 + except Exception: pass det = YOLO(a.weights) with open(a.out, "a", encoding="utf-8") as fo: diff --git a/scripts/r5_loopguard/lg_flags.py b/scripts/r5_loopguard/lg_flags.py index f9a3be4f1998fa9e38670102bb6727726de52efe..2e761c507e7de720c9bc88506ec72b2d06e52ab4 100644 --- a/scripts/r5_loopguard/lg_flags.py +++ b/scripts/r5_loopguard/lg_flags.py @@ -5,7 +5,7 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T ap = argparse.ArgumentParser() ap.add_argument("mode", choices=["val", "heldout"]) diff --git a/scripts/r5_loopguard/lg_run_gpu.sh b/scripts/r5_loopguard/lg_run_gpu.sh index bd473971f9129a313076e986f3e457ceff3537e3..3f5067036981a34ab3ee1517e9bc464a29da1378 100644 --- a/scripts/r5_loopguard/lg_run_gpu.sh +++ b/scripts/r5_loopguard/lg_run_gpu.sh @@ -93,26 +93,21 @@ score() { # tag, om_score options...: any non-zero exit stops the job before a } hostname; nvidia-smi --query-gpu=name,memory.total --format=csv,noheader 2>/dev/null || echo "no GPU visible (device $DEV)"; date -u +%FT%TZ echo "LOOPGUARD-1 job $SLURM_JOB_ID, resubmission $N of $MAXR, device $DEV, out $O, limit $LIMIT s, dry ${DRY:-no}" -# ---- 0 checks ( cd / && sha256sum -c --quiet $S/lg_pins_val.sha256 ) || fail "a pinned validation input changed" 3 if [ -z "$DRY" ]; then grep -q '"passed": true' $OFFICIAL/prep.done.json 2>/dev/null || fail "prep.done.json missing or not passed" 3 ( cd / && sha256sum -c --quiet $S/lg_pins_heldout.sha256 ) || fail "a pinned held-out input changed" 3 fi echo "=== checks passed $(date -u +%FT%TZ)" -# ---- 0b the fresh control arm A0 (unguarded, all validation pages, batch 8, no batch-1 probe) evalpages A0 A0 gen_val,school_val "--batch 8 --batch1-probe 0" -# ---- 1, 2 validation arms evalpages A1 A1 gen_val,school_val evalpages A2 A2 gen_val,school_val -# ---- 2b acceptance (before any score is read) $PK -I $S/lg_accept.py --a0 $A0F --a1 $O/page_preds/A1 --a2 $O/page_preds/A2 --stored $A0STORED --tol 0.01 --out $O/acceptance.json $XA RC=$? if [ $RC -ne 0 ]; then [ -z "$DRY" ] && fail "acceptance checks (exit $RC): investigate before scoring; no selection, no UNSEAL" 4 echo "DRY RUN: acceptance failed (exit $RC), continuing to exercise the scorer" fi -# ---- 3 validation scoring and selection if [ ! -f $O/selection.json ]; then echo "=== validation scoring $(date -u +%FT%TZ)" $PK -I $S/lg_flags.py val --a2 $O/page_preds/A2 --a0 $A0F --out $O/flags_val.json || fail "flags" @@ -128,7 +123,6 @@ fi SEL=$(head -n 1 $O/SELECTED) echo "selected: $SEL" if [ -n "$DRY" ]; then echo "DRY RUN: stops after selection; held-out stages are never run in a dry run"; rm -f $GUARD; exit 0; fi -# ---- 4 held-out runs, only under the unseal token if [ ! -f $UNSEAL ]; then if [ "$SEL" != "NONE" ]; then fail "arm $SEL was selected but no unseal token exists (see selection.json unseal_decision)" 6; fi echo "=== no arm eligible: the held-out sets stay sealed $(date -u +%FT%TZ)" @@ -143,7 +137,6 @@ case "$SEL" in evalpages $SEL $SEL clutter_spot "--max-new 256" ;; esac -# ---- 5 held-out scoring and confirmation if [ ! -f $O/confirm.json ]; then echo "=== held-out scoring $(date -u +%FT%TZ)" $PK -I $S/lg_flags.py heldout --a0obs $O/page_preds/A0obs --out $O/flags_test.json || fail "held-out flags" diff --git a/scripts/r5_loopguard/lg_smoke_check.py b/scripts/r5_loopguard/lg_smoke_check.py index ac7b68535b6e81f53330369f3df359fea83f7575..d2d2c4b1bc65c3e3ff5161bef4779198fdfffa31 100644 --- a/scripts/r5_loopguard/lg_smoke_check.py +++ b/scripts/r5_loopguard/lg_smoke_check.py @@ -5,7 +5,7 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T D = "/path/to/TURKIC_OCR_DATA" ap = argparse.ArgumentParser() diff --git a/scripts/r5_loopguard/om_baseline.py b/scripts/r5_loopguard/om_baseline.py index 3189d0ad3423c9e28312072afafb6c9b55296ddc..23ac6499200a4ef25b894e42a0b9a6a26b606c95 100644 --- a/scripts/r5_loopguard/om_baseline.py +++ b/scripts/r5_loopguard/om_baseline.py @@ -8,11 +8,11 @@ import unicodedata HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image vc = C.vc csv.field_size_limit(10 ** 9) diff --git a/scripts/r5_loopguard/om_build_pages.py b/scripts/r5_loopguard/om_build_pages.py index 8099477fd301c8bd2741c69069bf62e3cbf5f68e..cb169231598cdf60c3f00b7b95e9983db751a377 100644 --- a/scripts/r5_loopguard/om_build_pages.py +++ b/scripts/r5_loopguard/om_build_pages.py @@ -12,7 +12,7 @@ import zipfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T csv.field_size_limit(10 ** 9) DATA = "/path/to/TURKIC_OCR_DATA" @@ -70,7 +70,7 @@ def _open_original(job): orient = None try: orient = im.getexif().get(0x0112) - except Exception: # noqa: BLE001 + except Exception: orient = "unreadable" im.load() return im, src_sha, orient @@ -121,7 +121,7 @@ def work(job): "n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP, "counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())} return rec - except Exception as e: # noqa: BLE001 + except Exception as e: import traceback return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]} diff --git a/scripts/r5_loopguard/om_common.py b/scripts/r5_loopguard/om_common.py index 44469377982e0b7069afa030d6b87ae080dac127..08a2d600e14d1f0935b4131125fec6acb3f0d8c4 100644 --- a/scripts/r5_loopguard/om_common.py +++ b/scripts/r5_loopguard/om_common.py @@ -9,10 +9,10 @@ HERE = os.path.dirname(os.path.abspath(__file__)) if HERE not in sys.path: sys.path.insert(0, HERE) -import torch # noqa: E402 +import torch -import om_text as T # noqa: E402 -import vlm_common as vc # noqa: E402 +import om_text as T +import vlm_common as vc SHORT = "paddleocr_vl_1_6" CODE = "/path/to/TURKIC_OCR_CODE" diff --git a/scripts/r5_loopguard/om_eval_pages.py b/scripts/r5_loopguard/om_eval_pages.py index 78587ac5e51a0121b46e6de2f21394696a6ab80e..8f5f56e837b1487d488aeff9399023496686b679 100644 --- a/scripts/r5_loopguard/om_eval_pages.py +++ b/scripts/r5_loopguard/om_eval_pages.py @@ -9,12 +9,12 @@ from datetime import datetime, timezone HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image vc = C.vc csv.field_size_limit(10 ** 9) @@ -202,14 +202,14 @@ for s in sets: single = False try: recs = gen(imgs) - except Exception as ex: # noqa: BLE001 (as eval_vlm.py: retry one image at a time, record what still fails) + except Exception as ex: say("batch failed %s; one at a time (batch composition changes: byte identity with A0 not expected here)" % repr(ex)[:150]) single = True recs = [] for im in imgs: try: recs += gen([im]) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]}) dt = time.time() - t1 for r, im, x in zip(bb, imgs, recs): diff --git a/scripts/r5_loopguard/om_guard.py b/scripts/r5_loopguard/om_guard.py index f9d149d8e228f468dade4c68cae7eddd3b88f9e2..d431888dead69b1fb8b833d453ceec29ca1568a3 100644 --- a/scripts/r5_loopguard/om_guard.py +++ b/scripts/r5_loopguard/om_guard.py @@ -255,7 +255,6 @@ def selftest(a): t0 = time.time() rep = {"design": DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "checks": {}, "facts": {}} C = rep["checks"] - # --- the installed transformers has what the arms use rep["facts"]["transformers"] = transformers.__version__ rep["facts"]["torch"] = torch.__version__ sig = inspect.signature(GenerationMixin.generate).parameters @@ -273,13 +272,11 @@ def selftest(a): rep["facts"]["vocab_for_tests"] = vocab nl_like = [i for i in range(len(tok)) if i != NL_ID and "\n" in tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False)] rep["facts"]["other_tokens_whose_text_contains_a_newline"] = {"count": len(nl_like), "first_ids": nl_like[:20]} - # --- LogitsProcessorList calls the guard (2-argument signature) and leaves scores alone when nothing fires g = LineLoopGuard(3, 1, ids) sc = torch.zeros((1, vocab)) out = LogitsProcessorList([g])(torch.zeros((1, 3), dtype=torch.long), sc) C["processor_list_calls_guard"] = out is sc and g.calls == 1 - # --- synthetic rows syn = {} A, B_, Cc, D, E = 1000, 1001, 1002, 1003, 1004 base_unit = [500, 501, 502, 503, 504, 505, 506, 507] @@ -330,7 +327,6 @@ def selftest(a): C["synthetic_equal_to_design_triggers"] = all(eq) rep["synthetic"] = syn - # --- enforced mode: masks after a fire, location tokens untouched, then newline/end, then free; batch rows independent prompt = 4 unit = [700, 701, 702] row0 = [A] + unit * 12 # fires at its last token @@ -406,7 +402,6 @@ def selftest(a): C["clean_ids_identity_without_events"] = clean_ids(gen, [], end_ids=ids["end_ids"]) == gen rep["clean_example"] = {"events": st.events, "in_len": len(gen), "out_len": len(cl)} - # --- every reference target (train + val pages) through the guard: no event, no score change ref = {} rows_all = [] for s in ("school_train", "gen_train", "school_val", "gen_val"): @@ -429,7 +424,6 @@ def selftest(a): C["references_no_fire_no_score_change"] = all(v["pages_fired"] == 0 and v["calls_with_changed_scores"] == 0 and v["pages_fired_design_triggers"] == 0 for v in ref.values()) - # --- stored validation outputs (re-tokenised, as the design's check): observe mode fires on the predicted pages from tokenizers import Tokenizer fr = json.load(open(a.final_rule, encoding="utf-8")) tk = Tokenizer.from_file(os.path.join(a.tokenizer_dir, "tokenizer.json")) @@ -456,7 +450,6 @@ def selftest(a): and changed == 0) rep["stored_outputs"] = out_pages - # --- A1 sanity: NoRepeatNGramLogitsProcessor(20) bans the continuation of a repeated 20-gram, nothing on a fresh row nr = NoRepeatNGramLogitsProcessor(NGRAM) unit5 = [800, 801, 802, 803, 804] row = torch.tensor([[0] * 5 + unit5 * 5], dtype=torch.long) # 25 generated tokens, period 5 diff --git a/scripts/r5_loopguard/om_lg_select.py b/scripts/r5_loopguard/om_lg_select.py index c4a87d1307daefa1d9a6de536e4ee7d520413642..92e56290f4332732020cf2cf9ff9d1a13e8c4ea8 100644 --- a/scripts/r5_loopguard/om_lg_select.py +++ b/scripts/r5_loopguard/om_lg_select.py @@ -7,7 +7,7 @@ import time HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T OFFICIAL_ROOT = os.path.dirname(T.OFFICIAL_UNSEAL) VAL = {"gen_val": 300, "school_val": 150} @@ -129,7 +129,7 @@ def select(a): try: sel["diagnostics_file"] = os.path.join(root, "diagnostics_val.json") json.dump(diagnostics(root, a.a0, a.stored), open(sel["diagnostics_file"], "w"), indent=1) - except Exception as e: # noqa: BLE001 (diagnostics are descriptive; never block the selection) + except Exception as e: sel["diagnostics_error"] = repr(e)[:200] p = os.path.join(root, "selection.json") json.dump(sel, open(p, "w"), indent=1) diff --git a/scripts/r5_loopguard/om_score.py b/scripts/r5_loopguard/om_score.py index 06f845487bf2c099df3d5e5e43d9bec8daac6f7f..9aa387bbfce9b86ad01215963274ac21a82fc382 100644 --- a/scripts/r5_loopguard/om_score.py +++ b/scripts/r5_loopguard/om_score.py @@ -10,7 +10,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T DATA = "/path/to/TURKIC_OCR_DATA" CODE = "/path/to/TURKIC_OCR_CODE" diff --git a/scripts/r5_onemodel/om_baseline.py b/scripts/r5_onemodel/om_baseline.py index e5ad83a67c9258710ae830de86f631b03127dc95..52e76d34b68c0b097b9e2716b5c870b0d7d853fc 100644 --- a/scripts/r5_onemodel/om_baseline.py +++ b/scripts/r5_onemodel/om_baseline.py @@ -8,11 +8,11 @@ import unicodedata HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image vc = C.vc csv.field_size_limit(10 ** 9) diff --git a/scripts/r5_onemodel/om_build_pages.py b/scripts/r5_onemodel/om_build_pages.py index 5665143466548b6515fa922215193718a94f8e15..dd2c574b66f2595cd43d88faef25861642cb1852 100644 --- a/scripts/r5_onemodel/om_build_pages.py +++ b/scripts/r5_onemodel/om_build_pages.py @@ -12,7 +12,7 @@ import zipfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T csv.field_size_limit(10 ** 9) DATA = "/path/to/TURKIC_OCR_DATA" @@ -70,7 +70,7 @@ def _open_original(job): orient = None try: orient = im.getexif().get(0x0112) - except Exception: # noqa: BLE001 + except Exception: orient = "unreadable" im.load() return im, src_sha, orient @@ -121,7 +121,7 @@ def work(job): "n_target_lines": len(kept), "target_chars": len(target), "over_cap": len(tgt_ids) > T.TARGET_CAP, "counts": cnt, "roundtrip": rt, "roundtrip_ok": all(rt.values())} return rec - except Exception as e: # noqa: BLE001 + except Exception as e: import traceback return {"id": job["id"], "set": job["set"], "error": repr(e)[:300], "trace": traceback.format_exc()[-1200:]} diff --git a/scripts/r5_onemodel/om_common.py b/scripts/r5_onemodel/om_common.py index 646fe9065540dda64988350f3ba35ddec8c669d6..98ef22bb8d54d8c7d01e1c1792a4b21688400760 100644 --- a/scripts/r5_onemodel/om_common.py +++ b/scripts/r5_onemodel/om_common.py @@ -9,10 +9,10 @@ HERE = os.path.dirname(os.path.abspath(__file__)) if HERE not in sys.path: sys.path.insert(0, HERE) -import torch # noqa: E402 +import torch -import om_text as T # noqa: E402 -import vlm_common as vc # noqa: E402 +import om_text as T +import vlm_common as vc SHORT = "paddleocr_vl_1_6" CODE = "/path/to/TURKIC_OCR_CODE" diff --git a/scripts/r5_onemodel/om_eval_pages.py b/scripts/r5_onemodel/om_eval_pages.py index 847f2f0956ea935351f37bfd10950900525817ee..560bf345e8f9bf045281ceb55a85b1ea9bb98f1d 100644 --- a/scripts/r5_onemodel/om_eval_pages.py +++ b/scripts/r5_onemodel/om_eval_pages.py @@ -8,12 +8,12 @@ from datetime import datetime, timezone HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image vc = C.vc csv.field_size_limit(10 ** 9) @@ -152,13 +152,13 @@ for s in sets: t1 = time.time() try: recs = C.generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev) - except Exception as ex: # noqa: BLE001 (as eval_vlm.py: retry one image at a time, record what still fails) + except Exception as ex: say("batch failed %s; one at a time" % repr(ex)[:150]) recs = [] for im in imgs: try: recs += C.generate_pages(model, proc, tok, [im], max_new, tmpl_kw, gc, stop_set, dev) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "n_visual": None, "error": repr(ex2)[:200]}) dt = time.time() - t1 for r, im, x in zip(bb, imgs, recs): diff --git a/scripts/r5_onemodel/om_probe.py b/scripts/r5_onemodel/om_probe.py index f7dd4198c32387aa81e78fdeef3984ceb9ef03c1..71608e539f9e8cc94546efd8f6dae86fadfa30c6 100644 --- a/scripts/r5_onemodel/om_probe.py +++ b/scripts/r5_onemodel/om_probe.py @@ -7,12 +7,12 @@ import time HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image vc = C.vc ap = argparse.ArgumentParser() @@ -76,7 +76,7 @@ try: from transformers import image_utils src = inspect.getsource(image_utils.load_image) rep["load_image_mentions_exif_transpose"] = "exif_transpose" in src -except Exception as e: # noqa: BLE001 +except Exception as e: rep["load_image_source"] = repr(e)[:200] # timing: one full page sample vs one crop sample, forward + backward, bf16, gradient checkpointing diff --git a/scripts/r5_onemodel/om_score.py b/scripts/r5_onemodel/om_score.py index 09d3da5519a59b5555fa0fc763ef5ec3f237d44b..e931fff263227de329c53b1ed4cd684d5215f32f 100644 --- a/scripts/r5_onemodel/om_score.py +++ b/scripts/r5_onemodel/om_score.py @@ -10,7 +10,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T DATA = "/path/to/TURKIC_OCR_DATA" CODE = "/path/to/TURKIC_OCR_CODE" diff --git a/scripts/r5_onemodel/om_smoke_check.py b/scripts/r5_onemodel/om_smoke_check.py index 7b3a55a94604a41401d0d61b23ee2ead0470606f..e0a2dd240dc1c3c268f591d2c1973f7c63f6fef7 100644 --- a/scripts/r5_onemodel/om_smoke_check.py +++ b/scripts/r5_onemodel/om_smoke_check.py @@ -7,7 +7,7 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_text as T # noqa: E402 +import om_text as T DATA = "/path/to/TURKIC_OCR_DATA" PAGECHK = DATA + "/outputs/r5/b1_page_check" @@ -91,7 +91,6 @@ def main(): it["spotting_generation_parses"] = {"by_model": gen_items, "passed": parse_ok, "rule": "base PaddleOCR-VL 1.6 output on the generated val pages parses into lines with boxes; leader and smoke-trained outputs parse without error"} - # 5 baseline reproduces the PAGECHK detector + leader readings ref = {} for p in glob.glob(PAGECHK + "/*_detB1_c*.jsonl"): for r in jl(p): diff --git a/scripts/r5_onemodel/om_train.py b/scripts/r5_onemodel/om_train.py index c1ab14602fe223f9b4361753ceb3ae7f7342c2d0..313e30fdefa099f37f0f83922802524e7a1f87dc 100644 --- a/scripts/r5_onemodel/om_train.py +++ b/scripts/r5_onemodel/om_train.py @@ -11,12 +11,12 @@ from datetime import datetime, timezone HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import om_common as C # noqa: E402 -import om_text as T # noqa: E402 +import om_common as C +import om_text as T -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image vc = C.vc csv.field_size_limit(10 ** 9) @@ -68,7 +68,7 @@ STOP = {"flag": False, "why": ""} T_PROC = time.time() -def _sig(signum, frame): # noqa: ARG001 +def _sig(signum, frame): STOP["flag"] = True STOP["why"] = "signal %d" % signum @@ -256,11 +256,11 @@ def _wi(_): ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0) if os.getppid() != PARENT: os._exit(0) - except Exception: # noqa: BLE001 + except Exception: pass try: os.nice(10) - except Exception: # noqa: BLE001 + except Exception: pass torch.set_num_threads(1) diff --git a/scripts/r5_ref/ref_check_tasks.py b/scripts/r5_ref/ref_check_tasks.py index 6b61ba9f49a1f558b9ee79f196095ba1698cd59c..ef89ca6ad02ca7f39bb8fdc55c9dea74ed4165db 100644 --- a/scripts/r5_ref/ref_check_tasks.py +++ b/scripts/r5_ref/ref_check_tasks.py @@ -3,7 +3,7 @@ import os import sys sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from linedet import driver # LINEDET's driver module (own project code) +from linedet import driver spec = json.load(open(sys.argv[1])) names = {t["name"] for t in spec["tasks"]} diff --git a/scripts/r5_ref/ref_flor_predict.py b/scripts/r5_ref/ref_flor_predict.py index 873e3ac18546e7afb3be2370b3a987fa83001af8..32cc11a36fb4cc73f252ed14d76f8d8a87459b4b 100644 --- a/scripts/r5_ref/ref_flor_predict.py +++ b/scripts/r5_ref/ref_flor_predict.py @@ -10,7 +10,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc INPUT_SIZE = (1024, 128, 1) MAX_TEXT = 128 diff --git a/scripts/r5_ref/ref_flor_train.py b/scripts/r5_ref/ref_flor_train.py index 64f7622f46e412672505d6ca1f685e555947f33f..cd491bb6daa427828445e0cfba445911ad6982fc 100644 --- a/scripts/r5_ref/ref_flor_train.py +++ b/scripts/r5_ref/ref_flor_train.py @@ -13,7 +13,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc INPUT_SIZE = (1024, 128, 1) MAX_TEXT = 128 @@ -94,7 +94,6 @@ def main(): log.write(s + "\n") log.flush() - # ---- data (text only here; images are read by the worker processes) MIXRUN = a.run == "iii" if MIXRUN: trn, val = rc.read_manifest(a.mix_list), [] @@ -125,7 +124,6 @@ def main(): chars = json.load(open(os.path.join(a.refdata, "charset_%s.json" % a.run), encoding="utf-8"))["chars"] say("run", a.run, "train", len(trn), "val", len(val), "charset", len(chars)) - # ---- worker pool before TensorFlow is imported (fork after CUDA initialisation is unsafe) pool = mp.get_context("fork").Pool(a.workers, initializer=_winit, initargs=(rc.HTRFLOR_SRC, pool_path, 20261121)) os.environ.setdefault("TF_FORCE_GPU_ALLOW_GROWTH", "true") @@ -144,7 +142,7 @@ def main(): from network.model import HTRModel # pinned from data.generator import Tokenizer # pinned from data import preproc as pp # pinned (normalization) - from tensorflow.keras import backend as K # noqa: F401 + from tensorflow.keras import backend as K from itertools import groupby class KzTokenizer(Tokenizer): @@ -170,7 +168,6 @@ def main(): y = [np.pad(v, (0, tok.maxlen - len(v))) for v in y] return np.asarray(y, dtype=np.int16) - # ---- batch streams if MIXRUN: steps = (len(trn) // a.batch) // 4 if not a.steps_per_epoch else a.steps_per_epoch # quarter of the run per Keras epoch else: @@ -219,7 +216,6 @@ def main(): f, sl = pend.popleft() yield pp.normalization(f.get()), encode_batch([val[i] for i in sl]) - # ---- model (pinned) model = HTRModel(architecture="flor", input_size=INPUT_SIZE, vocab_size=tok.vocab_size, beam_width=10, stop_tolerance=a.stop_patience, reduce_tolerance=a.reduce_patience) model.compile(learning_rate=0.001) @@ -238,7 +234,6 @@ def main(): rl = [c for c in cbs if c.__class__.__name__ == "ReduceLROnPlateau"][0] mc = [c for c in cbs if c.__class__.__name__ == "ModelCheckpoint"][0] - # ---- resume state rdir = os.path.join(a.out, "resume") os.makedirs(rdir, exist_ok=True) state_path = os.path.join(rdir, "state.json") diff --git a/scripts/r5_ref/ref_make_mix_lists.py b/scripts/r5_ref/ref_make_mix_lists.py index 29aafe8aa88a2794909b18373d31a4bad36d3c20..959b19927679c775913e3ce2254923c104cdb0f3 100644 --- a/scripts/r5_ref/ref_make_mix_lists.py +++ b/scripts/r5_ref/ref_make_mix_lists.py @@ -11,7 +11,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc _WS = re.compile(r"\s+") diff --git a/scripts/r5_ref/ref_paper_metrics.py b/scripts/r5_ref/ref_paper_metrics.py index 8640ea8a0cb16a540912b2f1bc56f12f90ffdbd8..6ec2e9b3923dddb4c3f5377ab2bf1ee33297367e 100644 --- a/scripts/r5_ref/ref_paper_metrics.py +++ b/scripts/r5_ref/ref_paper_metrics.py @@ -5,11 +5,11 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc sys.path.insert(0, rc.HTRFLOR_SRC) from data import evaluation as flor_eval # pinned # noqa: E402 -import editdistance # noqa: E402 +import editdistance def metrics(refs, hyps): diff --git a/scripts/r5_ref/ref_ppocr_predict.py b/scripts/r5_ref/ref_ppocr_predict.py index 9fe33695b1bb8480b74cc02bea7da3124c3c5c87..f1a0c841b228970c758b4e38a2b3e8afb9d64441 100644 --- a/scripts/r5_ref/ref_ppocr_predict.py +++ b/scripts/r5_ref/ref_ppocr_predict.py @@ -9,7 +9,7 @@ import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc def main(): diff --git a/scripts/r5_ref/ref_ppocr_run.py b/scripts/r5_ref/ref_ppocr_run.py index cce2ee04847266539fdcf29b5db5adfeccedc48b..d50be1a6b2545311f9f1e5e92a6e9d54409fdadc 100644 --- a/scripts/r5_ref/ref_ppocr_run.py +++ b/scripts/r5_ref/ref_ppocr_run.py @@ -11,7 +11,7 @@ import time HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc STOP = {"flag": False} PROG = {} @@ -185,7 +185,6 @@ def main(): cfg_path = make_config(a, st["epochs"], a.out, resume_ckpt) json.dump(st, open(state_path, "w"), indent=1) - # ---- patches (in memory only) sys.path.insert(0, rc.PPOCR_ROOT) os.chdir(rc.PPOCR_ROOT) import ppocr.data as ppdata @@ -258,7 +257,7 @@ def main(): def finish(why): summ = write_summary(why, False) - try: # every file of the pinned repository that this process imported (rule 0.11: these are the files to read and hash) + try: mods = sorted({m.__file__ for m in list(sys.modules.values()) if getattr(m, "__file__", None) and str(m.__file__).startswith(rc.PPOCR_ROOT)}) open(a.out + "/executed_pinned_files.txt", "w").write("\n".join(mods) + "\n") except Exception as e: diff --git a/scripts/r5_ref/ref_register_rand_test.py b/scripts/r5_ref/ref_register_rand_test.py index 0f3d54ee20cd6461596174e7aeb4d6dfe513f6a8..4e5754d745d7e01f37b07374224a34b5c1703914 100644 --- a/scripts/r5_ref/ref_register_rand_test.py +++ b/scripts/r5_ref/ref_register_rand_test.py @@ -4,7 +4,7 @@ import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import ref_common as rc # noqa: E402 +import ref_common as rc rep = json.load(open(rc.REFDATA + "/build_report.json")) rt = rep["rand_test"] diff --git a/scripts/r5_release/rc1_prep_det.py b/scripts/r5_release/rc1_prep_det.py index 038546983f88d6ae5e188ecb2e04da44418c6062..daceecbfec7990dcaccecfef8fdd6057eb36cc39 100644 --- a/scripts/r5_release/rc1_prep_det.py +++ b/scripts/r5_release/rc1_prep_det.py @@ -6,9 +6,9 @@ import tempfile os.environ.setdefault("YOLO_OFFLINE", "1") os.environ.setdefault("YOLO_CONFIG_DIR", os.path.join(tempfile.gettempdir(), "ultralytics_cfg_rc1_prep")) -import torch # noqa: E402 -import ultralytics # noqa: E402 -from ultralytics import YOLO # noqa: E402 +import torch +import ultralytics +from ultralytics import YOLO def main(): diff --git a/scripts/r5_release/rc1_prep_vlm.py b/scripts/r5_release/rc1_prep_vlm.py index b4475065cf5f66eee9b4710c18667d8b4c910fe2..eb6a0b69bf357ead6730723e9c25ab723058ea09 100644 --- a/scripts/r5_release/rc1_prep_vlm.py +++ b/scripts/r5_release/rc1_prep_vlm.py @@ -7,9 +7,9 @@ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") for _k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): os.environ.pop(_k, None) -import torch # noqa: E402 -import transformers # noqa: E402 -from safetensors import safe_open # noqa: E402 +import torch +import transformers +from safetensors import safe_open def header_count(path): diff --git a/scripts/r5_release/rc1_ref_compare_a1.py b/scripts/r5_release/rc1_ref_compare_a1.py index 3751a34c46296508ceafb90cd3c5ed1285805eff..b02ea794e78168152d6b012bfe10b9d182e7c968 100644 --- a/scripts/r5_release/rc1_ref_compare_a1.py +++ b/scripts/r5_release/rc1_ref_compare_a1.py @@ -7,11 +7,11 @@ import sys sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image -from linedet import data as D # noqa: E402 -from linedet import lm_decode as LD # noqa: E402 +from linedet import data as D +from linedet import lm_decode as LD def main(): diff --git a/scripts/r5_release/rc1_ref_compare_vlm.py b/scripts/r5_release/rc1_ref_compare_vlm.py index 3f405c76db2b57b0494552f00e3325d23b97e725..2391976ff3c8063024b3b2fa7dbecfe811c54691 100644 --- a/scripts/r5_release/rc1_ref_compare_vlm.py +++ b/scripts/r5_release/rc1_ref_compare_vlm.py @@ -8,11 +8,11 @@ CODE_VLMA = "/path/to/TURKIC_OCR_CODE/scripts/r5_vlma" sys.path.insert(0, CODE_VLMA) os.environ.setdefault("HF_HUB_OFFLINE", "1") -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image -import vlm_common as vc # noqa: E402 +import vlm_common as vc def load(name, path): diff --git a/scripts/r5_showcase/showcase_detect.py b/scripts/r5_showcase/showcase_detect.py index 4689d42b1fe517839e76eef5e6ab02812591d714..6a28d653bca602e5a5e3f6e1e0a32124126839e8 100644 --- a/scripts/r5_showcase/showcase_detect.py +++ b/scripts/r5_showcase/showcase_detect.py @@ -6,10 +6,10 @@ import sys import time sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -import numpy as np # noqa: E402 -import torch # noqa: E402 +import numpy as np +import torch -from linedet import det_eval as DE # noqa: E402 +from linedet import det_eval as DE csv.field_size_limit(10 ** 9) diff --git a/scripts/r5_showcase/showcase_gen.py b/scripts/r5_showcase/showcase_gen.py index e15d445a39bdb915aced997042473a8d19435f1d..422f67000bdda8527310f28fdf41b83b03ba4e89 100644 --- a/scripts/r5_showcase/showcase_gen.py +++ b/scripts/r5_showcase/showcase_gen.py @@ -14,19 +14,19 @@ PS = CODE + "/src/pagesynth" sys.path.insert(0, PS) sys.path.insert(0, CODE + "/src") -import cv2 # noqa: E402 -import numpy as np # noqa: E402 - -import produce_r5 as PR # noqa: E402 -from pagesynth import crops as CR # noqa: E402 -from pagesynth import fonts as F # noqa: E402 -from pagesynth import generate as GEN # noqa: E402 -from pagesynth import geometry as GM # noqa: E402 -from pagesynth import ink as I # noqa: E402 -from pagesynth import layouts as L # noqa: E402 -from pagesynth import page as PG # noqa: E402 -from pagesynth import paper as P # noqa: E402 -from linedet import det_prep as DP # noqa: E402 +import cv2 +import numpy as np + +import produce_r5 as PR +from pagesynth import crops as CR +from pagesynth import fonts as F +from pagesynth import generate as GEN +from pagesynth import geometry as GM +from pagesynth import ink as I +from pagesynth import layouts as L +from pagesynth import page as PG +from pagesynth import paper as P +from linedet import det_prep as DP TEXT_DIR = DATA + "/data/processed/r5/pagesynth_text_split/val" SYNTH = DATA + "/data/processed/r5/synth" @@ -288,7 +288,6 @@ def stage_page(lang, idx, out, banks_cache, report): page_row = [r for r in rows if r.get("unit") == "page"][0] pid = page_row["id"] rec["page_id"] = pid - # ---- identity with production prod_img = os.path.join(SYNTH, "pages", "val", lang, pid + ".jpg") prod_json = os.path.join(SYNTH, "pages", "val", lang, pid + ".json") rec["identical_page_jpeg"] = sha_file(page_row["image"]) == sha_file(prod_img) @@ -316,11 +315,9 @@ def stage_page(lang, idx, out, banks_cache, report): files[name] = p return p - # ---- stage 1: sentences drawn from the bank rec["stage1_text"] = dict(text_file=TEXT_DIR + "/%s/sentences.tsv" % lang, sentence_bank_size=len(banks[lang]), units_calls=cap.get("units", []), n_bank_draws_including_rejected_and_font_probes=len(banks[lang].drawn), first_draws=[dict(source=s, text=t) for s, t in banks[lang].drawn[:40]]) - # ---- stage 2: writer and one line before and after the writer effects writers = cap.get("writers", []) rec["stage2_writers"] = writers body = None @@ -343,7 +340,6 @@ def stage_page(lang, idx, out, banks_cache, report): plain_render=dict(function="ink.render_line(..., hand=False)", style="ink.default_style(rng, face, hand=False)", rng_seed=12345), chosen_as="first handwriting body line of 3+ words with elastic distortion drawn" if el else "first handwriting body line of 3+ words (no line of the page drew elastic distortion)", composite_rule="page.py Page.finalize: reg *= 1 - alpha * (1 - ink_bgr / 255), on white 255; panel c uses the page item alpha (Page.add_line: _bleed sigma 0.9, times the ink multiplier)") - # ---- stage 3: paper and layout save("stage3_a_paper_make_paper.png", u8(cap["paper_base"])) steps = [] for k, s in enumerate(cap.get("paper_steps", [])): @@ -375,13 +371,11 @@ def stage_page(lang, idx, out, banks_cache, report): regions=[dict(id=r.get("id"), type=r.get("type"), generator=r.get("generator"), note=r.get("note")) for r in cap["regions_flat"]], paper_steps=steps, ghost_max=(None if cap.get("ghost") is None else round(float(cap["ghost"].max()), 4)), box_colours_bgr=KIND_COLOURS, region_outline_bgr=[0, 120, 255]) - # ---- stage 4 and 5 save("stage4_composite_after_geometry.png", cap["pre_photo"]) save("stage5_after_photo_effects.png", post) rec["stage4_5_capture"] = dict(strength=cap["strength"], strength_ranges=cap["strength_cfg"], geometry=cap["geo_params"], photo=cap["fx"], mode=cap["mode"], output_size=[int(post.shape[1]), int(post.shape[0])], effects=[e for e in pj["info"].get("effects", []) if not e.startswith(("font:", "ink:", "class:", "pen:"))]) - # ---- stage 6: line crops (production rows) and one line cut both ways lines = {ln["id"]: ln for ln in pj["lines"]} crops6 = [] for r in rows: @@ -395,7 +389,6 @@ def stage_page(lang, idx, out, banks_cache, report): save("stage6_both_%s_%s.png" % (crops6[0]["line_id"], mode), CR.crop_line(final, ln["polygon"], mode)) rec["stage6_crops"] = dict(production_crops=crops6, both_modes_line=crops6[0]["line_id"], both_modes_text=ln["text"], rule="produce_r5.work: K=%d lines per validation page drawn without replacement (weights 1 / 0.5 / 0.15 by word count), crop mode poly with p=%.2f else rect; crops.crop_line(img, polygon, mode, pad=4)" % (PR.CFG["lines_per_page"]["val"], PR.CFG["p_crop_poly"])) - # ---- stage 7: clutter cl = [r for r in rows if r.get("kind") == "clutter"] if cl: im = cv2.imread(cl[0]["image"], cv2.IMREAD_COLOR) diff --git a/scripts/r5_showcase/showcase_read.py b/scripts/r5_showcase/showcase_read.py index 25d64c05a64f5f947df7cfe47f54626d1a4b6149..bd27eccbc8e8d45a0b3dba9236ab16a9d8599399 100644 --- a/scripts/r5_showcase/showcase_read.py +++ b/scripts/r5_showcase/showcase_read.py @@ -15,10 +15,10 @@ ap.add_argument("--threads", type=int, default=16) ap.add_argument("--vlma", default="/path/to/TURKIC_OCR_CODE/scripts/r5_vlma") a = ap.parse_args() sys.path.insert(0, a.vlma) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image -import vlm_common as vc # noqa: E402 +import vlm_common as vc torch.set_num_threads(a.threads) SHORT = "paddleocr_vl_1_6" diff --git a/scripts/r5_showcase/showcase_score.py b/scripts/r5_showcase/showcase_score.py index 5c65ea8c09b76cf40dfce2ff8e54b5884462d512..0ce089d5d10b8a826763873f89b9527978812b4f 100644 --- a/scripts/r5_showcase/showcase_score.py +++ b/scripts/r5_showcase/showcase_score.py @@ -5,12 +5,12 @@ import os import sys sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -import numpy as np # noqa: E402 -from rapidfuzz import process # noqa: E402 -from rapidfuzz.distance import Levenshtein # noqa: E402 -from scipy.optimize import linear_sum_assignment # noqa: E402 +import numpy as np +from rapidfuzz import process +from rapidfuzz.distance import Levenshtein +from scipy.optimize import linear_sum_assignment -from linedet.det_eval import page_cers # noqa: E402 +from linedet.det_eval import page_cers ap = argparse.ArgumentParser() ap.add_argument("--read", required=True) diff --git a/scripts/r5_testpass2/tp2_a1_labelfree.py b/scripts/r5_testpass2/tp2_a1_labelfree.py index afcf42818d09b2c912763e7af60b84d227662a91..3852228c26c327f0375f488878e3f4fd2556c6fb 100644 --- a/scripts/r5_testpass2/tp2_a1_labelfree.py +++ b/scripts/r5_testpass2/tp2_a1_labelfree.py @@ -43,7 +43,7 @@ def main(): lm = rel.CharLM(os.path.join(REL, "lm", "char6.klm"), rec.c2l) outs = rec.read(imgs, 32, "lm_gated", lm, a.workers, "width", 256) secs = time.time() - t0 - sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest() # noqa: E731 + sha = lambda p: hashlib.sha256(open(p, "rb").read()).hexdigest() meta = {"arm": "A1", "model": "release rc1 turkic-ocr-ppocrv6-medium (A1 long2x exported to safetensors)", "infer_py_sha256": sha(os.path.join(REL, "infer.py")), "model_safetensors_sha256": sha(os.path.join(REL, "model", "model.safetensors")), "codec_sha256": sha(os.path.join(REL, "model", "codec.json")), "lm_sha256": sha(os.path.join(REL, "lm", "char6.klm")), diff --git a/scripts/r5_testpass2/tp2_az_latin.py b/scripts/r5_testpass2/tp2_az_latin.py index a8e094987c266c4ea47d1b4b8792a7296f83f482..4386c7ea75dfd7673515f3502e638d6f675fe116 100644 --- a/scripts/r5_testpass2/tp2_az_latin.py +++ b/scripts/r5_testpass2/tp2_az_latin.py @@ -16,13 +16,13 @@ if not os.path.exists(a.gate_file): sys.exit(3) sys.path.insert(0, a.vlma) sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image -import postproc as pp # noqa: E402 -import vlm_common as vc # noqa: E402 -from r5eval import textnorm # noqa: E402 +import postproc as pp +import vlm_common as vc +from r5eval import textnorm torch.set_num_threads(a.threads) SHORT = "paddleocr_vl_1_6" @@ -46,7 +46,7 @@ n_text = n_byte = 0 for i in range(V): try: s = tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False) - except Exception: # noqa: BLE001 + except Exception: s = "" piece = tok.convert_ids_to_tokens(i) if i < len(tok) else None if any("Cyrillic" in (textnorm.char_script_set(c) or ()) and "Latin" not in (textnorm.char_script_set(c) or ()) for c in s): diff --git a/scripts/r5_testpass2/tp2_az_latin_pair.py b/scripts/r5_testpass2/tp2_az_latin_pair.py index a759afa0760e0b7cf806e2c3d37a8b2cd9d7bac8..0c19f839d403d3b27dea0e43b4763687c1f36bc5 100644 --- a/scripts/r5_testpass2/tp2_az_latin_pair.py +++ b/scripts/r5_testpass2/tp2_az_latin_pair.py @@ -2,7 +2,7 @@ import json import sys sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import stats # noqa: E402 +from r5eval import stats L, M, SC, OUT = sys.argv[1:5] dl, dm = json.load(open(L, encoding="utf-8")), json.load(open(M, encoding="utf-8")) @@ -11,7 +11,7 @@ assert pl["cluster_ids"] == pm["cluster_ids"] pr = stats.paired_ratio_difference(pl["cluster_sums"]["all"]["dist"], pl["cluster_sums"]["all"]["ref_len"], pm["cluster_sums"]["all"]["dist"], pm["cluster_sums"]["all"]["ref_len"]) pr.pop("_rel_reps", None) -g = lambda d, k: {x: d["profiles"]["plain"]["groups"]["all"]["metrics"][k].get(x) for x in ("value", "lo", "hi", "num", "den")} # noqa: E731 +g = lambda d, k: {x: d["profiles"]["plain"]["groups"]["all"]["metrics"][k].get(x) for x in ("value", "lo", "hi", "num", "den")} res = {"note": "plan amendment 6 of 26 Nov (plan entry n 7): M1 with Latin-only decoding vs M1 unconstrained (test pass 2), all 442 lines; descriptive", "n": dl["set_info"]["n_scored"], "coverage_complete": dl["coverage"]["complete"], "latin_only": {k: g(dl, k) for k in ("cer", "wer", "exact_match", "hr3", "hr4", "fabricated_word_rate", "empty_output_rate")}, diff --git a/scripts/r5_testpass2/tp2_error_analysis.py b/scripts/r5_testpass2/tp2_error_analysis.py index 013b26df48cd8ef5088355273e225a4f90cf5535..7c05bfcff96e83eab9908e367c364dadb14870b5 100644 --- a/scripts/r5_testpass2/tp2_error_analysis.py +++ b/scripts/r5_testpass2/tp2_error_analysis.py @@ -10,8 +10,8 @@ import numpy as np from PIL import Image sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import textnorm # noqa: E402 -from r5eval.align import align_ops # noqa: E402 +from r5eval import textnorm +from r5eval.align import align_ops csv.field_size_limit(1 << 30) REG = "/path/to/TURKIC_OCR_DATA/data/processed/r5/evalsets.json" diff --git a/scripts/r5_testpass2/tp2_hashes.py b/scripts/r5_testpass2/tp2_hashes.py index 2416775a26eed31ab0ceebf5a2c8ffe17900fe0d..23bde328e0df9a4a69751f25f622f36ace16a5be 100644 --- a/scripts/r5_testpass2/tp2_hashes.py +++ b/scripts/r5_testpass2/tp2_hashes.py @@ -59,7 +59,7 @@ try: out["r5eval_code_sha256"] = r5eval.code_sha256() out["r5eval_version"] = r5eval.VERSION out["r5eval_code_sha256_matches_24nov_attested_9d5f3205"] = out["r5eval_code_sha256"].startswith("9d5f3205") -except Exception as e: # noqa: BLE001 +except Exception as e: out["r5eval_code_sha256"] = "error " + repr(e) reg_p = DATA + "/data/processed/r5/evalsets.json" diff --git a/scripts/r5_testpass2/tp2_kohtd_compare.py b/scripts/r5_testpass2/tp2_kohtd_compare.py index 4a1ffd25186ece09727696f37af8647fb0104bae..999641e333d9206dd84a7b5de20e55d278e0a22e 100644 --- a/scripts/r5_testpass2/tp2_kohtd_compare.py +++ b/scripts/r5_testpass2/tp2_kohtd_compare.py @@ -6,7 +6,7 @@ import sys import numpy as np sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import stats # noqa: E402 +from r5eval import stats GROUPS = ["all", "slice:P2", "slice:registry_P2", "slice:P2b", "slice:registry_P2b"] DROP = "kohtd_form_1868" diff --git a/scripts/r5_testpass2/tp2_kzb_fetch.py b/scripts/r5_testpass2/tp2_kzb_fetch.py index f5c8c7957658ca0859f37d7878c7dec7eb7a2d04..82f38c97b90b1c8a608c611e93b559bf702baa16 100644 --- a/scripts/r5_testpass2/tp2_kzb_fetch.py +++ b/scripts/r5_testpass2/tp2_kzb_fetch.py @@ -45,7 +45,7 @@ if a.mode == "card": p = hf_hub_download(REPO, "README.md", repo_type="dataset", revision=rev, local_dir=a.dest, token=False) try: lic = info.card_data.to_dict().get("license") - except Exception as e: # noqa: BLE001 + except Exception as e: lic = "unknown (%r)" % e res = {"repo": REPO, "revision": rev, "last_modified": str(getattr(info, "last_modified", "")), "gated": getattr(info, "gated", None), "card_data_licence": lic, "tree": tree, "readme": p, "readme_sha256": sha(p), diff --git a/scripts/r5_testpass2/tp2_kzb_prep.py b/scripts/r5_testpass2/tp2_kzb_prep.py index c06b405d0a54e496bc2a74361705f450d009652e..544f4ae5b68417fd619ecc0082e5a43db7bf15df 100644 --- a/scripts/r5_testpass2/tp2_kzb_prep.py +++ b/scripts/r5_testpass2/tp2_kzb_prep.py @@ -10,7 +10,7 @@ import cv2 import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import tp2_tob_img as ti # noqa: E402 +import tp2_tob_img as ti csv.field_size_limit(1 << 30) COLS = ["id", "kategori", "belge", "lisans", "image_orig", "image_1280", "width", "height", "scale", "exif_orientation", "ref_md"] diff --git a/scripts/r5_testpass2/tp2_kzb_score.py b/scripts/r5_testpass2/tp2_kzb_score.py index b1e9f934b2e92ceccdba54f63fcf3549e67febd6..7eb491d7ada4ac6745dd342286727daaabc45013 100644 --- a/scripts/r5_testpass2/tp2_kzb_score.py +++ b/scripts/r5_testpass2/tp2_kzb_score.py @@ -8,8 +8,8 @@ import unicodedata import numpy as np sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from linedet.det_eval import page_cers # noqa: E402 -from r5eval import stats # noqa: E402 +from linedet.det_eval import page_cers +from r5eval import stats def kz_ref_lines(text): diff --git a/scripts/r5_testpass2/tp2_page_score.py b/scripts/r5_testpass2/tp2_page_score.py index 91e4522fc59f360f94f66f1fdcdb2e8a611687b8..f37680b6c898ea3657d843dd6c934b59899a554d 100644 --- a/scripts/r5_testpass2/tp2_page_score.py +++ b/scripts/r5_testpass2/tp2_page_score.py @@ -12,9 +12,9 @@ import numpy as np CODE = "/path/to/TURKIC_OCR_CODE" sys.path.insert(0, CODE + "/src") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from linedet.det_eval import page_cers # noqa: E402 -from r5eval import stats, textnorm # noqa: E402 -from tp2_tob_img import tob_ref_lines # noqa: E402 +from linedet.det_eval import page_cers +from r5eval import stats, textnorm +from tp2_tob_img import tob_ref_lines def boot(groups, cols, B, seed): diff --git a/scripts/r5_testpass2/tp2_qwen_az_script.py b/scripts/r5_testpass2/tp2_qwen_az_script.py index 7987f4a26cbdfb12c5eb0380cb12c9251079beed..4d08e9a35ef61c770137f95d7e0a2a137f89e327 100644 --- a/scripts/r5_testpass2/tp2_qwen_az_script.py +++ b/scripts/r5_testpass2/tp2_qwen_az_script.py @@ -6,8 +6,8 @@ import sys import unicodedata sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import textnorm # noqa: E402 -from r5eval.align import align_ops # noqa: E402 +from r5eval import textnorm +from r5eval.align import align_ops csv.field_size_limit(1 << 30) MAN = "/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/az_localdoc_test.tsv" diff --git a/scripts/r5_testpass2/tp2_results.py b/scripts/r5_testpass2/tp2_results.py index 2e7c9ac60662c1a3a763f502c765b823b75a2b2d..ff4dc37b1f7525c256dce280da596ad79a69b102 100644 --- a/scripts/r5_testpass2/tp2_results.py +++ b/scripts/r5_testpass2/tp2_results.py @@ -7,8 +7,8 @@ import sys csv.field_size_limit(1 << 30) DATA = "/path/to/TURKIC_OCR_DATA" sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import stats, textnorm # noqa: E402 -from r5eval.align import lev_fast # noqa: E402 +from r5eval import stats, textnorm +from r5eval.align import lev_fast SETS = ["az_localdoc_test", "rukopys_test", "hkr_test1", "hkr_test2", "chd_test", "school_test", "synth_hand_test", "synth_typed_test"] KEYS = ("cer", "wer", "exact_match", "hr3", "hr4", "fabricated_word_rate", "empty_output_rate", "cer_casefold") diff --git a/scripts/r5_testpass2/tp2_rk_align_prep.py b/scripts/r5_testpass2/tp2_rk_align_prep.py index 060d6556bbb27f9a72c7cd000102c1f72124bfe9..651012164f37590de7da8759949706db849b1777 100644 --- a/scripts/r5_testpass2/tp2_rk_align_prep.py +++ b/scripts/r5_testpass2/tp2_rk_align_prep.py @@ -8,8 +8,8 @@ import cv2 import numpy as np sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from r5eval import textnorm # noqa: E402 -from r5eval.align import lev_fast # noqa: E402 +from r5eval import textnorm +from r5eval.align import lev_fast csv.field_size_limit(1 << 30) RAW = "/path/to/TURKIC_OCR_DATA/data/raw/rukopys_test/test" diff --git a/scripts/r5_testpass2/tp2_smoke_compare.py b/scripts/r5_testpass2/tp2_smoke_compare.py index 7f22d4158a312c8a178958046e9b74f18c1e2928..db21d74b7cf2ce4de2a3107c99a9f51bce3c2375 100644 --- a/scripts/r5_testpass2/tp2_smoke_compare.py +++ b/scripts/r5_testpass2/tp2_smoke_compare.py @@ -10,8 +10,8 @@ import numpy as np csv.field_size_limit(1 << 30) DATA = "/path/to/TURKIC_OCR_DATA" sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") -from linedet.det_eval import iou_matrix # noqa: E402 -from rapidfuzz.distance import Levenshtein # noqa: E402 +from linedet.det_eval import iou_matrix +from rapidfuzz.distance import Levenshtein ap = argparse.ArgumentParser() ap.add_argument("--smoke", required=True) diff --git a/scripts/r5_testpass2/tp2_tob_detect.py b/scripts/r5_testpass2/tp2_tob_detect.py index 28d5e747d3682b6fa95b9dafd688d1bd47d21d20..0edced3414e47b31033e1f13c74a9554773a49b2 100644 --- a/scripts/r5_testpass2/tp2_tob_detect.py +++ b/scripts/r5_testpass2/tp2_tob_detect.py @@ -7,7 +7,7 @@ import time os.environ.setdefault("YOLO_OFFLINE", "1") os.environ.setdefault("YOLO_CONFIG_DIR", "/path/to/TURKIC_OCR_DATA/tmp/ultralytics_cfg") -import torch # noqa: E402 +import torch ap = argparse.ArgumentParser() ap.add_argument("--pages", required=True) @@ -20,7 +20,7 @@ ap.add_argument("--max-pages", type=int, default=0) ap.add_argument("--threads", type=int, default=16) a = ap.parse_args() torch.set_num_threads(a.threads) -from ultralytics import YOLO # noqa: E402 +from ultralytics import YOLO with open(a.pages, encoding="utf-8", newline="") as f: pages = list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)) @@ -32,7 +32,7 @@ if os.path.exists(a.out): for ln in open(a.out, encoding="utf-8"): try: done.add(json.loads(ln)["id"]) - except Exception: # noqa: BLE001 + except Exception: pass det = YOLO(a.weights) with open(a.out, "a", encoding="utf-8") as fo: diff --git a/scripts/r5_testpass2/tp2_tob_img.py b/scripts/r5_testpass2/tp2_tob_img.py index 14b834ec4e510a3862066bf9b82c13bdcbf2998b..0984990617d3152271ee2c1d1a561e327f8d7a8f 100644 --- a/scripts/r5_testpass2/tp2_tob_img.py +++ b/scripts/r5_testpass2/tp2_tob_img.py @@ -32,7 +32,7 @@ HAND_CAT = "el_yazisi" def exif_orientation(im): try: return int(im.getexif().get(274, 1) or 1) - except Exception: # noqa: BLE001 + except Exception: return -1 diff --git a/scripts/r5_testpass2/tp2_tob_prep.py b/scripts/r5_testpass2/tp2_tob_prep.py index 2893cc59c0033a1d29b2cff14a83916ef2520bc4..b4d40cd29a878ecb9fa944fd7245abbacbd0f5c1 100644 --- a/scripts/r5_testpass2/tp2_tob_prep.py +++ b/scripts/r5_testpass2/tp2_tob_prep.py @@ -9,7 +9,7 @@ import cv2 import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import tp2_tob_img as ti # noqa: E402 +import tp2_tob_img as ti ROOT = "/path/to/TURKIC_OCR_DATA/data/raw/turkishocr_bench" COLS = ["id", "kategori", "belge", "lisans", "image_orig", "image_1280", "width", "height", "scale", "exif_orientation", "ref_md"] diff --git a/scripts/r5_testpass2/tp2_tob_read.py b/scripts/r5_testpass2/tp2_tob_read.py index c3e6472fecdef11e5e51bcb8a9c68a59bd0406ee..aeecfdd2f44ce93e3cc36c9e8fb2969dc6ad31aa 100644 --- a/scripts/r5_testpass2/tp2_tob_read.py +++ b/scripts/r5_testpass2/tp2_tob_read.py @@ -25,10 +25,10 @@ if not os.path.exists(a.gate_file): sys.path.insert(0, a.vlma) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 +import torch -import tp2_tob_img as ti # noqa: E402 -import vlm_common as vc # noqa: E402 +import tp2_tob_img as ti +import vlm_common as vc torch.set_num_threads(a.threads) with open(a.pages, encoding="utf-8", newline="") as f: @@ -49,7 +49,7 @@ if os.path.exists(a.out): for ln in open(a.out, encoding="utf-8"): try: done.add(json.loads(ln)["id"]) - except Exception: # noqa: BLE001 + except Exception: pass proc, tok = vc.load_processor("paddleocr_vl_1_6", a.model) diff --git a/scripts/r5_testpass2/tp2_tob_read_vlm.py b/scripts/r5_testpass2/tp2_tob_read_vlm.py index da90a34b49fa5bec69dd4a15b5e48ca74e4b4ee2..0b006cebb4799b0072f0dc3f1349b8a764a76134 100644 --- a/scripts/r5_testpass2/tp2_tob_read_vlm.py +++ b/scripts/r5_testpass2/tp2_tob_read_vlm.py @@ -27,10 +27,10 @@ if not os.path.exists(a.gate_file): sys.path.insert(0, a.vlma) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 +import torch -import tp2_tob_img as ti # noqa: E402 -import vlm_common as vc # noqa: E402 +import tp2_tob_img as ti +import vlm_common as vc torch.set_num_threads(a.threads) with open(a.pages, encoding="utf-8", newline="") as f: @@ -51,7 +51,7 @@ if os.path.exists(a.out): for ln in open(a.out, encoding="utf-8"): try: done.add(json.loads(ln)["id"]) - except Exception: # noqa: BLE001 + except Exception: pass proc, tok = vc.load_processor(a.short, a.model) diff --git a/scripts/r5_testpass2/tp2_tob_script.py b/scripts/r5_testpass2/tp2_tob_script.py index 305c302b96cf91d4330a2c1a5d77859e689cd198..bf426ff35600efbbcec3489cd3a6ab9247bf7dec 100644 --- a/scripts/r5_testpass2/tp2_tob_script.py +++ b/scripts/r5_testpass2/tp2_tob_script.py @@ -20,8 +20,8 @@ from rapidfuzz.distance import Levenshtein sys.path.insert(0, "/path/to/TURKIC_OCR_CODE/src") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from r5eval import textnorm # noqa: E402 -from tp2_tob_img import tob_ref_lines # noqa: E402 +from r5eval import textnorm +from tp2_tob_img import tob_ref_lines csv.field_size_limit(1 << 30) diff --git a/scripts/r5_vlma/check_inputs.py b/scripts/r5_vlma/check_inputs.py index 647cbd861841e5f25c0ccc493db3bbbe8d5056b0..77ed9ddf16c1de236dc4683abb5d276678de1cc6 100644 --- a/scripts/r5_vlma/check_inputs.py +++ b/scripts/r5_vlma/check_inputs.py @@ -4,10 +4,10 @@ import sys import traceback sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import vlm_common as vc # noqa: E402 +import vlm_common as vc -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import transformers +from PIL import Image registry, models_dir, seq, out_dir = sys.argv[1:5] shorts = sys.argv[5:] @@ -60,7 +60,7 @@ for short in shorts: "prompt_tokens": first, "seq_len": int(inp["attention_mask"][i].sum())}) rec["label_checks"] = checks rec["ok"] = all(c["ids_equal"] and c["input_ids_match_labels"] and c["label_part_equal"] for c in checks) - except Exception as e: # noqa: BLE001 + except Exception as e: rec["ok"] = False rec["errors"].append(repr(e)[:400] + " | " + traceback.format_exc()[-800:]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False) diff --git a/scripts/r5_vlma/eval_vlm.py b/scripts/r5_vlma/eval_vlm.py index 20358be8af807372ab43726d93dedd05919326a9..2d03b393123df6cca94ba327ca520e7f6bac6c59 100644 --- a/scripts/r5_vlma/eval_vlm.py +++ b/scripts/r5_vlma/eval_vlm.py @@ -7,12 +7,12 @@ import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import vlm_common as vc # noqa: E402 -import postproc as pp # noqa: E402 +import vlm_common as vc +import postproc as pp -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("--short", required=True) @@ -93,7 +93,7 @@ def cap_retry(e, name, rows, done): try: d = json.loads(line) rdone[d["id"]] = d - except Exception: # noqa: BLE001 + except Exception: pass need = [r for r in rows if done[r["id"]].get("hit_cap") and r["id"] not in rdone] torch.manual_seed(RETRY_SEED) @@ -253,7 +253,7 @@ def image_sizes(manifest): try: with Image.open(r["image"]) as im: out[r["id"]] = [im.width, im.height, r.get("unit", "word"), r["image"]] - except Exception: # noqa: BLE001 + except Exception: pass json.dump(out, open(cp, "w")) return out @@ -318,7 +318,7 @@ for e in todo: try: d = json.loads(line) done[d["id"]] = d - except Exception: # noqa: BLE001 + except Exception: pass for r in rows: if r["id"] in done: @@ -350,13 +350,13 @@ for e in todo: torch.cuda.synchronize() try: recs = gen([load_img(r["image"]) for r in same], MAXNEW[u]) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"batch failed {repr(ex)[:150]}; one at a time") recs = [] for r in same: try: recs += gen([load_img(r["image"])], MAXNEW[u]) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "error": repr(ex2)[:200]}) if use_cuda: torch.cuda.synchronize() diff --git a/scripts/r5_vlma/eval_vlm_test.py b/scripts/r5_vlma/eval_vlm_test.py index d7dce4e21133bc9a4ad9a24210cdc80b8415537a..02cc005359dad85440f9a8387b316042df17af3e 100644 --- a/scripts/r5_vlma/eval_vlm_test.py +++ b/scripts/r5_vlma/eval_vlm_test.py @@ -77,11 +77,11 @@ if not todo: sys.exit(0 if not refused else 4) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import vlm_common as vc # noqa: E402 -import postproc as pp # noqa: E402 -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import vlm_common as vc +import postproc as pp +import torch +import transformers +from PIL import Image dev = args.device deadline = ts(args.deadline_utc) @@ -123,7 +123,7 @@ def read_raw(p): try: x = json.loads(line) d[x["id"]] = x - except Exception: # noqa: BLE001 + except Exception: pass return d @@ -210,13 +210,13 @@ for e in todo: bb = ru[b:b + args.batch] try: recs = gen([load_img(r["image"]) for r in bb], MAXNEW[u]) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"batch failed {repr(ex)[:150]}; one at a time") recs = [] for r in bb: try: recs += gen([load_img(r["image"])], MAXNEW[u]) - except Exception as ex2: # noqa: BLE001 + except Exception as ex2: recs.append({"raw": "", "n_new": 0, "hit_cap": False, "error": repr(ex2)[:200]}) for r, x in zip(bb, recs): x["id"] = r["id"] diff --git a/scripts/r5_vlma/fetch_pinned.py b/scripts/r5_vlma/fetch_pinned.py index f72b6a063edc927959064682af719c09ea2dccd0..2a213a8f167bdc5b987f56a1c2bb4cc2fca301e5 100644 --- a/scripts/r5_vlma/fetch_pinned.py +++ b/scripts/r5_vlma/fetch_pinned.py @@ -94,7 +94,7 @@ for spec in specs: rec["ckpt_params_header"] = sum(header_params(os.path.join(local, g)) for g in got if g.endswith(".safetensors") and "/" not in g) rec["download_seconds"] = round(time.time() - t0, 1) - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("fetch: " + repr(e)[:400]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str) print(short, "FETCH ERROR", repr(e)[:300], flush=True) @@ -111,7 +111,7 @@ for spec in specs: rec["e3_symbols_bad_of_%d" % len(nonspace)] = len(bs) rec["e3_labels_bad_of_%d" % len(labels)] = len(bl) rec["e3_examples_bad"] = (bs + bl)[:10] - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("tokenizer: " + repr(e)[:300]) t1 = time.time() try: @@ -137,7 +137,7 @@ for spec in specs: proc = transformers.AutoProcessor.from_pretrained(local, trust_remote_code=False) rec["processor_class"] = type(proc).__module__ + "." + type(proc).__name__ del model - except Exception as e: # noqa: BLE001 + except Exception as e: rec["load_gate"] = "FAIL" rec["errors"].append("load: " + repr(e)[:500]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False, default=str) diff --git a/scripts/r5_vlma/leader_cmds.py b/scripts/r5_vlma/leader_cmds.py index 9aa1e798c04d35bce2edaa9615924f3667897e61..b3ac51ab9030768d34274f513ecf7a09c3f0bad2 100644 --- a/scripts/r5_vlma/leader_cmds.py +++ b/scripts/r5_vlma/leader_cmds.py @@ -36,7 +36,7 @@ def vlmb_precision(short): d = json.load(open(p)) names = d if isinstance(d, list) else list(d.get("arms", d.keys()) if isinstance(d, dict) else []) return "amp_bf16" if short in names else "pure_bf16" - except Exception: # noqa: BLE001 + except Exception: return "pure_bf16" diff --git a/scripts/r5_vlma/leader_runner.py b/scripts/r5_vlma/leader_runner.py index 23651d822f381cc19e691bf20bc4eb87c40ca6b3..949988e83ffc150b0bdb9610dafc5bee236043fb 100644 --- a/scripts/r5_vlma/leader_runner.py +++ b/scripts/r5_vlma/leader_runner.py @@ -10,7 +10,7 @@ import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import leader_cmds as lc # noqa: E402 +import leader_cmds as lc CFG = sys.argv[1] CODE = "/path/to/TURKIC_OCR_CODE" @@ -52,7 +52,7 @@ def say(*a): def jload(p, default=None): try: return json.load(open(p)) - except Exception: # noqa: BLE001 + except Exception: return default @@ -95,7 +95,7 @@ def run(tag, cmd, hard_deadline, env=None): p.kill() -def on_term(signum, frame): # noqa: ARG001 +def on_term(signum, frame): if CUR["proc"] is not None: CUR["proc"].send_signal(signal.SIGTERM) @@ -157,7 +157,7 @@ def eval_cmd(L, arm, ckpt, sets=""): return cmd -RUNS_DIR_OF = {} # arm -> its runs folder (VLMB/VLMC arms write to DATA/outputs/r5/vlmb/runs) +RUNS_DIR_OF = {} def run_json(arm, phase): @@ -242,7 +242,7 @@ def heartbeat_loop(): try: with open(os.path.join(LD, "claim_" + n, "heartbeat"), "w") as f: f.write(utc()) - except Exception: # noqa: BLE001 + except Exception: pass time.sleep(60) @@ -374,7 +374,7 @@ def get_plan(leaders, windows): pl = plan(leaders, windows) jdump(pl, p) say("P_lead planned:", pl["P_lead"], json.dumps(pl["placement"])) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("planning failed:", repr(ex)[:300], "; retry in 5 min") release("plan") time.sleep(300) @@ -423,7 +423,7 @@ def collect(): """results.json and runs.tsv of all VLMA arms in DATA/outputs/r5/vlma/ (cheap; reads logs and meta files only).""" try: run("collect", PY + [os.path.join(S, "collect_results.py"), REG, V], time.time() + 600) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("collect failed", repr(ex)[:200]) @@ -434,9 +434,6 @@ def retry_sets_done(arm, ckpt): return {k for k, v in (m.get("sets") or {}).items() if v.get("complete")} -# 1. catch-up of finished short arms (VLMA's own arms): D9 sets that became ready later, and the cap-retry folder -# (_retry: only the hit_cap rows are re-decoded). Claimed per arm, so both slots -# can share it. for short in cfg().get("short_arms", []): if time.time() >= ts(cfg()["train_deadline_utc"]): break @@ -477,9 +474,6 @@ while not os.path.exists(lf): say("waiting for", lf) time.sleep(300) LJ = jload(lf) -# "leaders" = the two leaders (two seeds each unless an entry says "seeds"), "extra" = the two extra -# arms (seed 1 only: continue from their short checkpoint on seed-1 data). kind "vlmb" (or "vlmc") = maker-code arm, -# launched through VLMB's leader_interface.json (leader_cmds.py). RUNS = [] for L in LJ.get("leaders", []): for si in L.get("seeds", [1, 2]): @@ -532,7 +526,7 @@ while time.time() < ts(cfg()["train_deadline_utc"]): HB["names"].add("run_" + name) try: ok = do_run(L, si, P) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{name}: error {repr(ex)[:300]}") ok = False finally: diff --git a/scripts/r5_vlma/ptrl.py b/scripts/r5_vlma/ptrl.py index daa39be15bb5f3b917005f6200de9a97d8c399cc..2618f3d86c86322528e2e08669e9babada62ad63 100644 --- a/scripts/r5_vlma/ptrl.py +++ b/scripts/r5_vlma/ptrl.py @@ -9,12 +9,12 @@ import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import vlm_common as vc # noqa: E402 -import postproc as pp # noqa: E402 +import vlm_common as vc +import postproc as pp -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("--arm-kind", required=True, choices=["C", "D", "G"]) @@ -219,11 +219,11 @@ def _wi(_): ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0) if os.getppid() != PARENT_PID: os._exit(0) - except Exception: # noqa: BLE001 + except Exception: pass try: os.nice(10) - except Exception: # noqa: BLE001 + except Exception: pass torch.set_num_threads(1) diff --git a/scripts/r5_vlma/ptrl_driver.py b/scripts/r5_vlma/ptrl_driver.py index 7f4ff8b746daa44995f8db69022594153581c420..f59cdd1f0ae815ec772666fd2da2b7f2ab7714f8 100644 --- a/scripts/r5_vlma/ptrl_driver.py +++ b/scripts/r5_vlma/ptrl_driver.py @@ -57,7 +57,7 @@ def run(tag, cmd, budget_s): try: rc = subprocess.run(["timeout", "-k", "120", str(int(max(budget_s, 60)))] + cmd, stdout=lf, stderr=subprocess.STDOUT, env=env).returncode - except Exception as e: # noqa: BLE001 + except Exception as e: rc = -1 lf.write(repr(e) + "\n") print(f"[ptrl_driver {utc()}] {tag}: rc {rc} after {time.time() - t0:.0f}s (log {lp})", flush=True) diff --git a/scripts/r5_vlma/runner.py b/scripts/r5_vlma/runner.py index ce007201fa7b14a71f3b34ea6054ab6de90d48bf..b5ad6fcdca2c0571355775bff6a1fd733931a080 100644 --- a/scripts/r5_vlma/runner.py +++ b/scripts/r5_vlma/runner.py @@ -105,7 +105,7 @@ def run(tid, cmd, timeout_s, poll=None): p.kill() -def on_term(signum, frame): # noqa: ARG001 +def on_term(signum, frame): say(f"runner got signal {signum}; passing SIGTERM to the running task") if CUR["proc"] is not None: CUR["proc"].send_signal(signal.SIGTERM) @@ -204,7 +204,7 @@ def leaders_for_slot(): e = d.get(SLOT) or d.get("slot_" + SLOT) if e: return dict(e, source=lf) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("leaders file unreadable", repr(ex)[:100]) auto = os.path.join(V, f"leaders_auto_{SLOT}.json") if os.path.exists(auto): @@ -335,7 +335,7 @@ while True: mark(tid, status="running", attempts=a + 1, started=utc()) try: ok = do_long(L) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{tid}: runner error {repr(ex)[:300]}") ok = False mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc()) @@ -361,7 +361,7 @@ while True: try: ok = do_smoke(s) if kind == "smoke" else do_short(s, stop_poll) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{tid}: runner error {repr(ex)[:300]}") ok = False mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc()) diff --git a/scripts/r5_vlma/testpass_build_tasks.py b/scripts/r5_vlma/testpass_build_tasks.py index b6ed05e0e3bf69712430c27f8325b2f30b2f23d9..d30673da6fdc8fccb0adc2c189bd1fd596544258 100644 --- a/scripts/r5_vlma/testpass_build_tasks.py +++ b/scripts/r5_vlma/testpass_build_tasks.py @@ -114,7 +114,7 @@ try: "b1_named": bool(sel.get("B1")) and isinstance((sel.get("roles") or {}).get("B1"), dict), "generated_by_not_before": bool(gen) and ts(gen) <= NOT_BEFORE and ts(gen) <= NOW, "generated_utc": gen} -except Exception: # noqa: BLE001 (unreadable or malformed: not frozen) +except Exception: sel_info["error"] = traceback.format_exc()[-600:] checks = {"readable": False} FROZEN = bool(checks) and all(v for k, v in checks.items() if k != "generated_utc") @@ -269,7 +269,7 @@ built = None if MODE == "selection": try: built = build("selection") - except Exception: # noqa: BLE001 (a malformed role: fall back, never fail) + except Exception: notes.append("building from selection.json failed, J2 fallback used instead: " + traceback.format_exc()[-500:]) MODE = "fallback" if MODE == "fallback": diff --git a/scripts/r5_vlma/testpass_runner.py b/scripts/r5_vlma/testpass_runner.py index f136ec2eada7ba8de3b2edb18b12eb4bdf818ccc..7311e042e57bb5c3f2bb0a2751bbc3cad1762f14 100644 --- a/scripts/r5_vlma/testpass_runner.py +++ b/scripts/r5_vlma/testpass_runner.py @@ -10,7 +10,7 @@ import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import leader_cmds as lc # noqa: E402 (read-only use of the shared VLMB interface helper) +import leader_cmds as lc ap = argparse.ArgumentParser() ap.add_argument("--config", required=True) @@ -58,7 +58,7 @@ def jload(p, d=None): try: with open(p, encoding="utf-8") as f: return json.load(f) - except Exception: # noqa: BLE001 + except Exception: return d @@ -135,7 +135,7 @@ def hb_loop(): try: with open(os.path.join(d, "heartbeat") if d else ALIVE, "w") as f: f.write(utc()) - except Exception: # noqa: BLE001 + except Exception: pass time.sleep(30) @@ -155,7 +155,7 @@ threading.Thread(target=hb_loop, daemon=True).start() CUR = {"proc": None, "term": False} -def on_term(signum, frame): # noqa: ARG001 +def on_term(signum, frame): CUR["term"] = True p = CUR["proc"] if p is not None: @@ -198,7 +198,7 @@ def eval_done(t): def command(t): if t["kind"] == "cmd": env = dict(os.environ) - env.update(CFG.get("cmd_env", {})) # tests only (scratch paths for LINEDET); absent in the real config + env.update(CFG.get("cmd_env", {})) env.update(t.get("env", {})) env["TESTPASS_DIR"] = TPD return list(t["argv"]), env diff --git a/scripts/r5_vlma/tptest.py b/scripts/r5_vlma/tptest.py index aafb8356a9b5a9f8111c9910275d4469c4d03717..f51d12f3af5e5a83f53c442098aa692276d33fd3 100644 --- a/scripts/r5_vlma/tptest.py +++ b/scripts/r5_vlma/tptest.py @@ -34,7 +34,7 @@ def check(name, ok, detail=""): def jl(p, d=None): try: return json.load(open(p, encoding="utf-8")) - except Exception: # noqa: BLE001 + except Exception: return d @@ -72,7 +72,7 @@ def head_rows(src, dst, n, blank_split=False): # scratch data: VALIDATION rows only, entered as locked so that the test-pass code reads them head_rows(V["print_real_val"]["manifest"], OUT + "/pr40.tsv", 40) -head_rows(V["print_real_val"]["manifest"], OUT + "/ld60.tsv", 60, blank_split=True) # LINEDET's test mode keeps rows of split test or blank +head_rows(V["print_real_val"]["manifest"], OUT + "/ld60.tsv", 60, blank_split=True) jd({"about": "SELF-TEST registry: validation manifests entered as locked; not test sets", "sets": [{"name": "LOCKEDV1", "manifest": V["V1"]["manifest"], "split": "val", "locked": True, "unit": "word"}, {"name": "LOCKEDPR", "manifest": OUT + "/pr40.tsv", "split": "val", "locked": True, "unit": "line"}, diff --git a/scripts/r5_vlma/train_vlm.py b/scripts/r5_vlma/train_vlm.py index 49e7d0b755615c2a1782147962220d60c1127915..19186d3908d6dcfd53e4fba09ae9a1ca10c3361f 100644 --- a/scripts/r5_vlma/train_vlm.py +++ b/scripts/r5_vlma/train_vlm.py @@ -8,12 +8,12 @@ import time from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import vlm_common as vc # noqa: E402 -import postproc as pp # noqa: E402 +import vlm_common as vc +import postproc as pp -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("--short", required=True) @@ -69,12 +69,12 @@ job_id = os.environ.get("SLURM_JOB_ID", "") STOP = {"flag": False, "why": ""} -def _sig(signum, frame): # noqa: ARG001 +def _sig(signum, frame): STOP["flag"] = True STOP["why"] = "signal %d" % signum -def _sig_leaders(signum, frame): # noqa: ARG001 +def _sig_leaders(signum, frame): STOP["flag"] = True STOP["why"] = "leaders" @@ -130,7 +130,7 @@ model.config.use_cache = False try: model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) gc_on = True -except Exception as e: # noqa: BLE001 +except Exception as e: gc_on = "failed: " + repr(e)[:200] for p in model.parameters(): p.requires_grad_(True) @@ -195,7 +195,7 @@ def save_state(d, extra=None): return time.time() - t0 -import shutil # noqa: E402 +import shutil for leftover in (state_dir + ".tmp",): if os.path.isdir(leftover): @@ -276,12 +276,12 @@ def _worker_init(_): ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0) if os.getppid() != PARENT_PID: # the parent died before prctl took effect os._exit(0) - except Exception: # noqa: BLE001 + except Exception: pass # loader workers yield the CPU to the main process, which launches the GPU kernels (performance only) try: os.nice(10) - except Exception: # noqa: BLE001 + except Exception: pass torch.set_num_threads(1) @@ -396,7 +396,7 @@ def run_curve(label): rec.update({"plain_cer": sc["plain"]["cer"], "pp_cer": sc["pp"]["cer"], "rows": len(rows_ok), "curve_eval_seconds": round(dt, 1)}) log(rec) say(f"curve point {label}: {len(rows_ok)} rows, plain CER {sc['plain']['cer']}, {dt:.0f}s (not counted in the cap)") - except Exception as ex: # noqa: BLE001 a failed curve point never stops training + except Exception as ex: st["curve_done"].append(label) rec["failed"] = repr(ex)[:300] log(rec) @@ -509,7 +509,7 @@ while st["step"] < total_steps: fpf.write(ka.table(sort_by="self_cpu_time_total", row_limit=35)) fpf.write("\n\nTOP BY CUDA TIME\n") fpf.write(ka.table(sort_by="cuda_time_total", row_limit=20)) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("profile write failed", repr(ex)[:200]) prof = None st["step"] += 1 diff --git a/scripts/r5_vlma/vlm_common.py b/scripts/r5_vlma/vlm_common.py index b5df28b748e9e759980f98b1de24d08cceaf57ba..6e42b9bb98a4982835e0458a919426da18567245 100644 --- a/scripts/r5_vlma/vlm_common.py +++ b/scripts/r5_vlma/vlm_common.py @@ -130,7 +130,7 @@ def answer_suffix(short, proc, tok, gen_cfg, tmpl_kw): {"role": "assistant", "content": content}] try: txt = proc.apply_chat_template(conv, add_generation_prompt=False, tokenize=False, **tmpl_kw) - except Exception: # noqa: BLE001 + except Exception: continue if SENTINEL in txt: tail = txt.split(SENTINEL, 1)[1] diff --git a/scripts/r5_vlmb/adapters/ad_dots_mocr.py b/scripts/r5_vlmb/adapters/ad_dots_mocr.py index fad5a33b82323eb149801f329562967fc61c4b31..d195bd13007d5df5559edb5e7fe2d82b8f04f98d 100644 --- a/scripts/r5_vlmb/adapters/ad_dots_mocr.py +++ b/scripts/r5_vlmb/adapters/ad_dots_mocr.py @@ -32,7 +32,7 @@ class Adapter: remote_files_check(model_dir) if STUBS not in sys.path: sys.path.insert(0, STUBS) - import flash_attn # noqa: F401 (the stub) + import flash_attn assert getattr(flash_attn, "IS_VLMB_STUB", False), "a real flash_attn was found; expected the stub" self.device = device cls = get_class_from_dynamic_module("modeling_dots_ocr.DotsOCRForCausalLM", model_dir) diff --git a/scripts/r5_vlmb/adapters/ad_unlimited_ocr_2.py b/scripts/r5_vlmb/adapters/ad_unlimited_ocr_2.py index 4c8e3335f1793c8b63887ffc9d92911ce6b421e8..5cc0da8348c8fa88aba585c27aad19640913f4d7 100644 --- a/scripts/r5_vlmb/adapters/ad_unlimited_ocr_2.py +++ b/scripts/r5_vlmb/adapters/ad_unlimited_ocr_2.py @@ -52,11 +52,11 @@ for _k, _v in (("DASH_K_START", "12"), ("DASH_K_END", "12"), ("DASH_STAGE0", "he os.environ[_k] = _v os.environ.pop("DASH_SPARSITY_SCHED", None) -import torch # noqa: E402 -import torch.nn.functional as F # noqa: E402 -from transformers import AutoModel, AutoTokenizer # noqa: E402 +import torch +import torch.nn.functional as F +from transformers import AutoModel, AutoTokenizer -from .common import INSTRUCTION, assert_no_token_env, autocast, master_dtype, remote_files_check # noqa: E402 +from .common import INSTRUCTION, assert_no_token_env, autocast, master_dtype, remote_files_check PROMPT = "" + INSTRUCTION + "" IMAGE_TOKEN_ID = 128815 diff --git a/scripts/r5_vlmb/vlmb_check.py b/scripts/r5_vlmb/vlmb_check.py index 96af20d16f35bce608c25c75c4fbc526e714b95b..25468cbfd8806682f7012c7209ea18fd350a732c 100644 --- a/scripts/r5_vlmb/vlmb_check.py +++ b/scripts/r5_vlmb/vlmb_check.py @@ -20,8 +20,8 @@ ap.add_argument("--threads", type=int, default=0) ap.add_argument("--precision", default="pure_bf16") args = ap.parse_args() sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image if args.threads: torch.set_num_threads(args.threads) diff --git a/scripts/r5_vlmb/vlmb_collect.py b/scripts/r5_vlmb/vlmb_collect.py index 716f783c29f614355c7487cc23848b97263778da..6e3cbc5199ecc326767cec109bf40936f876c2a8 100644 --- a/scripts/r5_vlmb/vlmb_collect.py +++ b/scripts/r5_vlmb/vlmb_collect.py @@ -12,7 +12,7 @@ PREDS = os.environ.get("VLMB_COLLECT_TEST_PREDS") or os.path.join(DATA, "outputs def jl(p, default=None): try: return json.load(open(p)) - except Exception: # noqa: BLE001 + except Exception: return default diff --git a/scripts/r5_vlmb/vlmb_fetch.py b/scripts/r5_vlmb/vlmb_fetch.py index 5f7bd5dce2efa6f836dbd43e409173caa28d99de..219f9dbbc4f88ca3eda8966955b4d2588d357aea 100644 --- a/scripts/r5_vlmb/vlmb_fetch.py +++ b/scripts/r5_vlmb/vlmb_fetch.py @@ -12,7 +12,7 @@ models_tsv, models_dir, out_dir = sys.argv[1:4] shorts = sys.argv[4:] os.makedirs(out_dir, exist_ok=True) -from huggingface_hub import HfApi, snapshot_download # noqa: E402 +from huggingface_hub import HfApi, snapshot_download SKIP_EXT = (".bin", ".pt", ".pth", ".ckpt", ".pkl", ".pickle", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".pdf", ".mp4", ".svg", ".pyc", ".pyo", ".so") # compiled code is never downloaded (added 2026-11-20 22:50) @@ -55,7 +55,7 @@ for short in shorts: rec["files"] = sorted(files, key=lambda d: d["path"]) rec["py_files"] = [d["path"] for d in rec["files"] if d["path"].endswith(".py")] rec["download_seconds"] = round(time.time() - t0, 1) - except Exception as e: # noqa: BLE001 + except Exception as e: rec["errors"].append("fetch: " + repr(e)[:500]) json.dump(rec, open(os.path.join(out_dir, short + ".json"), "w"), indent=1, ensure_ascii=False) print(short, "files", len(rec.get("files", [])), "py", rec.get("py_files"), "errors", rec["errors"], flush=True) diff --git a/scripts/r5_vlmb/vlmb_predict.py b/scripts/r5_vlmb/vlmb_predict.py index 9579517c6b3e8f708aab7a20b6527fa2cfc40e29..dd15aaf33d726b1b3f122e18ef52ea14bb09f7e7 100644 --- a/scripts/r5_vlmb/vlmb_predict.py +++ b/scripts/r5_vlmb/vlmb_predict.py @@ -32,8 +32,8 @@ args = ap.parse_args() assert "test" not in os.path.basename(args.manifest).lower(), "refusing a test manifest" sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image if args.threads: torch.set_num_threads(args.threads) @@ -95,13 +95,13 @@ with open(pred_path, "a", encoding="utf-8") as fo: tg = time.time() try: hyps = ad.generate(ims, mnt) - except Exception as e: # noqa: BLE001 + except Exception as e: print("batch failed, one at a time:", repr(e)[:300], flush=True) hyps = [] for im in ims: try: hyps.append(ad.generate([im], mnt)[0]) - except Exception as e2: # noqa: BLE001 + except Exception as e2: print("item failed:", repr(e2)[:300], flush=True) hyps.append("") if use_cuda: diff --git a/scripts/r5_vlmb/vlmb_runner.py b/scripts/r5_vlmb/vlmb_runner.py index 72780179896eddebfc25e6c049c3882d1a5f082f..30c0864bf1e6512b78c5306f9e9054a764fb6ab8 100644 --- a/scripts/r5_vlmb/vlmb_runner.py +++ b/scripts/r5_vlmb/vlmb_runner.py @@ -103,7 +103,7 @@ def jload_retry(path, default): for _ in range(5): try: return json.load(open(path)) if os.path.exists(path) else default - except Exception: # noqa: BLE001 + except Exception: time.sleep(1) return json.load(open(path)) @@ -116,7 +116,7 @@ def arm_lists(q): if sq: try: shared = [a for a in json.load(open(sq)).get("short", []) if a not in own] - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("shared queue unreadable", repr(ex)[:120]) claimable = set(shared) | (set(own) if q.get("claim_own") else set()) return own + shared, claimable @@ -145,7 +145,7 @@ def job_alive(job): alive = bool(states) and not all(s.startswith(JOB_END_STATES) for s in states) else: alive = "Invalid job id" not in (r.stderr or "") - except Exception: # noqa: BLE001 + except Exception: alive = True _JOBQ[job] = (time.time(), alive) return alive @@ -163,7 +163,7 @@ def claim_info(arm): return None try: return json.load(open(p)) - except Exception: # noqa: BLE001 + except Exception: return {"slot": "unreadable (being written by another runner)", "unreadable": True} @@ -242,7 +242,7 @@ class CurveClock: if os.path.exists(mp) and os.path.getmtime(mp) >= rm: try: es = float(json.load(open(mp)).get("eval_seconds")) - except Exception: # noqa: BLE001 + except Exception: es = max(0.0, os.path.getmtime(mp) - self.seen[d]) self.done[d] = es say(f"{tid}: curve evaluation {os.path.basename(d)} done, {es:.0f} s excluded from the training timeout") @@ -281,7 +281,7 @@ def run(tid, cmd, timeout_s, poll=None, curve_arm=None): if clock is not None: try: CUR["curve_s"] = clock.excluded(time.time(), tid) - except Exception: # noqa: BLE001 + except Exception: pass say(f"{tid}: exit {rc} after {time.time() - t0:.0f}s" + (f" ({CUR['curve_s']:.0f}s of curve evaluation not counted in the timeout)" if clock else "")) @@ -292,7 +292,7 @@ def run(tid, cmd, timeout_s, poll=None, curve_arm=None): if clock is not None: try: excl = clock.excluded(now, tid) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{tid}: curve clock error {repr(ex)[:120]}") CUR["curve_s"] = excl if termed is None and (now >= hard or now - t0 - excl >= timeout_s): @@ -308,7 +308,7 @@ def run(tid, cmd, timeout_s, poll=None, curve_arm=None): p.kill() -def on_term(signum, frame): # noqa: ARG001 +def on_term(signum, frame): say(f"runner got signal {signum}; passing SIGTERM to the running task") if CUR["proc"] is not None: CUR["proc"].send_signal(signal.SIGTERM) @@ -458,7 +458,7 @@ def leaders_for_slot(): e = d.get(SLOT) or d.get("slot_" + SLOT) if e: return dict(e, source=lf) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say("leaders file unreadable", repr(ex)[:100]) return None @@ -568,7 +568,7 @@ while True: mark(tid, status="running", attempts=a + 1, started=utc()) try: ok = do_long(L) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{tid}: runner error {repr(ex)[:300]}") ok = False mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc()) @@ -608,7 +608,7 @@ while True: try: ok = do_smoke(s) if kind == "smoke" else do_short(s, stop_poll) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"{tid}: runner error {repr(ex)[:300]}") ok = False mark(tid, status="done" if ok else ("failed" if a == 0 else "failed_final"), ended=utc()) diff --git a/scripts/r5_vlmb/vlmb_train.py b/scripts/r5_vlmb/vlmb_train.py index 65284875c36bfecdf3ef1ce7561206708eb87b31..b7103bb8e617b2b90cca3efcaa5ed4e9f0f85cdb 100644 --- a/scripts/r5_vlmb/vlmb_train.py +++ b/scripts/r5_vlmb/vlmb_train.py @@ -43,8 +43,8 @@ ap.add_argument("--precision", default="amp_bf16", choices=["amp_bf16", "pure_bf args = ap.parse_args() sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 -from PIL import Image # noqa: E402 +import torch +from PIL import Image if args.threads: torch.set_num_threads(args.threads) diff --git a/scripts/r5_vlmb/vlmb_train_vlm.py b/scripts/r5_vlmb/vlmb_train_vlm.py index a1b263b7f559774635125749de4d6ec9d4cbf340..611cb2bc0a03b81bff43654ca89e379b868e86fd 100644 --- a/scripts/r5_vlmb/vlmb_train_vlm.py +++ b/scripts/r5_vlmb/vlmb_train_vlm.py @@ -16,9 +16,9 @@ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1") os.environ.setdefault("TOKENIZERS_PARALLELISM", "false") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import torch # noqa: E402 -import transformers # noqa: E402 -from PIL import Image # noqa: E402 +import torch +import transformers +from PIL import Image # Performance only (same as scripts/r5_vlma/vlm_common.py): the # cuDNN backend of scaled_dot_product_attention builds a new execution plan for every new sequence shape (20.7 of @@ -87,12 +87,12 @@ job_id = os.environ.get("SLURM_JOB_ID", "") STOP = {"flag": False, "why": ""} -def _sig(signum, frame): # noqa: ARG001 +def _sig(signum, frame): STOP["flag"] = True STOP["why"] = "signal %d" % signum -def _sig_leaders(signum, frame): # noqa: ARG001 +def _sig_leaders(signum, frame): STOP["flag"] = True STOP["why"] = "leaders" @@ -143,7 +143,7 @@ model = ad.model try: ad.enable_gradient_checkpointing() gc_on = True -except Exception as e: # noqa: BLE001 +except Exception as e: gc_on = "failed: " + repr(e)[:200] for p in model.parameters(): p.requires_grad_(True) @@ -281,7 +281,7 @@ def _worker_init(_): ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0) if os.getppid() != PARENT_PID: # the parent died before prctl took effect os._exit(0) - except Exception: # noqa: BLE001 + except Exception: pass @@ -330,7 +330,7 @@ def curve_eval(nominal, note=""): bb = part[b:b + 16] try: hyps = ad.generate([Image.open(r["image"]).convert("RGB") for r in bb], cap) - except Exception as ex: # noqa: BLE001 + except Exception as ex: say(f"curve batch failed {repr(ex)[:150]}") hyps = [""] * len(bb) for r, h in zip(bb, hyps): diff --git a/scripts/r5eval/score.py b/scripts/r5eval/score.py index 2d1c4ac6aabba4a834456741a82979198d913079..4edc4a49146372c3052dd8b21f353a4ebd9ef6f8 100644 --- a/scripts/r5eval/score.py +++ b/scripts/r5eval/score.py @@ -2,14 +2,14 @@ import os for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(_v, "1") -import argparse # noqa: E402 -import concurrent.futures # noqa: E402 -import hashlib # noqa: E402 -import json # noqa: E402 -import multiprocessing # noqa: E402 -import sys # noqa: E402 -import time # noqa: E402 -import traceback # noqa: E402 +import argparse +import concurrent.futures +import hashlib +import json +import multiprocessing +import sys +import time +import traceback HERE = os.path.dirname(os.path.abspath(__file__)) SRC = os.path.normpath(os.path.join(HERE, "..", "..", "src")) @@ -96,7 +96,7 @@ def run_job(job, extra): for i, a, b in repairs: f.write("%s\t%s\t%s\n" % (i, a, b)) return {"job": job["out"], "status": res.get("status"), "seconds": round(time.time() - t0, 1)} - except Exception: # noqa: BLE001 + except Exception: return {"job": job["out"], "status": "error", "error": traceback.format_exc()[-1500:], "seconds": round(time.time() - t0, 1)} @@ -146,7 +146,7 @@ def score_pages(a, reg, gate_open, extra, plog): ioutil.write_json_atomic(out, res) plog["scored"].append(out) print("page file scored", out, flush=True) - except Exception: # noqa: BLE001 + except Exception: plog["errors"].append({"set": stem, "error": traceback.format_exc()[-1200:]}) diff --git a/scripts/release2/rel2_build_data.py b/scripts/release2/rel2_build_data.py index 21e72793b69ffee890e13d654def0babde5bf387..6172720f8f36bc1459839e0d416cd58aaaab4563 100644 --- a/scripts/release2/rel2_build_data.py +++ b/scripts/release2/rel2_build_data.py @@ -149,7 +149,6 @@ def main(): t0 = time.time() created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) - # ---- job B results regen = {} with open(REGEN + "/pages.jsonl", encoding="utf-8") as f: for line in f: @@ -191,7 +190,6 @@ def main(): m = RX_PAGE.match(rid) return (m.group(1), lang, "H", int(m.group(3))) - # ---- stored evidence per page: fonts of every stored row of the page (frozen, pre-freeze, val/test) and the saved page JSON stored_fonts = defaultdict(dict) # page key -> {font_id: licence class} stored_writer_or_print = defaultdict(set) saved_json = {} # page key -> path of the saved page JSON @@ -362,7 +360,6 @@ def main(): font_use[fid] += 1 print(kind, sp, "rows", len(rows), "kept so far", sum(c["kept"] for c in counts.values()), "%.0f s" % (time.time() - t0), flush=True) - # ---- dropped at the freeze (listed, never released) for kind in ("hand", "typed", "clutter"): fz = set(r["id"] for r in load_tsv(R5 + "/frozen_mix_v1/synth_%s_train.tsv" % kind)) for r in load_tsv(R5 + "/manifests/synth_%s_train.tsv" % kind): @@ -371,7 +368,6 @@ def main(): counts[ck]["dropped_at_freeze_not_in_frozen_split"] += 1 excluded_rows.append((r["id"], kind, "train", r["lang"], "dropped_at_freeze (near-duplicate of, or label equal to, a validation or test row; never in the frozen training mix)", "")) - # ---- copy images (verify bytes) sums = {} def do_copy(job): @@ -416,7 +412,6 @@ def main(): write_text(jrel, js + "\n") ET.fromstring(xml.split("\n", 1)[1]) # well-formed check (raises if not) - # ---- labels tsv_cols = ["id", "image", "text", "language", "script", "kind", "split", "font_id", "generator_version", "seed", "page_id", "line_id", "crop_mode", "text_licences"] for key, recs in sorted(label_rows.items()): write_text("labels/%s.jsonl" % key, "".join(json.dumps(x, ensure_ascii=False, sort_keys=True) + "\n" for x in recs)) @@ -430,12 +425,10 @@ def main(): lines.append("\t".join(vals)) write_text("labels/%s.tsv" % key, "\n".join(lines) + "\n") - # ---- exclusions write_text("excluded/excluded_items.tsv", "id\tkind\tsplit\tlanguage\treasons\tpersonal_use_fonts_on_page\n" + "".join("\t".join(x) + "\n" for x in sorted(excluded_rows))) write_text("excluded/exclusion_counts.json", json.dumps({k: dict(v) for k, v in sorted(counts.items())}, indent=1, sort_keys=True) + "\n") - # ---- attribution rows = ["language\twikipedia\tpage_id\turl\titems"] for (lang, d), n in sorted(attrib.get("wiki", {}).items()): pid = d.split(":", 1)[1] @@ -457,7 +450,6 @@ def main(): write_text("LICENSE", dec["licence_file_text"]) write_text("attribution/notices.json", json.dumps(dec["notices"], ensure_ascii=False, indent=1) + "\n") - # ---- real print pointers (train and val only; no images, no text) pointer_counts = Counter() if dec.get("build_print_pointers"): ids = {} @@ -505,7 +497,6 @@ def main(): pointer_counts["folder"] = PO.replace(D, "DATA") pointer_counts["bytes"] = sum(os.path.getsize(os.path.join(PO, k)) for k in psums) - # ---- scrub check over every text file written scrub_hits = [] for rel in sorted(sums): if rel.endswith((".jsonl", ".tsv", ".json", ".xml")) or rel == "LICENSE": diff --git a/scripts/release2/rel2_regen.py b/scripts/release2/rel2_regen.py index b9ce9288025e46d1ee7a0657ce0ec7369d65d08f..1f6117d73f7fe397a0c593ee359bbae15b52f7b2 100644 --- a/scripts/release2/rel2_regen.py +++ b/scripts/release2/rel2_regen.py @@ -19,9 +19,9 @@ os.environ["PAGESYNTH_FONTS"] = CODE_GEN + "/assets/fonts" sys.path.insert(0, CODE_GEN) csv.field_size_limit(10 ** 9) -import cv2 # noqa: E402 +import cv2 cv2.setNumThreads(1) -import produce_r5 as P5 # noqa: E402 (the production driver, unchanged) +import produce_r5 as P5 LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"] RX_LINE = re.compile(r"^(hs|ts|cl)_(train|val|test)_(.+)_(\d{6})_(\d{2})$") diff --git a/src/linedet/data.py b/src/linedet/data.py index cc45d0f83c5ec8d606a339a6225287d4960d7cb8..45e4bb01fd3215ae0491ce72310b0e666ca4f980 100644 --- a/src/linedet/data.py +++ b/src/linedet/data.py @@ -44,7 +44,6 @@ SPECS = { } -# ----------------------------------------------------------------------------------------------- mix definition _COMP_KEYS = ("components", "sources", "mix", "parts", "entries", "streams", "groups", "shares") _MEMBER_KEYS = ("members", "items", "sources", "manifests", "components", "children") _MAN_KEYS = ("manifest", "path", "file", "tsv") @@ -141,7 +140,6 @@ def load_components(mix_comps, use_split="train"): return comps -# ----------------------------------------------------------------------------------------------- deterministic stream class MixStream: """Deterministic endless stream of batches. Sample s belongs to pool s // pool_size. Pool p draws its component counts from a multinomial over the shares; inside a component the items are read in seeded epoch permutations @@ -217,7 +215,6 @@ class FlatItems: return len(self.items) -# ----------------------------------------------------------------------------------------------- images def load_tensor(path, spec, aug=None): """Load, height-normalise, pad, invert, augment. Returns float tensor (C, H, W).""" return pil_tensor(Image.open(path), spec, aug) diff --git a/src/linedet/lm_decode.py b/src/linedet/lm_decode.py index 4266de75b193483fba793a77fde340523497c886..a6eb99a5d4362fe6fb233d2662d22aa975dc3280 100644 --- a/src/linedet/lm_decode.py +++ b/src/linedet/lm_decode.py @@ -180,7 +180,6 @@ def main(): tune = None t0 = time.time() with Pool(a.workers, initializer=_init, initargs=(a.lm, c2l)) as pool: - # ---- tune alpha, beta on the lmtune set only tuned = None if tune and "cer" in meta0["per_set"].get(tune, {}): npz = load_npz(os.path.join(lg_dir, tune + ".npz")) diff --git a/src/linedet/models.py b/src/linedet/models.py index bac2ed655efe67bbf9fd974a13b036eadb05b2f6..2cbb1a73c9aeffc925d51bf06bb97cb8ce16f48b 100644 --- a/src/linedet/models.py +++ b/src/linedet/models.py @@ -20,7 +20,6 @@ AMP = {"on": True} A4_OPTS = {"output_ln": True} # A4 diagnostic variant v1 (clarification H8) sets output_ln False; the checkpoint records it # bf16 autocast on CUDA; train_arm --no_amp switches it off -# ------------------------------------------------------------------------------------------------ helpers def n_params(m): return sum(p.numel() for p in m.parameters()) @@ -59,7 +58,6 @@ def ctc_from_logits(logits_btc, in_lens, target, target_lens): return F.ctc_loss(lp, target, in_lens, target_lens, blank=CTC_BLANK, zero_infinity=True, reduction="mean") -# ------------------------------------------------------------------------------------------------ PP-OCRv6 arms class PPOCRArm: kind = "ppocr" @@ -196,7 +194,6 @@ class PPOCRArm: return {"deployed": layer_report(self.net.nn), "aux_training_only": layer_report(self.aux, 1)[0]} -# ------------------------------------------------------------------------------------------------ A3: CRNN def _cbr(i, o): return [nn.Conv2d(i, o, 3, padding=1, bias=False), nn.BatchNorm2d(o), nn.ReLU(inplace=True)] @@ -306,7 +303,6 @@ class CRNNArm: return {"deployed": layer_report(self.net)} -# ------------------------------------------------------------------------------------------------ A4: HTR-VT design class _BasicBlock(nn.Module): def __init__(self, inp, planes, stride=1, downsample=None): super().__init__() @@ -589,7 +585,6 @@ class HTRVTArm: return {"deployed": layer_report(self.net)} -# ------------------------------------------------------------------------------------------------ factory BASE = {"A1": ("medium", "zenodo_ppocrv6_medium_21788410/medium.safetensors"), "A2": ("small", "zenodo_ppocrv6_small_21788405/small.safetensors")} diff --git a/src/linedet/train_arm.py b/src/linedet/train_arm.py index 67aed604815f7a696d2031918885aa487cdffff3..9c50bfbc03aba45d8da3b1529857c2731d3127a4 100644 --- a/src/linedet/train_arm.py +++ b/src/linedet/train_arm.py @@ -26,7 +26,7 @@ RECIPE = { "A3": dict(bs=32, lr=1e-3, min_lr=1e-6, opt="AdamW wd 0.01, grad clip 5", source="own default (stated before the run)"), "A4": dict(bs=128, lr=1e-3, min_lr=1e-7, opt="SAM(rho 0.05)+AdamW(betas 0.9/0.99, wd 0.5), EMA 0.9999, span mask 0.4/8", source="HTR-VT paper section 4 'Implementation details' and run/lam.sh"), } -WARMUP_FRACTION = 0.03 # amendment 3.2 C1 uses 3 % warm-up for the VLM arms; the same value is used here +WARMUP_FRACTION = 0.03 # columns (samples x padded width in pixels) allowed in one micro-batch; a larger batch is split and its gradients accumulated. diff --git a/src/pagesynth/generate_pages.py b/src/pagesynth/generate_pages.py index 68c8814e3737a2329c7d148da4fe67de69fa2ae6..99b12132a3467a394b2745f2ec8dd8af84101db2 100644 --- a/src/pagesynth/generate_pages.py +++ b/src/pagesynth/generate_pages.py @@ -8,13 +8,13 @@ import time os.environ.setdefault("OMP_NUM_THREADS", "1") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import cv2 # noqa: E402 +import cv2 cv2.setNumThreads(1) -from pagesynth import fonts as F # noqa: E402 -from pagesynth import generate as GEN # noqa: E402 -from pagesynth import qa as QA # noqa: E402 -from pagesynth import text as T # noqa: E402 +from pagesynth import fonts as F +from pagesynth import generate as GEN +from pagesynth import qa as QA +from pagesynth import text as T def code_hash(root): diff --git a/src/pagesynth/pagesynth/ink.py b/src/pagesynth/pagesynth/ink.py index 1d974f813d9a039b8f7de0fa80b2c0f68e75e06d..80f9f189e32cc57cda608d3df4f1c69565eb3205 100644 --- a/src/pagesynth/pagesynth/ink.py +++ b/src/pagesynth/pagesynth/ink.py @@ -165,7 +165,6 @@ def render_line(face, axes, text, x0, ybase, size_px, rng, style, hand=True): size_ss = int(round(size_px * S)) f = face.pil(size_ss, axes) xh_ss = face.xheight_px(size_px, axes) * S - # ---- layout: list of items (string, pen_x in SS px, params) items = [] pen = 0.0 words = text.split(" ") @@ -274,7 +273,6 @@ def render_line(face, axes, text, x0, ybase, size_px, rng, style, hand=True): char_boxes.append((chr_, x_ + xs[i], x_ + xs[i + 1])) else: char_boxes.append((s, x_, x_ + adv * style["spacing"])) - # ---- ink texture along the strokes, line-level pen pressure and dropouts (never to zero) if hand and style.get("tex_depth", 0) > 0: canvas *= _texture(ch_, cw, style["tex_depth"], style["tex_scale"] * S, rng) if hand and style["pressure_depth"] > 0: @@ -291,7 +289,6 @@ def render_line(face, axes, text, x0, ybase, size_px, rng, style, hand=True): yy, xx = np.ogrid[:ch_, :cw] m = ((xx - cx) ** 2 + (yy - cy) ** 2) < r * r canvas[m] *= 0.45 - # ---- elastic distortion (Simard style) with probability elastic_p, before the per-character ink check below elastic_used = False alpha_eff = 0.0 if hand and style.get("elastic_p", 0) > 0 and rng.random() < style["elastic_p"]: @@ -301,7 +298,6 @@ def render_line(face, axes, text, x0, ybase, size_px, rng, style, hand=True): alpha_eff = min(style["elastic_alpha"], 0.3 * sig_ss) canvas = _elastic(canvas, alpha_eff, sig_ss, rng) elastic_used = True - # ---- downsample to the flat grid; crop to the ink bounding box with padding ch2, cw2 = (ch_ // S) * S, (cw // S) * S small = cv2.resize(canvas[:ch2, :cw2], (cw2 // S, ch2 // S), interpolation=cv2.INTER_AREA) np.clip(small, 0, 1, out=small) diff --git a/src/pagesynth/pagesynth/page.py b/src/pagesynth/pagesynth/page.py index d7dd99da1f56e24c45535c23678bbec6b9a94036..e3bf1dc91d8a4c56f202f0b0ede6c524d4ebb1c2 100644 --- a/src/pagesynth/pagesynth/page.py +++ b/src/pagesynth/pagesynth/page.py @@ -174,7 +174,6 @@ class Page: sh = cv2.GaussianBlur(np.roll(inside, (6, 8), axis=(0, 1)), (0, 0), 7) table = table * (1 - 0.45 * sh)[..., None] out = out * inside[..., None] + table * (1 - inside[..., None]) - # ---- warp items warped = [] for it in self.items: if it.rgb is not None: @@ -185,7 +184,6 @@ class Page: else: wb, X0, Y0, ins = geo.warp_band(it.alpha.astype(np.float32), it.x_off, it.y_off) warped.append((it, wb, X0, Y0, ins)) - # ---- composite in z order for it, wb, X0, Y0, ins in sorted(warped, key=lambda r: r[0].z): if wb is None: continue @@ -196,7 +194,6 @@ class Page: reg[:] = reg * (1 - a) + wb[..., :3] * a else: reg *= (1 - wb[..., None] * (1 - (it.color / 255.0))[None, None, :]) - # ---- polygons and gates lines_json = [] L = [(it, wb, X0, Y0, ins) for (it, wb, X0, Y0, ins) in warped if it.label is not None] polys = [] @@ -285,7 +282,6 @@ class Page: if strict and leak > 0: raise GateFailure("g_text_outside", "stamp ink outside its ignore region: %d px" % leak) qa["lines"] = recs - # ---- photo effects (post geometry, content independent) final, fx = G.photo_effects(np.clip(out, 0, 255).astype(np.uint8), cfg, rng_fx, self.strength, geo.mode) qa["fx"] = fx self.fxs.update(["geometry:" + geo.mode, "strength:" + self.strength, "paper:" + layout["kind"], "paper_style:" + str(layout.get("grid_style")), @@ -300,7 +296,6 @@ class Page: self.fxs.update(["scanner_skew", "scanner_white_clip"]) if ghost is not None: self.fxs.add("show_through_ghost") - # ---- page JSON # reading order: top to bottom by baseline, left to right inside a row (rows: baselines closer than # 0.55 x the line height); it replaces the provisional per-scene counters, which could repeat numbers order_src = [] diff --git a/src/pagesynth/pagesynth/textbuild.py b/src/pagesynth/pagesynth/textbuild.py index aac27f6010bc11cb1cb1615e9626e78868e190a8..e44186bb30ef460e636805a0bc830487c2eb7d13 100644 --- a/src/pagesynth/pagesynth/textbuild.py +++ b/src/pagesynth/pagesynth/textbuild.py @@ -63,7 +63,6 @@ def build(lang, out_dir, quota_wiki=400000, quota_fw=400000, max_groups=400, sak rows.append((src_id, s)) per_source[tag] += 1 - # ---- Wikipedia try: files = sorted(p for p in fs.ls("datasets/wikimedia/wikipedia/%s.%s" % (WIKI_REV, prof["wiki"]), detail=False) if p.endswith(".parquet")) except Exception as e: # recorded, not hidden @@ -79,7 +78,6 @@ def build(lang, out_dir, quota_wiki=400000, quota_fw=400000, max_groups=400, sak break log(lang, "wiki sentences", per_source["wiki"], "t=%.0fs" % (time.time() - t0)) - # ---- FineWeb-2 try: fw_files = sorted(p for p in fs.ls("datasets/HuggingFaceFW/fineweb-2/data/%s/train" % prof["fw2"], detail=False) if p.endswith(".parquet")) except Exception as e: @@ -95,7 +93,6 @@ def build(lang, out_dir, quota_wiki=400000, quota_fw=400000, max_groups=400, sak break log(lang, "fineweb sentences", per_source["fw2"], "t=%.0fs" % (time.time() - t0)) - # ---- Sakha newspaper corpus (local) if lang == "sah" and sakha_dir: import pyarrow.parquet as pq for name in sorted(os.listdir(sakha_dir)): diff --git a/src/pagesynth/produce_r5.py b/src/pagesynth/produce_r5.py index 11a02dc6ab84575a0f6dd41488e7a61a3b5b83c7..e1d3ba0279e9869a7dbb72cf21cdf21450ee9f62 100644 --- a/src/pagesynth/produce_r5.py +++ b/src/pagesynth/produce_r5.py @@ -10,15 +10,15 @@ import unicodedata os.environ.setdefault("OMP_NUM_THREADS", "1") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import cv2 # noqa: E402 -import numpy as np # noqa: E402 +import cv2 +import numpy as np cv2.setNumThreads(1) -from pagesynth import crops as CR # noqa: E402 -from pagesynth import fonts as F # noqa: E402 -from pagesynth import generate as GEN # noqa: E402 -from pagesynth import page as PG # noqa: E402 -from pagesynth import text as T # noqa: E402 +from pagesynth import crops as CR +from pagesynth import fonts as F +from pagesynth import generate as GEN +from pagesynth import page as PG +from pagesynth import text as T CFG = dict( version=GEN.VERSION, diff --git a/src/pagesynth/scripts/build_label_vocab.py b/src/pagesynth/scripts/build_label_vocab.py index b67d9d166710c161cc3e302b7829555f22e3567e..978df8a096168041f337b3124cb7c0470a414225 100644 --- a/src/pagesynth/scripts/build_label_vocab.py +++ b/src/pagesynth/scripts/build_label_vocab.py @@ -5,8 +5,8 @@ import sys import time sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) -from pagesynth import text as T # noqa: E402 -from pagesynth import vocab as V # noqa: E402 +from pagesynth import text as T +from pagesynth import vocab as V ap = argparse.ArgumentParser() ap.add_argument("--text-dir", required=True) diff --git a/src/pagesynth/scripts/build_text.py b/src/pagesynth/scripts/build_text.py index 5be59e794e8150d5dc18fdc481b9fd30707a7874..dd3f545cff47ff505f8e14e619f342b6864ea0b2 100644 --- a/src/pagesynth/scripts/build_text.py +++ b/src/pagesynth/scripts/build_text.py @@ -3,7 +3,7 @@ import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) -from pagesynth import textbuild # noqa: E402 +from pagesynth import textbuild def main(): diff --git a/src/pagesynth/scripts/fonts_report.py b/src/pagesynth/scripts/fonts_report.py index d601f16bf14b0cc20d9b1c47912b9b16cf128d8c..e2e0e5e3897710bdccf5e4e4189c5ad9313587a5 100644 --- a/src/pagesynth/scripts/fonts_report.py +++ b/src/pagesynth/scripts/fonts_report.py @@ -14,8 +14,8 @@ ap.add_argument("--heldout-latn", default="mynerve,mali") a = ap.parse_args() if a.fonts_dir: os.environ["PAGESYNTH_FONTS"] = a.fonts_dir -from pagesynth import fonts as F # noqa: E402 -from pagesynth import text as T # noqa: E402 +from pagesynth import fonts as F +from pagesynth import text as T LANGS = ["kk", "ky", "uz_cyrl", "tt", "ba", "sah", "uz_latn", "tr", "az", "tk"] held = set(a.heldout_cyrl.split(",") + a.heldout_latn.split(",")) diff --git a/src/pagesynth/scripts/r5_text_split.py b/src/pagesynth/scripts/r5_text_split.py index 451be64a110d69a34b59cc0f3dcf3d8e7515d645..6086106d50506ce3c93d11d67a91df87f5599fbe 100644 --- a/src/pagesynth/scripts/r5_text_split.py +++ b/src/pagesynth/scripts/r5_text_split.py @@ -6,7 +6,7 @@ import shutil import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) -from pagesynth import vocab as V # noqa: E402 +from pagesynth import vocab as V ap = argparse.ArgumentParser() ap.add_argument("--lang", required=True) diff --git a/src/pagesynth/scripts/refilter_text.py b/src/pagesynth/scripts/refilter_text.py index a70a33026f0f85ecfba742d9caaaa9744d604002..f5479063a2ad70d6f65f4140029843fb211c3fa9 100644 --- a/src/pagesynth/scripts/refilter_text.py +++ b/src/pagesynth/scripts/refilter_text.py @@ -3,7 +3,7 @@ import os import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) -from pagesynth import textbuild # noqa: E402 +from pagesynth import textbuild ap = argparse.ArgumentParser() ap.add_argument("--lang", required=True) diff --git a/src/r5eval/ioutil.py b/src/r5eval/ioutil.py index be7f341f49425c054ef20d468b561be6ba23a147..454205f228814f9c381e9b27d0dba7830b501b28 100644 --- a/src/r5eval/ioutil.py +++ b/src/r5eval/ioutil.py @@ -150,7 +150,7 @@ def clean(o): """JSON-safe copy: numpy scalars to Python, NaN and infinity to None, tuples to lists.""" try: import numpy as np - except ImportError: # pragma: no cover + except ImportError: np = None if isinstance(o, dict): return {str(k): clean(v) for k, v in o.items()} diff --git a/src/r5eval/selection.py b/src/r5eval/selection.py index 577e95e19180b532b03548a6923c7927e2cc7152..6b86918812355f674648916aaa3f2ea84a050601 100644 --- a/src/r5eval/selection.py +++ b/src/r5eval/selection.py @@ -413,10 +413,6 @@ def leaders(scores_dir, preds_dir, arms_info, vlm_allow=None, ck="short", B=stat "not_eligible": ineligible, "outside_allow_list": outside, "not_started_or_not_finished": expected, "warnings": warnings} -# The six reference roles of the published-method and same-data comparisons: role, arm folder, checkpoint folder, variant. The folders are the ones REF writes -# (DATA/outputs/r5/preds/R1/{ours,rand,mix}, R2/{ours,rand,mix}; REF's test_pass_commands.sh): (i) trained on our form split ('ours'), (ii) on the random replication split ('rand', -# scored on kohtd_rand_test), (iii) on mix_v1 to 150,016 samples ('mix'). The folders R1/_paperdec (beam search of HTR-Flor's own decoder) and the mix_curve_ folders are -# descriptive and no role: the rule scores the greedy decoding (rule 0.3) and reads the paper's own metric from the same predictions (scoreset N4). REFERENCE_ROLES = (("R1", "R1", "ours", "i"), ("R2", "R2", "ours", "i"), ("R1_rand", "R1", "rand", "ii"), ("R2_rand", "R2", "rand", "ii"), ("R1_iii", "R1", "mix", "iii"), ("R2_iii", "R2", "mix", "iii")) @@ -573,7 +569,7 @@ def select(scores_dir, arms_info, line_checkpoint="auto", line_arms=LINE_ARMS, f out["roles"][a]["short_seed2_checkpoint"] = s2s[1] if s2s[0] != a: out["roles"][a]["short_seed2_arm"] = s2s[0] - s2 = find_seed2(scores_dir, a, ck) # A1 and A2 have a second seed: _seed2 in the arm, or the arm folder _s2 (LINEDET) + s2 = find_seed2(scores_dir, a, ck) if s2: out["roles"][a]["seed2_checkpoint"] = s2[1] if s2[0] != a: diff --git a/src/r5eval/summary.py b/src/r5eval/summary.py index cecfc4dd57af07451349360b65dd495b763bdbe6..1ea97077473f94241524fb87fe0241bea9f5a941 100644 --- a/src/r5eval/summary.py +++ b/src/r5eval/summary.py @@ -121,7 +121,6 @@ def build_rows(scores_dir, preds_dir): arm_names = {a for a, _ in rows} for (arm, ck), r in sorted(rows.items()): sets = r.pop("_sets") - # second-seed rows are marked, not hidden: the arm folder _s2 is the second seed of (naming conventions 2 and 3 of the seed-2 runs), c_seed2 / c_s2 of VLMA arms if arm.endswith("_s2") and arm[:-3] in arm_names: r["seed"], r["seed_of_arm"] = "2", arm[:-3] elif ck.endswith(("_seed2", "_s2")) or "_seed2_" in ck: diff --git a/src/r5eval/verdictgather.py b/src/r5eval/verdictgather.py index cf5a6ffdf50bf720e252ac73ddc81895d0c26b89..77ba827c169e2470c13dab00a5306446980a6eab 100644 --- a/src/r5eval/verdictgather.py +++ b/src/r5eval/verdictgather.py @@ -98,8 +98,6 @@ class Gather: return None key = (role, stem, seed) if key not in self._cache: - # the score file is found by what it scored (registry name without a trailing '(...)', file stem or manifest basename), not by its file name - # the second seed of a maker-code VLM arm or of a line arm is the arm folder _s2 (seed2_arm in the role); of a VLMA arm a checkpoint _seed2 of the same arm arm = r["arm"] if seed == 1 else (r.get("seed2_arm") or r["arm"]) sc = ioutil.find_score(os.path.join(self.dir, arm, ck), [stem]) if sc is not None and sc.get("locked") and not self.ok_locked: diff --git a/src/rq2/geom.py b/src/rq2/geom.py index 08164476cdbd49ae8df0981c04c7efb853417323..77d9c51cf7a8819c5c5fec9f839cc2450b16d6c4 100644 --- a/src/rq2/geom.py +++ b/src/rq2/geom.py @@ -16,11 +16,11 @@ MAX_WIDTH = 2560 # files the wrappers depend on (sha256 read on the cluster 2026-11-26; design.json lists the same prefixes) PINNED = { - CODE + "/src/linedet/train_arm.py": "55369cd0773b08df064db8fd17e3586bf9bfc2ad84774c36198cbd2d74faef47", - CODE + "/src/linedet/data.py": "0502c2f556e2cd0145b7afaa1fa19ec8760a112460a853b33d76aa524191cb6d", - CODE + "/src/linedet/models.py": "9ada511fbc072c73069a5999adca7c90c2de29e9536ad481c101f734b4d7306b", + CODE + "/src/linedet/train_arm.py": "a43fdca4c38e3c8a796e9fbfdd48d4b2eb685de67b1f71a96779c37aa3c51df4", + CODE + "/src/linedet/data.py": "26567ab5fe6f5b82f82e4c423c8e90e7016bfca4828a206618b39d6d8644fb1b", + CODE + "/src/linedet/models.py": "8566f711c4205ab4650d746af5ee534dcf865bfa1616b273462b2f21864907f0", CODE + "/src/linedet/predict.py": "0ad3f3d647e5f9af6846927673e4d3ae9999f42feb77a904e09114f33bff5ae9", - CODE + "/src/linedet/common.py": "00d606e432e688d8f6f7620105cf9010a1d3138624416d32893b170bd868c52a", + CODE + "/src/linedet/common.py": "5a38acd2c52d5498d2ced8d035ef57e5ad95e79980537ea13710ee0c2cf0ba75", KRAKEN + "/backbone.py": "ab517cf88124847beb0cf3f1fd87c7270f9ec7fa8e3f773b6177b352f491462d", KRAKEN + "/network.py": "ed4592d7cf9937753cfd3d0fb5be6c083035370a2c3bc46bb647285ea9da48d1", KRAKEN + "/necks.py": "dcc7cb0ca045b71c2356ff82d97a7b91ab24b900ed3665feb274432d87c2b483", diff --git a/src/rq2/marks.py b/src/rq2/marks.py index a5195d3ea8da4d36a308bf6395a03744d1500924..183628a5f70e6b4bdbcac4975d23af2ced0795c4 100644 --- a/src/rq2/marks.py +++ b/src/rq2/marks.py @@ -5,8 +5,8 @@ import unicodedata CODE = "/path/to/TURKIC_OCR_CODE" if CODE + "/src/pagesynth" not in sys.path: sys.path.insert(0, CODE + "/src/pagesynth") -from pagesynth import text as ptext # noqa: E402 project alphabet tables -from r5eval.align import align_ops, lev_fast # noqa: E402 scorer alignment, unchanged +from pagesynth import text as ptext +from r5eval.align import align_ops, lev_fast LANGS = ptext.LANG_ORDER LANG_RX = re.compile(r"(?:^|[_:])(uz_cyrl|uz_latn|kk|ky|tt|ba|sah|tr|az|tk)_\d") diff --git a/tests_r5eval/test_cli.py b/tests_r5eval/test_cli.py index a6bc6cea930b70f8086e7d4525ee03ffc70750e4..2f8cc73defb4fad7f31bcced8ba822cf58aea035 100644 --- a/tests_r5eval/test_cli.py +++ b/tests_r5eval/test_cli.py @@ -8,7 +8,7 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import synth_world as sw # noqa: E402 +import synth_world as sw SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py") RESULTS = [] @@ -19,7 +19,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) @@ -91,7 +91,6 @@ def t_score_file_values_match_hand_computation(): sc = load("A1/short/V1.json") assert sc["status"] == "scored" and sc["locked"] is False and sc["registry_name"] == "V1" assert sc["coverage"]["complete"] and sc["coverage"]["scored_rows"] == 300 - # recompute the pooled CER independently with the frozen J2 library sys.path.insert(0, os.path.join(HERE, "..", "src")) from r5eval import frozen d = n = 0 diff --git a/tests_r5eval/test_core.py b/tests_r5eval/test_core.py index 27db7250133bea419bad2baf2ce9546096fc10b2..d6f7f62547935d9a61011a42b495e7a3464a7f2f 100644 --- a/tests_r5eval/test_core.py +++ b/tests_r5eval/test_core.py @@ -6,10 +6,10 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "src")) -import numpy as np # noqa: E402 +import numpy as np -from r5eval import analyse, frozen, lookalike, stats, textnorm # noqa: E402 -from r5eval.align import align_ops, lev_fast, min_cost_line_assignment, op_counts # noqa: E402 +from r5eval import analyse, frozen, lookalike, stats, textnorm +from r5eval.align import align_ops, lev_fast, min_cost_line_assignment, op_counts RESULTS = [] @@ -19,7 +19,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True, "")) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False, traceback.format_exc())) print("FAIL", fn.__name__) print(traceback.format_exc()) diff --git a/tests_r5eval/test_curve.py b/tests_r5eval/test_curve.py index 3d9aa254c4a0a7b79bdadcfb7c118a580aac94c5..8873ee83d909fbac23ff6ccaccec7b90e9f1ef06 100644 --- a/tests_r5eval/test_curve.py +++ b/tests_r5eval/test_curve.py @@ -8,7 +8,7 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -import synth_world as sw # noqa: E402 +import synth_world as sw BUILD = os.path.join(HERE, "..", "scripts", "r5eval", "build_curve_set.py") LANGS = ["kk", "ky", "uz_cyrl", "uz_latn", "tr", "az", "tt", "ba", "tk", "sah"] @@ -22,7 +22,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) diff --git a/tests_r5eval/test_ktrain.py b/tests_r5eval/test_ktrain.py index 6f14ead17aa494c5aa90cb2f5ea2be26f13b4f86..13f6815d6214b334e83d494ab4fde97a12cd8cd1 100644 --- a/tests_r5eval/test_ktrain.py +++ b/tests_r5eval/test_ktrain.py @@ -8,7 +8,7 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "src")) -from r5eval import ktrain # noqa: E402 +from r5eval import ktrain BUILD = os.path.join(HERE, "..", "scripts", "r5eval", "build_ktrain.py") HDR = ["id", "image", "text", "lang", "script", "kind", "source", "split", "group", "unit"] @@ -20,7 +20,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) diff --git a/tests_r5eval/test_leaders.py b/tests_r5eval/test_leaders.py index a457f8f812bc367d96c5e39818d7794d68e01eb3..ce4e9452e91870d84950a6d923338c65cb59afe2 100644 --- a/tests_r5eval/test_leaders.py +++ b/tests_r5eval/test_leaders.py @@ -11,8 +11,8 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) sys.path.insert(0, os.path.join(HERE, "..", "src")) -import synth_world as sw # noqa: E402 -from r5eval import selection, verdictgather # noqa: E402 +import synth_world as sw +from r5eval import selection, verdictgather SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py") LEADERS = os.path.join(HERE, "..", "scripts", "r5eval", "select_leaders.py") @@ -28,7 +28,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) @@ -272,9 +272,6 @@ def t_line_final_checkpoint_long2x_budget_and_seeds(): assert "seed2_checkpoint" not in gb.roles["A1@s4"] or gb.roles["A1@s4"]["seed2_checkpoint"] in ("long2x_seed2", "long2x") or any("not paired" in n for n in gb.notes) -# The three seed-2 naming conventions: -# 1. VLMA arms: /_seed2. 2. maker-code VLM arms run by the leader runner: the arm folder _s2 with the same checkpoint names (short, leader). -# 3. line arms of LINEDET: the arm folders A1_s2 and A2_s2 (short, long). The extra arms of the leader rule have one seed; their final checkpoint is 'leader'. S2_SPEC = [("va", "short", 0.12, {}), ("va", "short_seed2", 0.13, {}), ("va", "leader", 0.08, {"samples_seen": 300000}), ("va", "leader_seed2", 0.10, {"samples_seen": 300000}), # 1 ("mk", "short", 0.14, {}), ("mk", "leader", 0.02, {"samples_seen": 300000}), # 2 ("mk_s2", "short", 0.15, {}), ("mk_s2", "leader", 0.04, {"samples_seen": 300000}), diff --git a/tests_r5eval/test_pages.py b/tests_r5eval/test_pages.py index d4fb85981988a1e5c4a1907f594f3104679e5575..90c067847984de15a0706b75578bda2a7582ddf2 100644 --- a/tests_r5eval/test_pages.py +++ b/tests_r5eval/test_pages.py @@ -6,7 +6,7 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "src")) -from r5eval import pages # noqa: E402 +from r5eval import pages RESULTS = [] @@ -16,7 +16,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) diff --git a/tests_r5eval/test_report_cards.py b/tests_r5eval/test_report_cards.py index 50bf6ababc79cc43a1d3749a93df8f3a5f78dc95..5500797bdc2bc001857227dff657e304a7c94ded 100644 --- a/tests_r5eval/test_report_cards.py +++ b/tests_r5eval/test_report_cards.py @@ -10,8 +10,8 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) sys.path.insert(0, os.path.join(HERE, "..", "src")) -import synth_world as sw # noqa: E402 -from r5eval import cards, verdictlib # noqa: E402 +import synth_world as sw +from r5eval import cards, verdictlib SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py") CARDS = os.path.join(HERE, "..", "scripts", "r5eval", "report_cards.py") @@ -24,7 +24,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) diff --git a/tests_r5eval/test_verdict.py b/tests_r5eval/test_verdict.py index 793c120164d61ce34bcdedd631bf998cee54e146..b060f37be3d7b3c872a636ae8f26aa4c555e2e82 100644 --- a/tests_r5eval/test_verdict.py +++ b/tests_r5eval/test_verdict.py @@ -10,10 +10,10 @@ import traceback HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) sys.path.insert(0, os.path.join(HERE, "..", "src")) -import numpy as np # noqa: E402 +import numpy as np -import synth_world as sw # noqa: E402 -from r5eval import selection, stats, verdictlib as vl # noqa: E402 +import synth_world as sw +from r5eval import selection, stats, verdictlib as vl SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py") VERDICT = os.path.join(HERE, "..", "scripts", "r5eval", "verdict.py") @@ -26,7 +26,7 @@ def test(fn): fn() RESULTS.append((fn.__name__, True)) print("PASS", fn.__name__) - except Exception: # noqa: BLE001 + except Exception: RESULTS.append((fn.__name__, False)) print("FAIL", fn.__name__) print(traceback.format_exc()) @@ -673,7 +673,7 @@ def t_j1_section3_at_p_long_section4_and_h10_at_the_furthest_checkpoint(): json.dump(j, open(W["sel_path"], "w")) try: v = run_verdict("verdict_j1.json", ["--sota-checklist", chk]) - j["roles"]["A1"]["section4_checkpoint"] = "long3x" # a section-4 checkpoint without test scores: J1 could not be applied, and it says so + j["roles"]["A1"]["section4_checkpoint"] = "long3x" json.dump(j, open(W["sel_path"], "w")) v_missing = run_verdict("verdict_j1_missing.json", ["--sota-checklist", chk]) finally: