Spaces:
Running on Zero
Running on Zero
update app
Browse files
app.py
CHANGED
|
@@ -2,27 +2,20 @@ import os
|
|
| 2 |
import random
|
| 3 |
import uuid
|
| 4 |
import json
|
| 5 |
-
import time
|
| 6 |
-
import asyncio
|
| 7 |
from threading import Thread
|
| 8 |
-
from typing import Iterable
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
import spaces
|
| 12 |
import torch
|
| 13 |
from PIL import Image, ImageOps
|
| 14 |
-
import requests
|
| 15 |
|
| 16 |
from transformers import (
|
| 17 |
-
Qwen2VLForConditionalGeneration,
|
| 18 |
Qwen2_5_VLForConditionalGeneration,
|
| 19 |
Qwen3VLForConditionalGeneration,
|
| 20 |
-
AutoModelForCausalLM,
|
| 21 |
AutoModelForVision2Seq,
|
| 22 |
AutoProcessor,
|
| 23 |
TextIteratorStreamer,
|
| 24 |
)
|
| 25 |
-
from transformers.image_utils import load_image
|
| 26 |
|
| 27 |
from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
| 28 |
|
|
@@ -59,17 +52,7 @@ footer{display:none!important}
|
|
| 59 |
padding:0!important;
|
| 60 |
}
|
| 61 |
|
| 62 |
-
#gradio-run-btn
|
| 63 |
-
position:absolute!important;
|
| 64 |
-
left:-9999px!important;
|
| 65 |
-
top:-9999px!important;
|
| 66 |
-
width:1px!important;
|
| 67 |
-
height:1px!important;
|
| 68 |
-
opacity:0.01!important;
|
| 69 |
-
pointer-events:none!important;
|
| 70 |
-
overflow:hidden!important;
|
| 71 |
-
}
|
| 72 |
-
|
| 73 |
#example-load-btn{
|
| 74 |
position:absolute!important;
|
| 75 |
left:-9999px!important;
|
|
@@ -546,7 +529,7 @@ footer{display:none!important}
|
|
| 546 |
white-space:pre-wrap;
|
| 547 |
word-break:break-word;
|
| 548 |
}
|
| 549 |
-
.formatted-output code,
|
| 550 |
font-family:'IBM Plex Mono',monospace;
|
| 551 |
}
|
| 552 |
|
|
@@ -768,6 +751,10 @@ footer{display:none!important}
|
|
| 768 |
}
|
| 769 |
.exp-note a:hover{text-decoration:underline}
|
| 770 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 771 |
@media(max-width:980px){
|
| 772 |
.app-main{flex-direction:column}
|
| 773 |
.app-left{border-right:none;border-bottom:1px solid rgba(211,245,39,.12)}
|
|
@@ -808,7 +795,6 @@ class RadioAnimated(gr.HTML):
|
|
| 808 |
|
| 809 |
js_on_load = r"""
|
| 810 |
(() => {
|
| 811 |
-
const wrap = element.querySelector('.ra-wrap');
|
| 812 |
const highlight = element.querySelector('.ra-highlight');
|
| 813 |
const inputs = Array.from(element.querySelectorAll('.ra-input'));
|
| 814 |
if (!inputs.length) return;
|
|
@@ -833,19 +819,12 @@ class RadioAnimated(gr.HTML):
|
|
| 833 |
setCheckedByValue(props.value ?? choices[0], false);
|
| 834 |
|
| 835 |
inputs.forEach((inp) => {
|
| 836 |
-
inp.addEventListener('change', () =>
|
| 837 |
-
setCheckedByValue(inp.value, true);
|
| 838 |
-
});
|
| 839 |
});
|
| 840 |
})();
|
| 841 |
"""
|
| 842 |
|
| 843 |
-
super().__init__(
|
| 844 |
-
value=value,
|
| 845 |
-
html_template=html_template,
|
| 846 |
-
js_on_load=js_on_load,
|
| 847 |
-
**kwargs
|
| 848 |
-
)
|
| 849 |
|
| 850 |
def apply_gpu_duration(val: str):
|
| 851 |
try:
|
|
@@ -853,7 +832,6 @@ def apply_gpu_duration(val: str):
|
|
| 853 |
except Exception:
|
| 854 |
return 60
|
| 855 |
|
| 856 |
-
|
| 857 |
MODEL_ID_F = "FireRedTeam/FireRed-OCR"
|
| 858 |
processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
|
| 859 |
model_f = Qwen3VLForConditionalGeneration.from_pretrained(
|
|
@@ -874,11 +852,7 @@ model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 874 |
|
| 875 |
MODEL_ID_G = "echo840/MonkeyOCR"
|
| 876 |
SUBFOLDER = "Recognition"
|
| 877 |
-
processor_g = AutoProcessor.from_pretrained(
|
| 878 |
-
MODEL_ID_G,
|
| 879 |
-
trust_remote_code=True,
|
| 880 |
-
subfolder=SUBFOLDER
|
| 881 |
-
)
|
| 882 |
model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 883 |
MODEL_ID_G,
|
| 884 |
attn_implementation="kernels-community/flash-attn2",
|
|
@@ -913,7 +887,6 @@ model_n = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 913 |
torch_dtype=torch.float16
|
| 914 |
).to(device).eval()
|
| 915 |
|
| 916 |
-
|
| 917 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
| 918 |
image = image.convert("RGB")
|
| 919 |
width, height = image.size
|
|
@@ -922,9 +895,7 @@ def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
|
| 922 |
pad_w = int(width * pad_w_percent)
|
| 923 |
pad_h = int(height * pad_h_percent)
|
| 924 |
corner_pixel = image.getpixel((0, 0))
|
| 925 |
-
|
| 926 |
-
return padded_image
|
| 927 |
-
|
| 928 |
|
| 929 |
def normalize_values(text, target_max=500):
|
| 930 |
def normalize_list(values):
|
|
@@ -937,9 +908,7 @@ def normalize_values(text, target_max=500):
|
|
| 937 |
return "".join([f"<loc_{num}>" for num in normalized])
|
| 938 |
|
| 939 |
pattern = r"\[([\d\.\s,]+)\]"
|
| 940 |
-
|
| 941 |
-
return normalized_text
|
| 942 |
-
|
| 943 |
|
| 944 |
def calc_timeout_image(model_name: str, text: str, image: Image.Image,
|
| 945 |
max_new_tokens: int, temperature: float, top_p: float,
|
|
@@ -949,7 +918,6 @@ def calc_timeout_image(model_name: str, text: str, image: Image.Image,
|
|
| 949 |
except Exception:
|
| 950 |
return 60
|
| 951 |
|
| 952 |
-
|
| 953 |
@spaces.GPU(duration=calc_timeout_image)
|
| 954 |
def generate_image(model_name: str, text: str, image: Image.Image,
|
| 955 |
max_new_tokens: int = 1024,
|
|
@@ -990,14 +958,11 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 990 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 991 |
text = normalize_values(text, target_max=500)
|
| 992 |
|
| 993 |
-
messages = [
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
]
|
| 999 |
-
}
|
| 1000 |
-
]
|
| 1001 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 1002 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 1003 |
|
|
@@ -1011,16 +976,14 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 1011 |
"top_k": int(top_k),
|
| 1012 |
"repetition_penalty": float(repetition_penalty),
|
| 1013 |
}
|
|
|
|
| 1014 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 1015 |
thread.start()
|
| 1016 |
|
| 1017 |
buffer = ""
|
| 1018 |
-
formatted_final = ""
|
| 1019 |
-
|
| 1020 |
for new_text in streamer:
|
| 1021 |
buffer += new_text.replace("<|im_end|>", "")
|
| 1022 |
-
|
| 1023 |
-
yield buffer, formatted_final
|
| 1024 |
|
| 1025 |
if model_name == "SmolDocling-256M-preview":
|
| 1026 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
|
@@ -1035,7 +998,6 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 1035 |
else:
|
| 1036 |
yield buffer, cleaned_output
|
| 1037 |
|
| 1038 |
-
|
| 1039 |
image_examples = [
|
| 1040 |
["Generate Markdown", "examples/6.jpg"],
|
| 1041 |
["Perform OCR on the image precisely.", "examples/5.jpg"],
|
|
@@ -1045,7 +1007,6 @@ image_examples = [
|
|
| 1045 |
["Convert this page to docling", "examples/3.jpg"],
|
| 1046 |
]
|
| 1047 |
|
| 1048 |
-
|
| 1049 |
def make_thumb_b64(path, max_dim=360):
|
| 1050 |
if not os.path.exists(path):
|
| 1051 |
return ""
|
|
@@ -1061,7 +1022,6 @@ def make_thumb_b64(path, max_dim=360):
|
|
| 1061 |
print(f"Example thumbnail error for {path}: {e}")
|
| 1062 |
return ""
|
| 1063 |
|
| 1064 |
-
|
| 1065 |
def encode_full_image(path):
|
| 1066 |
if not os.path.exists(path):
|
| 1067 |
return ""
|
|
@@ -1076,17 +1036,13 @@ def encode_full_image(path):
|
|
| 1076 |
print(f"Example encode error for {path}: {e}")
|
| 1077 |
return ""
|
| 1078 |
|
| 1079 |
-
|
| 1080 |
def build_example_cards_html():
|
| 1081 |
cards = ""
|
| 1082 |
for i, item in enumerate(image_examples):
|
| 1083 |
prompt_text, path = item
|
| 1084 |
thumb = make_thumb_b64(path)
|
| 1085 |
prompt_short = html.escape(prompt_text[:80] + ("..." if len(prompt_text) > 80 else ""))
|
| 1086 |
-
if thumb
|
| 1087 |
-
image_html = f'<img class="example-thumb" src="{thumb}" alt="example">'
|
| 1088 |
-
else:
|
| 1089 |
-
image_html = '<div class="example-thumb"></div>'
|
| 1090 |
cards += f"""
|
| 1091 |
<div class="example-card" data-idx="{i}">
|
| 1092 |
{image_html}
|
|
@@ -1098,7 +1054,6 @@ def build_example_cards_html():
|
|
| 1098 |
"""
|
| 1099 |
return cards
|
| 1100 |
|
| 1101 |
-
|
| 1102 |
def load_example_data(idx_str):
|
| 1103 |
try:
|
| 1104 |
idx = int(float(idx_str)) if idx_str and str(idx_str).strip() else -1
|
|
@@ -1120,7 +1075,6 @@ def load_example_data(idx_str):
|
|
| 1120 |
"name": os.path.basename(path)
|
| 1121 |
})
|
| 1122 |
|
| 1123 |
-
|
| 1124 |
EXAMPLE_CARDS_HTML = build_example_cards_html()
|
| 1125 |
|
| 1126 |
VISION_LOGO_SVG = """
|
|
@@ -1188,7 +1142,7 @@ function init() {
|
|
| 1188 |
toast = document.createElement('div');
|
| 1189 |
toast.id = 'app-toast';
|
| 1190 |
toast.className = 'toast-notification';
|
| 1191 |
-
toast.innerHTML = '<span class="toast-
|
| 1192 |
document.body.appendChild(toast);
|
| 1193 |
}
|
| 1194 |
toast.className = 'toast-notification ' + (type || 'error');
|
|
@@ -1229,22 +1183,22 @@ function init() {
|
|
| 1229 |
|
| 1230 |
function syncImage() {
|
| 1231 |
setGradioValue('hidden-image-b64', uploadedImage ? uploadedImage.b64 : '');
|
| 1232 |
-
setGradioValue('hidden-image-name', uploadedImage ? uploadedImage.name : '');
|
| 1233 |
const status = document.getElementById('sb-image-status');
|
| 1234 |
if (status) status.textContent = uploadedImage ? 'Image loaded' : 'No image';
|
| 1235 |
}
|
| 1236 |
|
| 1237 |
function renderImageState() {
|
|
|
|
| 1238 |
if (uploadedImage && uploadedImage.b64) {
|
| 1239 |
if (emptyState) emptyState.style.display = 'none';
|
| 1240 |
if (previewWrap) previewWrap.classList.add('visible');
|
| 1241 |
if (previewImg) previewImg.src = uploadedImage.b64;
|
| 1242 |
-
if (
|
| 1243 |
} else {
|
| 1244 |
if (emptyState) emptyState.style.display = '';
|
| 1245 |
if (previewWrap) previewWrap.classList.remove('visible');
|
| 1246 |
if (previewImg) previewImg.removeAttribute('src');
|
| 1247 |
-
if (
|
| 1248 |
}
|
| 1249 |
syncImage();
|
| 1250 |
}
|
|
@@ -1268,9 +1222,7 @@ function init() {
|
|
| 1268 |
return;
|
| 1269 |
}
|
| 1270 |
const reader = new FileReader();
|
| 1271 |
-
reader.onload = (e) =>
|
| 1272 |
-
setImage(e.target.result, file.name);
|
| 1273 |
-
};
|
| 1274 |
reader.readAsDataURL(file);
|
| 1275 |
}
|
| 1276 |
|
|
@@ -1531,7 +1483,6 @@ watchExampleResults();
|
|
| 1531 |
|
| 1532 |
with gr.Blocks() as demo:
|
| 1533 |
hidden_image_b64 = gr.Textbox(value="", elem_id="hidden-image-b64", elem_classes="hidden-input", container=False)
|
| 1534 |
-
hidden_image_name = gr.Textbox(value="", elem_id="hidden-image-name", elem_classes="hidden-input", container=False)
|
| 1535 |
query_input_hidden = gr.Textbox(value="", elem_id="query-gradio-input", elem_classes="hidden-input", container=False)
|
| 1536 |
|
| 1537 |
model_choice = gr.Textbox(value="FireRed-OCR", elem_id="gradio-model-choice", elem_classes="hidden-input", container=False)
|
|
@@ -1542,19 +1493,13 @@ with gr.Blocks() as demo:
|
|
| 1542 |
top_k = gr.Slider(minimum=1, maximum=1000, step=1, value=50, elem_id="gradio-top-k", elem_classes="hidden-input", container=False)
|
| 1543 |
repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, step=0.05, value=1.2, elem_id="gradio-repetition-penalty", elem_classes="hidden-input", container=False)
|
| 1544 |
|
| 1545 |
-
|
| 1546 |
-
|
| 1547 |
-
formatted_output_hidden = gr.Textbox(label="Formatted Output", lines=10, elem_id="gradio-formatted-output", elem_classes="hidden-input", container=False)
|
| 1548 |
|
| 1549 |
example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
|
| 1550 |
example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
|
| 1551 |
example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
|
| 1552 |
|
| 1553 |
-
radioanimated_gpu_duration = RadioAnimated(
|
| 1554 |
-
choices=["60", "90", "120", "180", "240", "300"],
|
| 1555 |
-
value="60",
|
| 1556 |
-
elem_id="radioanimated_gpu_duration"
|
| 1557 |
-
)
|
| 1558 |
gpu_duration_state = gr.Number(value=60, visible=False)
|
| 1559 |
|
| 1560 |
gr.HTML(f"""
|
|
@@ -1687,6 +1632,8 @@ with gr.Blocks() as demo:
|
|
| 1687 |
|
| 1688 |
<div class="gpu-group">
|
| 1689 |
<div class="gpu-title">GPU Duration (seconds)</div>
|
|
|
|
|
|
|
| 1690 |
</div>
|
| 1691 |
</div>
|
| 1692 |
</div>
|
|
@@ -1705,18 +1652,17 @@ with gr.Blocks() as demo:
|
|
| 1705 |
</div>
|
| 1706 |
""")
|
| 1707 |
|
| 1708 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1709 |
|
| 1710 |
-
|
| 1711 |
|
| 1712 |
-
demo.load(
|
| 1713 |
-
|
| 1714 |
-
js=gallery_js
|
| 1715 |
-
)
|
| 1716 |
-
demo.load(
|
| 1717 |
-
fn=None,
|
| 1718 |
-
js=wire_outputs_js
|
| 1719 |
-
)
|
| 1720 |
|
| 1721 |
example_load_btn.click(
|
| 1722 |
fn=load_example_data,
|
|
@@ -1738,10 +1684,7 @@ with gr.Blocks() as demo:
|
|
| 1738 |
if not data_url:
|
| 1739 |
return None
|
| 1740 |
try:
|
| 1741 |
-
if "," in data_url
|
| 1742 |
-
_, data = data_url.split(",", 1)
|
| 1743 |
-
else:
|
| 1744 |
-
data = data_url
|
| 1745 |
image_data = base64.b64decode(data)
|
| 1746 |
return Image.open(BytesIO(image_data)).convert("RGB")
|
| 1747 |
except Exception:
|
|
|
|
| 2 |
import random
|
| 3 |
import uuid
|
| 4 |
import json
|
|
|
|
|
|
|
| 5 |
from threading import Thread
|
|
|
|
| 6 |
|
| 7 |
import gradio as gr
|
| 8 |
import spaces
|
| 9 |
import torch
|
| 10 |
from PIL import Image, ImageOps
|
|
|
|
| 11 |
|
| 12 |
from transformers import (
|
|
|
|
| 13 |
Qwen2_5_VLForConditionalGeneration,
|
| 14 |
Qwen3VLForConditionalGeneration,
|
|
|
|
| 15 |
AutoModelForVision2Seq,
|
| 16 |
AutoProcessor,
|
| 17 |
TextIteratorStreamer,
|
| 18 |
)
|
|
|
|
| 19 |
|
| 20 |
from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
| 21 |
|
|
|
|
| 52 |
padding:0!important;
|
| 53 |
}
|
| 54 |
|
| 55 |
+
#gradio-run-btn,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
#example-load-btn{
|
| 57 |
position:absolute!important;
|
| 58 |
left:-9999px!important;
|
|
|
|
| 529 |
white-space:pre-wrap;
|
| 530 |
word-break:break-word;
|
| 531 |
}
|
| 532 |
+
.formatted-output code,.formatted-output pre{
|
| 533 |
font-family:'IBM Plex Mono',monospace;
|
| 534 |
}
|
| 535 |
|
|
|
|
| 751 |
}
|
| 752 |
.exp-note a:hover{text-decoration:underline}
|
| 753 |
|
| 754 |
+
.gpu-radio-mount{
|
| 755 |
+
margin-top:6px;
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
@media(max-width:980px){
|
| 759 |
.app-main{flex-direction:column}
|
| 760 |
.app-left{border-right:none;border-bottom:1px solid rgba(211,245,39,.12)}
|
|
|
|
| 795 |
|
| 796 |
js_on_load = r"""
|
| 797 |
(() => {
|
|
|
|
| 798 |
const highlight = element.querySelector('.ra-highlight');
|
| 799 |
const inputs = Array.from(element.querySelectorAll('.ra-input'));
|
| 800 |
if (!inputs.length) return;
|
|
|
|
| 819 |
setCheckedByValue(props.value ?? choices[0], false);
|
| 820 |
|
| 821 |
inputs.forEach((inp) => {
|
| 822 |
+
inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
|
|
|
|
|
|
|
| 823 |
});
|
| 824 |
})();
|
| 825 |
"""
|
| 826 |
|
| 827 |
+
super().__init__(value=value, html_template=html_template, js_on_load=js_on_load, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 828 |
|
| 829 |
def apply_gpu_duration(val: str):
|
| 830 |
try:
|
|
|
|
| 832 |
except Exception:
|
| 833 |
return 60
|
| 834 |
|
|
|
|
| 835 |
MODEL_ID_F = "FireRedTeam/FireRed-OCR"
|
| 836 |
processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
|
| 837 |
model_f = Qwen3VLForConditionalGeneration.from_pretrained(
|
|
|
|
| 852 |
|
| 853 |
MODEL_ID_G = "echo840/MonkeyOCR"
|
| 854 |
SUBFOLDER = "Recognition"
|
| 855 |
+
processor_g = AutoProcessor.from_pretrained(MODEL_ID_G, trust_remote_code=True, subfolder=SUBFOLDER)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
model_g = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 857 |
MODEL_ID_G,
|
| 858 |
attn_implementation="kernels-community/flash-attn2",
|
|
|
|
| 887 |
torch_dtype=torch.float16
|
| 888 |
).to(device).eval()
|
| 889 |
|
|
|
|
| 890 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
| 891 |
image = image.convert("RGB")
|
| 892 |
width, height = image.size
|
|
|
|
| 895 |
pad_w = int(width * pad_w_percent)
|
| 896 |
pad_h = int(height * pad_h_percent)
|
| 897 |
corner_pixel = image.getpixel((0, 0))
|
| 898 |
+
return ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
|
|
|
|
|
|
| 899 |
|
| 900 |
def normalize_values(text, target_max=500):
|
| 901 |
def normalize_list(values):
|
|
|
|
| 908 |
return "".join([f"<loc_{num}>" for num in normalized])
|
| 909 |
|
| 910 |
pattern = r"\[([\d\.\s,]+)\]"
|
| 911 |
+
return re.sub(pattern, process_match, text)
|
|
|
|
|
|
|
| 912 |
|
| 913 |
def calc_timeout_image(model_name: str, text: str, image: Image.Image,
|
| 914 |
max_new_tokens: int, temperature: float, top_p: float,
|
|
|
|
| 918 |
except Exception:
|
| 919 |
return 60
|
| 920 |
|
|
|
|
| 921 |
@spaces.GPU(duration=calc_timeout_image)
|
| 922 |
def generate_image(model_name: str, text: str, image: Image.Image,
|
| 923 |
max_new_tokens: int = 1024,
|
|
|
|
| 958 |
if "OCR at text at" in text or "Identify element" in text or "formula" in text:
|
| 959 |
text = normalize_values(text, target_max=500)
|
| 960 |
|
| 961 |
+
messages = [{
|
| 962 |
+
"role": "user",
|
| 963 |
+
"content": [{"type": "image"} for _ in images] + [{"type": "text", "text": text}]
|
| 964 |
+
}]
|
| 965 |
+
|
|
|
|
|
|
|
|
|
|
| 966 |
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
|
| 967 |
inputs = processor(text=prompt, images=images, return_tensors="pt").to(device)
|
| 968 |
|
|
|
|
| 976 |
"top_k": int(top_k),
|
| 977 |
"repetition_penalty": float(repetition_penalty),
|
| 978 |
}
|
| 979 |
+
|
| 980 |
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 981 |
thread.start()
|
| 982 |
|
| 983 |
buffer = ""
|
|
|
|
|
|
|
| 984 |
for new_text in streamer:
|
| 985 |
buffer += new_text.replace("<|im_end|>", "")
|
| 986 |
+
yield buffer, buffer
|
|
|
|
| 987 |
|
| 988 |
if model_name == "SmolDocling-256M-preview":
|
| 989 |
cleaned_output = buffer.replace("<end_of_utterance>", "").strip()
|
|
|
|
| 998 |
else:
|
| 999 |
yield buffer, cleaned_output
|
| 1000 |
|
|
|
|
| 1001 |
image_examples = [
|
| 1002 |
["Generate Markdown", "examples/6.jpg"],
|
| 1003 |
["Perform OCR on the image precisely.", "examples/5.jpg"],
|
|
|
|
| 1007 |
["Convert this page to docling", "examples/3.jpg"],
|
| 1008 |
]
|
| 1009 |
|
|
|
|
| 1010 |
def make_thumb_b64(path, max_dim=360):
|
| 1011 |
if not os.path.exists(path):
|
| 1012 |
return ""
|
|
|
|
| 1022 |
print(f"Example thumbnail error for {path}: {e}")
|
| 1023 |
return ""
|
| 1024 |
|
|
|
|
| 1025 |
def encode_full_image(path):
|
| 1026 |
if not os.path.exists(path):
|
| 1027 |
return ""
|
|
|
|
| 1036 |
print(f"Example encode error for {path}: {e}")
|
| 1037 |
return ""
|
| 1038 |
|
|
|
|
| 1039 |
def build_example_cards_html():
|
| 1040 |
cards = ""
|
| 1041 |
for i, item in enumerate(image_examples):
|
| 1042 |
prompt_text, path = item
|
| 1043 |
thumb = make_thumb_b64(path)
|
| 1044 |
prompt_short = html.escape(prompt_text[:80] + ("..." if len(prompt_text) > 80 else ""))
|
| 1045 |
+
image_html = f'<img class="example-thumb" src="{thumb}" alt="example">' if thumb else '<div class="example-thumb"></div>'
|
|
|
|
|
|
|
|
|
|
| 1046 |
cards += f"""
|
| 1047 |
<div class="example-card" data-idx="{i}">
|
| 1048 |
{image_html}
|
|
|
|
| 1054 |
"""
|
| 1055 |
return cards
|
| 1056 |
|
|
|
|
| 1057 |
def load_example_data(idx_str):
|
| 1058 |
try:
|
| 1059 |
idx = int(float(idx_str)) if idx_str and str(idx_str).strip() else -1
|
|
|
|
| 1075 |
"name": os.path.basename(path)
|
| 1076 |
})
|
| 1077 |
|
|
|
|
| 1078 |
EXAMPLE_CARDS_HTML = build_example_cards_html()
|
| 1079 |
|
| 1080 |
VISION_LOGO_SVG = """
|
|
|
|
| 1142 |
toast = document.createElement('div');
|
| 1143 |
toast.id = 'app-toast';
|
| 1144 |
toast.className = 'toast-notification';
|
| 1145 |
+
toast.innerHTML = '<span class="toast-text"></span>';
|
| 1146 |
document.body.appendChild(toast);
|
| 1147 |
}
|
| 1148 |
toast.className = 'toast-notification ' + (type || 'error');
|
|
|
|
| 1183 |
|
| 1184 |
function syncImage() {
|
| 1185 |
setGradioValue('hidden-image-b64', uploadedImage ? uploadedImage.b64 : '');
|
|
|
|
| 1186 |
const status = document.getElementById('sb-image-status');
|
| 1187 |
if (status) status.textContent = uploadedImage ? 'Image loaded' : 'No image';
|
| 1188 |
}
|
| 1189 |
|
| 1190 |
function renderImageState() {
|
| 1191 |
+
const actions = document.getElementById('preview-actions');
|
| 1192 |
if (uploadedImage && uploadedImage.b64) {
|
| 1193 |
if (emptyState) emptyState.style.display = 'none';
|
| 1194 |
if (previewWrap) previewWrap.classList.add('visible');
|
| 1195 |
if (previewImg) previewImg.src = uploadedImage.b64;
|
| 1196 |
+
if (actions) actions.classList.add('visible');
|
| 1197 |
} else {
|
| 1198 |
if (emptyState) emptyState.style.display = '';
|
| 1199 |
if (previewWrap) previewWrap.classList.remove('visible');
|
| 1200 |
if (previewImg) previewImg.removeAttribute('src');
|
| 1201 |
+
if (actions) actions.classList.remove('visible');
|
| 1202 |
}
|
| 1203 |
syncImage();
|
| 1204 |
}
|
|
|
|
| 1222 |
return;
|
| 1223 |
}
|
| 1224 |
const reader = new FileReader();
|
| 1225 |
+
reader.onload = (e) => setImage(e.target.result, file.name);
|
|
|
|
|
|
|
| 1226 |
reader.readAsDataURL(file);
|
| 1227 |
}
|
| 1228 |
|
|
|
|
| 1483 |
|
| 1484 |
with gr.Blocks() as demo:
|
| 1485 |
hidden_image_b64 = gr.Textbox(value="", elem_id="hidden-image-b64", elem_classes="hidden-input", container=False)
|
|
|
|
| 1486 |
query_input_hidden = gr.Textbox(value="", elem_id="query-gradio-input", elem_classes="hidden-input", container=False)
|
| 1487 |
|
| 1488 |
model_choice = gr.Textbox(value="FireRed-OCR", elem_id="gradio-model-choice", elem_classes="hidden-input", container=False)
|
|
|
|
| 1493 |
top_k = gr.Slider(minimum=1, maximum=1000, step=1, value=50, elem_id="gradio-top-k", elem_classes="hidden-input", container=False)
|
| 1494 |
repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, step=0.05, value=1.2, elem_id="gradio-repetition-penalty", elem_classes="hidden-input", container=False)
|
| 1495 |
|
| 1496 |
+
raw_output_hidden = gr.Textbox(lines=10, elem_id="gradio-raw-output", elem_classes="hidden-input", container=False)
|
| 1497 |
+
formatted_output_hidden = gr.Textbox(lines=10, elem_id="gradio-formatted-output", elem_classes="hidden-input", container=False)
|
|
|
|
| 1498 |
|
| 1499 |
example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
|
| 1500 |
example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
|
| 1501 |
example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
|
| 1502 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1503 |
gpu_duration_state = gr.Number(value=60, visible=False)
|
| 1504 |
|
| 1505 |
gr.HTML(f"""
|
|
|
|
| 1632 |
|
| 1633 |
<div class="gpu-group">
|
| 1634 |
<div class="gpu-title">GPU Duration (seconds)</div>
|
| 1635 |
+
<div class="gpu-radio-mount"></div>
|
| 1636 |
+
<div class="gpu-note">Higher GPU duration allows longer processing but uses more GPU quota.</div>
|
| 1637 |
</div>
|
| 1638 |
</div>
|
| 1639 |
</div>
|
|
|
|
| 1652 |
</div>
|
| 1653 |
""")
|
| 1654 |
|
| 1655 |
+
with gr.Group(elem_classes="gpu-radio-mount"):
|
| 1656 |
+
radioanimated_gpu_duration = RadioAnimated(
|
| 1657 |
+
choices=["60", "90", "120", "180", "240", "300"],
|
| 1658 |
+
value="60",
|
| 1659 |
+
elem_id="radioanimated_gpu_duration"
|
| 1660 |
+
)
|
| 1661 |
|
| 1662 |
+
gradio_run_btn = gr.Button("Run", elem_id="gradio-run-btn")
|
| 1663 |
|
| 1664 |
+
demo.load(fn=None, js=gallery_js)
|
| 1665 |
+
demo.load(fn=None, js=wire_outputs_js)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1666 |
|
| 1667 |
example_load_btn.click(
|
| 1668 |
fn=load_example_data,
|
|
|
|
| 1684 |
if not data_url:
|
| 1685 |
return None
|
| 1686 |
try:
|
| 1687 |
+
data = data_url.split(",", 1)[1] if "," in data_url else data_url
|
|
|
|
|
|
|
|
|
|
| 1688 |
image_data = base64.b64decode(data)
|
| 1689 |
return Image.open(BytesIO(image_data)).convert("RGB")
|
| 1690 |
except Exception:
|