"""Read the title and author on a book spine with ScoutReader 2 (Qwen3-VL 2B + this LoRA adapter). pip install -r requirements.txt python read_spine.py examples/spine-hebrew.jpg examples/spine-latin.jpg The picture should be one spine, turned level (the way its title reads, left to right or right to left). Seferehov reads each cut-out both ways up and keeps the reading a catalogue or OCR confirms. Prompt, picture size and decoding are the app's own (fastread/fast_read.py): longest side at most 1024 px, at least 96 px high, greedy, 80 tokens. Answer: "TITLE | AUTHOR", or "NONE" when it cannot read it (it was taught to say NONE for an upside-down spine). """ import sys, time import torch from PIL import Image from peft import PeftModel from transformers import AutoProcessor, Qwen3VLForConditionalGeneration BASE = "Qwen/Qwen3-VL-2B-Instruct" ADAPTER = sys.argv[sys.argv.index("--adapter") + 1] if "--adapter" in sys.argv else "." PROMPT = ("This is one book spine or cover. Read its title and author exactly as printed, in the original language " "and script. Answer one line: TITLE | AUTHOR. If unreadable answer NONE.") def load(path, long=1024): im = Image.open(path).convert("RGB") w, h = im.size if h < 96: im = im.resize((round(w * 96 / h), 96)); w, h = im.size k = long / max(w, h) return im.resize((max(32, round(w * k)), max(32, round(h * k)))) if k < 1 else im device = "cuda" if torch.cuda.is_available() else "cpu" model = Qwen3VLForConditionalGeneration.from_pretrained(BASE, dtype=torch.float16 if device == "cuda" else torch.float32) model = PeftModel.from_pretrained(model, ADAPTER).merge_and_unload().to(device).eval() proc = AutoProcessor.from_pretrained(BASE) for path in [a for a in sys.argv[1:] if not a.startswith("--") and a != ADAPTER]: msgs = [{"role": "user", "content": [{"type": "image", "image": load(path)}, {"type": "text", "text": PROMPT}]}] b = proc.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt").to(device) t = time.time() with torch.no_grad(): g = model.generate(**b, max_new_tokens=80, do_sample=False) text = proc.batch_decode(g[:, b["input_ids"].shape[1]:], skip_special_tokens=True)[0].strip() print(f"{path}: {text} ({time.time() - t:.2f} s)")