from unsloth import FastVisionModelfrom peft import PeftModel base, proc = FastVisionModel.from_pretrained("unsloth/Qwen3.5-2B", load_in_4bit=False)model = PeftModel.from_pretrained(base, "anilkr01/qwen3.5-2b-receipt-json-lora")FastVisionModel.for_inference(model) SYSTEM = """You extract structured data from receipt and invoice text.Return one JSON object with exactly these keys, in this order: line_items, subtotal, tax, total.Fields:- line_items: list of purchased items, each {"description": item text as printed, "quantity": number, "unit_price": number, "amount": line total number}; use null inside an item for a value that is not printed- subtotal: amount before tax and service (number)- tax: tax amount (number)- total: final amount to pay (number)Rules:- Use null for any value the document does not show.- Numbers are JSON numbers: no currency symbols, no thousands separators, dot as the decimal mark (16,500 -> 16500).- Output only the JSON object: no code fences, no explanations, no extra keys.""" def extract(receipt_text: str) -> str: msgs = [{"role": "system", "content": [{"type": "text", "text": SYSTEM}]}, {"role": "user", "content": [{"type": "text", "text": receipt_text}]}] prompt = proc.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False) tok = proc.tokenizer enc = tok(prompt, return_tensors="pt", add_special_tokens=False).to(model.device) stop = [tok.convert_tokens_to_ids(t) for t in ("<|im_end|>", "<|endoftext|>")] out = model.generate(**enc, max_new_tokens=640, do_sample=False, repetition_penalty=1.0, eos_token_id=stop, pad_token_id=tok.pad_token_id or stop[-1]) return tok.decode(out[0, enc["input_ids"].shape[1]:], skip_special_tokens=True)