prithivMLmods commited on
Commit
9d70534
·
verified ·
1 Parent(s): cc5d860

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +205 -120
app.py CHANGED
@@ -1,51 +1,61 @@
1
- import gradio as gr
2
- from transformers.image_utils import load_image
3
- from threading import Thread
 
4
  import time
5
- import torch
 
 
 
6
  import spaces
7
- import cv2
8
  import numpy as np
9
  from PIL import Image
 
 
10
  from transformers import (
11
  Qwen2VLForConditionalGeneration,
12
  Qwen2_5_VLForConditionalGeneration,
 
13
  AutoProcessor,
14
  TextIteratorStreamer,
15
  )
16
- # Helper Functions
17
- def progress_bar_html(label: str, primary_color: str = "#FF4500", secondary_color: str = "#FFA07A") -> str:
18
- """
19
- Returns an HTML snippet for a thin animated progress bar with a label.
20
- Colors can be customized; default colors are used for Qwen2VL/Aya-Vision.
21
- """
22
- return f'''
23
- <div style="display: flex; align-items: center;">
24
- <span style="margin-right: 10px; font-size: 14px;">{label}</span>
25
- <div style="width: 110px; height: 5px; background-color: {secondary_color}; border-radius: 2px; overflow: hidden;">
26
- <div style="width: 100%; height: 100%; background-color: {primary_color}; animation: loading 1.5s linear infinite;"></div>
27
- </div>
28
- </div>
29
- <style>
30
- @keyframes loading {{
31
- 0% {{ transform: translateX(-100%); }}
32
- 100% {{ transform: translateX(100%); }}
33
- }}
34
- </style>
35
- '''
 
 
 
 
 
 
36
 
37
  def downsample_video(video_path):
38
  """
39
- Downsamples a video file by extracting 10 evenly spaced frames.
40
- Returns a list of tuples (PIL.Image, timestamp).
41
  """
42
  vidcap = cv2.VideoCapture(video_path)
43
  total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
44
  fps = vidcap.get(cv2.CAP_PROP_FPS)
45
  frames = []
46
- if total_frames <= 0 or fps <= 0:
47
- vidcap.release()
48
- return frames
49
  frame_indices = np.linspace(0, total_frames - 1, 10, dtype=int)
50
  for i in frame_indices:
51
  vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
@@ -58,115 +68,190 @@ def downsample_video(video_path):
58
  vidcap.release()
59
  return frames
60
 
61
- # Model and Processor Setup
62
- QV_MODEL_ID = "prithivMLmods/coreOCR-7B-050325-preview"
63
- qwen_processor = AutoProcessor.from_pretrained(QV_MODEL_ID, trust_remote_code=True)
64
- qwen_model = Qwen2VLForConditionalGeneration.from_pretrained(
65
- QV_MODEL_ID,
66
- trust_remote_code=True,
67
- torch_dtype=torch.float16
68
- ).to("cuda").eval()
69
-
70
- COREOCR_MODEL_ID = "prithivMLmods/docscopeOCR-7B-050425-exp"
71
- coreocr_processor = AutoProcessor.from_pretrained(COREOCR_MODEL_ID, trust_remote_code=True)
72
- coreocr_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
73
- COREOCR_MODEL_ID,
74
- trust_remote_code=True,
75
- torch_dtype=torch.bfloat16
76
- ).to("cuda").eval()
77
-
78
- # Main Inference Function
79
  @spaces.GPU
80
- @torch.no_grad()
81
- def model_inference(message, history, use_coreocr):
82
- text = message["text"].strip()
83
- files = message.get("files", [])
84
-
85
- if not text and not files:
86
- yield "Error: Please input a text query or provide image or video files."
 
 
 
 
 
 
 
 
 
 
87
  return
88
 
89
- # Process files: images and videos
90
- image_list = []
91
- for idx, file in enumerate(files):
92
- if file.lower().endswith((".mp4", ".avi", ".mov")):
93
- frames = downsample_video(file)
94
- if not frames:
95
- yield "Error: Could not extract frames from the video."
96
- return
97
- for frame, timestamp in frames:
98
- label = f"Video {idx+1} Frame {timestamp}:"
99
- image_list.append((label, frame))
100
- else:
101
- try:
102
- img = load_image(file)
103
- label = f"Image {idx+1}:"
104
- image_list.append((label, img))
105
- except Exception as e:
106
- yield f"Error loading image: {str(e)}"
107
- return
108
-
109
- # Build content list
110
- content = [{"type": "text", "text": text}]
111
- for label, img in image_list:
112
- content.append({"type": "text", "text": label})
113
- content.append({"type": "image", "image": img})
114
-
115
- messages = [{"role": "user", "content": content}]
116
-
117
- # Select processor and model
118
- if use_coreocr:
119
- processor = coreocr_processor
120
- model = coreocr_model
121
- model_name = "DocScopeOCR"
122
- else:
123
- processor = qwen_processor
124
- model = qwen_model
125
- model_name = "CoreOCR"
126
 
 
 
 
 
 
 
 
127
  prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
