1import torch
2from transformers import AutoModelForCausalLM, AutoProcessor
3from PIL import Image
4from huggingface_hub import snapshot_download
5
6from qwen_vl_utils import process_vision_info
7
8MODEL_ID = "helizac/dots.ocr-4bit"
9
10local_model_path = snapshot_download(repo_id=MODEL_ID)
11
12model = AutoModelForCausalLM.from_pretrained(local_model_path, device_map="auto", trust_remote_code=True, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
13processor = AutoProcessor.from_pretrained(local_model_path, trust_remote_code=True, use_fast=True)
14
15image_path = "test.jpg"
16image = Image.open(image_path)
17
18prompt_text = """\
19Please output the layout information from the image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
201. Bbox format: [x1, y1, x2, y2]
212. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
223. Text Extraction & Formatting Rules:
23- Picture: For the 'Picture' category, the text field should be omitted.
24- Formula: Format its text as LaTeX.
25- Table: Format its text as HTML.
26- All Others (Text, Title, etc.): Format their text as Markdown.
274. Constraints:
28- The output text must be the original text from the image, with no translation.
29- All layout elements must be sorted according to human reading order.
305. Final Output: The entire output must be a single JSON object.\
31"""
32
33messages = [{"role": "user", "content": [{"type": "image", "image": image_path}, {"type": "text", "text": prompt_text}]}]
34
35text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
36image_inputs, _ = process_vision_info(messages)
37inputs = processor(text=[text], images=image_inputs, padding=True, return_tensors="pt").to(model.device)
38
39generated_ids = model.generate(**inputs, max_new_tokens=256, do_sample=True, temperature=0.6, top_p=0.9, repetition_penalty=1.15)
40
41generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
42output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
43
44print(output_text)