Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,9 @@
|
|
| 1 |
import os
|
| 2 |
import random
|
| 3 |
import uuid
|
| 4 |
-
import
|
| 5 |
import time
|
| 6 |
-
import
|
| 7 |
-
from http import HTTPStatus
|
| 8 |
from threading import Thread
|
| 9 |
|
| 10 |
import gradio as gr
|
|
@@ -15,369 +14,358 @@ from PIL import Image, ImageOps
|
|
| 15 |
import cv2
|
| 16 |
|
| 17 |
from transformers import (
|
|
|
|
| 18 |
Qwen2_5_VLForConditionalGeneration,
|
|
|
|
| 19 |
AutoModelForVision2Seq,
|
| 20 |
AutoProcessor,
|
| 21 |
TextIteratorStreamer,
|
| 22 |
)
|
| 23 |
-
from
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
MAX_MAX_NEW_TOKENS = 5120
|
| 31 |
DEFAULT_MAX_NEW_TOKENS = 3072
|
|
|
|
|
|
|
| 32 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 33 |
|
| 34 |
# --- Model Loading ---
|
| 35 |
-
#
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
# --- Preprocessing and Helper Functions ---
|
| 75 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
| 76 |
-
"""Add random padding to an image."""
|
| 77 |
image = image.convert("RGB")
|
| 78 |
width, height = image.size
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
| 82 |
return padded_image
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
"""
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
vidcap = cv2.VideoCapture(video_path)
|
| 88 |
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
|
|
| 89 |
frames = []
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
| 97 |
vidcap.release()
|
| 98 |
return frames
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
if
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
@spaces.GPU
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 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 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
}
|
| 211 |
-
|
| 212 |
-
conv_id = state_value["conversation_id"]
|
| 213 |
-
history = state_value["conversation_contexts"][conv_id]["history"]
|
| 214 |
-
history.append({
|
| 215 |
-
"key": str(uuid.uuid4()),
|
| 216 |
-
"role": "user",
|
| 217 |
-
"content": [{"type": "file", "content": files}, {"type": "text", "content": text}]
|
| 218 |
-
})
|
| 219 |
-
|
| 220 |
-
yield Gradio_Events.preprocess_submit(clear_input=True)(state_value)
|
| 221 |
-
for chunk in Gradio_Events.submit(state_value):
|
| 222 |
-
yield chunk
|
| 223 |
-
yield Gradio_Events.postprocess_submit(state_value)
|
| 224 |
-
|
| 225 |
-
@staticmethod
|
| 226 |
-
def preprocess_submit(clear_input=True):
|
| 227 |
-
def handler(state_value):
|
| 228 |
-
conv_id = state_value["conversation_id"]
|
| 229 |
-
history = state_value["conversation_contexts"][conv_id]["history"]
|
| 230 |
-
return {
|
| 231 |
-
input_comp: gr.update(value={'text': '', 'files': []} if clear_input else {}, loading=True),
|
| 232 |
-
conversations: gr.update(active_key=conv_id, items=state_value["conversations"]),
|
| 233 |
-
add_conversation_btn: gr.update(disabled=True),
|
| 234 |
-
chatbot: gr.update(value=history),
|
| 235 |
-
state: gr.update(value=state_value),
|
| 236 |
-
}
|
| 237 |
-
return handler
|
| 238 |
-
|
| 239 |
-
@staticmethod
|
| 240 |
-
def postprocess_submit(state_value):
|
| 241 |
-
conv_id = state_value["conversation_id"]
|
| 242 |
-
history = state_value["conversation_contexts"][conv_id]["history"]
|
| 243 |
-
return {
|
| 244 |
-
input_comp: gr.update(loading=False),
|
| 245 |
-
add_conversation_btn: gr.update(disabled=False),
|
| 246 |
-
chatbot: gr.update(value=history),
|
| 247 |
-
state: gr.update(value=state_value),
|
| 248 |
-
}
|
| 249 |
-
|
| 250 |
-
@staticmethod
|
| 251 |
-
def apply_prompt(e: gr.EventData):
|
| 252 |
-
# Example format: {"description": "Query text", "urls": ["path/to/image.png"]}
|
| 253 |
-
prompt_data = e._data["payload"][0]["value"]
|
| 254 |
-
return gr.update(value={'text': prompt_data['description'], 'files': prompt_data['urls']})
|
| 255 |
-
|
| 256 |
-
@staticmethod
|
| 257 |
-
def new_chat(state_value):
|
| 258 |
-
state_value["conversation_id"] = ""
|
| 259 |
-
return gr.update(active_key=""), gr.update(value=None), gr.update(value=state_value), gr.update(value=MODEL_CHOICES[0])
|
| 260 |
-
|
| 261 |
-
@staticmethod
|
| 262 |
-
def select_conversation(state_value, e: gr.EventData):
|
| 263 |
-
active_key = e._data["payload"][0]
|
| 264 |
-
if state_value["conversation_id"] == active_key or active_key not in state_value["conversation_contexts"]:
|
| 265 |
-
return gr.skip()
|
| 266 |
-
state_value["conversation_id"] = active_key
|
| 267 |
-
context = state_value["conversation_contexts"][active_key]
|
| 268 |
-
return gr.update(active_key=active_key), gr.update(value=context["history"]), gr.update(value=state_value), gr.update(value=context.get("selected_model", MODEL_CHOICES[0]))
|
| 269 |
-
|
| 270 |
-
@staticmethod
|
| 271 |
-
def on_model_change(model_name, state_value):
|
| 272 |
-
if state_value["conversation_id"]:
|
| 273 |
-
state_value["conversation_contexts"][state_value["conversation_id"]]["selected_model"] = model_name
|
| 274 |
-
return state_value
|
| 275 |
|
| 276 |
|
| 277 |
-
# --- UI
|
| 278 |
css = """
|
| 279 |
-
.gradio-container {
|
| 280 |
-
main
|
| 281 |
-
|
| 282 |
-
#
|
| 283 |
-
|
| 284 |
-
}
|
| 285 |
-
|
|
|
|
| 286 |
"""
|
| 287 |
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
{
|
| 296 |
-
"title": "Describe Image",
|
| 297 |
-
"description": "Describe the image!",
|
| 298 |
-
"urls": ["https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR2/resolve/main/images/8.png"]
|
| 299 |
-
},
|
| 300 |
-
{
|
| 301 |
-
"title": "OCR Image",
|
| 302 |
-
"description": "OCR the image",
|
| 303 |
-
"urls": ["https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR2/resolve/main/images/2.jpg"]
|
| 304 |
-
},
|
| 305 |
-
{
|
| 306 |
-
"title": "Convert to Docling",
|
| 307 |
-
"description": "Convert this page to docling",
|
| 308 |
-
"urls": ["https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR2/resolve/main/images/1.png"]
|
| 309 |
-
},
|
| 310 |
-
]
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
with
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
)
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
)
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
outputs=[
|
| 380 |
)
|
| 381 |
|
|
|
|
| 382 |
if __name__ == "__main__":
|
| 383 |
-
demo.queue().launch(
|
|
|
|
| 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
|
|
|
|
| 14 |
import cv2
|
| 15 |
|
| 16 |
from transformers import (
|
| 17 |
+
Qwen2VLForConditionalGeneration,
|
| 18 |
Qwen2_5_VLForConditionalGeneration,
|
| 19 |
+
AutoModelForCausalLM,
|
| 20 |
AutoModelForVision2Seq,
|
| 21 |
AutoProcessor,
|
| 22 |
TextIteratorStreamer,
|
| 23 |
)
|
| 24 |
+
from transformers.image_utils import load_image
|
| 25 |
+
|
| 26 |
+
# These imports seem to be from a custom library.
|
| 27 |
+
# If you have 'docling_core' installed, you can uncomment them.
|
| 28 |
+
# from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
| 29 |
|
| 30 |
+
import re
|
| 31 |
+
import ast
|
| 32 |
+
import html
|
| 33 |
+
|
| 34 |
+
# --- Constants ---
|
| 35 |
MAX_MAX_NEW_TOKENS = 5120
|
| 36 |
DEFAULT_MAX_NEW_TOKENS = 3072
|
| 37 |
+
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
| 38 |
+
|
| 39 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 40 |
|
| 41 |
# --- Model Loading ---
|
| 42 |
+
# Load Nanonets-OCR-s
|
| 43 |
+
MODEL_ID_M = "nanonets/Nanonets-OCR-s"
|
| 44 |
+
processor_m = AutoProcessor.from_pretrained(MODEL_ID_M, trust_remote_code=True)
|
| 45 |
+
model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 46 |
+
MODEL_ID_M,
|
| 47 |
+
trust_remote_code=True,
|
| 48 |
+
torch_dtype=torch.float16
|
| 49 |
+
).to(device).eval()
|
| 50 |
+
|
| 51 |
+
# Load MonkeyOCR
|
| 52 |
+
MODEL_ID_G = "echo840/MonkeyOCR"
|
| 53 |
+
SUBFOLDER = "Recognition"
|
| 54 |
+
processor_g = AutoProcessor.from_pretrained(
|
| 55 |
+
MODEL_ID_G,
|
| 56 |
+
trust_remote_code=True,
|
| 57 |
+
subfolder=SUBFOLDER
|
| 58 |
+
)
|
| 59 |
+
model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 60 |
+
MODEL_ID_G,
|
| 61 |
+
trust_remote_code=True,
|
| 62 |
+
subfolder=SUBFOLDER,
|
| 63 |
+
torch_dtype=torch.float16
|
| 64 |
+
).to(device).eval()
|
| 65 |
+
|
| 66 |
+
# Load Typhoon-OCR-7B
|
| 67 |
+
MODEL_ID_L = "scb10x/typhoon-ocr-7b"
|
| 68 |
+
processor_l = AutoProcessor.from_pretrained(MODEL_ID_L, trust_remote_code=True)
|
| 69 |
+
model_l = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 70 |
+
MODEL_ID_L,
|
| 71 |
+
trust_remote_code=True,
|
| 72 |
+
torch_dtype=torch.float16
|
| 73 |
+
).to(device).eval()
|
| 74 |
+
|
| 75 |
+
# Load SmolDocling-256M-preview
|
| 76 |
+
MODEL_ID_X = "ds4sd/SmolDocling-256M-preview"
|
| 77 |
+
processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
|
| 78 |
+
model_x = AutoModelForVision2Seq.from_pretrained(
|
| 79 |
+
MODEL_ID_X,
|
| 80 |
+
trust_remote_code=True,
|
| 81 |
+
torch_dtype=torch.float16
|
| 82 |
+
).to(device).eval()
|
| 83 |
+
|
| 84 |
+
# Thyme-RL
|
| 85 |
+
MODEL_ID_N = "Kwai-Keye/Thyme-RL"
|
| 86 |
+
processor_n = AutoProcessor.from_pretrained(MODEL_ID_N, trust_remote_code=True)
|
| 87 |
+
model_n = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 88 |
+
MODEL_ID_N,
|
| 89 |
+
trust_remote_code=True,
|
| 90 |
+
torch_dtype=torch.float16
|
| 91 |
+
).to(device).eval()
|
| 92 |
|
| 93 |
|
| 94 |
# --- Preprocessing and Helper Functions ---
|
| 95 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
| 96 |
+
"""Add random padding to an image based on its size."""
|
| 97 |
image = image.convert("RGB")
|
| 98 |
width, height = image.size
|
| 99 |
+
pad_w_percent = random.uniform(min_percent, max_percent)
|
| 100 |
+
pad_h_percent = random.uniform(min_percent, max_percent)
|
| 101 |
+
pad_w = int(width * pad_w_percent)
|
| 102 |
+
pad_h = int(height * pad_h_percent)
|
| 103 |
+
corner_pixel = image.getpixel((0, 0)) # Top-left corner
|
| 104 |
+
padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
| 105 |
return padded_image
|
| 106 |
|
| 107 |
+
def normalize_values(text, target_max=500):
|
| 108 |
+
"""Normalize numerical values in text to a target maximum."""
|
| 109 |
+
def normalize_list(values):
|
| 110 |
+
max_value = max(values) if values else 1
|
| 111 |
+
return [round((v / max_value) * target_max) for v in values]
|
| 112 |
+
|
| 113 |
+
def process_match(match):
|
| 114 |
+
num_list = ast.literal_eval(match.group(0))
|
| 115 |
+
normalized = normalize_list(num_list)
|
| 116 |
+
return "".join([f"<loc_{num}>" for num in normalized])
|
| 117 |
+
|
| 118 |
+
pattern = r"\[([\d\.\s,]+)\]"
|
| 119 |
+
normalized_text = re.sub(pattern, process_match, text)
|
| 120 |
+
return normalized_text
|
| 121 |
+
|
| 122 |
+
def downsample_video(video_path):
|
| 123 |
+
"""Downsample a video to evenly spaced frames, returning PIL images with timestamps."""
|
| 124 |
vidcap = cv2.VideoCapture(video_path)
|
| 125 |
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 126 |
+
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
| 127 |
frames = []
|
| 128 |
+
# Use 10 frames for video processing
|
| 129 |
+
frame_indices = np.linspace(0, total_frames - 1, 10, dtype=int)
|
| 130 |
+
for i in frame_indices:
|
| 131 |
+
vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
|
| 132 |
+
success, image = vidcap.read()
|
| 133 |
+
if success:
|
| 134 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 135 |
+
pil_image = Image.fromarray(image)
|
| 136 |
+
timestamp = round(i / fps, 2)
|
| 137 |
+
frames.append((pil_image, timestamp))
|
| 138 |
vidcap.release()
|
| 139 |
return frames
|
| 140 |
|
| 141 |
+
# A placeholder function in case docling_core is not installed
|
| 142 |
+
def format_smoldocling_output(buffer_text, images):
|
| 143 |
+
cleaned_output = buffer_text.replace("<end_of_utterance>", "").strip()
|
| 144 |
+
# Check if docling_core is available and was imported
|
| 145 |
+
if 'DocTagsDocument' in globals() and 'DoclingDocument' in globals():
|
| 146 |
+
if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
| 147 |
+
if "<chart>" in cleaned_output:
|
| 148 |
+
cleaned_output = cleaned_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
|
| 149 |
+
cleaned_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', cleaned_output)
|
| 150 |
+
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([cleaned_output], images)
|
| 151 |
+
doc = DoclingDocument.load_from_doctags(doctags_doc, document_name="Document")
|
| 152 |
+
markdown_output = doc.export_to_markdown()
|
| 153 |
+
return markdown_output
|
| 154 |
+
# Fallback if library is not available or tags are not present
|
| 155 |
+
return cleaned_output
|
| 156 |
+
|
| 157 |
+
# --- Core Generation Logic ---
|
| 158 |
+
def get_model_and_processor(model_name):
|
| 159 |
+
"""Helper to select model and processor."""
|
| 160 |
+
if model_name == "Nanonets-OCR-s":
|
| 161 |
+
return processor_m, model_m
|
| 162 |
+
elif model_name == "MonkeyOCR-Recognition":
|
| 163 |
+
return processor_g, model_g
|
| 164 |
+
elif model_name == "SmolDocling-256M-preview":
|
| 165 |
+
return processor_x, model_x
|
| 166 |
+
elif model_name == "Typhoon-OCR-7B":
|
| 167 |
+
return processor_l, model_l
|
| 168 |
+
elif model_name == "Thyme-RL":
|
| 169 |
+
return processor_n, model_n
|
| 170 |
+
else:
|
| 171 |
+
return None, None
|
| 172 |
+
|
| 173 |
+
def is_video_file(filepath):
|
| 174 |
+
"""Check if a file has a common video extension."""
|
| 175 |
+
if not filepath:
|
| 176 |
+
return False
|
| 177 |
+
video_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.webm']
|
| 178 |
+
return any(filepath.lower().endswith(ext) for ext in video_extensions)
|
| 179 |
|
| 180 |
@spaces.GPU
|
| 181 |
+
def generate_response(
|
| 182 |
+
media_file: str,
|
| 183 |
+
query: str,
|
| 184 |
+
model_name: str,
|
| 185 |
+
max_new_tokens: int,
|
| 186 |
+
temperature: float,
|
| 187 |
+
top_p: float
|
| 188 |
+
):
|
| 189 |
+
"""Unified generation function for both image and video."""
|
| 190 |
+
if media_file is None:
|
| 191 |
+
yield "Please upload an image or video file first.", "Please upload an image or video file first."
|
| 192 |
+
return
|
| 193 |
+
|
| 194 |
+
processor, model = get_model_and_processor(model_name)
|
| 195 |
+
if not processor or not model:
|
| 196 |
+
yield "Invalid model selected.", "Invalid model selected."
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
media_type = "video" if is_video_file(media_file) else "image"
|
| 200 |
+
|
| 201 |
+
if media_type == "video":
|
| 202 |
+
frames = downsample_video(media_file)
|
| 203 |
+
images = [frame for frame, _ in frames]
|
| 204 |
+
else: # image
|
| 205 |
+
images = [Image.open(media_file)]
|
| 206 |
+
|
| 207 |
+
if model_name == "SmolDocling-256M-preview":
|
| 208 |
+
if "OTSL" in query or "code" in query:
|
| 209 |
+
images = [add_random_padding(img) for img in images]
|
| 210 |
+
if "OCR at text at" in query or "Identify element" in query or "formula" in query:
|
| 211 |
+
query = normalize_values(query, target_max=500)
|
| 212 |
+
|
| 213 |
+
messages = [
|
| 214 |
+
{"role": "user", "content": [{"type": "image"} for _ in images] + [{"type": "text", "text": query}]}
|
| 215 |
+
]
|
| 216 |
+
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 217 |
+
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 218 |
+
|
| 219 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 220 |
+
generation_kwargs = {
|
| 221 |
+
**inputs,
|
| 222 |
+
"streamer": streamer,
|
| 223 |
+
"max_new_tokens": max_new_tokens,
|
| 224 |
+
"temperature": temperature,
|
| 225 |
+
"top_p": top_p,
|
| 226 |
+
}
|
| 227 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 228 |
+
thread.start()
|
| 229 |
+
|
| 230 |
+
buffer = ""
|
| 231 |
+
for new_text in streamer:
|
| 232 |
+
buffer += new_text.replace("<|im_end|>", "")
|
| 233 |
+
yield buffer
|
| 234 |
+
|
| 235 |
+
if model_name == "SmolDocling-256M-preview":
|
| 236 |
+
formatted_output = format_smoldocling_output(buffer, images)
|
| 237 |
+
yield formatted_output
|
| 238 |
+
else:
|
| 239 |
+
yield buffer.strip()
|
| 240 |
+
|
| 241 |
+
# --- Gradio Interface ---
|
| 242 |
+
|
| 243 |
+
# --- Examples ---
|
| 244 |
+
image_examples = [
|
| 245 |
+
["images/0.png", "Reconstruct the doc [table] as it is."],
|
| 246 |
+
["images/8.png", "Describe the image!"],
|
| 247 |
+
["images/2.jpg", "OCR the image"],
|
| 248 |
+
["images/1.png", "Convert this page to docling"],
|
| 249 |
+
["images/3.png", "Convert this page to docling"],
|
| 250 |
+
["images/4.png", "Convert chart to OTSL."],
|
| 251 |
+
["images/5.jpg", "Convert code to text"],
|
| 252 |
+
["images/6.jpg", "Convert this table to OTSL."],
|
| 253 |
+
["images/7.jpg", "Convert formula to latex."],
|
| 254 |
+
]
|
| 255 |
+
video_examples = [
|
| 256 |
+
["videos/1.mp4", "Explain the video in detail."],
|
| 257 |
+
["videos/2.mp4", "Explain the video in detail."]
|
| 258 |
+
]
|
| 259 |
+
all_examples = image_examples + video_examples
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
|
| 262 |
+
# --- UI Styling and Helper Functions ---
|
| 263 |
css = """
|
| 264 |
+
body, .gradio-container { font-family: 'Inter', sans-serif; }
|
| 265 |
+
.main-container { padding: 20px; }
|
| 266 |
+
.sidebar { background-color: #F7F7F7; border-right: 1px solid #E0E0E0; padding: 15px; border-radius: 15px; }
|
| 267 |
+
.chat-window { min-height: 60vh; border: 1px solid #E0E0E0; border-radius: 15px; padding: 20px; box-shadow: 0 4px 8px rgba(0,0,0,0.05); }
|
| 268 |
+
.input-bar { padding: 10px; border-radius: 15px; background-color: #FFFFFF; border: 1px solid #E0E0E0; margin-top: 20px;}
|
| 269 |
+
.submit-button { background-color: #007AFF !important; color: white !important; font-weight: bold !important; }
|
| 270 |
+
.media-display {text-align: center; background-color: #F0F0F0; border-radius: 10px; padding: 10px; margin-bottom: 20px;}
|
| 271 |
+
.media-display img, .media-display video {max-height: 400px; margin: auto;}
|
| 272 |
"""
|
| 273 |
|
| 274 |
+
def handle_file_upload(file):
|
| 275 |
+
if file is None:
|
| 276 |
+
return None, gr.update(visible=False)
|
| 277 |
+
if is_video_file(file.name):
|
| 278 |
+
return gr.update(value=file.name, visible=False), gr.update(value=file.name, visible=True)
|
| 279 |
+
else:
|
| 280 |
+
return gr.update(value=file.name, visible=True), gr.update(value=file.name, visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
+
def clear_all():
|
| 283 |
+
return None, None, None, ""
|
| 284 |
+
|
| 285 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
| 286 |
+
# Hidden state to store the path to the uploaded file
|
| 287 |
+
media_file_path = gr.State(None)
|
| 288 |
+
|
| 289 |
+
with gr.Row(elem_classes="main-container"):
|
| 290 |
+
# --- Sidebar ---
|
| 291 |
+
with gr.Column(scale=1, elem_classes="sidebar"):
|
| 292 |
+
gr.Markdown("### OCR Conversations")
|
| 293 |
+
add_conv_btn = gr.Button("+ Add Conversation")
|
| 294 |
+
gr.Markdown("---")
|
| 295 |
+
gr.Markdown("#### Advanced Options")
|
| 296 |
+
with gr.Accordion("⚙️ Generation Settings", open=False):
|
| 297 |
+
max_new_tokens = gr.Slider(
|
| 298 |
+
label="Max New Tokens",
|
| 299 |
+
minimum=256,
|
| 300 |
+
maximum=MAX_MAX_NEW_TOKENS,
|
| 301 |
+
step=64,
|
| 302 |
+
value=DEFAULT_MAX_NEW_TOKENS,
|
| 303 |
+
)
|
| 304 |
+
temperature = gr.Slider(
|
| 305 |
+
label="Temperature", minimum=0.1, maximum=1.0, step=0.05, value=0.6
|
| 306 |
+
)
|
| 307 |
+
top_p = gr.Slider(
|
| 308 |
+
label="Top-p", minimum=0.1, maximum=1.0, step=0.05, value=0.9
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# --- Main Content Panel ---
|
| 312 |
+
with gr.Column(scale=4):
|
| 313 |
+
gr.Markdown("# Multimodal OCR")
|
| 314 |
+
|
| 315 |
+
# --- Media Display Area ---
|
| 316 |
+
with gr.Column(elem_classes="media-display"):
|
| 317 |
+
image_display = gr.Image(type="filepath", label="Image Preview", visible=False)
|
| 318 |
+
video_display = gr.Video(label="Video Preview", visible=False)
|
| 319 |
+
gr.Markdown("Upload an image or video to begin.")
|
| 320 |
+
|
| 321 |
+
# --- Examples ---
|
| 322 |
+
gr.Examples(
|
| 323 |
+
examples=all_examples,
|
| 324 |
+
inputs=[media_file_path, "query_input"],
|
| 325 |
+
label="Examples (Click to run)",
|
| 326 |
+
fn=handle_file_upload, # Custom function to update media display
|
| 327 |
+
outputs=[image_display, video_display]
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# --- Chat/Output Window ---
|
| 331 |
+
output_display = gr.Markdown(elem_classes="chat-window", value="### Output will be shown here")
|
| 332 |
+
|
| 333 |
+
# --- Input Bar ---
|
| 334 |
+
with gr.Row(elem_classes="input-bar", vertical=False):
|
| 335 |
+
upload_btn = gr.UploadButton("📁 Add Files", file_types=["image", "video"])
|
| 336 |
+
model_dropdown = gr.Dropdown(
|
| 337 |
+
choices=["Nanonets-OCR-s", "MonkeyOCR-Recognition", "Thyme-RL", "Typhoon-OCR-7B", "SmolDocling-256M-preview"],
|
| 338 |
+
label="Select Model",
|
| 339 |
+
value="Nanonets-OCR-s"
|
| 340 |
+
)
|
| 341 |
+
query_input = gr.Textbox(
|
| 342 |
+
placeholder="Enter your query here...",
|
| 343 |
+
show_label=False,
|
| 344 |
+
scale=4,
|
| 345 |
+
)
|
| 346 |
+
submit_btn = gr.Button("▶", elem_classes="submit-button")
|
| 347 |
+
|
| 348 |
+
# --- Event Handlers ---
|
| 349 |
+
upload_btn.upload(
|
| 350 |
+
fn=handle_file_upload,
|
| 351 |
+
inputs=[upload_btn],
|
| 352 |
+
outputs=[image_display, video_display]
|
| 353 |
)
|
| 354 |
+
|
| 355 |
+
# When file is uploaded, also store its path in the state
|
| 356 |
+
upload_btn.upload(lambda f: f.name if f else None, upload_btn, media_file_path)
|
| 357 |
+
|
| 358 |
+
submit_btn.click(
|
| 359 |
+
fn=generate_response,
|
| 360 |
+
inputs=[media_file_path, query_input, model_dropdown, max_new_tokens, temperature, top_p],
|
| 361 |
+
outputs=[output_display]
|
| 362 |
)
|
| 363 |
+
|
| 364 |
+
add_conv_btn.click(
|
| 365 |
+
fn=clear_all,
|
| 366 |
+
outputs=[media_file_path, image_display, video_display, output_display]
|
| 367 |
)
|
| 368 |
|
| 369 |
+
|
| 370 |
if __name__ == "__main__":
|
| 371 |
+
demo.queue(max_size=50).launch(share=True, show_error=True)
|