Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,30 +1,27 @@
|
|
1 |
-
import os
|
2 |
-
import random
|
3 |
-
import uuid
|
4 |
-
import json
|
5 |
-
import time
|
6 |
-
import re
|
7 |
-
from threading import Thread
|
8 |
-
from datetime import datetime, timedelta
|
9 |
-
|
10 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
11 |
import torch
|
12 |
-
import
|
13 |
-
|
|
|
|
|
14 |
import cv2
|
15 |
-
|
16 |
-
|
|
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
# -----------------------------------------------------------------------------
|
21 |
-
MAX_MAX_NEW_TOKENS = 2048
|
22 |
-
DEFAULT_MAX_NEW_TOKENS = 1024
|
23 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
24 |
|
25 |
-
#
|
26 |
# Helper Functions
|
27 |
-
#
|
|
|
28 |
def progress_bar_html(label: str) -> str:
|
29 |
return f'''
|
30 |
<div style="display: flex; align-items: center;">
|
@@ -41,165 +38,218 @@ def progress_bar_html(label: str) -> str:
|
|
41 |
</style>
|
42 |
'''
|
43 |
|
44 |
-
def
|
45 |
-
"""
|
46 |
-
Download and load a system prompt template from the given Hugging Face repo.
|
47 |
-
The template may include placeholders (e.g. {name}, {today}, {yesterday}) that get formatted.
|
48 |
-
"""
|
49 |
-
file_path = hf_hub_download(repo_id=repo_id, filename=filename)
|
50 |
-
with open(file_path, "r") as file:
|
51 |
-
system_prompt = file.read()
|
52 |
-
today = datetime.today().strftime("%Y-%m-%d")
|
53 |
-
yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
|
54 |
-
model_name = repo_id.split("/")[-1]
|
55 |
-
return system_prompt.format(name=model_name, today=today, yesterday=yesterday)
|
56 |
-
|
57 |
-
def downsample_video(video_path: str):
|
58 |
-
"""
|
59 |
-
Extracts 10 evenly spaced frames from the video.
|
60 |
-
Returns a list of tuples (PIL.Image, timestamp_in_seconds).
|
61 |
-
"""
|
62 |
vidcap = cv2.VideoCapture(video_path)
|
63 |
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
|
64 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
65 |
frames = []
|
66 |
-
if total_frames
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
76 |
vidcap.release()
|
77 |
return frames
|
78 |
|
79 |
-
def
|
80 |
-
""
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
#
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
for
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
model =
|
109 |
-
|
110 |
-
torch_dtype=torch.
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
def generate(
|
120 |
-
input_dict: dict,
|
121 |
-
chat_history: list,
|
122 |
-
max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
123 |
-
temperature: float = 0.6,
|
124 |
-
top_p: float = 0.9,
|
125 |
-
top_k: int = 50,
|
126 |
-
repetition_penalty: float = 1.2,
|
127 |
-
):
|
128 |
-
text = input_dict.get("text", "")
|
129 |
files = input_dict.get("files", [])
|
130 |
|
131 |
-
#
|
132 |
video_extensions = (".mp4", ".mov", ".avi", ".mkv", ".webm")
|
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 |
demo = gr.ChatInterface(
|
177 |
-
fn=
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50),
|
183 |
-
gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2),
|
184 |
-
],
|
185 |
-
examples=[
|
186 |
-
[{"text": "Describe the content of the video.", "files": ["examples/sample_video.mp4"]}],
|
187 |
-
[{"text": "Explain what is in this image.", "files": ["examples/sample_image.jpg"]}],
|
188 |
-
["Tell me a fun fact about space."],
|
189 |
-
],
|
190 |
-
cache_examples=False,
|
191 |
-
type="messages",
|
192 |
-
description="# **Mistral Chatbot with Video Inference**\nA chatbot built with Mistral (via Transformers) that supports text, image, and video (frame extraction) inputs.",
|
193 |
-
fill_height=True,
|
194 |
-
textbox=gr.MultimodalTextbox(
|
195 |
-
label="Query Input",
|
196 |
-
file_types=["image", "video"],
|
197 |
-
file_count="multiple",
|
198 |
-
placeholder="Type your message here. Optionally attach images or video."
|
199 |
),
|
|
|
|
|
200 |
stop_btn="Stop Generation",
|
201 |
multimodal=True,
|
|
|
202 |
)
|
203 |
|
204 |
if __name__ == "__main__":
|
205 |
-
demo.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoProcessor, AutoModelForVision2Seq, TextIteratorStreamer
|
3 |
+
from transformers.image_utils import load_image
|
4 |
+
from threading import Thread
|
5 |
+
import re
|
6 |
+
import time
|
7 |
import torch
|
8 |
+
import spaces
|
9 |
+
import ast
|
10 |
+
import html
|
11 |
+
import random
|
12 |
import cv2
|
13 |
+
import numpy as np
|
14 |
+
import uuid
|
15 |
+
|
16 |
+
from PIL import Image, ImageOps
|
17 |
|
18 |
+
from docling_core.types.doc import DoclingDocument
|
19 |
+
from docling_core.types.doc.document import DocTagsDocument
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# ---------------------------
|
22 |
# Helper Functions
|
23 |
+
# ---------------------------
|
24 |
+
|
25 |
def progress_bar_html(label: str) -> str:
|
26 |
return f'''
|
27 |
<div style="display: flex; align-items: center;">
|
|
|
38 |
</style>
|
39 |
'''
|
40 |
|
41 |
+
def downsample_video(video_path, num_frames=10):
|
42 |
+
"""Downsamples a video to a fixed number of evenly spaced frames."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
vidcap = cv2.VideoCapture(video_path)
|
44 |
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
|
45 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
46 |
frames = []
|
47 |
+
if total_frames <= 0 or fps <= 0:
|
48 |
+
vidcap.release()
|
49 |
+
return frames
|
50 |
+
# Get indices for num_frames evenly spaced frames.
|
51 |
+
frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
|
52 |
+
for i in frame_indices:
|
53 |
+
vidcap.set(cv2.CAP_PROP_POS_FRAMES, i)
|
54 |
+
success, image = vidcap.read()
|
55 |
+
if success:
|
56 |
+
# Convert from BGR (OpenCV) to RGB (PIL) and then to PIL Image.
|
57 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
58 |
+
pil_image = Image.fromarray(image)
|
59 |
+
timestamp = round(i / fps, 2)
|
60 |
+
frames.append((pil_image, timestamp))
|
61 |
vidcap.release()
|
62 |
return frames
|
63 |
|
64 |
+
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
65 |
+
image = image.convert("RGB")
|
66 |
+
width, height = image.size
|
67 |
+
pad_w_percent = random.uniform(min_percent, max_percent)
|
68 |
+
pad_h_percent = random.uniform(min_percent, max_percent)
|
69 |
+
pad_w = int(width * pad_w_percent)
|
70 |
+
pad_h = int(height * pad_h_percent)
|
71 |
+
corner_pixel = image.getpixel((0, 0)) # Top-left corner for padding color
|
72 |
+
padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
73 |
+
return padded_image
|
74 |
+
|
75 |
+
def normalize_values(text, target_max=500):
|
76 |
+
def normalize_list(values):
|
77 |
+
max_value = max(values) if values else 1
|
78 |
+
return [round((v / max_value) * target_max) for v in values]
|
79 |
+
|
80 |
+
def process_match(match):
|
81 |
+
num_list = ast.literal_eval(match.group(0))
|
82 |
+
normalized = normalize_list(num_list)
|
83 |
+
return "".join([f"<loc_{num}>" for num in normalized])
|
84 |
+
|
85 |
+
pattern = r"\[([\d\.\s,]+)\]"
|
86 |
+
normalized_text = re.sub(pattern, process_match, text)
|
87 |
+
return normalized_text
|
88 |
+
|
89 |
+
# ---------------------------
|
90 |
+
# Model & Processor Setup
|
91 |
+
# ---------------------------
|
92 |
+
processor = AutoProcessor.from_pretrained("ds4sd/SmolDocling-256M-preview")
|
93 |
+
model = AutoModelForVision2Seq.from_pretrained(
|
94 |
+
"ds4sd/SmolDocling-256M-preview",
|
95 |
+
torch_dtype=torch.bfloat16,
|
96 |
+
).to("cuda")
|
97 |
+
|
98 |
+
# ---------------------------
|
99 |
+
# Main Inference Function
|
100 |
+
# ---------------------------
|
101 |
+
@spaces.GPU
|
102 |
+
def model_inference(input_dict, history):
|
103 |
+
text = input_dict["text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
files = input_dict.get("files", [])
|
105 |
|
106 |
+
# If there are files, check if any is a video
|
107 |
video_extensions = (".mp4", ".mov", ".avi", ".mkv", ".webm")
|
108 |
+
if files and any(str(f).lower().endswith(video_extensions) for f in files):
|
109 |
+
# -------- Video Inference Branch --------
|
110 |
+
video_file = files[0] # Assume first file is a video
|
111 |
+
frames = downsample_video(video_file)
|
112 |
+
if not frames:
|
113 |
+
yield "Could not process video file."
|
114 |
+
return
|
115 |
+
images = [frame[0] for frame in frames]
|
116 |
+
timestamps = [frame[1] for frame in frames]
|
117 |
+
# Append frame timestamps to the query text.
|
118 |
+
text_with_timestamps = text + " " + " ".join([f"Frame at {ts} seconds." for ts in timestamps])
|
119 |
+
resulting_messages = [{
|
120 |
+
"role": "user",
|
121 |
+
"content": [{"type": "image"} for _ in range(len(images))] + [{"type": "text", "text": text_with_timestamps}]
|
122 |
+
}]
|
123 |
+
prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
|
124 |
+
inputs = processor(text=prompt, images=[images], return_tensors="pt").to("cuda")
|
125 |
+
|
126 |
+
yield progress_bar_html("Processing video with SmolDocling")
|
127 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=False)
|
128 |
+
generation_args = dict(inputs, streamer=streamer, max_new_tokens=8192)
|
129 |
+
thread = Thread(target=model.generate, kwargs=generation_args)
|
130 |
+
thread.start()
|
131 |
+
buffer = ""
|
132 |
+
full_output = ""
|
133 |
+
for new_text in streamer:
|
134 |
+
full_output += new_text
|
135 |
+
buffer += html.escape(new_text)
|
136 |
+
yield buffer
|
137 |
+
cleaned_output = full_output.replace("<end_of_utterance>", "").strip()
|
138 |
+
if cleaned_output:
|
139 |
+
doctag_output = cleaned_output
|
140 |
+
yield cleaned_output
|
141 |
+
if any(tag in doctag_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
142 |
+
doc = DoclingDocument(name="Document")
|
143 |
+
if "<chart>" in doctag_output:
|
144 |
+
doctag_output = doctag_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
|
145 |
+
doctag_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', doctag_output)
|
146 |
+
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([doctag_output], images)
|
147 |
+
doc.load_from_doctags(doctags_doc)
|
148 |
+
yield f"**MD Output:**\n\n{doc.export_to_markdown()}"
|
149 |
+
return
|
150 |
+
|
151 |
+
elif files:
|
152 |
+
# -------- Image Inference Branch --------
|
153 |
+
if len(files) > 1:
|
154 |
+
if "OTSL" in text or "code" in text:
|
155 |
+
images = [add_random_padding(load_image(image)) for image in files]
|
156 |
+
else:
|
157 |
+
images = [load_image(image) for image in files]
|
158 |
+
elif len(files) == 1:
|
159 |
+
if "OTSL" in text or "code" in text:
|
160 |
+
images = [add_random_padding(load_image(files[0]))]
|
161 |
+
else:
|
162 |
+
images = [load_image(files[0])]
|
163 |
+
resulting_messages = [{
|
164 |
+
"role": "user",
|
165 |
+
"content": [{"type": "image"} for _ in range(len(images))] + [{"type": "text", "text": text}]
|
166 |
+
}]
|
167 |
+
prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
|
168 |
+
inputs = processor(text=prompt, images=[images], return_tensors="pt").to("cuda")
|
169 |
+
|
170 |
+
yield progress_bar_html("Processing with SmolDocling")
|
171 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=False)
|
172 |
+
generation_args = dict(inputs, streamer=streamer, max_new_tokens=8192)
|
173 |
+
thread = Thread(target=model.generate, kwargs=generation_args)
|
174 |
+
thread.start()
|
175 |
+
yield "..."
|
176 |
+
buffer = ""
|
177 |
+
full_output = ""
|
178 |
+
for new_text in streamer:
|
179 |
+
full_output += new_text
|
180 |
+
buffer += html.escape(new_text)
|
181 |
+
yield buffer
|
182 |
+
cleaned_output = full_output.replace("<end_of_utterance>", "").strip()
|
183 |
+
if cleaned_output:
|
184 |
+
doctag_output = cleaned_output
|
185 |
+
yield cleaned_output
|
186 |
+
if any(tag in doctag_output for tag in ["<doctag>", "<otsl>", "<code>", "<chart>", "<formula>"]):
|
187 |
+
doc = DoclingDocument(name="Document")
|
188 |
+
if "<chart>" in doctag_output:
|
189 |
+
doctag_output = doctag_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
|
190 |
+
doctag_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', doctag_output)
|
191 |
+
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([doctag_output], images)
|
192 |
+
doc.load_from_doctags(doctags_doc)
|
193 |
+
yield f"**MD Output:**\n\n{doc.export_to_markdown()}"
|
194 |
+
return
|
195 |
+
|
196 |
+
else:
|
197 |
+
# -------- Text-Only Inference Branch --------
|
198 |
+
if text == "":
|
199 |
+
gr.Error("Please input a query and optionally image(s).")
|
200 |
+
resulting_messages = [{
|
201 |
+
"role": "user",
|
202 |
+
"content": [{"type": "text", "text": text}]
|
203 |
+
}]
|
204 |
+
prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
|
205 |
+
inputs = processor(text=prompt, return_tensors="pt").to("cuda")
|
206 |
+
yield progress_bar_html("Processing text with SmolDocling")
|
207 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=False)
|
208 |
+
generation_args = dict(inputs, streamer=streamer, max_new_tokens=8192)
|
209 |
+
thread = Thread(target=model.generate, kwargs=generation_args)
|
210 |
+
thread.start()
|
211 |
+
yield "..."
|
212 |
+
buffer = ""
|
213 |
+
full_output = ""
|
214 |
+
for new_text in streamer:
|
215 |
+
full_output += new_text
|
216 |
+
buffer += html.escape(new_text)
|
217 |
+
yield buffer
|
218 |
+
cleaned_output = full_output.replace("<end_of_utterance>", "").strip()
|
219 |
+
if cleaned_output:
|
220 |
+
yield cleaned_output
|
221 |
+
return
|
222 |
+
|
223 |
+
# ---------------------------
|
224 |
+
# Gradio Interface Setup
|
225 |
+
# ---------------------------
|
226 |
+
examples = [
|
227 |
+
[{"text": "Convert this page to docling.", "files": ["example_images/2d0fbcc50e88065a040a537b717620e964fb4453314b71d83f3ed3425addcef6.png"]}],
|
228 |
+
[{"text": "Convert this table to OTSL.", "files": ["example_images/image-2.jpg"]}],
|
229 |
+
[{"text": "Convert code to text.", "files": ["example_images/7666.jpg"]}],
|
230 |
+
[{"text": "Convert formula to latex.", "files": ["example_images/2433.jpg"]}],
|
231 |
+
[{"text": "Convert chart to OTSL.", "files": ["example_images/06236926002285.png"]}],
|
232 |
+
[{"text": "OCR the text in location [47, 531, 167, 565]", "files": ["example_images/s2w_example.png"]}],
|
233 |
+
[{"text": "Extract all section header elements on the page.", "files": ["example_images/paper_3.png"]}],
|
234 |
+
[{"text": "Identify element at location [123, 413, 1059, 1061]", "files": ["example_images/redhat.png"]}],
|
235 |
+
[{"text": "Convert this page to docling.", "files": ["example_images/gazette_de_france.jpg"]}],
|
236 |
+
# Example video file (if available)
|
237 |
+
[{"text": "Describe the events in this video.", "files": ["example_videos/sample_video.mp4"]}],
|
238 |
+
]
|
239 |
+
|
240 |
demo = gr.ChatInterface(
|
241 |
+
fn=model_inference,
|
242 |
+
title="SmolDocling-256M: Ultra-compact VLM for Document Conversion 💫",
|
243 |
+
description=(
|
244 |
+
"Play with [ds4sd/SmolDocling-256M-preview](https://huggingface.co/ds4sd/SmolDocling-256M-preview) in this demo. "
|
245 |
+
"Upload an image, video, and text query or try one of the examples. Each chat starts a new conversation."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
),
|
247 |
+
examples=examples,
|
248 |
+
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image", "video"], file_count="multiple"),
|
249 |
stop_btn="Stop Generation",
|
250 |
multimodal=True,
|
251 |
+
cache_examples=False
|
252 |
)
|
253 |
|
254 |
if __name__ == "__main__":
|
255 |
+
demo.launch(debug=True)
|