prithivMLmods commited on
Commit
5a7cced
·
verified ·
1 Parent(s): 0c028cf

update app

Browse files
Files changed (1) hide show
  1. app.py +106 -68
app.py CHANGED
@@ -2,9 +2,11 @@ import os
2
  import random
3
  import uuid
4
  import json
 
5
  import time
6
  import asyncio
7
  from threading import Thread
 
8
 
9
  import gradio as gr
10
  import spaces
@@ -14,16 +16,81 @@ from PIL import Image
14
  import cv2
15
 
16
  from transformers import (
17
- Qwen2VLForConditionalGeneration,
18
  Qwen2_5_VLForConditionalGeneration,
19
- AutoModelForImageTextToText,
20
  AutoProcessor,
 
21
  TextIteratorStreamer,
22
  )
23
- from transformers.image_utils import load_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  # Constants for text generation
26
- MAX_MAX_NEW_TOKENS = 2048
27
  DEFAULT_MAX_NEW_TOKENS = 1024
28
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
29
 
@@ -84,7 +151,7 @@ def downsample_video(video_path):
84
  total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
85
  fps = vidcap.get(cv2.CAP_PROP_FPS)
86
  frames = []
87
- frame_indices = np.linspace(0, total_frames - 1, 10, dtype=int)
88
  for i in frame_indices:
89
  vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
90
  success, image = vidcap.read()
