Spaces:
Running
on
Zero
Running
on
Zero
Upload 15 files
Browse files- .gitattributes +6 -0
- README.md +6 -5
- app.py +146 -148
- example_images/06236926002285.png +0 -0
- example_images/2433.jpg +0 -0
- example_images/2d0fbcc50e88065a040a537b717620e964fb4453314b71d83f3ed3425addcef6.png +3 -0
- example_images/7666.jpg +0 -0
- example_images/annual_rep_14.png +3 -0
- example_images/annual_rep_15.png +3 -0
- example_images/examples_invoice.png +0 -0
- example_images/gazette_de_france.jpg +3 -0
- example_images/image-2.jpg +0 -0
- example_images/paper_3.png +3 -0
- example_images/redhat.png +3 -0
- example_images/s2w_example.png +0 -0
- requirements.txt +6 -4
.gitattributes
CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
example_images/2d0fbcc50e88065a040a537b717620e964fb4453314b71d83f3ed3425addcef6.png filter=lfs diff=lfs merge=lfs -text
|
37 |
+
example_images/annual_rep_14.png filter=lfs diff=lfs merge=lfs -text
|
38 |
+
example_images/annual_rep_15.png filter=lfs diff=lfs merge=lfs -text
|
39 |
+
example_images/gazette_de_france.jpg filter=lfs diff=lfs merge=lfs -text
|
40 |
+
example_images/paper_3.png filter=lfs diff=lfs merge=lfs -text
|
41 |
+
example_images/redhat.png filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 5.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
10 |
---
|
11 |
|
12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: SmolVLM
|
3 |
+
emoji: π
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: green
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.12.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: apache-2.0
|
11 |
---
|
12 |
|
13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
@@ -1,154 +1,152 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
import
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
import torch
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
|
10 |
-
model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
|
11 |
-
|
12 |
-
if torch.cuda.is_available():
|
13 |
-
torch_dtype = torch.float16
|
14 |
-
else:
|
15 |
-
torch_dtype = torch.float32
|
16 |
-
|
17 |
-
pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
|
18 |
-
pipe = pipe.to(device)
|
19 |
-
|
20 |
-
MAX_SEED = np.iinfo(np.int32).max
|
21 |
-
MAX_IMAGE_SIZE = 1024
|
22 |
-
|
23 |
-
|
24 |
-
# @spaces.GPU #[uncomment to use ZeroGPU]
|
25 |
-
def infer(
|
26 |
-
prompt,
|
27 |
-
negative_prompt,
|
28 |
-
seed,
|
29 |
-
randomize_seed,
|
30 |
-
width,
|
31 |
-
height,
|
32 |
-
guidance_scale,
|
33 |
-
num_inference_steps,
|
34 |
-
progress=gr.Progress(track_tqdm=True),
|
35 |
-
):
|
36 |
-
if randomize_seed:
|
37 |
-
seed = random.randint(0, MAX_SEED)
|
38 |
-
|
39 |
-
generator = torch.Generator().manual_seed(seed)
|
40 |
-
|
41 |
-
image = pipe(
|
42 |
-
prompt=prompt,
|
43 |
-
negative_prompt=negative_prompt,
|
44 |
-
guidance_scale=guidance_scale,
|
45 |
-
num_inference_steps=num_inference_steps,
|
46 |
-
width=width,
|
47 |
-
height=height,
|
48 |
-
generator=generator,
|
49 |
-
).images[0]
|
50 |
-
|
51 |
-
return image, seed
|
52 |
-
|
53 |
-
|
54 |
-
examples = [
|
55 |
-
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
56 |
-
"An astronaut riding a green horse",
|
57 |
-
"A delicious ceviche cheesecake slice",
|
58 |
-
]
|
59 |
-
|
60 |
-
css = """
|
61 |
-
#col-container {
|
62 |
-
margin: 0 auto;
|
63 |
-
max-width: 640px;
|
64 |
-
}
|
65 |
-
"""
|
66 |
-
|
67 |
-
with gr.Blocks(css=css) as demo:
|
68 |
-
with gr.Column(elem_id="col-container"):
|
69 |
-
gr.Markdown(" # Text-to-Image Gradio Template")
|
70 |
-
|
71 |
-
with gr.Row():
|
72 |
-
prompt = gr.Text(
|
73 |
-
label="Prompt",
|
74 |
-
show_label=False,
|
75 |
-
max_lines=1,
|
76 |
-
placeholder="Enter your prompt",
|
77 |
-
container=False,
|
78 |
-
)
|
79 |
-
|
80 |
-
run_button = gr.Button("Run", scale=0, variant="primary")
|
81 |
-
|
82 |
-
result = gr.Image(label="Result", show_label=False)
|
83 |
-
|
84 |
-
with gr.Accordion("Advanced Settings", open=False):
|
85 |
-
negative_prompt = gr.Text(
|
86 |
-
label="Negative prompt",
|
87 |
-
max_lines=1,
|
88 |
-
placeholder="Enter a negative prompt",
|
89 |
-
visible=False,
|
90 |
-
)
|
91 |
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
)
|
99 |
|
100 |
-
|
101 |
-
|
102 |
-
with gr.Row():
|
103 |
-
width = gr.Slider(
|
104 |
-
label="Width",
|
105 |
-
minimum=256,
|
106 |
-
maximum=MAX_IMAGE_SIZE,
|
107 |
-
step=32,
|
108 |
-
value=1024, # Replace with defaults that work for your model
|
109 |
-
)
|
110 |
-
|
111 |
-
height = gr.Slider(
|
112 |
-
label="Height",
|
113 |
-
minimum=256,
|
114 |
-
maximum=MAX_IMAGE_SIZE,
|
115 |
-
step=32,
|
116 |
-
value=1024, # Replace with defaults that work for your model
|
117 |
-
)
|
118 |
-
|
119 |
-
with gr.Row():
|
120 |
-
guidance_scale = gr.Slider(
|
121 |
-
label="Guidance scale",
|
122 |
-
minimum=0.0,
|
123 |
-
maximum=10.0,
|
124 |
-
step=0.1,
|
125 |
-
value=0.0, # Replace with defaults that work for your model
|
126 |
-
)
|
127 |
-
|
128 |
-
num_inference_steps = gr.Slider(
|
129 |
-
label="Number of inference steps",
|
130 |
-
minimum=1,
|
131 |
-
maximum=50,
|
132 |
-
step=1,
|
133 |
-
value=2, # Replace with defaults that work for your model
|
134 |
-
)
|
135 |
-
|
136 |
-
gr.Examples(examples=examples, inputs=[prompt])
|
137 |
-
gr.on(
|
138 |
-
triggers=[run_button.click, prompt.submit],
|
139 |
-
fn=infer,
|
140 |
-
inputs=[
|
141 |
-
prompt,
|
142 |
-
negative_prompt,
|
143 |
-
seed,
|
144 |
-
randomize_seed,
|
145 |
-
width,
|
146 |
-
height,
|
147 |
-
guidance_scale,
|
148 |
-
num_inference_steps,
|
149 |
-
],
|
150 |
-
outputs=[result, seed],
|
151 |
-
)
|
152 |
-
|
153 |
-
if __name__ == "__main__":
|
154 |
-
demo.launch()
|
|
|
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 re
|
10 |
+
import ast
|
11 |
+
import html
|
12 |
+
import random
|
13 |
|
14 |
+
from PIL import Image, ImageOps
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
from docling_core.types.doc import DoclingDocument
|
17 |
+
from docling_core.types.doc.document import DocTagsDocument
|
18 |
+
|
19 |
+
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
20 |
+
image = image.convert("RGB")
|
21 |
+
|
22 |
+
width, height = image.size
|
23 |
+
|
24 |
+
pad_w_percent = random.uniform(min_percent, max_percent)
|
25 |
+
pad_h_percent = random.uniform(min_percent, max_percent)
|
26 |
+
|
27 |
+
pad_w = int(width * pad_w_percent)
|
28 |
+
pad_h = int(height * pad_h_percent)
|
29 |
+
|
30 |
+
corner_pixel = image.getpixel((0, 0)) # Top-left corner
|
31 |
+
padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
32 |
+
|
33 |
+
return padded_image
|
34 |
+
|
35 |
+
def normalize_values(text, target_max=500):
|
36 |
+
def normalize_list(values):
|
37 |
+
max_value = max(values) if values else 1
|
38 |
+
return [round((v / max_value) * target_max) for v in values]
|
39 |
+
|
40 |
+
def process_match(match):
|
41 |
+
num_list = ast.literal_eval(match.group(0))
|
42 |
+
normalized = normalize_list(num_list)
|
43 |
+
return "".join([f"<loc_{num}>" for num in normalized])
|
44 |
+
|
45 |
+
pattern = r"\[([\d\.\s,]+)\]"
|
46 |
+
normalized_text = re.sub(pattern, process_match, text)
|
47 |
+
return normalized_text
|
48 |
+
|
49 |
+
|
50 |
+
processor = AutoProcessor.from_pretrained("ds4sd/SmolDocling-256M-preview")
|
51 |
+
model = AutoModelForVision2Seq.from_pretrained("ds4sd/SmolDocling-256M-preview",
|
52 |
+
torch_dtype=torch.bfloat16,
|
53 |
+
#_attn_implementation="flash_attention_2"
|
54 |
+
).to("cuda")
|
55 |
+
|
56 |
+
@spaces.GPU
|
57 |
+
def model_inference(
|
58 |
+
input_dict, history
|
59 |
+
):
|
60 |
+
text = input_dict["text"]
|
61 |
+
print(input_dict["files"])
|
62 |
+
if len(input_dict["files"]) > 1:
|
63 |
+
if "OTSL" in text or "code" in text:
|
64 |
+
images = [add_random_padding(load_image(image)) for image in input_dict["files"]]
|
65 |
+
else:
|
66 |
+
images = [load_image(image) for image in input_dict["files"]]
|
67 |
+
|
68 |
+
elif len(input_dict["files"]) == 1:
|
69 |
+
if "OTSL" in text or "code" in text:
|
70 |
+
images = [add_random_padding(load_image(input_dict["files"][0]))]
|
71 |
+
else:
|
72 |
+
images = [load_image(input_dict["files"][0])]
|
73 |
+
|
74 |
+
else:
|
75 |
+
images = []
|
76 |
+
|
77 |
+
if text == "" and not images:
|
78 |
+
gr.Error("Please input a query and optionally image(s).")
|
79 |
+
|
80 |
+
if text == "" and images:
|
81 |
+
gr.Error("Please input a text query along the image(s).")
|
82 |
+
|
83 |
+
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
84 |
+
text = normalize_values(text, target_max=500)
|
85 |
+
|
86 |
+
resulting_messages = [
|
87 |
+
{
|
88 |
+
"role": "user",
|
89 |
+
"content": [{"type": "image"} for _ in range(len(images))] + [
|
90 |
+
{"type": "text", "text": text}
|
91 |
+
]
|
92 |
+
}
|
93 |
+
]
|
94 |
+
prompt = processor.apply_chat_template(resulting_messages, add_generation_prompt=True)
|
95 |
+
inputs = processor(text=prompt, images=[images], return_tensors="pt").to('cuda')
|
96 |
+
|
97 |
+
generation_args = {
|
98 |
+
"input_ids": inputs.input_ids,
|
99 |
+
"pixel_values": inputs.pixel_values,
|
100 |
+
"attention_mask": inputs.attention_mask,
|
101 |
+
"num_return_sequences": 1,
|
102 |
+
"no_repeat_ngram_size": 10,
|
103 |
+
"max_new_tokens": 8192,
|
104 |
+
}
|
105 |
+
|
106 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=False)
|
107 |
+
generation_args = dict(inputs, streamer=streamer, max_new_tokens=8192)
|
108 |
+
|
109 |
+
thread = Thread(target=model.generate, kwargs=generation_args)
|
110 |
+
thread.start()
|
111 |
+
|
112 |
+
yield "..."
|
113 |
+
buffer = ""
|
114 |
+
doctag_output = ""
|
115 |
+
|
116 |
+
for new_text in streamer:
|
117 |
+
if new_text != "<end_of_utterance>":
|
118 |
+
buffer += html.escape(new_text)
|
119 |
+
doctag_output += new_text
|
120 |
+
yield buffer
|
121 |
+
|
122 |
+
if any(tag in doctag_output for tag in ["<doctag>", "<otsl>", "<code>", "<formula>", "<chart>"]):
|
123 |
+
# final_output = buffer
|
124 |
+
# cleaned_output = final_output[len(inputs.input_ids):] if len(final_output) > prompt_length else final_output
|
125 |
+
doc = DoclingDocument(name="Document")
|
126 |
+
if "<chart>" in doctag_output:
|
127 |
+
doctag_output = doctag_output.replace("<chart>", "<otsl>").replace("</chart>", "</otsl>")
|
128 |
+
doctag_output = re.sub(r'(<loc_500>)(?!.*<loc_500>)<[^>]+>', r'\1', doctag_output)
|
129 |
+
|
130 |
+
doctags_doc = DocTagsDocument.from_doctags_and_image_pairs([doctag_output], images)
|
131 |
+
doc.load_from_doctags(doctags_doc)
|
132 |
+
yield f"**MD Output:**\n\n{doc.export_to_markdown()}"
|
133 |
+
|
134 |
+
examples=[[{"text": "Convert this page to docling.", "files": ["example_images/2d0fbcc50e88065a040a537b717620e964fb4453314b71d83f3ed3425addcef6.png"]}],
|
135 |
+
[{"text": "Convert this table to OTSL.", "files": ["example_images/image-2.jpg"]}],
|
136 |
+
[{"text": "Convert code to text.", "files": ["example_images/7666.jpg"]}],
|
137 |
+
[{"text": "Convert formula to latex.", "files": ["example_images/2433.jpg"]}],
|
138 |
+
[{"text": "Convert chart to OTSL.", "files": ["example_images/06236926002285.png"]}],
|
139 |
+
[{"text": "OCR the text in location [47, 531, 167, 565]", "files": ["example_images/s2w_example.png"]}],
|
140 |
+
[{"text": "Extract all section header elements on the page.", "files": ["example_images/paper_3.png"]}],
|
141 |
+
[{"text": "Identify element at location [123, 413, 1059, 1061]", "files": ["example_images/redhat.png"]}],
|
142 |
+
[{"text": "Convert this page to docling.", "files": ["example_images/gazette_de_france.jpg"]}],
|
143 |
+
]
|
144 |
+
|
145 |
+
demo = gr.ChatInterface(fn=model_inference, title="SmolDocling-256M: Ultra-compact VLM for Document Conversion π«",
|
146 |
+
description="Play with [ds4sd/SmolDocling-256M-preview](https://huggingface.co/ds4sd/SmolDocling-256M-preview) in this demo. To get started, upload an image and text or try one of the examples. This demo doesn't use history for the chat, so every chat you start is a new conversation.",
|
147 |
+
examples=examples,
|
148 |
+
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple"), stop_btn="Stop Generation", multimodal=True,
|
149 |
+
cache_examples=False
|
150 |
)
|
151 |
|
152 |
+
demo.launch(debug=True, share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
example_images/06236926002285.png
ADDED
![]() |
example_images/2433.jpg
ADDED
![]() |
example_images/2d0fbcc50e88065a040a537b717620e964fb4453314b71d83f3ed3425addcef6.png
ADDED
![]() |
Git LFS Details
|
example_images/7666.jpg
ADDED
![]() |
example_images/annual_rep_14.png
ADDED
![]() |
Git LFS Details
|
example_images/annual_rep_15.png
ADDED
![]() |
Git LFS Details
|
example_images/examples_invoice.png
ADDED
![]() |
example_images/gazette_de_france.jpg
ADDED
![]() |
Git LFS Details
|
example_images/image-2.jpg
ADDED
![]() |
example_images/paper_3.png
ADDED
![]() |
Git LFS Details
|
example_images/redhat.png
ADDED
![]() |
Git LFS Details
|
example_images/s2w_example.png
ADDED
![]() |
requirements.txt
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
-
accelerate
|
2 |
-
diffusers
|
3 |
-
invisible_watermark
|
4 |
torch
|
|
|
|
|
|
|
5 |
transformers
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
torch
|
2 |
+
accelerate
|
3 |
+
huggingface_hub
|
4 |
+
gradio
|
5 |
transformers
|
6 |
+
spaces
|
7 |
+
docling
|
8 |
+
docling-core
|