prithivMLmods commited on
Commit
e66544e
·
verified ·
1 Parent(s): b82683f

upload app

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