@@ -108,17 +175,13 @@ def generate_image(model_name: str, text: str, image: Image.Image,
108
  Yields raw text and Markdown-formatted text.
109
  """
110
  if model_name == "docscopeOCR-7B-050425-exp":
111
- processor = processor_m
112
- model = model_m
113
  elif model_name == "coreOCR-7B-050325-preview":
114
- processor = processor_x
115
- model = model_x
116
  elif model_name == "MonkeyOCR-Recognition":
117
- processor = processor_g
118
- model = model_g
119
  elif model_name == "Camel-Doc-OCR-080125(v2)":
120
- processor = processor_o
121
- model = model_o
122
  else:
123
  yield "Invalid model selected.", "Invalid model selected."
124
  return
@@ -130,7 +193,7 @@ def generate_image(model_name: str, text: str, image: Image.Image,
130
  messages = [{
131
  "role": "user",
132
  "content": [
133
- {"type": "image", "image": image},
134
  {"type": "text", "text": text},
135
  ]
136
  }]
@@ -140,8 +203,8 @@ def generate_image(model_name: str, text: str, image: Image.Image,
140
  images=[image],
141
  return_tensors="pt",
142
  padding=True,
143
- truncation=False,
144
- max_length=MAX_INPUT_TOKEN_LENGTH
145
  ).to(device)
146
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
147
  generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
@@ -166,17 +229,13 @@ def generate_video(model_name: str, text: str, video_path: str,
166
  Yields raw text and Markdown-formatted text.
167
  """
168
  if model_name == "docscopeOCR-7B-050425-exp":
169
- processor = processor_m
170
- model = model_m
171
  elif model_name == "coreOCR-7B-050325-preview":
172
- processor = processor_x
173
- model = model_x
174
  elif model_name == "MonkeyOCR-Recognition":
175
- processor = processor_g
176
- model = model_g
177
  elif model_name == "Camel-Doc-OCR-080125(v2)":
178
- processor = processor_o
179
- model = model_o
180
  else:
181
  yield "Invalid model selected.", "Invalid model selected."
182
  return
@@ -200,8 +259,8 @@ def generate_video(model_name: str, text: str, video_path: str,
200
  add_generation_prompt=True,
201
  return_dict=True,
202
  return_tensors="pt",
203
- truncation=False,
204
- max_length=MAX_INPUT_TOKEN_LENGTH
205
  ).to(device)
206
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
207
  generation_kwargs = {
@@ -236,83 +295,62 @@ image_examples = [
236
  video_examples = [
237
  ["Explain the video in detail", "videos/2.mp4"],
238
  ["Explain the video in detail", "videos/1.mp4"]
239
-
240
  ]
241
 
242
  css = """
243
- .submit-btn {
244
- background-color: #2980b9 !important;
245
- color: white !important;
246
  }
247
- .submit-btn:hover {
248
- background-color: #3498db !important;
249
- }
250
- .canvas-output {
251
- border: 2px solid #4682B4;
252
- border-radius: 10px;
253
- padding: 20px;
254
  }
255
  """
256
 
257
  # Create the Gradio Interface
258
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
259
- gr.Markdown("# **[core OCR](https://huggingface.co/collections/prithivMLmods/multimodal-implementations-67c9982ea04b39f0608badb0)**")
260
  with gr.Row():
261
- with gr.Column():
262
  with gr.Tabs():
263
  with gr.TabItem("Image Inference"):
264
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
265
  image_upload = gr.Image(type="pil", label="Image", height=290)
266
- image_submit = gr.Button("Submit", elem_classes="submit-btn")
267
- gr.Examples(
268
- examples=image_examples,
269
- inputs=[image_query, image_upload]
270
- )
271
  with gr.TabItem("Video Inference"):
272
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
273
  video_upload = gr.Video(label="Video", height=290)
274
- video_submit = gr.Button("Submit", elem_classes="submit-btn")
275
- gr.Examples(
276
- examples=video_examples,
277
- inputs=[video_query, video_upload]
278
- )
279
  with gr.Accordion("Advanced options", open=False):
280
  max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
281
  temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
282
  top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
283
  top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
284
- repetition_cost = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
285
 
286
- with gr.Column():
287
- with gr.Column(elem_classes="canvas-output"):
288
- gr.Markdown("## Output")
289
- output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=5, show_copy_button=True)
290
-
291
- with gr.Accordion("(Result.md)", open=False):
292
- markdown_output = gr.Markdown(label="(Result.Md)")
293
 
294
  model_choice = gr.Radio(
295
  choices=["Camel-Doc-OCR-080125(v2)", "docscopeOCR-7B-050425-exp", "MonkeyOCR-Recognition", "coreOCR-7B-050325-preview"],
296
  label="Select Model",
297
  value="Camel-Doc-OCR-080125(v2)"
298
  )
299
- gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/core-OCR/discussions)")
300
- gr.Markdown("> [docscopeOCR-7B-050425-exp](https://huggingface.co/prithivMLmods/docscopeOCR-7B-050425-exp): The docscopeOCR-7B-050425-exp model is a fine-tuned version of Qwen2.5-VL-7B-Instruct, optimized for Document-Level Optical Character Recognition (OCR), long-context vision-language understanding, and accurate image-to-text conversion with mathematical LaTeX formatting.")
301
- gr.Markdown("> [MonkeyOCR](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.")
302
- gr.Markdown("> [Camel-Doc-OCR-080125](https://huggingface.co/prithivMLmods/Camel-Doc-OCR-080125): The Camel-Doc-OCR-080125 model is a fine-tuned version of Qwen2.5-VL-7B-Instruct, optimized for Document Retrieval, Content Extraction, and Analysis Recognition. Built on top of the Qwen2.5-VL architecture, this model enhances document comprehension capabilities")
303
- gr.Markdown("> [coreOCR-7B-050325-preview](https://huggingface.co/prithivMLmods/coreOCR-7B-050325-preview): The coreOCR-7B-050325-preview model is a fine-tuned version of Qwen2-VL-7B, optimized for Document-Level Optical Character Recognition (OCR), long-context vision-language understanding, and accurate image-to-text conversion with mathematical LaTeX formatting.")
304
- gr.Markdown(">⚠️note: all the models in space are not guaranteed to perform well in video inference use cases.")
305
-
306
  image_submit.click(
307
  fn=generate_image,
308
- inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_cost],
309
  outputs=[output, markdown_output]
310
  )
311
  video_submit.click(
312
  fn=generate_video,
313
- inputs=[model_choice, video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_cost],
314
  outputs=[output, markdown_output]
315
  )
