turkic-ocr-code / scripts /j2 /check_images_kwargs.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
1.53 kB
"""Does images_kwargs (size) reach the image processor in apply_chat_template? Processor only, one crop, no model.
usage: check_images_kwargs.py MODELS_DIR PROMPTS_JSON IMG_DIR CROP_FILE short [short ...]"""
import json
import os
import sys
os.environ["HF_HUB_OFFLINE"] = "1"
import transformers
from PIL import Image
models_dir, prompts_json, img_dir, crop = sys.argv[1:5]
P = json.load(open(prompts_json, encoding="utf-8"))
im = Image.open(os.path.join(img_dir, crop)).convert("RGB")
print("crop size", im.size)
for short in sys.argv[5:]:
proc = transformers.AutoProcessor.from_pretrained(os.path.join(models_dir, short), trust_remote_code=False)
ik = P[short].get("images_kwargs")
if ik and ik["size"]["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)
txt = [{"type": "text", "text": P[short]["prompt"]}] if P[short]["prompt"] else []
conv = [[{"role": "user", "content": [{"type": "image", "image": im}] + txt}]]
for label, kw in (("without images_kwargs", {}), ("with images_kwargs", {"images_kwargs": ik} if ik else {})):
out = proc.apply_chat_template(conv, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", padding=True, **kw)
grid = out.get("image_grid_thw")
print(short, label, "input_ids", tuple(out["input_ids"].shape), "image_grid_thw", None if grid is None else grid.tolist(), "ik", ik)