128
- all_images = [item["image"] for item in content if item["type"] == "image"]
129
  inputs = processor(
130
  text=[prompt_full],
131
- images=all_images if all_images else None,
132
  return_tensors="pt",
133
  padding=True,
134
- ).to("cuda")
135
-
 
136
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
137
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
138
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
139
  thread.start()
140
  buffer = ""
141
- yield progress_bar_html(f"Processing with {model_name}")
142
  for new_text in streamer:
143
  buffer += new_text
144
  buffer = buffer.replace("<|im_end|>", "")
145
  time.sleep(0.01)
146
  yield buffer
147
 
148
- # Gradio Interface
149
- examples = [
150
- [{"text": "Validate the worksheet answers", "files": ["example/image1.png"]}],
151
- [{"text": "Explain the scene", "files": ["example/image2.jpg"]}],
152
- [{"text": "Fill the correct numbers", "files": ["example/image3.png"]}],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  ]
154
 
155
- demo = gr.ChatInterface(
156
- fn=model_inference,
157
- description="# **CoreOCR `VL/OCR`**",
158
- examples=examples,
159
- textbox=gr.MultimodalTextbox(
160
- label="Query Input",
161
- file_types=["image", "video"],
162
- file_count="multiple",
163
- placeholder="Input your query and optionally upload image(s) or video(s). Select the model using the checkbox."
164
- ),
165
- stop_btn="Stop Generation",
166
- multimodal=True,
167
- cache_examples=False,
168
- theme="bethecloud/storj_theme",
169
- additional_inputs=[gr.Checkbox(label="Use CoreOCR", value=True, info="Check to use CoreOCR, uncheck to use DocScopeOCR")],
170
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
- demo.launch(debug=True, ssr_mode=False)
 
 
1
+ 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
11
+ import torch
12
  import numpy as np
13
  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
+
30
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
31
+
32
+ # Load docscopeOCR-7B-050425-exp
33
+ MODEL_ID_M = "prithivMLmods/docscopeOCR-7B-050425-exp"
34
+ processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
35
+ model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
36
+ MODEL_ID_M,
37
+ trust_remote_code=True,
38
+ torch_dtype=torch.float16
39
+ ).to(device).eval()
40
+
41
+ # Load coreOCR-7B-050325-preview
42
+ MODEL_ID_X = "prithivMLmods/coreOCR-7B-050325-preview"
43
+ processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
44
+ model_x = Qwen2VLForConditionalGeneration.from_pretrained(
45
+ MODEL_ID_X,
46
+ trust_remote_code=True,
47
+ torch_dtype=torch.float16
48
+ ).to(device).eval()
49
 
50
  def downsample_video(video_path):
51
  """
52
+ Downsamples the video to evenly spaced frames.
53
+ Each frame is returned as a PIL image along with its timestamp.
54
  """
55
  vidcap = cv2.VideoCapture(video_path)
56
  total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
57
  fps = vidcap.get(cv2.CAP_PROP_FPS)
58
  frames = []
 
 
 
59
  frame_indices = np.linspace(0, total_frames - 1, 10, dtype=int)
60
  for i in frame_indices:
61
  vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
 
68
  vidcap.release()
69
  return frames
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  @spaces.GPU
72
+ def generate_image(model_name: str, text: str, image: Image.Image,
73
+ max_new_tokens: int = 1024,
74
+ temperature: float = 0.6,
75
+ top_p: float = 0.9,
76
+ top_k: int = 50,
77
+ repetition_penalty: float = 1.2):
78
+ """
79
+ Generates responses using the selected model for image input.
80
+ """
81
+ if model_name == "docscopeOCR-7B-050425-exp":
82
+ processor = processor_m
83
+ model = model_m
84
+ elif model_name == "coreOCR-7B-050325-preview":
85
+ processor = processor_x
86
+ model = model_x
87
+ else:
88
+ yield "Invalid model selected."
89
  return
90
 
91
+ if image is None:
92
+ yield "Please upload an image."
93
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ messages = [{
96
+ "role": "user",
97
+ "content": [
98
+ {"type": "image", "image": image},
99
+ {"type": "text", "text": text},
100
+ ]
101
+ }]
102
  prompt_full = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
 
103
  inputs = processor(
104
  text=[prompt_full],
105
+ images=[image],
106
  return_tensors="pt",
107
  padding=True,
108
+ truncation=False,
109
+ max_length=MAX_INPUT_TOKEN_LENGTH
110
+ ).to(device)
111
  streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
112
+ generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
113
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
114
  thread.start()
115
  buffer = ""
 
116
  for new_text in streamer:
117
  buffer += new_text
118
  buffer = buffer.replace("<|im_end|>", "")
119
  time.sleep(0.01)
120
  yield buffer
121
 
