Views
No views yet
dots.ocr for document OCR, with a focus on tables and structured documents using QLora.1import torch
2from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
3from qwen_vl_utils import process_vision_info
4from dots_ocr.utils import dict_promptmode_to_prompt
5import math
6from PIL import Image
7from io import BytesIO
8import requests
9
10MIN_PIXELS = 3136
11MAX_PIXELS = 11289600
12IMAGE_FACTOR = 28
13
14model_path = "thangtv27/dots_ocr_finetuned"
15model = AutoModelForCausalLM.from_pretrained(
16 model_path,
17 attn_implementation="flash_attention_2",
18 torch_dtype=torch.bfloat16,
19 trust_remote_code=True
20).to("cuda")
21processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
22
23prompt = """Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
24
251. Bbox format: [x1, y1, x2, y2]
26
272. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
28
293. Text Extraction & Formatting Rules:
30 - Picture: For the 'Picture' category, the text field should be omitted.
31 - Formula: Format its text as LaTeX.
32 - Table: Format its text as HTML.
33 - All Others (Text, Title, etc.): Format their text as Markdown.
34
354. Constraints:
36 - The output text must be the original text from the image, with no translation.
37 - All layout elements must be sorted according to human reading order.
38
395. Final Output: The entire output must be a single JSON object.
40"""
41
42image = "test.jpg"
43
44messages = [
45 {
46 "role": "user",
47 "content": [
48 {
49 "type": "image",
50 "image": image
51 },
52 {"type": "text", "text": prompt}
53 ]
54 }
55 ]
56
57# Preparation for inference
58text = processor.apply_chat_template(
59 messages,
60 tokenize=False,
61 add_generation_prompt=True
62)
63
64image_inputs, video_inputs = process_vision_info(messages)
65
66inputs = processor(
67 text=[text],
68 images=image_inputs,
69 videos=video_inputs,
70 padding=True,
71 return_tensors="pt",
72)
73
74inputs = inputs.to("cuda")
75model.eval()
76
77generated_ids = model.generate(**inputs, repetition_penalty=1.15, max_new_tokens=5000)
78generated_ids_trimmed = [
79 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
80]
81output_text = processor.batch_decode(
82 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
83)
84print(output_text)