CieLZ commited on
Commit
8533ea2
·
verified ·
1 Parent(s): 17a6c18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -136
app.py CHANGED
@@ -13,13 +13,10 @@ from PIL import Image, ImageOps
13
  import cv2
14
  from transformers import (
15
  Qwen2_5_VLForConditionalGeneration,
16
- AutoModelForVision2Seq,
17
  AutoProcessor,
18
  TextIteratorStreamer,
19
  )
20
 
21
- from docling_core.types.doc import DoclingDocument, DocTagsDocument
22
-
23
  # --- Constants ---
24
  MAX_MAX_NEW_TOKENS = 5120
25
  DEFAULT_MAX_NEW_TOKENS = 3072
@@ -27,51 +24,19 @@ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
27
  DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
28
 
29
  # --- Model Loading ---
30
- def load_model(model_id, model_class, subfolder=None):
31
- """Generic function to load a model and its processor."""
32
  processor_kwargs = {"trust_remote_code": True}
33
  model_kwargs = {"trust_remote_code": True, "torch_dtype": torch.float16}
34
 
35
- if subfolder:
36
- processor_kwargs["subfolder"] = subfolder
37
- model_kwargs["subfolder"] = subfolder
38
-
39
- processor = AutoProcessor.from_pretrained(model_id, **processor_kwargs)
40
- model = model_class.from_pretrained(model_id, **model_kwargs).to(DEVICE).eval()
41
  return processor, model
42
 
43
- # Load Nanonets-OCR-s
44
- processor_m, model_m = load_model(
45
- "nanonets/Nanonets-OCR-s", Qwen2_5_VLForConditionalGeneration
46
- )
47
-
48
- # Load MonkeyOCR
49
- processor_g, model_g = load_model(
50
- "echo840/MonkeyOCR", Qwen2_5_VLForConditionalGeneration, subfolder="Recognition"
51
- )
52
-
53
- # Load Typhoon-OCR-7B
54
- processor_l, model_l = load_model(
55
- "scb10x/typhoon-ocr-7b", Qwen2_5_VLForConditionalGeneration
56
- )
57
-
58
- # Load SmolDocling-256M-preview
59
- processor_x, model_x = load_model(
60
- "ds4sd/SmolDocling-256M-preview", AutoModelForVision2Seq
61
- )
62
-
63
- # Thyme-RL
64
- processor_n, model_n = load_model(
65
- "Kwai-Keye/Thyme-RL", Qwen2_5_VLForConditionalGeneration
66
- )
67
-
68
- MODEL_MAPPING = {
69
- "Nanonets-OCR-s": (processor_m, model_m),
70
- "MonkeyOCR-Recognition": (processor_g, model_g),
71
- "Typhoon-OCR-7B": (processor_l, model_l),
72
- "SmolDocling-256M-preview": (processor_x, model_x),
73
- "Thyme-RL": (processor_n, model_n),
74
- }
75
 
76
  # --- Preprocessing Functions ---
77
  def add_random_padding(image, min_percent=0.1, max_percent=0.10):
@@ -88,23 +53,6 @@ def add_random_padding(image, min_percent=0.1, max_percent=0.10):
88
  )
89
  return padded_image
90
 
91
- def normalize_values(text, target_max=500):
92
- """Normalize numerical values in text to a target maximum for SmolDocling."""
93
- def normalize_list(values):
94
- max_value = max(values) if values else 1
95
- return [round((v / max_value) * target_max) for v in values]
96
-
97
- def process_match(match):
98
- try:
99
- num_list = ast.literal_eval(match.group(0))
100
- normalized = normalize_list(num_list)
101
- return "".join([f"<loc_{num}>" for num in normalized])
102
- except (ValueError, SyntaxError):
103
- return match.group(0)
104
-
105
- pattern = r"\[([\d\.\s,]+)\]"
106
- return re.sub(pattern, process_match, text)
107
-
108
  def downsample_video(video_path, num_frames=10):
109
  """Downsample a video to evenly spaced frames, returning PIL images."""
110
  if not video_path:
@@ -124,25 +72,12 @@ def downsample_video(video_path, num_frames=10):
124
  return frames
125
 
126
  # --- Core Generation Logic ---
127
- def _generate_response(model_name, text, images, max_new_tokens, temperature, top_p, top_k, repetition_penalty):
128
  """Helper function to handle model inference."""
129
  if not images:
130
  yield "Please upload an image or video.", ""
131
  return
132
 