122
+ @spaces.GPU
123
+ def generate_video(model_name: str, text: str, video_path: str,
124
+ max_new_tokens: int = 1024,
125
+ temperature: float = 0.6,
126
+ top_p: float = 0.9,
127
+ top_k: int = 50,
128
+ repetition_penalty: float = 1.2):
129
+ """
130
+ Generates responses using the selected model for video input.
131
+ """
132
+ if model_name == "docscopeOCR-7B-050425-exp":
133
+ processor = processor_m
134
+ model = model_m
135
+ elif model_name == "coreOCR-7B-050325-preview":
136
+ processor = processor_x
137
+ model = model_x
138
+ else:
139
+ yield "Invalid model selected."
140
+ return
141
+
142
+ if video_path is None:
143
+ yield "Please upload a video."
144
+ return
145
+
146
+ frames = downsample_video(video_path)
147
+ messages = [
148
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
149
+ {"role": "user", "content": [{"type": "text", "text": text}]}
150
+ ]
151
+ for frame in frames:
152
+ image, timestamp = frame
153
+ messages[1]["content"].append({"type": "text", "text": f"Frame {timestamp}:"})
154
+ messages[1]["content"].append({"type": "image", "image": image})
155
+ inputs = processor.apply_chat_template(
156
+ messages,
157
+ tokenize=True,
158
+ add_generation_prompt=True,
159
+ return_dict=True,
160
+ return_tensors="pt",
161
+ truncation=False,
162
+ max_length=MAX_INPUT_TOKEN_LENGTH
163
+ ).to(device)
164
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
165
+ generation_kwargs = {
166
+ **inputs,
167
+ "streamer": streamer,
168
+ "max_new_tokens": max_new_tokens,
169
+ "do_sample": True,
170
+ "temperature": temperature,
171
+ "top_p": top_p,
172
+ "top_k": top_k,
173
+ "repetition_penalty": repetition_penalty,
174
+ }
175
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
176
+ thread.start()
177
+ buffer = ""
178
+ for new_text in streamer:
179
+ buffer += new_text
180
+ time.sleep(0.01)
181
+ yield buffer
182
+
183
+ # Define examples for image and video inference
184
+ image_examples = [
185
+ ["Validate the worksheet answers..", "example/image1.png"],
186
+ ["Explain the scene", "example/image2.jpg"],
187
+ ["Fill the correct numbers", "example/image3.png"],
188
  ]
189
 
190
+ video_examples = [
191
+ ["Explain the ad in detail", "example/1.mp4"],
192
+ ["Identify the main actions in the coca cola ad...", "example/2.mp4"]
193
+ ]
194
+
195
+ css = """
196
+ .submit-btn {
197
+ background-color: #2980b9 !important;
198
+ color: white !important;
199
+ }
200
+ .submit-btn:hover {
201
+ background-color: #3498db !important;
202
+ }
203
+ """
204
+
205
+ # Create the Gradio Interface
206
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
207
+ gr.Markdown("# **[core OCR](https://huggingface.co/collections/prithivMLmods/core-and-docscope-ocr-models-6816d7f1bde3f911c6c852bc)**")
208
+ with gr.Row():
209
+ with gr.Column():
210
+ with gr.Tabs():
211
+ with gr.TabItem("Image Inference"):
212
+ image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
213
+ image_upload = gr.Image(type="pil", label="Image")
214
+ image_submit = gr.Button("Submit", elem_classes="submit-btn")
215
+ gr.Examples(
216
+ examples=image_examples,
217
+ inputs=[image_query, image_upload]
218
+ )
219
+ with gr.TabItem("Video Inference"):
220
+ video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
221
+ video_upload = gr.Video(label="Video")
222
+ video_submit = gr.Button("Submit", elem_classes="submit-btn")
223
+ gr.Examples(
224
+ examples=video_examples,
225
+ inputs=[video_query, video_upload]
226
+ )
227
+ with gr.Accordion("Advanced options", open=False):
228
+ max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
229
+ temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
230
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
231
+ top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
232
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
233
+ with gr.Column():
234
+ output = gr.Textbox(label="Output", interactive=False, lines=2, scale=2)
235
+ model_choice = gr.Radio(
236
+ choices=["docscopeOCR-7B-050425-exp", "coreOCR-7B-050325-preview"],
237
+ label="Select Model",
238
+ value="docscopeOCR-7B-050425-exp"
239
+ )
240
+
241
+ gr.Markdown("**Model Info**")
242
+ 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 Qwen/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.")
243
+ 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 Qwen/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.")
244
+
245
+ image_submit.click(
246
+ fn=generate_image,
247
+ inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
248
+ outputs=output
249
+ )
250
+ video_submit.click(
251
+ fn=generate_video,
252
+ inputs=[model_choice, video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
253
+ outputs=output
254
+ )
255
 
256
+ if __name__ == "__main__":
257
+ demo.queue(max_size=30).launch(share=True, mcp_server=True, ssr_mode=False, show_error=True)