Download scripts/j2/harness_audit.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/j2/harness_audit.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/j2/harness_audit.py
-
curl -L -o harness_audit.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/j2/harness_audit.py
5.06 kB
| """J2 harness audit: what exactly goes into each model for 5 KOHTD validation crops and 5 positive-control images. | |
| Processor only (no model weights), CPU. The input is built the same way as run_screen.py (build_inputs, batch of one). | |
| Text and numbers only; no image data is printed. | |
| usage: harness_audit.py MODELS_DIR PROMPTS_JSON SCREEN_SET KOHTD_IMG_DIR CONTROL_LIST CONTROL_IMG_DIR OUT_TXT short [short ...] | |
| """ | |
| import copy | |
| import json | |
| import os | |
| import re | |
| import sys | |
| os.environ["HF_HUB_OFFLINE"] = "1" | |
| import torch | |
| import transformers | |
| from PIL import Image | |
| models_dir, prompts_json, screen_set, kohtd_dir, control_list, control_dir, out_txt = sys.argv[1:8] | |
| shorts = sys.argv[8:] | |
| P = json.load(open(prompts_json, encoding="utf-8")) | |
| CARD_PROC = {"lightonocr_3_1b": "LightOnOcrProcessor"} | |
| TWO_STEP = {"granite_docling_258m"} | |
| def read_list(path): | |
| rows = [] | |
| with open(path, encoding="utf-8", newline="") as f: | |
| f.readline() | |
| for line in f: | |
| rows.append(line.rstrip("\n").split("\t")[0]) | |
| return rows | |
| kohtd = read_list(screen_set)[:5] | |
| ctl_all = read_list(control_list) | |
| ctl = [ctl_all[i] for i in (0, 1, 100, 200, 300)] # kk h40, kk h40, ky h40, kk h80, ky h80 | |
| items = [("KOHTD validation crop", kohtd_dir, c) for c in kohtd] + [("positive-control image", control_dir, c) for c in ctl] | |
| RUN = re.compile(r"((?:<\|[^>]*\|>|<[^>\s]{1,40}>))\1{2,}") | |
| def collapse(s): | |
| return RUN.sub(lambda m: f"{m.group(1)}x{len(m.group(0)) // len(m.group(1))}", s) | |
| out = [] | |
| for short in shorts: | |
| pcls = getattr(transformers, CARD_PROC.get(short, ""), None) or transformers.AutoProcessor | |
| proc = pcls.from_pretrained(os.path.join(models_dir, short), trust_remote_code=False) | |
| tok = getattr(proc, "tokenizer", proc) | |
| tok.padding_side = "left" | |
| prompt = P[short]["prompt"] | |
| ik = copy.deepcopy(P[short].get("images_kwargs")) | |
| if ik and ik.get("size", {}).get("shortest_edge") == "MIN_PIXELS_FROM_PROCESSOR": | |
| sz = proc.image_processor.size | |
| ik["size"]["shortest_edge"] = int(sz["shortest_edge"] if isinstance(sz, dict) else sz.shortest_edge) | |
| tk = {"enable_thinking": False} if P[short].get("enable_thinking_false") else {} | |
| out.append("=" * 100) | |
| out.append(f"MODEL {short} processor {type(proc).__module__}.{type(proc).__name__}") | |
| out.append(f" prompt (frozen in prompts.json) = {prompt!r}") | |
| out.append(f" images_kwargs = {ik} chat-template kwargs = {tk} two-step path = {short in TWO_STEP}") | |
| ip = getattr(proc, "image_processor", None) | |
| if ip is not None: | |
| out.append(f" image processor: {type(ip).__name__}; size = {getattr(ip, 'size', None)}; do_convert_rgb = {getattr(ip, 'do_convert_rgb', None)}; " | |
| f"mean = {getattr(ip, 'image_mean', None)}; std = {getattr(ip, 'image_std', None)}; do_rescale = {getattr(ip, 'do_rescale', None)}; " | |
| f"rescale_factor = {getattr(ip, 'rescale_factor', None)}") | |
| for kind, d, c in items: | |
| raw = Image.open(os.path.join(d, c)) | |
| rmode, rsize, rfmt = raw.mode, raw.size, raw.format | |
| im = raw.convert("RGB") | |
| content_text = [{"type": "text", "text": prompt}] if prompt else [] | |
| if short in TWO_STEP: | |
| conv = [{"role": "user", "content": [{"type": "image"}] + content_text}] | |
| templ = proc.apply_chat_template(conv, add_generation_prompt=True) | |
| inputs = proc(text=[templ], images=[[im]], return_tensors="pt", padding=True) | |
| else: | |
| conv = [{"role": "user", "content": [{"type": "image", "image": im}] + content_text}] | |
| templ = proc.apply_chat_template([conv][0], add_generation_prompt=True, tokenize=False, **tk) | |
| kw = dict(tk) | |
| if ik: | |
| kw["images_kwargs"] = ik | |
| inputs = proc.apply_chat_template([conv], add_generation_prompt=True, tokenize=True, return_dict=True, | |
| return_tensors="pt", padding=True, **kw) | |
| pv = inputs.get("pixel_values") | |
| pvs = "none" | |
| if pv is not None: | |
| pvf = pv.float() | |
| pvs = (f"shape {tuple(pv.shape)} dtype {pv.dtype} min {pvf.min().item():.3f} max {pvf.max().item():.3f} " | |
| f"mean {pvf.mean().item():.3f}") | |
| grid = inputs.get("image_grid_thw") | |
| ids = inputs["input_ids"][0] | |
| decoded = collapse(tok.decode(ids, skip_special_tokens=False)).replace("\n", "\\n") | |
| out.append(f" [{kind}] {c}: PIL as loaded: mode {rmode}, size {rsize[0]}x{rsize[1]} (w x h), format {rfmt}; after convert('RGB'): {im.mode} {im.size[0]}x{im.size[1]}") | |
| out.append(f" pixel_values: {pvs}; image_grid_thw: {None if grid is None else grid.tolist()}; input_ids length {ids.shape[0]}") | |
| out.append(f" template string (before expansion): {templ[:400]!r}") | |
| out.append(f" decoded input_ids (image placeholder runs collapsed): {decoded[:700]}") | |
| print(short, "done", flush=True) | |
| open(out_txt, "w", encoding="utf-8").write("\n".join(out) + "\n") | |
| print("written", out_txt) | |