316
 
317
  if __name__ == "__main__":
318
- demo.queue(max_size=30).launch(share=True, mcp_server=True, ssr_mode=False, show_error=True)
 
2
  import random
3
  import uuid
4
  import json
5
+ import requests
6
  import time
7
  import asyncio
8
  from threading import Thread
9
+ from typing import Iterable
10
 
11
  import gradio as gr
12
  import spaces
 
16
  import cv2
17
 
18
  from transformers import (
 
19
  Qwen2_5_VLForConditionalGeneration,
20
+ Qwen2VLForConditionalGeneration,
21
  AutoProcessor,
22
+ AutoTokenizer,
23
  TextIteratorStreamer,
24
  )
25
+ from gradio.themes import Soft
26
+ from gradio.themes.utils import colors, fonts, sizes
27
+
28
+ # --- Theme and CSS Definition ---
29
+
30
+ colors.steel_blue = colors.Color(
31
+ name="steel_blue",
32
+ c50="#EBF3F8",
33
+ c100="#D3E5F0",
34
+ c200="#A8CCE1",
35
+ c300="#7DB3D2",
36
+ c400="#529AC3",
37
+ c500="#4682B4", # SteelBlue base color
38
+ c600="#3E72A0",
39
+ c700="#36638C",
40
+ c800="#2E5378",
41
+ c900="#264364",
42
+ c950="#1E3450",
43
+ )
44
+
45
+ class SteelBlueTheme(Soft):
46
+ def __init__(
47
+ self,
48
+ *,
49
+ primary_hue: colors.Color | str = colors.gray,
50
+ secondary_hue: colors.Color | str = colors.steel_blue,
51
+ neutral_hue: colors.Color | str = colors.slate,
52
+ text_size: sizes.Size | str = sizes.text_lg,
53
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
54
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
55
+ ),
56
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
57
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
58
+ ),
59
+ ):
60
+ super().__init__(
61
+ primary_hue=primary_hue,
62
+ secondary_hue=secondary_hue,
63
+ neutral_hue=neutral_hue,
64
+ text_size=text_size,
65
+ font=font,
66
+ font_mono=font_mono,
67
+ )
68
+ super().set(
69
+ background_fill_primary="*primary_50",
70
+ background_fill_primary_dark="*primary_900",
71
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
72
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
73
+ button_primary_text_color="white",
74
+ button_primary_text_color_hover="white",
75
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
76
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
77
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_800)",
78
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_500)",
79
+ slider_color="*secondary_500",
80
+ slider_color_dark="*secondary_600",
81
+ block_title_text_weight="600",
82
+ block_border_width="3px",
83
+ block_shadow="*shadow_drop_lg",
84
+ button_primary_shadow="*shadow_drop_lg",
85
+ button_large_padding="11px",
86
+ color_accent_soft="*primary_100",
87
+ block_label_background_fill="*primary_200",
88
+ )
89
+
90
+ steel_blue_theme = SteelBlueTheme()
91
 
92
  # Constants for text generation
93
+ MAX_MAX_NEW_TOKENS = 4096
94
  DEFAULT_MAX_NEW_TOKENS = 1024
95
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
96
 
 
151
  total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
152
  fps = vidcap.get(cv2.CAP_PROP_FPS)
153
  frames = []
154
+ frame_indices = np.linspace(0, total_frames - 1, min(total_frames, 10), dtype=int)
155
  for i in frame_indices:
156
  vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
157
  success, image = vidcap.read()
 
175
  Yields raw text and Markdown-formatted text.
