Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,51 +1,61 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
|
|
4 |
import time
|
5 |
-
import
|
|
|
|
|
|
|
6 |
import spaces
|
7 |
-
import
|
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 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
def downsample_video(video_path):
|
38 |
"""
|
39 |
-
Downsamples
|
40 |
-
|
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 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
return
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
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=
|
132 |
return_tensors="pt",
|
133 |
padding=True,
|
134 |
-
|
135 |
-
|
|
|
136 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
137 |
-
generation_kwargs =
|
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 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
]
|
154 |
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
-
|
|
|
|
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)
|