Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -27,6 +27,7 @@ from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
|
| 27 |
import re
|
| 28 |
import ast
|
| 29 |
import html
|
|
|
|
| 30 |
|
| 31 |
# Constants for text generation
|
| 32 |
MAX_MAX_NEW_TOKENS = 2048
|
|
@@ -44,7 +45,6 @@ model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 44 |
torch_dtype=torch.float16
|
| 45 |
).to(device).eval()
|
| 46 |
|
| 47 |
-
#-----------------------------subfolder-----------------------------#
|
| 48 |
# Load MonkeyOCR
|
| 49 |
MODEL_ID_G = "echo840/MonkeyOCR"
|
| 50 |
SUBFOLDER = "Recognition"
|
|
@@ -59,7 +59,6 @@ model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 59 |
subfolder=SUBFOLDER,
|
| 60 |
torch_dtype=torch.float16
|
| 61 |
).to(device).eval()
|
| 62 |
-
#-----------------------------subfolder-----------------------------#
|
| 63 |
|
| 64 |
# Load Typhoon-OCR-7B
|
| 65 |
MODEL_ID_L = "scb10x/typhoon-ocr-7b"
|
|
@@ -133,7 +132,6 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 133 |
top_k: int = 50,
|
| 134 |
repetition_penalty: float = 1.2):
|
| 135 |
"""Generate responses for image input using the selected model."""
|
| 136 |
-
# Model selection
|
| 137 |
if model_name == "Nanonets-OCR-s":
|
| 138 |
processor = processor_m
|
| 139 |
model = model_m
|
|
@@ -154,17 +152,14 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 154 |
yield "Please upload an image.", "Please upload an image."
|
| 155 |
return
|
| 156 |
|
| 157 |
-
# Prepare images as a list (single image for image inference)
|
| 158 |
images = [image]
|
| 159 |
|
| 160 |
-
# SmolDocling-256M specific preprocessing
|
| 161 |
if model_name == "SmolDocling-256M-preview":
|
| 162 |
if "OTSL" in text or "code" in text:
|
| 163 |
images = [add_random_padding(img) for img in images]
|
| 164 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 165 |
text = normalize_values(text, target_max=500)
|
| 166 |
|
| 167 |
-
# Unified message structure for all models
|
| 168 |
messages = [
|
| 169 |
{
|
| 170 |
"role": "user",
|
|
@@ -176,7 +171,6 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 176 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 177 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 178 |
|
| 179 |
-
# Generation with streaming
|
| 180 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 181 |
generation_kwargs = {
|
| 182 |
**inputs,
|
|
@@ -190,13 +184,11 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 190 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 191 |
thread.start()
|
| 192 |
|
| 193 |
-
# Stream output
|
| 194 |
buffer = ""
|
| 195 |
for new_text in streamer:
|
| 196 |
buffer += new_text.replace("<|im_end|>", "")
|
| 197 |
yield buffer, buffer
|
| 198 |
|
| 199 |
-
# SmolDocling-256M specific postprocessing
|
| 200 |
if model_name == "SmolDocling-256M-preview":
|
| 201 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
| 202 |
if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
|
@@ -218,7 +210,6 @@ def generate_video(model_name: str, text: str, video_path: str,
|
|
| 218 |
top_k: int = 50,
|
| 219 |
repetition_penalty: float = 1.2):
|
| 220 |
"""Generate responses for video input using the selected model."""
|
| 221 |
-
# Model selection
|
| 222 |
if model_name == "Nanonets-OCR-s":
|
| 223 |
processor = processor_m
|
| 224 |
model = model_m
|
|
@@ -239,18 +230,15 @@ def generate_video(model_name: str, text: str, video_path: str,
|
|
| 239 |
yield "Please upload a video.", "Please upload a video."
|
| 240 |
return
|
| 241 |
|
| 242 |
-
# Extract frames from video
|
| 243 |
frames = downsample_video(video_path)
|
| 244 |
images = [frame for frame, _ in frames]
|
| 245 |
|
| 246 |
-
# SmolDocling-256M specific preprocessing
|
| 247 |
if model_name == "SmolDocling-256M-preview":
|
| 248 |
if "OTSL" in text or "code" in text:
|
| 249 |
images = [add_random_padding(img) for img in images]
|
| 250 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 251 |
text = normalize_values(text, target_max=500)
|
| 252 |
|
| 253 |
-
# Unified message structure for all models
|
| 254 |
messages = [
|
| 255 |
{
|
| 256 |
"role": "user",
|
|
@@ -262,7 +250,6 @@ def generate_video(model_name: str, text: str, video_path: str,
|
|
| 262 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 263 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 264 |
|
| 265 |
-
# Generation with streaming
|
| 266 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 267 |
generation_kwargs = {
|
| 268 |
**inputs,
|
|
@@ -276,13 +263,11 @@ def generate_video(model_name: str, text: str, video_path: str,
|
|
| 276 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 277 |
thread.start()
|
| 278 |
|
| 279 |
-
# Stream output
|
| 280 |
buffer = ""
|
| 281 |
for new_text in streamer:
|
| 282 |
buffer += new_text.replace("<|im_end|>", "")
|
| 283 |
yield buffer, buffer
|
| 284 |
|
| 285 |
-
# SmolDocling-256M specific postprocessing
|
| 286 |
if model_name == "SmolDocling-256M-preview":
|
| 287 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
| 288 |
if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
|
@@ -313,20 +298,84 @@ video_examples = [
|
|
| 313 |
["Explain the video in detail.", "videos/2.mp4"]
|
| 314 |
]
|
| 315 |
|
| 316 |
-
#
|
| 317 |
-
|
| 318 |
-
.
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
"""
|
| 331 |
|
| 332 |
# Create the Gradio Interface
|
|
@@ -338,7 +387,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
|
|
| 338 |
with gr.TabItem("Image Inference"):
|
| 339 |
image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
|
| 340 |
image_upload = gr.Image(type="pil", label="Image")
|
| 341 |
-
image_submit = gr.Button("Submit", elem_classes="
|
| 342 |
gr.Examples(
|
| 343 |
examples=image_examples,
|
| 344 |
inputs=[image_query, image_upload]
|
|
@@ -346,7 +395,7 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
|
|
| 346 |
with gr.TabItem("Video Inference"):
|
| 347 |
video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
|
| 348 |
video_upload = gr.Video(label="Video")
|
| 349 |
-
video_submit = gr.Button("Submit", elem_classes="
|
| 350 |
gr.Examples(
|
| 351 |
examples=video_examples,
|
| 352 |
inputs=[video_query, video_upload]
|
|
@@ -354,12 +403,11 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
|
|
| 354 |
with gr.Accordion("Advanced options", open=False):
|
| 355 |
max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
|
| 356 |
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
|
| 357 |
-
top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.
|
| 358 |
top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
|
| 359 |
repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
|
| 360 |
|
| 361 |
with gr.Column():
|
| 362 |
-
# Result Canvas with raw and formatted outputs
|
| 363 |
with gr.Column(elem_classes="canvas-output"):
|
| 364 |
gr.Markdown("## Output")
|
| 365 |
raw_output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=2)
|
|
@@ -380,7 +428,6 @@ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
|
|
| 380 |
gr.Markdown("> [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.")
|
| 381 |
gr.Markdown(">⚠️note: all the models in space are not guaranteed to perform well in video inference use cases.")
|
| 382 |
|
| 383 |
-
# Connect submit buttons to generation functions with both outputs
|
| 384 |
image_submit.click(
|
| 385 |
fn=generate_image,
|
| 386 |
inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
|
|
|
|
| 27 |
import re
|
| 28 |
import ast
|
| 29 |
import html
|
| 30 |
+
import urllib.parse
|
| 31 |
|
| 32 |
# Constants for text generation
|
| 33 |
MAX_MAX_NEW_TOKENS = 2048
|
|
|
|
| 45 |
torch_dtype=torch.float16
|
| 46 |
).to(device).eval()
|
| 47 |
|
|
|
|
| 48 |
# Load MonkeyOCR
|
| 49 |
MODEL_ID_G = "echo840/MonkeyOCR"
|
| 50 |
SUBFOLDER = "Recognition"
|
|
|
|
| 59 |
subfolder=SUBFOLDER,
|
| 60 |
torch_dtype=torch.float16
|
| 61 |
).to(device).eval()
|
|
|
|
| 62 |
|
| 63 |
# Load Typhoon-OCR-7B
|
| 64 |
MODEL_ID_L = "scb10x/typhoon-ocr-7b"
|
|
|
|
| 132 |
top_k: int = 50,
|
| 133 |
repetition_penalty: float = 1.2):
|
| 134 |
"""Generate responses for image input using the selected model."""
|
|
|
|
| 135 |
if model_name == "Nanonets-OCR-s":
|
| 136 |
processor = processor_m
|
| 137 |
model = model_m
|
|
|
|
| 152 |
yield "Please upload an image.", "Please upload an image."
|
| 153 |
return
|
| 154 |
|
|
|
|
| 155 |
images = [image]
|
| 156 |
|
|
|
|
| 157 |
if model_name == "SmolDocling-256M-preview":
|
| 158 |
if "OTSL" in text or "code" in text:
|
| 159 |
images = [add_random_padding(img) for img in images]
|
| 160 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 161 |
text = normalize_values(text, target_max=500)
|
| 162 |
|
|
|
|
| 163 |
messages = [
|
| 164 |
{
|
| 165 |
"role": "user",
|
|
|
|
| 171 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 172 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 173 |
|
|
|
|
| 174 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 175 |
generation_kwargs = {
|
| 176 |
**inputs,
|
|
|
|
| 184 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 185 |
thread.start()
|
| 186 |
|
|
|
|
| 187 |
buffer = ""
|
| 188 |
for new_text in streamer:
|
| 189 |
buffer += new_text.replace("<|im_end|>", "")
|
| 190 |
yield buffer, buffer
|
| 191 |
|
|
|
|
| 192 |
if model_name == "SmolDocling-256M-preview":
|
| 193 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
| 194 |
if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
|
|
|
| 210 |
top_k: int = 50,
|
| 211 |
repetition_penalty: float = 1.2):
|
| 212 |
"""Generate responses for video input using the selected model."""
|
|
|
|
| 213 |
if model_name == "Nanonets-OCR-s":
|
| 214 |
processor = processor_m
|
| 215 |
model = model_m
|
|
|
|
| 230 |
yield "Please upload a video.", "Please upload a video."
|
| 231 |
return
|
| 232 |
|
|
|
|
| 233 |
frames = downsample_video(video_path)
|
| 234 |
images = [frame for frame, _ in frames]
|
| 235 |
|
|
|
|
| 236 |
if model_name == "SmolDocling-256M-preview":
|
| 237 |
if "OTSL" in text or "code" in text:
|
| 238 |
images = [add_random_padding(img) for img in images]
|
| 239 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 240 |
text = normalize_values(text, target_max=500)
|
| 241 |
|
|
|
|
| 242 |
messages = [
|
| 243 |
{
|
| 244 |
"role": "user",
|
|
|
|
| 250 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 251 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 252 |
|
|
|
|
| 253 |
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
| 254 |
generation_kwargs = {
|
| 255 |
**inputs,
|
|
|
|
| 263 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 264 |
thread.start()
|
| 265 |
|
|
|
|
| 266 |
buffer = ""
|
| 267 |
for new_text in streamer:
|
| 268 |
buffer += new_text.replace("<|im_end|>", "")
|
| 269 |
yield buffer, buffer
|
| 270 |
|
|
|
|
| 271 |
if model_name == "SmolDocling-256M-preview":
|
| 272 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
| 273 |
if any(tag in cleaned_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
|
|
|
| 298 |
["Explain the video in detail.", "videos/2.mp4"]
|
| 299 |
]
|
| 300 |
|
| 301 |
+
# SVG data URL for the button icon
|
| 302 |
+
svg_code = '''
|
| 303 |
+
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5">
|
| 304 |
+
<polyline points="13.18 1.37 13.18 9.64 21.45 9.64 10.82 22.63 10.82 14.36 2.55 14.36 13.18 1.37"></polyline>
|
| 305 |
+
</svg>
|
| 306 |
+
'''
|
| 307 |
+
svg_data_url = 'data:image/svg+xml,' + urllib.parse.quote(svg_code)
|
| 308 |
+
|
| 309 |
+
# Updated CSS with fancy-button styles
|
| 310 |
+
css = f"""
|
| 311 |
+
.fancy-button {{
|
| 312 |
+
--round: 0.75rem;
|
| 313 |
+
cursor: pointer;
|
| 314 |
+
position: relative;
|
| 315 |
+
display: inline-flex;
|
| 316 |
+
align-items: center;
|
| 317 |
+
justify-content: center;
|
| 318 |
+
overflow: hidden;
|
| 319 |
+
transition: all 0.25s ease;
|
| 320 |
+
background: radial-gradient(
|
| 321 |
+
65.28% 65.28% at 50% 100%,
|
| 322 |
+
rgba(223, 113, 255, 0.8) 0%,
|
| 323 |
+
rgba(223, 113, 255, 0) 100%
|
| 324 |
+
),
|
| 325 |
+
linear-gradient(0deg, #7a5af8, #7a5af8);
|
| 326 |
+
border-radius: var(--round);
|
| 327 |
+
border: none;
|
| 328 |
+
outline: none;
|
| 329 |
+
padding: 12px 18px 12px 40px;
|
| 330 |
+
color: white;
|
| 331 |
+
font-size: 16px;
|
| 332 |
+
font-weight: 500;
|
| 333 |
+
}}
|
| 334 |
+
|
| 335 |
+
.fancy-button::before {{
|
| 336 |
+
content: '';
|
| 337 |
+
position: absolute;
|
| 338 |
+
left: 10px;
|
| 339 |
+
top: 50%;
|
| 340 |
+
transform: translateY(-50%);
|
| 341 |
+
width: 18px;
|
| 342 |
+
height: 18px;
|
| 343 |
+
background: url('{svg_data_url}') no-repeat center;
|
| 344 |
+
background-size: contain;
|
| 345 |
+
}}
|
| 346 |
+
|
| 347 |
+
.fancy-button::after {{
|
| 348 |
+
content: '';
|
| 349 |
+
position: absolute;
|
| 350 |
+
top: 0;
|
| 351 |
+
right: 0;
|
| 352 |
+
width: 1rem;
|
| 353 |
+
height: 1rem;
|
| 354 |
+
background: radial-gradient(
|
| 355 |
+
100% 75% at 55%,
|
| 356 |
+
rgba(223, 113, 255, 0.8) 0%,
|
| 357 |
+
rgba(223, 113, 255, 0) 100%
|
| 358 |
+
);
|
| 359 |
+
box-shadow: 0 0 3px black;
|
| 360 |
+
border-bottom-left-radius: 0.5rem;
|
| 361 |
+
border-top-right-radius: var(--round);
|
| 362 |
+
transition: all 0.5s ease-in-out;
|
| 363 |
+
}}
|
| 364 |
+
|
| 365 |
+
.fancy-button:hover::after {{
|
| 366 |
+
margin-top: -1rem;
|
| 367 |
+
margin-right: -1rem;
|
| 368 |
+
}}
|
| 369 |
+
|
| 370 |
+
.fancy-button:active {{
|
| 371 |
+
transform: scale(0.95);
|
| 372 |
+
}}
|
| 373 |
+
|
| 374 |
+
.canvas-output {{
|
| 375 |
+
border: 2px solid #4682B4;
|
| 376 |
+
border-radius: 10px;
|
| 377 |
+
padding: 20px;
|
| 378 |
+
}}
|
| 379 |
"""
|
| 380 |
|
| 381 |
# Create the Gradio Interface
|
|
|
|
| 387 |
with gr.TabItem("Image Inference"):
|
| 388 |
image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
|
| 389 |
image_upload = gr.Image(type="pil", label="Image")
|
| 390 |
+
image_submit = gr.Button("Submit", elem_classes="fancy-button")
|
| 391 |
gr.Examples(
|
| 392 |
examples=image_examples,
|
| 393 |
inputs=[image_query, image_upload]
|
|
|
|
| 395 |
with gr.TabItem("Video Inference"):
|
| 396 |
video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
|
| 397 |
video_upload = gr.Video(label="Video")
|
| 398 |
+
video_submit = gr.Button("Submit", elem_classes="fancy-button")
|
| 399 |
gr.Examples(
|
| 400 |
examples=video_examples,
|
| 401 |
inputs=[video_query, video_upload]
|
|
|
|
| 403 |
with gr.Accordion("Advanced options", open=False):
|
| 404 |
max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
|
| 405 |
temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
|
| 406 |
+
top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.
|
| 407 |
top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
|
| 408 |
repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
|
| 409 |
|
| 410 |
with gr.Column():
|
|
|
|
| 411 |
with gr.Column(elem_classes="canvas-output"):
|
| 412 |
gr.Markdown("## Output")
|
| 413 |
raw_output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=2)
|
|
|
|
| 428 |
gr.Markdown("> [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.")
|
| 429 |
gr.Markdown(">⚠️note: all the models in space are not guaranteed to perform well in video inference use cases.")
|
| 430 |
|
|
|
|
| 431 |
image_submit.click(
|
| 432 |
fn=generate_image,
|
| 433 |
inputs=[model_choice, image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
|