176
  """
177
  if model_name == "docscopeOCR-7B-050425-exp":
178
+ processor, model = processor_m, model_m
 
179
  elif model_name == "coreOCR-7B-050325-preview":
180
+ processor, model = processor_x, model_x
 
181
  elif model_name == "MonkeyOCR-Recognition":
182
+ processor, model = processor_g, model_g
 
183
  elif model_name == "Camel-Doc-OCR-080125(v2)":
184
+ processor, model = processor_o, model_o
 
185
  else:
186
  yield "Invalid model selected.", "Invalid model selected."
187
  return
 
193
  messages = [{
194
  "role": "user",
195
  "content": [
196
+ {"type": "image"},
197
  {"type": "text", "text": text},
198
  ]
199
  }]
 
203
  images=[image],
204
  return_tensors="pt",
205
  padding=True,
206
+ #truncation=True,
207
+ #max_length=MAX_INPUT_TOKEN_LENGTH
208
  ).to(device)
209
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
210
  generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
 
229
  Yields raw text and Markdown-formatted text.
230
  """
231
  if model_name == "docscopeOCR-7B-050425-exp":
232
+ processor, model = processor_m, model_m
 
233
  elif model_name == "coreOCR-7B-050325-preview":
234
+ processor, model = processor_x, model_x
 
235
  elif model_name == "MonkeyOCR-Recognition":
236
+ processor, model = processor_g, model_g
 
237
  elif model_name == "Camel-Doc-OCR-080125(v2)":
238
+ processor, model = processor_o, model_o
 
239
  else:
240
  yield "Invalid model selected.", "Invalid model selected."
241
  return
 
259
  add_generation_prompt=True,
260
  return_dict=True,
261
  return_tensors="pt",
262
+ #truncation=True,
263
+ #max_length=MAX_INPUT_TOKEN_LENGTH
264
  ).to(device)
265
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
266
  generation_kwargs = {
 
295
  video_examples = [
296
  ["Explain the video in detail", "videos/2.mp4"],
297
  ["Explain the video in detail", "videos/1.mp4"]
 
298
  ]
299
 
300
  css = """
301
+ #main-title h1 {
302
+ font-size: 2.3em !important;
 
303
  }
304
+ #output-title h2 {
305
+ font-size: 2.1em !important;
 
 
 
 
 
306
  }
307
  """
308
 
309
  # Create the Gradio Interface
310
+ with gr.Blocks(css=css, theme=steel_blue_theme) as demo:
311
+ gr.Markdown("# **core OCR**", elem_id="main-title")
312
  with gr.Row():
313
+ with gr.Column(scale=2):
314
  with gr.Tabs():
315
  with gr.TabItem("Image Inference"):
316
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
317
  image_upload = gr.Image(type="pil", label="Image", height=290)
318
+ image_submit = gr.Button("Submit", variant="primary")
319
+ gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
 
 
 
320
  with gr.TabItem("Video Inference"):
321
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
322
  video_upload = gr.Video(label="Video", height=290)
323
+ video_submit = gr.Button("Submit", variant="primary")
324
+ gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
 
 
 
325
  with gr.Accordion("Advanced options", open=False):
326
  max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
327
  temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
328
  top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
329
  top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
330
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
331
 
332
+ with gr.Column(scale=3):
333
+ gr.Markdown("## Output", elem_id="output-title")
334
+ output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=14, show_copy_button=True)
335
+ with gr.Accordion("(Result.md)", open=False):
336
+ markdown_output = gr.Markdown(label="(Result.Md)")
 
 
337
 
338
  model_choice = gr.Radio(
339
  choices=["Camel-Doc-OCR-080125(v2)", "docscopeOCR-7B-050425-exp", "MonkeyOCR-Recognition", "coreOCR-7B-050325-preview"],
340
  label="Select Model",
341
  value="Camel-Doc-OCR-080125(v2)"
342
  )
343
+
 
 
 
 
 
 
344
  image_submit.click(
345
  fn=generate_image,
346
+ inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
347
  outputs=[output, markdown_output]
348
  )
349
  video_submit.click(
350
  fn=generate_video,
351
+ inputs=[model_choice, video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
352
  outputs=[output, markdown_output]
353
  )
354
 
355
  if __name__ == "__main__":
356
+ demo.queue(max_size=50).launch(mcp_server=True, ssr_mode=False, show_error=True)