133
- try:
134
- processor, model = MODEL_MAPPING[model_name]
135
- except KeyError:
136
- yield "Invalid model selected.", ""
137
- return
138
-
139
- # Model-specific preprocessing
140
- if model_name == "SmolDocling-256M-preview":
141
- if any(keyword in text for keyword in ["OTSL", "code"]):
142
- images = [add_random_padding(img) for img in images]
143
- if any(keyword in text for keyword in ["OCR at text at", "Identify element", "formula"]):
144
- text = normalize_values(text, target_max=500)
145
-
146
  messages = [
147
  {
148
  "role": "user",
@@ -175,38 +110,16 @@ def _generate_response(model_name, text, images, max_new_tokens, temperature, to
175
  buffer += new_text.replace("<|im_end|>", "")
176
  yield buffer, buffer
177
 
178
- # Model-specific post-processing
179
- if model_name == "SmolDocling-256M-preview":
180
- cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
181
- is_doc_tag = any(
182
- tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]
183
- )
184
- if is_doc_tag:
185
- if "<chart>" in cleaned_output:
186
- cleaned_output = cleaned_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
187
- cleaned_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', cleaned_output)
188
-
189
- try:
190
- doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([cleaned_output], images)
191
- doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
192
- markdown_output = doc.export_to_markdown()
193
- yield buffer, markdown_output
194
- except Exception as e:
195
- yield buffer, f"Error processing Docling output: {e}"
196
- else:
197
- yield buffer, cleaned_output
198
-
199
  @spaces.GPU
200
- def generate_for_image(model_name, text, image, *args):
201
  """Generate responses for a single image input."""
202
  if image is None:
203
  yield "Please upload an image.", ""
204
  return
205
- yield from _generate_response(model_name, text, [image], *args)
206
-
207
 
208
  @spaces.GPU
209
- def generate_for_video(model_name, text, video_path, *args):
210
  """Generate responses for video input by downsampling frames."""
211
  if video_path is None:
212
  yield "Please upload a video.", ""
@@ -215,8 +128,7 @@ def generate_for_video(model_name, text, video_path, *args):
215
  if not frames:
216
  yield "Could not process video. Please check the file.", ""
217
  return
218
- yield from _generate_response(model_name, text, frames, *args)
219
-
220
 
221
  # --- Gradio Interface ---
222
  css = """
@@ -243,53 +155,42 @@ image_examples = [
243
  ["Reconstruct the doc [table] as it is.", "images/0.png"],
244
  ["Describe the image!", "images/8.png"],
245
  ["OCR the image", "images/2.jpg"],
246
- ["Convert this page to docling", "images/1.png"],
247
- ["Convert this page to docling", "images/3.png"],
248
- ["Convert chart to OTSL.", "images/4.png"],
249
  ["Convert code to text", "images/5.jpg"],
250
- ["Convert this table to OTSL.", "images/6.jpg"],
251
- ["Convert formula to latex.", "images/7.jpg"],
252
  ]
253
 
254
  video_examples = [
255
  ["Explain the video in detail.", "videos/1.mp4"],
256
- ["Explain the video in detail.", "videos/2.mp4"],
257
  ]
258
 
259
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
260
- gr.Markdown("# **[Multimodal OCR2](https://huggingface.co/collections/prithivMLmods/multimodal-implementations-67c9982ea04b39f0608badb0)**")
261
- gr.Markdown("A unified interface for state-of-the-art multimodal and document AI models. Select a model, upload an image or video, and enter a query to begin.")
262
 
263
  with gr.Row():
264
  # --- LEFT COLUMN (INPUTS) ---
265
  with gr.Column(scale=1):
266
- model_choice = gr.Dropdown(
267
- choices=[
268
- "Nanonets-OCR-s",
269
- "MonkeyOCR-Recognition",
270
- "Thyme-RL",
271
- "Typhoon-OCR-7B",
272
- "SmolDocling-256M-preview",
273
- ],
274
- label="Select Model⚡",
275
- value="Nanonets-OCR-s",
276
- )
277
 
278
  with gr.Tabs():
279
  with gr.TabItem("🖼️ Image Inference"):
280
- image_query = gr.Textbox(label="Query", placeholder="e.g., 'OCR the document'")
281
  image_upload = gr.Image(type="pil", label="Upload Image", height="299")
282
  image_submit = gr.Button("Generate", elem_classes="submit-btn")
283
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
284
 
285
  with gr.TabItem("🎬 Video Inference"):
286
- video_query = gr.Textbox(label="Query", placeholder="e.g., 'What is happening in this video?'")
287
  video_upload = gr.Video(label="Upload Video", height="299")
288
  video_submit = gr.Button("Generate", elem_classes="submit-btn")
289
  gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
290
 
291
  with gr.Accordion("⚙️ Advanced Options", open=False):
292
- # FIX: Changed 'min' to 'minimum' and 'max' to 'maximum'
293
  max_new_tokens = gr.Slider(
294
  label="Max New Tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS
295
  )
@@ -311,36 +212,48 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
311
  with gr.Column(elem_classes="output-container"):
312
  gr.Markdown("## Output")
313
  raw_output = gr.Textbox(
314
- label="Raw Output Stream", interactive=False, lines=8
315
  )
316
- with gr.Accordion("(Result.md)", open=False):
317
- formatted_output = gr.Markdown(label="Formatted Result (Markdown)")
318
 
319
  with gr.Accordion("💻 Model Information", open=True):
320
  gr.Markdown(
321
  """
322
- - **[Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s)**: nanonets-ocr-s is a powerful, state-of-the-art image-to-markdown ocr model that goes far beyond traditional text extraction. it transforms documents into structured markdown with intelligent content recognition and semantic tagging.
323
- - **[SmolDocling-256M](https://huggingface.co/ds4sd/SmolDocling-256M-preview)**: SmolDocling is a multimodal Image-Text-to-Text model designed for efficient document conversion. It retains Docling's most popular features while ensuring full compatibility with Docling through seamless support for DoclingDocuments.
324
- - **[MonkeyOCR-Recognition](https://huggingface.co/echo840/MonkeyOCR)**: MonkeyOCR adopts a Structure-Recognition-Relation (SRR) triplet paradigm, which simplifies the multi-tool pipeline of modular approaches while avoiding the inefficiency of using large multimodal models for full-page document processing.
325
- - **[Typhoon-OCR-7B](https://huggingface.co/scb10x/typhoon-ocr-7b)**: A bilingual document parsing model built specifically for real-world documents in Thai and English inspired by models like olmOCR based on Qwen2.5-VL-Instruction. Extracts and interprets embedded text (e.g., chart labels, captions) in Thai or English.
326
- - **[Thyme-RL](https://huggingface.co/Kwai-Keye/Thyme-RL)**: Think Beyond Images. Thyme transcends traditional ``thinking with images'' paradigms by autonomously generating and executing diverse image processing and computational operations through executable code, significantly enhancing performance on high-resolution perception and complex reasoning tasks.
327
-
328
- - **⚠️Note**: Performance on video inference tasks is experimental and may vary between models.
 
 
 
 
 
 
 
 
 
 
 
 
329
 
330
- > [Report a Bug](https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR2/discussions)
331
  """
332
  )
333
 
334
  # --- Event Handlers ---
335
  image_submit.click(
336
  fn=generate_for_image,
337
- inputs=[model_choice, image_query, image_upload] + advanced_params,
338
  outputs=[raw_output, formatted_output],
339
  )
340
 
341
  video_submit.click(
342
  fn=generate_for_video,
343
- inputs=[model_choice, video_query, video_upload] + advanced_params,
344
  outputs=[raw_output, formatted_output],
345
  )
346
 
 
13
  import cv2
14
  from transformers import (
15
  Qwen2_5_VLForConditionalGeneration,
 
16
  AutoProcessor,
17
  TextIteratorStreamer,
18
  )
19
 
 
 
20
  # --- Constants ---
21
  MAX_MAX_NEW_TOKENS = 5120
22
  DEFAULT_MAX_NEW_TOKENS = 3072
 
24
  DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
25
 
26
  # --- Model Loading ---
27
+ def load_model():
28
+ """Load the Nanonets-OCR-s model and its processor."""
29
  processor_kwargs = {"trust_remote_code": True}
30
  model_kwargs = {"trust_remote_code": True, "torch_dtype": torch.float16}
31
 
32
+ processor = AutoProcessor.from_pretrained("nanonets/Nanonets-OCR-s", **processor_kwargs)
33
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained("nanonets/Nanonets-OCR-s", **model_kwargs).to(DEVICE).eval()
 
 
 
 
34
  return processor, model
35
 
36
+ # Load single model
37
+ print("Loading Nanonets-OCR-s model...")
38
+ processor, model = load_model()
39
+ print("Model loaded successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  # --- Preprocessing Functions ---
42
  def add_random_padding(image, min_percent=0.1, max_percent=0.10):
 
53
  )
54
  return padded_image
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def downsample_video(video_path, num_frames=10):
57
  """Downsample a video to evenly spaced frames, returning PIL images."""
58
  if not video_path:
 
72
  return frames
73
 
74
  # --- Core Generation Logic ---
75
+ def _generate_response(text, images, max_new_tokens, temperature, top_p, top_k, repetition_penalty):
76
  """Helper function to handle model inference."""
77
  if not images:
78
  yield "Please upload an image or video.", ""
79
  return
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  messages = [
82
  {
83
  "role": "user",
 
110
  buffer += new_text.replace("<|im_end|>", "")
111
  yield buffer, buffer
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  @spaces.GPU
114
+ def generate_for_image(text, image, *args):
115
  """Generate responses for a single image input."""
116
  if image is None:
117
  yield "Please upload an image.", ""
118
  return
119
+ yield from _generate_response(text, [image], *args)
 
120
 
121
  @spaces.GPU
122
+ def generate_for_video(text, video_path, *args):
123
  """Generate responses for video input by downsampling frames."""
124
  if video_path is None:
125
  yield "Please upload a video.", ""
 
128
  if not frames:
129
  yield "Could not process video. Please check the file.", ""
130
  return
131
+ yield from _generate_response(text, frames, *args)
 
132
 
133
  # --- Gradio Interface ---
134
  css = """
 
155
  ["Reconstruct the doc [table] as it is.", "images/0.png"],
156
  ["Describe the image!", "images/8.png"],
157
  ["OCR the image", "images/2.jpg"],
158
+ ["Convert this page to markdown", "images/1.png"],
159
+ ["Extract text from this document", "images/3.png"],
160
+ ["Read the text in this image", "images/4.png"],
161
  ["Convert code to text", "images/5.jpg"],
162
+ ["Extract table data", "images/6.jpg"],
163
+ ["Read the formula", "images/7.jpg"],
164
  ]
165
 
166
  video_examples = [
167
  ["Explain the video in detail.", "videos/1.mp4"],
168
+ ["Describe what you see in this video.", "videos/2.mp4"],
169
  ]
170
 
171
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
172
+ gr.Markdown("# **Nanonets OCR Interface**")
173
+ gr.Markdown("A powerful OCR interface using Nanonets-OCR-s model. Upload an image or video and enter a query to extract and analyze text content.")
174
 
175
  with gr.Row():
176
  # --- LEFT COLUMN (INPUTS) ---
177
  with gr.Column(scale=1):
178
+ gr.Markdown("### **Model: Nanonets-OCR-s** ⚡")
 
 
 
 
 
 
 
 
 
 
179
 
180
  with gr.Tabs():
181
  with gr.TabItem("🖼️ Image Inference"):
182
+ image_query = gr.Textbox(label="Query", placeholder="e.g., 'OCR the document'", value="OCR the image")
183
  image_upload = gr.Image(type="pil", label="Upload Image", height="299")
184
  image_submit = gr.Button("Generate", elem_classes="submit-btn")
185
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
186
 
187
  with gr.TabItem("🎬 Video Inference"):
188
+ video_query = gr.Textbox(label="Query", placeholder="e.g., 'What text appears in this video?'", value="Describe the video and extract any text")
189
  video_upload = gr.Video(label="Upload Video", height="299")
190
  video_submit = gr.Button("Generate", elem_classes="submit-btn")
191
  gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
192
 
193
  with gr.Accordion("⚙️ Advanced Options", open=False):
 
194
  max_new_tokens = gr.Slider(
195
  label="Max New Tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS
196
  )
 
212
  with gr.Column(elem_classes="output-container"):
213
  gr.Markdown("## Output")
214
  raw_output = gr.Textbox(
215
+ label="Raw Output Stream", interactive=False, lines=12
216
  )
217
+ with gr.Accordion("📄 Formatted Output", open=False):
218
+ formatted_output = gr.Markdown(label="Formatted Result")
219
 
220
  with gr.Accordion("💻 Model Information", open=True):
221
  gr.Markdown(
222
  """
223
+ ### **Nanonets-OCR-s**
224
+
225
+ **Nanonets-OCR-s** is a powerful, state-of-the-art image-to-markdown OCR model that goes far beyond traditional text extraction. It transforms documents into structured markdown with intelligent content recognition and semantic tagging.
226
+
227
+ **Key Features:**
228
+ - 📄 Document structure recognition
229
+ - 🔤 High-accuracy text extraction
230
+ - 📊 Table and chart processing
231
+ - 🎯 Semantic content understanding
232
+ - ⚡ Fast inference speed
233
+
234
+ **Best for:**
235
+ - Document digitization
236
+ - Table extraction
237
+ - Form processing
238
+ - Academic paper analysis
239
+ - Receipt and invoice processing
240
+
241
+ **Note:** Video processing works by extracting key frames and analyzing them sequentially.
242
 
243
+ > [Model Card](https://huggingface.co/nanonets/Nanonets-OCR-s) | [Report Issues](https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR2/discussions)
244
  """
245
  )
246
 
247
  # --- Event Handlers ---
248
  image_submit.click(
249
  fn=generate_for_image,
250
+ inputs=[image_query, image_upload] + advanced_params,
251
  outputs=[raw_output, formatted_output],
252
  )
253
 
254
  video_submit.click(
255
  fn=generate_for_video,
256
+ inputs=[video_query, video_upload] + advanced_params,
257
  outputs=[raw_output, formatted_output],
258
  )
259