from PIL import Imageimport torchfrom transformers import AutoModelForImageTextToText, AutoProcessorfrom qwen_vl_utils import process_vision_info # Load the model and processormodel = AutoModelForImageTextToText.from_pretrained( "infly/Infinity-Parser2-Pro", torch_dtype="float16", device_map="auto",)processor = AutoProcessor.from_pretrained("infly/Infinity-Parser2-Pro") # Build the messages for the modelpil_image = Image.open("demo_data/demo.png").convert("RGB")min_pixels = 2048 # 32 * 64max_pixels = 16777216 # 4096 * 4096prompt = """- Extract layout information from the provided PDF image.- For each layout element, output its bbox, category, and the text content within the bbox.- Bbox format: [x1, y1, x2, y2].- Allowed layout categories: ['header', 'title', 'text', 'figure', 'table', 'formula', 'figure_caption', 'table_caption', 'formula_caption', 'figure_footnote', 'table_footnote', 'page_footnote', 'footer'].- Text extraction and formatting: 1) For 'figure', the text field must be an empty string. 2) For 'formula', format text as LaTeX. 3) For 'table', format text as HTML. 4) For all other categories (e.g., text, title), format text as Markdown.- The output text must be exactly the original text from the image, with no translation or rewriting.- Sort all layout elements in human reading order.- Final output must be a single JSON object.""" messages = [ { "role": "user", "content": [ { "type": "image", "image": pil_image, "min_pixels": min_pixels, "max_pixels": max_pixels, }, {"type": "text", "text": prompt}, ], }] chat_template_kwargs = {"enable_thinking": False} text = processor.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, **chat_template_kwargs)image_inputs, _ = process_vision_info(messages, image_patch_size=16) inputs = processor( text=text, images=image_inputs, do_resize=False, padding=True, return_tensors="pt",) # Move all tensors to the same device as the modelinputs = { k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()} # Generate the responsegenerated_ids = model.generate( **inputs, max_new_tokens=32768, temperature=0.0, top_p=1.0,) # Strip input tokens, keeping only the newly generated responsegenerated_ids_trimmed = [ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)]output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)print(output_text)