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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import json
|
3 |
+
import math
|
4 |
+
import os
|
5 |
+
import traceback
|
6 |
+
from io import BytesIO
|
7 |
+
from typing import Any, Dict, List, Optional, Tuple
|
8 |
+
import re
|
9 |
+
import time
|
10 |
+
from threading import Thread
|
11 |
+
|
12 |
+
import gradio as gr
|
13 |
+
import requests
|
14 |
+
import torch
|
15 |
+
from PIL import Image
|
16 |
+
|
17 |
+
from transformers import (
|
18 |
+
Qwen2VLForConditionalGeneration,
|
19 |
+
Qwen2_5_VLForConditionalGeneration,
|
20 |
+
AutoModelForImageTextToText,
|
21 |
+
AutoProcessor,
|
22 |
+
TextIteratorStreamer,
|
23 |
+
AutoModel,
|
24 |
+
AutoTokenizer,
|
25 |
+
)
|
26 |
+
|
27 |
+
# --- Activate Forced Dark Mode ---
|
28 |
+
js_func = """
|
29 |
+
function refresh() {
|
30 |
+
const url = new URL(window.location);
|
31 |
+
if (url.searchParams.get('__theme') !== 'dark') {
|
32 |
+
url.searchParams.set('__theme', 'dark');
|
33 |
+
window.location.href = url.href;
|
34 |
+
}
|
35 |
+
}
|
36 |
+
"""
|
37 |
+
|
38 |
+
# --- Constants and Model Setup ---
|
39 |
+
MAX_INPUT_TOKEN_LENGTH = 4096
|
40 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
41 |
+
|
42 |
+
# --- Prompts for Different Tasks ---
|
43 |
+
layout_prompt = """Please output the layout information from the image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
|
44 |
+
|
45 |
+
1. Bbox format: [x1, y1, x2, y2]
|
46 |
+
2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
|
47 |
+
3. Text Extraction & Formatting Rules:
|
48 |
+
- For tables, provide the content in a structured JSON format.
|
49 |
+
- For all other elements, provide the plain text.
|
50 |
+
4. Constraints:
|
51 |
+
- The output must be the original text from the image.
|
52 |
+
- All layout elements must be sorted according to human reading order.
|
53 |
+
5. Final Output: The entire output must be a single JSON object wrapped in ```json ... ```.
|
54 |
+
"""
|
55 |
+
|
56 |
+
ocr_prompt = "Perform precise OCR on the image. Extract all text content, maintaining the original structure, paragraphs, and tables as formatted markdown."
|
57 |
+
|
58 |
+
# --- Model Loading ---
|
59 |
+
MODEL_ID_M = "prithivMLmods/Camel-Doc-OCR-080125"
|
60 |
+
processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
|
61 |
+
model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
62 |
+
MODEL_ID_M, trust_remote_code=True, torch_dtype=torch.float16
|
63 |
+
).to(device).eval()
|
64 |
+
|
65 |
+
MODEL_ID_T = "prithivMLmods/Megalodon-OCR-Sync-0713"
|
66 |
+
processor_t = AutoProcessor.from_pretrained(MODEL_ID_T, trust_remote_code=True)
|
67 |
+
model_t = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
68 |
+
MODEL_ID_T, trust_remote_code=True, torch_dtype=torch.float16
|
69 |
+
).to(device).eval()
|
70 |
+
|
71 |
+
MODEL_ID_C = "nanonets/Nanonets-OCR-s"
|
72 |
+
processor_c = AutoProcessor.from_pretrained(MODEL_ID_C, trust_remote_code=True)
|
73 |
+
model_c = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
74 |
+
MODEL_ID_C, trust_remote_code=True, torch_dtype=torch.float16
|
75 |
+
).to(device).eval()
|
76 |
+
|
77 |
+
MODEL_ID_G = "echo840/MonkeyOCR"
|
78 |
+
SUBFOLDER = "Recognition"
|
79 |
+
processor_g = AutoProcessor.from_pretrained(
|
80 |
+
MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER
|
81 |
+
)
|
82 |
+
model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
83 |
+
MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER, torch_dtype=torch.float16
|
84 |
+
).to(device).eval()
|
85 |
+
|
86 |
+
MODEL_ID_I = "allenai/olmOCR-7B-0725"
|
87 |
+
processor_i = AutoProcessor.from_pretrained(MODEL_ID_I, trust_remote_code=True)
|
88 |
+
model_i = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
89 |
+
MODEL_ID_I, trust_remote_code=True, torch_dtype=torch.float16
|
90 |
+
).to(device).eval()
|
91 |
+
|
92 |
+
# Load typhoon-ocr-3b
|
93 |
+
MODEL_ID_J = "scb10x/typhoon-ocr-3b"
|
94 |
+
processor_j = AutoProcessor.from_pretrained(
|
95 |
+
MODEL_ID_J,
|
96 |
+
trust_remote_code=True
|
97 |
+
)
|
98 |
+
model_j = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
99 |
+
MODEL_ID_J,
|
100 |
+
trust_remote_code=True,
|
101 |
+
torch_dtype=torch.float16
|
102 |
+
).to(device).eval()
|
103 |
+
|
104 |
+
# --- Utility Functions ---
|
105 |
+
def layoutjson2md(layout_data: List[Dict]) -> str:
|
106 |
+
"""Converts the structured JSON from Layout Analysis into formatted Markdown."""
|
107 |
+
markdown_lines = []
|
108 |
+
try:
|
109 |
+
# Sort items by reading order (top-to-bottom, left-to-right)
|
110 |
+
sorted_items = sorted(layout_data, key=lambda x: (x.get('bbox', [0,0,0,0])[1], x.get('bbox', [0,0,0,0])[0]))
|
111 |
+
for item in sorted_items:
|
112 |
+
category = item.get('category', '')
|
113 |
+
text = item.get('text', '')
|
114 |
+
if not text: continue
|
115 |
+
|
116 |
+
if category == 'Title': markdown_lines.append(f"# {text}\n")
|
117 |
+
elif category == 'Section-header': markdown_lines.append(f"## {text}\n")
|
118 |
+
elif category == 'Table':
|
119 |
+
# Handle structured table JSON
|
120 |
+
if isinstance(text, dict) and 'header' in text and 'rows' in text:
|
121 |
+
header = '| ' + ' | '.join(map(str, text['header'])) + ' |'
|
122 |
+
separator = '| ' + ' | '.join(['---'] * len(text['header'])) + ' |'
|
123 |
+
rows = ['| ' + ' | '.join(map(str, row)) + ' |' for row in text['rows']]
|
124 |
+
markdown_lines.extend([header, separator] + rows)
|
125 |
+
markdown_lines.append("\n")
|
126 |
+
else: # Fallback for simple text
|
127 |
+
markdown_lines.append(f"{text}\n")
|
128 |
+
else:
|
129 |
+
markdown_lines.append(f"{text}\n")
|
130 |
+
except Exception as e:
|
131 |
+
print(f"Error converting to markdown: {e}")
|
132 |
+
return "### Error converting JSON to Markdown."
|
133 |
+
return "\n".join(markdown_lines)
|
134 |
+
|
135 |
+
# --- Core Application Logic ---
|
136 |
+
@spaces.GPU
|
137 |
+
def process_document_stream(model_name: str, task_choice: str, image: Image.Image, max_new_tokens: int):
|
138 |
+
"""
|
139 |
+
Main generator function that handles both OCR and Layout Analysis tasks.
|
140 |
+
"""
|
141 |
+
if image is None:
|
142 |
+
yield "Please upload an image.", "Please upload an image.", None
|
143 |
+
return
|
144 |
+
|
145 |
+
# 1. Select prompt based on user's task choice
|
146 |
+
text_prompt = ocr_prompt if task_choice == "Content Extraction" else layout_prompt
|
147 |
+
|
148 |
+
# 2. Select model and processor
|
149 |
+
if model_name == "Camel-Doc-OCR-080125": processor, model = processor_m, model_m
|
150 |
+
elif model_name == "Megalodon-OCR-Sync-0713": processor, model = processor_t, model_t
|
151 |
+
elif model_name == "Nanonets-OCR-s": processor, model = processor_c, model_c
|
152 |
+
elif model_name == "MonkeyOCR-Recognition": processor, model = processor_g, model_g
|
153 |
+
elif model_name == "olmOCR-7B-0725": processor, model = processor_i, model_i
|
154 |
+
elif model_name == "typhoon-ocr-3b": processor, model = processor_j, model_j
|
155 |
+
else:
|
156 |
+
yield "Invalid model selected.", "Invalid model selected.", None
|
157 |
+
return
|
158 |
+
|
159 |
+
# 3. Prepare model inputs and streamer
|
160 |
+
messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": text_prompt}]}]
|
161 |
+
prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
162 |
+
inputs = processor(text=[prompt_full], images=[image], return_tensors="pt", padding=True, truncation=True, max_length=MAX_INPUT_TOKEN_LENGTH).to(device)
|
163 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
164 |
+
generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
|
165 |
+
|
166 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
167 |
+
thread.start()
|
168 |
+
|
169 |
+
# 4. Stream raw output to the UI in real-time
|
170 |
+
buffer = ""
|
171 |
+
for new_text in streamer:
|
172 |
+
buffer += new_text
|
173 |
+
buffer = buffer.replace("<|im_end|>", "")
|
174 |
+
time.sleep(0.01)
|
175 |
+
yield buffer, "⏳ Processing...", {"status": "streaming"}
|
176 |
+
|
177 |
+
# 5. Post-process the final buffer based on the selected task
|
178 |
+
if task_choice == "Content Extraction":
|
179 |
+
# For OCR, the buffer is the final result.
|
180 |
+
yield buffer, buffer, None
|
181 |
+
else: # Layout Analysis
|
182 |
+
try:
|
183 |
+
json_match = re.search(r'```json\s*([\s\S]+?)\s*```', buffer)
|
184 |
+
if not json_match:
|
185 |
+
raise json.JSONDecodeError("JSON object not found in output.", buffer, 0)
|
186 |
+
|
187 |
+
json_str = json_match.group(1)
|
188 |
+
layout_data = json.loads(json_str)
|
189 |
+
markdown_content = layoutjson2md(layout_data)
|
190 |
+
|
191 |
+
yield buffer, markdown_content, layout_data
|
192 |
+
except Exception as e:
|
193 |
+
error_md = f"❌ **Error:** Failed to parse Layout JSON.\n\n**Details:**\n`{str(e)}`"
|
194 |
+
error_json = {"error": "ProcessingError", "details": str(e), "raw_output": buffer}
|
195 |
+
yield buffer, error_md, error_json
|
196 |
+
|
197 |
+
# --- Gradio UI Definition ---
|
198 |
+
def create_gradio_interface():
|
199 |
+
"""Builds and returns the Gradio web interface."""
|
200 |
+
css = """
|
201 |
+
.main-container { max-width: 1400px; margin: 0 auto; }
|
202 |
+
.process-button { border: none !important; color: white !important; font-weight: bold !important; background-color: blue !important;}
|
203 |
+
.process-button:hover { background-color: darkblue !important; transform: translateY(-2px) !important; box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important; }
|
204 |
+
"""
|
205 |
+
with gr.Blocks(theme="bethecloud/storj_theme", css=css, js=js_func) as demo:
|
206 |
+
gr.HTML("""
|
207 |
+
<div class="title" style="text-align: center">
|
208 |
+
<h1>OCR Comparator👨🏫</h1>
|
209 |
+
<p style="font-size: 1.1em; color: #6b7280; margin-bottom: 0.6em;">
|
210 |
+
Advanced Vision-Language Model for Image Content and Layout Extraction
|
211 |
+
</p>
|
212 |
+
</div>
|
213 |
+
""")
|
214 |
+
|
215 |
+
with gr.Row():
|
216 |
+
# Left Column (Inputs)
|
217 |
+
with gr.Column(scale=1):
|
218 |
+
model_choice = gr.Dropdown(
|
219 |
+
choices=["Camel-Doc-OCR-080125",
|
220 |
+
"MonkeyOCR-Recognition",
|
221 |
+
"olmOCR-7B-0725",
|
222 |
+
"Nanonets-OCR-s",
|
223 |
+
"Megalodon-OCR-Sync-0713",
|
224 |
+
"typhoon-ocr-3b"
|
225 |
+
],
|
226 |
+
label="Select Model", value="Nanonets-OCR-s"
|
227 |
+
)
|
228 |
+
task_choice = gr.Dropdown(
|
229 |
+
choices=["Content Extraction", "Layout Analysis(.json)"],
|
230 |
+
label="Select Task", value="Content Extraction"
|
231 |
+
)
|
232 |
+
image_input = gr.Image(label="Upload Image", type="pil", sources=['upload'])
|
233 |
+
with gr.Accordion("Advanced Settings", open=False):
|
234 |
+
max_new_tokens = gr.Slider(minimum=512, maximum=8192, value=4096, step=256, label="Max New Tokens")
|
235 |
+
|
236 |
+
process_btn = gr.Button("🚀 Process Document", variant="primary", elem_classes=["process-button"], size="lg")
|
237 |
+
clear_btn = gr.Button("🗑️ Clear All", variant="secondary")
|
238 |
+
|
239 |
+
# Right Column (Outputs)
|
240 |
+
with gr.Column(scale=2):
|
241 |
+
with gr.Tabs() as tabs:
|
242 |
+
with gr.Tab("📝 Extracted Content"):
|
243 |
+
raw_output_stream = gr.Textbox(label="Raw Model Output Stream", interactive=False, lines=13, show_copy_button=True)
|
244 |
+
with gr.Row():
|
245 |
+
examples = gr.Examples(
|
246 |
+
examples=["examples/1.png", "examples/2.png", "examples/3.png", "examples/4.png", "examples/5.png"],
|
247 |
+
inputs=image_input,
|
248 |
+
label="Examples"
|
249 |
+
)
|
250 |
+
with gr.Tab("📰 README.md"):
|
251 |
+
with gr.Accordion("(Formatted Result)", open=True):
|
252 |
+
markdown_output = gr.Markdown(label="Formatted Markdown")
|
253 |
+
|
254 |
+
with gr.Tab("📋 Layout Analysis Results"):
|
255 |
+
json_output = gr.JSON(label="Structured Layout Data (JSON)")
|
256 |
+
|
257 |
+
# Event Handlers
|
258 |
+
def clear_all_outputs():
|
259 |
+
return None, "Raw output will appear here.", "Formatted results will appear here.", None
|
260 |
+
|
261 |
+
process_btn.click(
|
262 |
+
fn=process_document_stream,
|
263 |
+
inputs=[model_choice,
|
264 |
+
task_choice,
|
265 |
+
image_input,
|
266 |
+
max_new_tokens],
|
267 |
+
outputs=[raw_output_stream,
|
268 |
+
markdown_output,
|
269 |
+
json_output]
|
270 |
+
)
|
271 |
+
clear_btn.click(
|
272 |
+
clear_all_outputs,
|
273 |
+
outputs=[image_input,
|
274 |
+
raw_output_stream,
|
275 |
+
markdown_output,
|
276 |
+
json_output]
|
277 |
+
)
|
278 |
+
return demo
|
279 |
+
|
280 |
+
if __name__ == "__main__":
|
281 |
+
demo = create_gradio_interface()
|
282 |
+
demo.queue().launch(share=True, mcp_server=True, ssr_mode=False, show_error=True)
|
requirements.txt
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
git+https://github.com/huggingface/transformers.git
|
2 |
+
git+https://github.com/huggingface/accelerate.git
|
3 |
+
git+https://github.com/huggingface/peft.git
|
4 |
+
transformers-stream-generator
|
5 |
+
huggingface_hub
|
6 |
+
opencv-python
|
7 |
+
sentencepiece
|
8 |
+
qwen-vl-utils
|
9 |
+
safetensors
|
10 |
+
torchvision
|
11 |
+
requests
|
12 |
+
spaces
|
13 |
+
gradio
|
14 |
+
pillow
|
15 |
+
gradio
|
16 |
+
torch
|
17 |
+
av
|