Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,11 @@ import random
|
|
| 3 |
import uuid
|
| 4 |
import json
|
| 5 |
import time
|
| 6 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from threading import Thread
|
| 8 |
from typing import Iterable
|
| 9 |
|
|
@@ -23,200 +27,18 @@ from transformers import (
|
|
| 23 |
TextIteratorStreamer,
|
| 24 |
)
|
| 25 |
from transformers.image_utils import load_image
|
| 26 |
-
from gradio.themes import Soft
|
| 27 |
-
from gradio.themes.utils import colors, fonts, sizes
|
| 28 |
|
| 29 |
from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
| 30 |
|
| 31 |
-
import re
|
| 32 |
-
import ast
|
| 33 |
-
import html
|
| 34 |
-
|
| 35 |
-
colors.steel_blue = colors.Color(
|
| 36 |
-
name="steel_blue",
|
| 37 |
-
c50="#EBF3F8",
|
| 38 |
-
c100="#D3E5F0",
|
| 39 |
-
c200="#A8CCE1",
|
| 40 |
-
c300="#7DB3D2",
|
| 41 |
-
c400="#529AC3",
|
| 42 |
-
c500="#4682B4",
|
| 43 |
-
c600="#3E72A0",
|
| 44 |
-
c700="#36638C",
|
| 45 |
-
c800="#2E5378",
|
| 46 |
-
c900="#264364",
|
| 47 |
-
c950="#1E3450",
|
| 48 |
-
)
|
| 49 |
-
|
| 50 |
-
class SteelBlueTheme(Soft):
|
| 51 |
-
def __init__(
|
| 52 |
-
self,
|
| 53 |
-
*,
|
| 54 |
-
primary_hue: colors.Color | str = colors.gray,
|
| 55 |
-
secondary_hue: colors.Color | str = colors.steel_blue,
|
| 56 |
-
neutral_hue: colors.Color | str = colors.slate,
|
| 57 |
-
text_size: sizes.Size | str = sizes.text_lg,
|
| 58 |
-
font: fonts.Font | str | Iterable[fonts.Font | str] = (
|
| 59 |
-
fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
|
| 60 |
-
),
|
| 61 |
-
font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
|
| 62 |
-
fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
|
| 63 |
-
),
|
| 64 |
-
):
|
| 65 |
-
super().__init__(
|
| 66 |
-
primary_hue=primary_hue,
|
| 67 |
-
secondary_hue=secondary_hue,
|
| 68 |
-
neutral_hue=neutral_hue,
|
| 69 |
-
text_size=text_size,
|
| 70 |
-
font=font,
|
| 71 |
-
font_mono=font_mono,
|
| 72 |
-
)
|
| 73 |
-
super().set(
|
| 74 |
-
background_fill_primary="*primary_50",
|
| 75 |
-
background_fill_primary_dark="*primary_900",
|
| 76 |
-
body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
|
| 77 |
-
body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
|
| 78 |
-
button_primary_text_color="white",
|
| 79 |
-
button_primary_text_color_hover="white",
|
| 80 |
-
button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
|
| 81 |
-
button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
|
| 82 |
-
button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
|
| 83 |
-
button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
|
| 84 |
-
slider_color="*secondary_500",
|
| 85 |
-
slider_color_dark="*secondary_600",
|
| 86 |
-
block_title_text_weight="600",
|
| 87 |
-
block_border_width="3px",
|
| 88 |
-
block_shadow="*shadow_drop_lg",
|
| 89 |
-
button_primary_shadow="*shadow_drop_lg",
|
| 90 |
-
button_large_padding="11px",
|
| 91 |
-
color_accent_soft="*primary_100",
|
| 92 |
-
block_label_background_fill="*primary_200",
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
steel_blue_theme = SteelBlueTheme()
|
| 96 |
-
|
| 97 |
-
css = """
|
| 98 |
-
#main-title h1 {
|
| 99 |
-
font-size: 2.3em !important;
|
| 100 |
-
}
|
| 101 |
-
#output-title h2 {
|
| 102 |
-
font-size: 2.1em !important;
|
| 103 |
-
}
|
| 104 |
-
|
| 105 |
-
/* RadioAnimated Styles */
|
| 106 |
-
.ra-wrap{ width: fit-content; }
|
| 107 |
-
.ra-inner{
|
| 108 |
-
position: relative; display: inline-flex; align-items: center; gap: 0; padding: 6px;
|
| 109 |
-
background: var(--neutral-200); border-radius: 9999px; overflow: hidden;
|
| 110 |
-
}
|
| 111 |
-
.ra-input{ display: none; }
|
| 112 |
-
.ra-label{
|
| 113 |
-
position: relative; z-index: 2; padding: 8px 16px;
|
| 114 |
-
font-family: inherit; font-size: 14px; font-weight: 600;
|
| 115 |
-
color: var(--neutral-500); cursor: pointer; transition: color 0.2s; white-space: nowrap;
|
| 116 |
-
}
|
| 117 |
-
.ra-highlight{
|
| 118 |
-
position: absolute; z-index: 1; top: 6px; left: 6px;
|
| 119 |
-
height: calc(100% - 12px); border-radius: 9999px;
|
| 120 |
-
background: white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
| 121 |
-
transition: transform 0.2s, width 0.2s;
|
| 122 |
-
}
|
| 123 |
-
.ra-input:checked + .ra-label{ color: black; }
|
| 124 |
-
|
| 125 |
-
/* Dark mode adjustments for Radio */
|
| 126 |
-
.dark .ra-inner { background: var(--neutral-800); }
|
| 127 |
-
.dark .ra-label { color: var(--neutral-400); }
|
| 128 |
-
.dark .ra-highlight { background: var(--neutral-600); }
|
| 129 |
-
.dark .ra-input:checked + .ra-label { color: white; }
|
| 130 |
-
|
| 131 |
-
#gpu-duration-container {
|
| 132 |
-
padding: 10px;
|
| 133 |
-
border-radius: 8px;
|
| 134 |
-
background: var(--background-fill-secondary);
|
| 135 |
-
border: 1px solid var(--border-color-primary);
|
| 136 |
-
margin-top: 10px;
|
| 137 |
-
}
|
| 138 |
-
"""
|
| 139 |
-
|
| 140 |
MAX_MAX_NEW_TOKENS = 4096
|
| 141 |
DEFAULT_MAX_NEW_TOKENS = 2048
|
| 142 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
| 143 |
|
| 144 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
raise ValueError("RadioAnimated requires at least 2 choices.")
|
| 150 |
-
if value is None:
|
| 151 |
-
value = choices[0]
|
| 152 |
-
|
| 153 |
-
uid = uuid.uuid4().hex[:8]
|
| 154 |
-
group_name = f"ra-{uid}"
|
| 155 |
-
|
| 156 |
-
inputs_html = "\n".join(
|
| 157 |
-
f"""
|
| 158 |
-
<input class="ra-input" type="radio" name="{group_name}" id="{group_name}-{i}" value="{c}">
|
| 159 |
-
<label class="ra-label" for="{group_name}-{i}">{c}</label>
|
| 160 |
-
"""
|
| 161 |
-
for i, c in enumerate(choices)
|
| 162 |
-
)
|
| 163 |
-
|
| 164 |
-
html_template = f"""
|
| 165 |
-
<div class="ra-wrap" data-ra="{uid}">
|
| 166 |
-
<div class="ra-inner">
|
| 167 |
-
<div class="ra-highlight"></div>
|
| 168 |
-
{inputs_html}
|
| 169 |
-
</div>
|
| 170 |
-
</div>
|
| 171 |
-
"""
|
| 172 |
-
|
| 173 |
-
js_on_load = r"""
|
| 174 |
-
(() => {
|
| 175 |
-
const wrap = element.querySelector('.ra-wrap');
|
| 176 |
-
const inner = element.querySelector('.ra-inner');
|
| 177 |
-
const highlight = element.querySelector('.ra-highlight');
|
| 178 |
-
const inputs = Array.from(element.querySelectorAll('.ra-input'));
|
| 179 |
-
|
| 180 |
-
if (!inputs.length) return;
|
| 181 |
-
|
| 182 |
-
const choices = inputs.map(i => i.value);
|
| 183 |
-
|
| 184 |
-
function setHighlightByIndex(idx) {
|
| 185 |
-
const n = choices.length;
|
| 186 |
-
const pct = 100 / n;
|
| 187 |
-
highlight.style.width = `calc(${pct}% - 6px)`;
|
| 188 |
-
highlight.style.transform = `translateX(${idx * 100}%)`;
|
| 189 |
-
}
|
| 190 |
-
|
| 191 |
-
function setCheckedByValue(val, shouldTrigger=false) {
|
| 192 |
-
const idx = Math.max(0, choices.indexOf(val));
|
| 193 |
-
inputs.forEach((inp, i) => { inp.checked = (i === idx); });
|
| 194 |
-
setHighlightByIndex(idx);
|
| 195 |
-
|
| 196 |
-
props.value = choices[idx];
|
| 197 |
-
if (shouldTrigger) trigger('change', props.value);
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
setCheckedByValue(props.value ?? choices[0], false);
|
| 201 |
-
|
| 202 |
-
inputs.forEach((inp) => {
|
| 203 |
-
inp.addEventListener('change', () => {
|
| 204 |
-
setCheckedByValue(inp.value, true);
|
| 205 |
-
});
|
| 206 |
-
});
|
| 207 |
-
})();
|
| 208 |
-
"""
|
| 209 |
-
|
| 210 |
-
super().__init__(
|
| 211 |
-
value=value,
|
| 212 |
-
html_template=html_template,
|
| 213 |
-
js_on_load=js_on_load,
|
| 214 |
-
**kwargs
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
def apply_gpu_duration(val: str):
|
| 218 |
-
return int(val)
|
| 219 |
-
|
| 220 |
|
| 221 |
MODEL_ID_F = "FireRedTeam/FireRed-OCR"
|
| 222 |
processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
|
|
@@ -260,7 +82,6 @@ model_l = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 260 |
torch_dtype=torch.float16
|
| 261 |
).to(device).eval()
|
| 262 |
|
| 263 |
-
|
| 264 |
MODEL_ID_X = "ds4sd/SmolDocling-256M-preview"
|
| 265 |
processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
|
| 266 |
model_x = AutoModelForVision2Seq.from_pretrained(
|
|
@@ -278,20 +99,167 @@ model_n = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
| 278 |
torch_dtype=torch.float16
|
| 279 |
).to(device).eval()
|
| 280 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
| 282 |
-
"""Add random padding to an image based on its size."""
|
| 283 |
image = image.convert("RGB")
|
| 284 |
width, height = image.size
|
| 285 |
pad_w_percent = random.uniform(min_percent, max_percent)
|
| 286 |
pad_h_percent = random.uniform(min_percent, max_percent)
|
| 287 |
pad_w = int(width * pad_w_percent)
|
| 288 |
pad_h = int(height * pad_h_percent)
|
| 289 |
-
corner_pixel = image.getpixel((0, 0))
|
| 290 |
padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
| 291 |
return padded_image
|
| 292 |
|
|
|
|
| 293 |
def normalize_values(text, target_max=500):
|
| 294 |
-
"""Normalize numerical values in text to a target maximum."""
|
| 295 |
def normalize_list(values):
|
| 296 |
max_value = max(values) if values else 1
|
| 297 |
return [round((v / max_value) * target_max) for v in values]
|
|
@@ -305,15 +273,16 @@ def normalize_values(text, target_max=500):
|
|
| 305 |
normalized_text = re.sub(pattern, process_match, text)
|
| 306 |
return normalized_text
|
| 307 |
|
|
|
|
| 308 |
def calc_timeout_image(model_name: str, text: str, image: Image.Image,
|
| 309 |
max_new_tokens: int, temperature: float, top_p: float,
|
| 310 |
top_k: int, repetition_penalty: float, gpu_timeout: int):
|
| 311 |
-
"""Calculate GPU timeout duration for image inference."""
|
| 312 |
try:
|
| 313 |
return int(gpu_timeout)
|
| 314 |
-
except:
|
| 315 |
return 60
|
| 316 |
|
|
|
|
| 317 |
@spaces.GPU(duration=calc_timeout_image)
|
| 318 |
def generate_image(model_name: str, text: str, image: Image.Image,
|
| 319 |
max_new_tokens: int = 1024,
|
|
@@ -322,7 +291,6 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 322 |
top_k: int = 50,
|
| 323 |
repetition_penalty: float = 1.2,
|
| 324 |
gpu_timeout: int = 60):
|
| 325 |
-
"""Generate responses for image input using the selected model."""
|
| 326 |
if model_name == "Nanonets-OCR-s":
|
| 327 |
processor, model = processor_m, model_m
|
| 328 |
elif model_name == "MonkeyOCR-Recognition":
|
|
@@ -343,6 +311,10 @@ def generate_image(model_name: str, text: str, image: Image.Image,
|
|
| 343 |
yield "Please upload an image.", "Please upload an image."
|
| 344 |
return
|
| 345 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
images = [image]
|
| 347 |
|
| 348 |
if model_name == "SmolDocling-256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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
fn=apply_gpu_duration,
|
| 448 |
-
inputs=
|
| 449 |
outputs=[gpu_duration_state],
|
| 450 |
-
api_visibility="private"
|
| 451 |
)
|
| 452 |
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
fn=generate_image,
|
| 455 |
-
inputs=[
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
)
|
| 458 |
|
| 459 |
if __name__ == "__main__":
|
| 460 |
-
demo.queue(max_size=50).launch(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import uuid
|
| 4 |
import json
|
| 5 |
import time
|
| 6 |
+
import base64
|
| 7 |
+
import re
|
| 8 |
+
import ast
|
| 9 |
+
import html
|
| 10 |
+
from io import BytesIO
|
| 11 |
from threading import Thread
|
| 12 |
from typing import Iterable
|
| 13 |
|
|
|
|
| 27 |
TextIteratorStreamer,
|
| 28 |
)
|
| 29 |
from transformers.image_utils import load_image
|
|
|
|
|
|
|
| 30 |
|
| 31 |
from docling_core.types.doc import DoclingDocument, DocTagsDocument
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
MAX_MAX_NEW_TOKENS = 4096
|
| 34 |
DEFAULT_MAX_NEW_TOKENS = 2048
|
| 35 |
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
| 36 |
|
| 37 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 38 |
|
| 39 |
+
# ----------------------------
|
| 40 |
+
# Model Loading
|
| 41 |
+
# ----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
MODEL_ID_F = "FireRedTeam/FireRed-OCR"
|
| 44 |
processor_f = AutoProcessor.from_pretrained(MODEL_ID_F, trust_remote_code=True)
|
|
|
|
| 82 |
torch_dtype=torch.float16
|
| 83 |
).to(device).eval()
|
| 84 |
|
|
|
|
| 85 |
MODEL_ID_X = "ds4sd/SmolDocling-256M-preview"
|
| 86 |
processor_x = AutoProcessor.from_pretrained(MODEL_ID_X, trust_remote_code=True)
|
| 87 |
model_x = AutoModelForVision2Seq.from_pretrained(
|
|
|
|
| 99 |
torch_dtype=torch.float16
|
| 100 |
).to(device).eval()
|
| 101 |
|
| 102 |
+
MODEL_CHOICES = [
|
| 103 |
+
"FireRed-OCR",
|
| 104 |
+
"Nanonets-OCR-s",
|
| 105 |
+
"MonkeyOCR-Recognition",
|
| 106 |
+
"Thyme-RL",
|
| 107 |
+
"Typhoon-OCR-7B",
|
| 108 |
+
"SmolDocling-256M-preview",
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
GPU_DURATION_CHOICES = ["60", "90", "120", "180", "240", "300"]
|
| 112 |
+
|
| 113 |
+
DEFAULT_QUERY = "Perform OCR on the image precisely."
|
| 114 |
+
|
| 115 |
+
image_examples = [
|
| 116 |
+
["Generate Markdown", "examples/6.jpg"],
|
| 117 |
+
["Perform OCR on the image precisely.", "examples/5.jpg"],
|
| 118 |
+
["Run OCR on the image and ensure high accuracy.", "examples/4.jpg"],
|
| 119 |
+
["Conduct OCR on the image with exact text recognition.", "examples/2.jpg"],
|
| 120 |
+
["Perform precise OCR extraction on the image.", "examples/1.jpg"],
|
| 121 |
+
["Convert this page to docling", "examples/3.jpg"],
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
LANCZOS = getattr(Image, "Resampling", Image).LANCZOS
|
| 125 |
+
|
| 126 |
+
def pil_to_b64(img: Image.Image, fmt="PNG"):
|
| 127 |
+
if img is None:
|
| 128 |
+
return ""
|
| 129 |
+
buf = BytesIO()
|
| 130 |
+
img.save(buf, format=fmt)
|
| 131 |
+
return f"data:image/{fmt.lower()};base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def b64_to_pil(b64_str):
|
| 135 |
+
if not b64_str or not isinstance(b64_str, str) or not b64_str.startswith("data:image"):
|
| 136 |
+
return None
|
| 137 |
+
try:
|
| 138 |
+
_, data = b64_str.split(",", 1)
|
| 139 |
+
image_data = base64.b64decode(data)
|
| 140 |
+
return Image.open(BytesIO(image_data)).convert("RGB")
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"Error decoding image: {e}")
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def make_thumb_b64(path, max_dim=280):
|
| 147 |
+
if not os.path.exists(path):
|
| 148 |
+
return ""
|
| 149 |
+
try:
|
| 150 |
+
img = Image.open(path).convert("RGB")
|
| 151 |
+
thumb = img.copy()
|
| 152 |
+
thumb.thumbnail((max_dim, max_dim), LANCZOS)
|
| 153 |
+
buf = BytesIO()
|
| 154 |
+
thumb.save(buf, format="JPEG", quality=70)
|
| 155 |
+
return f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 156 |
+
except Exception as e:
|
| 157 |
+
print(f"Thumbnail error for {path}: {e}")
|
| 158 |
+
return ""
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def encode_full_image(path):
|
| 162 |
+
if not os.path.exists(path):
|
| 163 |
+
return ""
|
| 164 |
+
try:
|
| 165 |
+
with open(path, "rb") as f:
|
| 166 |
+
data = f.read()
|
| 167 |
+
ext = path.rsplit(".", 1)[-1].lower()
|
| 168 |
+
mime = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp"}.get(ext, "image/jpeg")
|
| 169 |
+
return f"data:{mime};base64,{base64.b64encode(data).decode()}"
|
| 170 |
+
except Exception as e:
|
| 171 |
+
print(f"Encode error for {path}: {e}")
|
| 172 |
+
return ""
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def preload_example_thumbnails():
|
| 176 |
+
results = []
|
| 177 |
+
for idx, item in enumerate(image_examples):
|
| 178 |
+
try:
|
| 179 |
+
prompt_text, path = item
|
| 180 |
+
img = Image.open(path).convert("RGB")
|
| 181 |
+
thumb_b64 = make_thumb_b64(path, max_dim=280)
|
| 182 |
+
results.append({
|
| 183 |
+
"thumb": thumb_b64,
|
| 184 |
+
"name": os.path.basename(path).rsplit(".", 1)[0].capitalize(),
|
| 185 |
+
"size": f"{img.width}×{img.height}",
|
| 186 |
+
"prompt": prompt_text,
|
| 187 |
+
"idx": idx,
|
| 188 |
+
})
|
| 189 |
+
except Exception as e:
|
| 190 |
+
print(f"Warning: Could not load example {item}: {e}")
|
| 191 |
+
results.append(None)
|
| 192 |
+
return results
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def build_examples_html(thumbs):
|
| 196 |
+
cards_html = ""
|
| 197 |
+
for i, data in enumerate(thumbs):
|
| 198 |
+
if data is None or not data.get("thumb"):
|
| 199 |
+
continue
|
| 200 |
+
safe_prompt = html.escape(data["prompt"])
|
| 201 |
+
cards_html += f"""
|
| 202 |
+
<div class="example-card" data-example-idx="{i}" title="Click to load {data['name']}">
|
| 203 |
+
<div class="example-img-wrap">
|
| 204 |
+
<img src="{data['thumb']}" alt="{data['name']}" draggable="false" />
|
| 205 |
+
<div class="example-overlay"></div>
|
| 206 |
+
</div>
|
| 207 |
+
<div class="example-info">
|
| 208 |
+
<span class="example-label">{data['name']}</span>
|
| 209 |
+
<span class="example-size">{data['size']}</span>
|
| 210 |
+
</div>
|
| 211 |
+
<div class="example-prompt">{safe_prompt}</div>
|
| 212 |
+
</div>
|
| 213 |
+
"""
|
| 214 |
+
return f"""
|
| 215 |
+
<div class="examples-section">
|
| 216 |
+
<div class="examples-title">Quick Examples</div>
|
| 217 |
+
<div class="examples-grid">{cards_html}</div>
|
| 218 |
+
</div>
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def load_example_data(idx_str):
|
| 223 |
+
try:
|
| 224 |
+
idx = int(float(idx_str)) if idx_str and str(idx_str).strip() else -1
|
| 225 |
+
except (ValueError, TypeError):
|
| 226 |
+
idx = -1
|
| 227 |
+
|
| 228 |
+
if idx < 0 or idx >= len(image_examples):
|
| 229 |
+
return json.dumps({"image": "", "query": "", "status": "error"})
|
| 230 |
+
|
| 231 |
+
query, path = image_examples[idx]
|
| 232 |
+
b64 = encode_full_image(path)
|
| 233 |
+
if b64:
|
| 234 |
+
return json.dumps({
|
| 235 |
+
"image": b64,
|
| 236 |
+
"query": query,
|
| 237 |
+
"name": os.path.basename(path),
|
| 238 |
+
"status": "ok"
|
| 239 |
+
})
|
| 240 |
+
return json.dumps({"image": "", "query": "", "status": "error"})
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def apply_gpu_duration(val: str):
|
| 244 |
+
try:
|
| 245 |
+
return int(val)
|
| 246 |
+
except Exception:
|
| 247 |
+
return 60
|
| 248 |
+
|
| 249 |
+
|
| 250 |
def add_random_padding(image, min_percent=0.1, max_percent=0.10):
|
|
|
|
| 251 |
image = image.convert("RGB")
|
| 252 |
width, height = image.size
|
| 253 |
pad_w_percent = random.uniform(min_percent, max_percent)
|
| 254 |
pad_h_percent = random.uniform(min_percent, max_percent)
|
| 255 |
pad_w = int(width * pad_w_percent)
|
| 256 |
pad_h = int(height * pad_h_percent)
|
| 257 |
+
corner_pixel = image.getpixel((0, 0))
|
| 258 |
padded_image = ImageOps.expand(image, border=(pad_w, pad_h, pad_w, pad_h), fill=corner_pixel)
|
| 259 |
return padded_image
|
| 260 |
|
| 261 |
+
|
| 262 |
def normalize_values(text, target_max=500):
|
|
|
|
| 263 |
def normalize_list(values):
|
| 264 |
max_value = max(values) if values else 1
|
| 265 |
return [round((v / max_value) * target_max) for v in values]
|
|
|
|
| 273 |
normalized_text = re.sub(pattern, process_match, text)
|
| 274 |
return normalized_text
|
| 275 |
|
| 276 |
+
|
| 277 |
def calc_timeout_image(model_name: str, text: str, image: Image.Image,
|
| 278 |
max_new_tokens: int, temperature: float, top_p: float,
|
| 279 |
top_k: int, repetition_penalty: float, gpu_timeout: int):
|
|
|
|
| 280 |
try:
|
| 281 |
return int(gpu_timeout)
|
| 282 |
+
except Exception:
|
| 283 |
return 60
|
| 284 |
|
| 285 |
+
|
| 286 |
@spaces.GPU(duration=calc_timeout_image)
|
| 287 |
def generate_image(model_name: str, text: str, image: Image.Image,
|
| 288 |
max_new_tokens: int = 1024,
|
|
|
|
| 291 |
top_k: int = 50,
|
| 292 |
repetition_penalty: float = 1.2,
|
| 293 |
gpu_timeout: int = 60):
|
|
|
|
| 294 |
if model_name == "Nanonets-OCR-s":
|
| 295 |
processor, model = processor_m, model_m
|
| 296 |
elif model_name == "MonkeyOCR-Recognition":
|
|
|
|
| 311 |
yield "Please upload an image.", "Please upload an image."
|
| 312 |
return
|
| 313 |
|
| 314 |
+
if text is None or not str(text).strip():
|
| 315 |
+
yield "Please enter a query.", "Please enter a query."
|
| 316 |
+
return
|
| 317 |
+
|
| 318 |
images = [image]
|
| 319 |
|
| 320 |
if model_name == "SmolDocling-256M-preview":
|
|
|
|
| 365 |
else:
|
| 366 |
yield buffer, cleaned_output
|
| 367 |
|
| 368 |
+
|
| 369 |
+
print("Building example thumbnails...")
|
| 370 |
+
example_thumbs = preload_example_thumbnails()
|
| 371 |
+
examples_html_block = build_examples_html(example_thumbs)
|
| 372 |
+
print(f"Built {len(image_examples)} example cards.")
|
| 373 |
+
|
| 374 |
+
css = r"""
|
| 375 |
+
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap');
|
| 376 |
+
|
| 377 |
+
:root{
|
| 378 |
+
--ruby:#E0115F;
|
| 379 |
+
--ruby-2:#ff2d7d;
|
| 380 |
+
--ruby-3:#ff5c98;
|
| 381 |
+
--bg:#0f0f13;
|
| 382 |
+
--panel:#18181b;
|
| 383 |
+
--panel-2:#1e1e24;
|
| 384 |
+
--muted:#a1a1aa;
|
| 385 |
+
--muted-2:#71717a;
|
| 386 |
+
--line:#27272a;
|
| 387 |
+
--soft:#09090b;
|
| 388 |
+
--text:#e4e4e7;
|
| 389 |
+
--white:#ffffff;
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
*{box-sizing:border-box;margin:0;padding:0}
|
| 393 |
+
body,.gradio-container{
|
| 394 |
+
background:var(--bg)!important;
|
| 395 |
+
font-family:'Inter',system-ui,-apple-system,sans-serif!important;
|
| 396 |
+
font-size:14px!important;
|
| 397 |
+
color:var(--text)!important;
|
| 398 |
+
min-height:100vh;
|
| 399 |
+
}
|
| 400 |
+
.dark body,.dark .gradio-container{background:var(--bg)!important;color:var(--text)!important}
|
| 401 |
+
footer{display:none!important}
|
| 402 |
+
.hidden-input{display:none!important;height:0!important;overflow:hidden!important;margin:0!important;padding:0!important}
|
| 403 |
+
|
| 404 |
+
#gradio-run-btn,
|
| 405 |
+
#example-load-btn{
|
| 406 |
+
position:absolute!important;left:-9999px!important;top:-9999px!important;
|
| 407 |
+
width:1px!important;height:1px!important;opacity:0.01!important;
|
| 408 |
+
pointer-events:none!important;overflow:hidden!important;
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
.toast-notification{
|
| 412 |
+
position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);
|
| 413 |
+
z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;
|
| 414 |
+
font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;
|
| 415 |
+
box-shadow:0 8px 24px rgba(0,0,0,.5);
|
| 416 |
+
transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;
|
| 417 |
+
opacity:0;pointer-events:none;
|
| 418 |
+
}
|
| 419 |
+
.toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}
|
| 420 |
+
.toast-notification.error{background:linear-gradient(135deg,#dc2626,#b91c1c);color:#fff;border:1px solid rgba(255,255,255,.15)}
|
| 421 |
+
.toast-notification.warning{background:linear-gradient(135deg,#d97706,#b45309);color:#fff;border:1px solid rgba(255,255,255,.15)}
|
| 422 |
+
.toast-notification.info{background:linear-gradient(135deg,var(--ruby),#b90e4f);color:#fff;border:1px solid rgba(255,255,255,.15)}
|
| 423 |
+
.toast-notification .toast-icon{font-size:16px;line-height:1}
|
| 424 |
+
.toast-notification .toast-text{line-height:1.3}
|
| 425 |
+
|
| 426 |
+
.app-shell{
|
| 427 |
+
background:var(--panel);
|
| 428 |
+
border:1px solid var(--line);
|
| 429 |
+
border-radius:16px;
|
| 430 |
+
margin:12px auto;
|
| 431 |
+
max-width:1450px;
|
| 432 |
+
overflow:hidden;
|
| 433 |
+
box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03);
|
| 434 |
+
}
|
| 435 |
+
.app-header{
|
| 436 |
+
background:linear-gradient(135deg,var(--panel),var(--panel-2));
|
| 437 |
+
border-bottom:1px solid var(--line);
|
| 438 |
+
padding:14px 24px;
|
| 439 |
+
display:flex;
|
| 440 |
+
align-items:center;
|
| 441 |
+
justify-content:space-between;
|
| 442 |
+
flex-wrap:wrap;
|
| 443 |
+
gap:12px;
|
| 444 |
+
}
|
| 445 |
+
.app-header-left{display:flex;align-items:center;gap:12px}
|
| 446 |
+
.app-logo{
|
| 447 |
+
width:42px;height:42px;
|
| 448 |
+
background:linear-gradient(135deg,var(--ruby),var(--ruby-2),#ff9aba);
|
| 449 |
+
border-radius:12px;display:flex;align-items:center;justify-content:center;
|
| 450 |
+
box-shadow:0 4px 12px rgba(224,17,95,.35);
|
| 451 |
+
overflow:hidden;
|
| 452 |
+
}
|
| 453 |
+
.app-logo svg{width:26px;height:26px}
|
| 454 |
+
.app-title{
|
| 455 |
+
font-size:18px;font-weight:700;
|
| 456 |
+
background:linear-gradient(135deg,#fff,#d4d4d8);
|
| 457 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;
|
| 458 |
+
letter-spacing:-.3px;
|
| 459 |
+
}
|
| 460 |
+
.app-badge{
|
| 461 |
+
font-size:11px;font-weight:600;padding:3px 10px;border-radius:20px;
|
| 462 |
+
background:rgba(224,17,95,.15);color:#ff87b0;border:1px solid rgba(224,17,95,.25);letter-spacing:.3px;
|
| 463 |
+
}
|
| 464 |
+
.model-switcher{
|
| 465 |
+
display:flex;gap:4px;background:var(--soft);border:1px solid var(--line);border-radius:10px;padding:3px;
|
| 466 |
+
flex-wrap:wrap;
|
| 467 |
+
}
|
| 468 |
+
.model-btn{
|
| 469 |
+
display:inline-flex;align-items:center;justify-content:center;gap:6px;
|
| 470 |
+
padding:6px 14px;border:none;border-radius:8px;cursor:pointer;
|
| 471 |
+
font-size:13px;font-weight:600;font-family:'Inter',sans-serif;
|
| 472 |
+
color:var(--muted-2);background:transparent;transition:all .2s ease;white-space:nowrap;
|
| 473 |
+
}
|
| 474 |
+
.model-btn:hover{color:var(--muted);background:rgba(224,17,95,.08)}
|
| 475 |
+
.model-btn.active{
|
| 476 |
+
color:#fff!important;-webkit-text-fill-color:#fff!important;
|
| 477 |
+
background:linear-gradient(135deg,var(--ruby),#b90e4f)!important;
|
| 478 |
+
box-shadow:0 2px 8px rgba(224,17,95,.35);
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
.app-main-row{display:flex;gap:0;flex:1;overflow:hidden}
|
| 482 |
+
.app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid var(--line)}
|
| 483 |
+
.app-main-right{width:460px;display:flex;flex-direction:column;flex-shrink:0;background:var(--panel)}
|
| 484 |
+
|
| 485 |
+
#vision-drop-wrap{
|
| 486 |
+
position:relative;background:var(--soft);margin:0;min-height:480px;overflow:hidden;
|
| 487 |
+
display:flex;align-items:center;justify-content:center;
|
| 488 |
+
}
|
| 489 |
+
#vision-drop-wrap.drag-over{
|
| 490 |
+
outline:2px solid var(--ruby);outline-offset:-2px;background:rgba(224,17,95,.04)
|
| 491 |
+
}
|
| 492 |
+
#vision-preview-image{
|
| 493 |
+
display:none;
|
| 494 |
+
max-width:100%;max-height:540px;object-fit:contain;
|
| 495 |
+
}
|
| 496 |
+
.upload-prompt-modern{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:20}
|
| 497 |
+
.upload-click-area{
|
| 498 |
+
display:flex;flex-direction:column;align-items:center;justify-content:center;
|
| 499 |
+
cursor:pointer;padding:36px 52px;border:2px dashed #3f3f46;border-radius:16px;
|
| 500 |
+
background:rgba(224,17,95,.03);transition:all .2s ease;gap:8px;
|
| 501 |
+
}
|
| 502 |
+
.upload-click-area:hover{background:rgba(224,17,95,.08);border-color:var(--ruby);transform:scale(1.03)}
|
| 503 |
+
.upload-click-area:active{background:rgba(224,17,95,.12);transform:scale(.98)}
|
| 504 |
+
.upload-click-area svg{width:88px;height:88px}
|
| 505 |
+
.upload-main-text{color:var(--muted-2);font-size:14px;font-weight:500;margin-top:4px}
|
| 506 |
+
.upload-sub-text{color:#52525b;font-size:12px}
|
| 507 |
+
|
| 508 |
+
.hint-bar{
|
| 509 |
+
background:rgba(224,17,95,.06);border-top:1px solid var(--line);border-bottom:1px solid var(--line);
|
| 510 |
+
padding:10px 20px;font-size:13px;color:var(--muted);line-height:1.7;
|
| 511 |
+
}
|
| 512 |
+
.hint-bar b{color:#ffb0ca;font-weight:600}
|
| 513 |
+
.hint-bar kbd{
|
| 514 |
+
display:inline-block;padding:1px 6px;background:var(--line);border:1px solid #3f3f46;
|
| 515 |
+
border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:var(--muted);
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
.examples-section{background:var(--panel);border-top:1px solid var(--line)}
|
| 519 |
+
.examples-title{
|
| 520 |
+
padding:8px 16px;font-size:12px;font-weight:600;color:var(--muted-2);text-transform:uppercase;
|
| 521 |
+
letter-spacing:.8px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:8px;
|
| 522 |
+
}
|
| 523 |
+
.examples-title::before{
|
| 524 |
+
content:'✦';font-size:12px;color:var(--ruby);background:rgba(224,17,95,.12);
|
| 525 |
+
padding:2px 6px;border-radius:4px;
|
| 526 |
+
}
|
| 527 |
+
.examples-grid{display:flex;gap:10px;padding:12px 16px;overflow-x:auto}
|
| 528 |
+
.examples-grid::-webkit-scrollbar{height:6px}
|
| 529 |
+
.examples-grid::-webkit-scrollbar-track{background:var(--panel)}
|
| 530 |
+
.examples-grid::-webkit-scrollbar-thumb{background:var(--line);border-radius:3px}
|
| 531 |
+
.examples-grid::-webkit-scrollbar-thumb:hover{background:#3f3f46}
|
| 532 |
+
.example-card{
|
| 533 |
+
flex:0 0 auto;width:170px;cursor:pointer;border:2px solid var(--line);border-radius:10px;
|
| 534 |
+
overflow:hidden;transition:all .2s ease;background:var(--soft);user-select:none;-webkit-user-select:none;position:relative;
|
| 535 |
+
}
|
| 536 |
+
.example-card:hover{
|
| 537 |
+
border-color:var(--ruby);transform:translateY(-3px);
|
| 538 |
+
box-shadow:0 6px 20px rgba(224,17,95,.25),0 0 0 1px rgba(224,17,95,.1);
|
| 539 |
+
}
|
| 540 |
+
.example-card:active{transform:translateY(-1px) scale(.98);box-shadow:0 2px 8px rgba(224,17,95,.2)}
|
| 541 |
+
.example-card.example-loading{pointer-events:none;opacity:.7}
|
| 542 |
+
.example-card.example-loading .example-overlay{display:flex!important;background:rgba(9,9,11,.85)!important}
|
| 543 |
+
.example-card.example-loading .example-overlay::after{
|
| 544 |
+
content:'';width:24px;height:24px;border:2px solid var(--line);border-top-color:var(--ruby);
|
| 545 |
+
border-radius:50%;animation:spin .7s linear infinite;
|
| 546 |
+
}
|
| 547 |
+
.example-card.example-active{
|
| 548 |
+
border-color:#ff6f9f!important;
|
| 549 |
+
box-shadow:0 0 0 2px rgba(224,17,95,.3),0 4px 12px rgba(224,17,95,.2)!important;
|
| 550 |
+
}
|
| 551 |
+
.example-img-wrap{position:relative;overflow:hidden}
|
| 552 |
+
.example-img-wrap img{width:100%;height:105px;object-fit:cover;display:block;transition:transform .3s ease}
|
| 553 |
+
.example-card:hover .example-img-wrap img{transform:scale(1.06)}
|
| 554 |
+
.example-overlay{
|
| 555 |
+
position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.5);
|
| 556 |
+
display:none;align-items:center;justify-content:center;transition:all .2s ease;
|
| 557 |
+
}
|
| 558 |
+
.example-info{
|
| 559 |
+
padding:7px 10px;display:flex;align-items:center;justify-content:space-between;
|
| 560 |
+
border-top:1px solid var(--line);gap:4px;
|
| 561 |
+
}
|
| 562 |
+
.example-label{font-size:12px;font-weight:600;color:var(--muted)}
|
| 563 |
+
.example-size{
|
| 564 |
+
font-family:'JetBrains Mono',monospace;font-size:10px;color:#52525b;
|
| 565 |
+
background:var(--panel);padding:1px 6px;border-radius:4px;border:1px solid var(--line);
|
| 566 |
+
}
|
| 567 |
+
.example-prompt{
|
| 568 |
+
padding:8px 10px 10px;
|
| 569 |
+
color:#8f8f96;
|
| 570 |
+
font-size:11px;
|
| 571 |
+
line-height:1.4;
|
| 572 |
+
border-top:1px solid rgba(39,39,42,.6);
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
.panel-card{border-bottom:1px solid var(--line)}
|
| 576 |
+
.panel-card-title{
|
| 577 |
+
padding:12px 20px;font-size:12px;font-weight:600;color:var(--muted-2);text-transform:uppercase;
|
| 578 |
+
letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);
|
| 579 |
+
}
|
| 580 |
+
.panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:10px}
|
| 581 |
+
.modern-label{font-size:13px;font-weight:500;color:var(--muted);margin-bottom:4px;display:block}
|
| 582 |
+
.modern-textarea,.modern-select{
|
| 583 |
+
width:100%;background:var(--soft);border:1px solid var(--line);border-radius:8px;
|
| 584 |
+
padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:var(--text);
|
| 585 |
+
resize:vertical;outline:none;min-height:42px;transition:border-color .2s;
|
| 586 |
+
}
|
| 587 |
+
.modern-select{min-height:44px}
|
| 588 |
+
.modern-textarea:focus,.modern-select:focus{border-color:var(--ruby);box-shadow:0 0 0 3px rgba(224,17,95,.15)}
|
| 589 |
+
.modern-textarea::placeholder{color:#3f3f46}
|
| 590 |
+
.modern-textarea.error-flash,.image-box.error-flash{
|
| 591 |
+
border-color:var(--ruby)!important;box-shadow:0 0 0 3px rgba(224,17,95,.25)!important;animation:shake .4s ease;
|
| 592 |
+
}
|
| 593 |
+
@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}
|
| 594 |
+
|
| 595 |
+
.btn-run{
|
| 596 |
+
display:flex;align-items:center;justify-content:center;gap:8px;width:100%;
|
| 597 |
+
background:linear-gradient(135deg,var(--ruby),#b90e4f);border:none;border-radius:10px;
|
| 598 |
+
padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif;
|
| 599 |
+
color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px;
|
| 600 |
+
box-shadow:0 4px 16px rgba(224,17,95,.3),inset 0 1px 0 rgba(255,255,255,.1);
|
| 601 |
+
}
|
| 602 |
+
.btn-run:hover{
|
| 603 |
+
background:linear-gradient(135deg,var(--ruby-3),var(--ruby));transform:translateY(-1px);
|
| 604 |
+
box-shadow:0 6px 24px rgba(224,17,95,.45),inset 0 1px 0 rgba(255,255,255,.15);
|
| 605 |
+
}
|
| 606 |
+
.btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(224,17,95,.3)}
|
| 607 |
+
.btn-run svg{width:18px;height:18px;fill:#ffffff!important}
|
| 608 |
+
.btn-run svg path{fill:#ffffff!important}
|
| 609 |
+
|
| 610 |
+
.output-frame{border-bottom:1px solid var(--line);display:flex;flex-direction:column;position:relative}
|
| 611 |
+
.output-frame .out-title{
|
| 612 |
+
padding:10px 20px;font-size:13px;font-weight:700;color:#ffffff!important;
|
| 613 |
+
-webkit-text-fill-color:#ffffff!important;text-transform:uppercase;letter-spacing:.8px;
|
| 614 |
+
border-bottom:1px solid rgba(39,39,42,.6);display:flex;align-items:center;justify-content:space-between;
|
| 615 |
+
}
|
| 616 |
+
.output-frame .out-title span{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important}
|
| 617 |
+
.output-frame .out-body{
|
| 618 |
+
flex:1;background:var(--soft);display:flex;align-items:flex-start;justify-content:flex-start;
|
| 619 |
+
overflow:auto;min-height:190px;position:relative;padding:14px;
|
| 620 |
+
}
|
| 621 |
+
.output-frame .out-placeholder{color:#3f3f46;font-size:13px;text-align:center;padding:20px;width:100%}
|
| 622 |
+
.out-download-btn{
|
| 623 |
+
display:none;align-items:center;justify-content:center;background:rgba(224,17,95,.1);
|
| 624 |
+
border:1px solid rgba(224,17,95,.2);border-radius:6px;cursor:pointer;padding:3px 10px;
|
| 625 |
+
font-size:11px;font-weight:500;color:#ffc1d6!important;gap:4px;height:24px;transition:all .15s;
|
| 626 |
+
}
|
| 627 |
+
.out-download-btn:hover{background:rgba(224,17,95,.2);border-color:rgba(224,17,95,.35);color:#ffffff!important}
|
| 628 |
+
.out-download-btn.visible{display:inline-flex}
|
| 629 |
+
.out-download-btn svg{width:12px;height:12px;fill:#ffc1d6}
|
| 630 |
+
|
| 631 |
+
.modern-loader{
|
| 632 |
+
display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);
|
| 633 |
+
z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);
|
| 634 |
+
}
|
| 635 |
+
.modern-loader.active{display:flex}
|
| 636 |
+
.modern-loader .loader-spinner{
|
| 637 |
+
width:36px;height:36px;border:3px solid var(--line);border-top-color:var(--ruby);
|
| 638 |
+
border-radius:50%;animation:spin .8s linear infinite;
|
| 639 |
+
}
|
| 640 |
+
@keyframes spin{to{transform:rotate(360deg)}}
|
| 641 |
+
.modern-loader .loader-text{font-size:13px;color:var(--muted);font-weight:500}
|
| 642 |
+
.loader-bar-track{width:200px;height:4px;background:var(--line);border-radius:2px;overflow:hidden}
|
| 643 |
+
.loader-bar-fill{
|
| 644 |
+
height:100%;background:linear-gradient(90deg,var(--ruby),var(--ruby-3),var(--ruby));
|
| 645 |
+
background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;
|
| 646 |
+
}
|
| 647 |
+
@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
|
| 648 |
+
|
| 649 |
+
.settings-group{border:1px solid var(--line);border-radius:10px;margin:12px 16px;padding:0;overflow:hidden}
|
| 650 |
+
.settings-group-title{
|
| 651 |
+
font-size:12px;font-weight:600;color:var(--muted-2);text-transform:uppercase;letter-spacing:.8px;
|
| 652 |
+
padding:10px 16px;border-bottom:1px solid var(--line);background:rgba(24,24,27,.5);
|
| 653 |
+
}
|
| 654 |
+
.settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}
|
| 655 |
+
.slider-row{display:flex;align-items:center;gap:10px;min-height:28px}
|
| 656 |
+
.slider-row label{font-size:13px;font-weight:500;color:var(--muted);min-width:120px;flex-shrink:0}
|
| 657 |
+
.slider-row input[type="range"]{
|
| 658 |
+
flex:1;-webkit-appearance:none;appearance:none;height:6px;background:var(--line);
|
| 659 |
+
border-radius:3px;outline:none;min-width:0;
|
| 660 |
+
}
|
| 661 |
+
.slider-row input[type="range"]::-webkit-slider-thumb{
|
| 662 |
+
-webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,var(--ruby),#b90e4f);
|
| 663 |
+
border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(224,17,95,.4);transition:transform .15s;
|
| 664 |
+
}
|
| 665 |
+
.slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}
|
| 666 |
+
.slider-row input[type="range"]::-moz-range-thumb{
|
| 667 |
+
width:16px;height:16px;background:linear-gradient(135deg,var(--ruby),#b90e4f);
|
| 668 |
+
border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(224,17,95,.4);
|
| 669 |
+
}
|
| 670 |
+
.slider-row .slider-val{
|
| 671 |
+
min-width:58px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;
|
| 672 |
+
font-weight:500;padding:3px 8px;background:var(--soft);border:1px solid var(--line);
|
| 673 |
+
border-radius:6px;color:var(--muted);flex-shrink:0;
|
| 674 |
+
}
|
| 675 |
+
.note-text{
|
| 676 |
+
color:var(--muted-2);
|
| 677 |
+
font-size:12px;
|
| 678 |
+
line-height:1.5;
|
| 679 |
+
padding:0 16px 12px;
|
| 680 |
+
}
|
| 681 |
+
.raw-text{
|
| 682 |
+
width:100%;
|
| 683 |
+
min-height:220px;
|
| 684 |
+
background:var(--soft);
|
| 685 |
+
border:1px solid var(--line);
|
| 686 |
+
border-radius:10px;
|
| 687 |
+
padding:14px;
|
| 688 |
+
color:var(--text);
|
| 689 |
+
font-family:'JetBrains Mono',monospace;
|
| 690 |
+
font-size:12px;
|
| 691 |
+
line-height:1.6;
|
| 692 |
+
white-space:pre-wrap;
|
| 693 |
+
word-break:break-word;
|
| 694 |
+
outline:none;
|
| 695 |
+
}
|
| 696 |
+
.md-view{
|
| 697 |
+
width:100%;
|
| 698 |
+
color:var(--text);
|
| 699 |
+
line-height:1.6;
|
| 700 |
+
font-size:14px;
|
| 701 |
+
}
|
| 702 |
+
.md-view h1,.md-view h2,.md-view h3,.md-view h4{color:#fff}
|
| 703 |
+
.md-view pre,.md-view code{
|
| 704 |
+
background:#111217;
|
| 705 |
+
border:1px solid var(--line);
|
| 706 |
+
border-radius:8px;
|
| 707 |
+
}
|
| 708 |
+
.md-view table{border-collapse:collapse;width:100%}
|
| 709 |
+
.md-view th,.md-view td{border:1px solid var(--line);padding:8px}
|
| 710 |
+
.md-view blockquote{border-left:3px solid var(--ruby);padding-left:12px;color:#c4c4cb}
|
| 711 |
+
|
| 712 |
+
.app-statusbar{
|
| 713 |
+
background:var(--panel);border-top:1px solid var(--line);padding:6px 20px;
|
| 714 |
+
display:flex;gap:12px;height:34px;align-items:center;font-size:12px;
|
| 715 |
+
}
|
| 716 |
+
.app-statusbar .sb-section{
|
| 717 |
+
padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;
|
| 718 |
+
font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap;
|
| 719 |
+
}
|
| 720 |
+
.app-statusbar .sb-fixed,.app-statusbar .sb-model{
|
| 721 |
+
flex:0 0 auto;min-width:120px;text-align:center;justify-content:center;
|
| 722 |
+
padding:3px 12px;background:rgba(224,17,95,.08);border-radius:6px;color:#ff87b0;font-weight:500;
|
| 723 |
+
}
|
| 724 |
+
.app-statusbar .sb-fixed{min-width:90px}
|
| 725 |
+
|
| 726 |
+
::-webkit-scrollbar{width:8px;height:8px}
|
| 727 |
+
::-webkit-scrollbar-track{background:var(--soft)}
|
| 728 |
+
::-webkit-scrollbar-thumb{background:var(--line);border-radius:4px}
|
| 729 |
+
::-webkit-scrollbar-thumb:hover{background:#3f3f46}
|
| 730 |
+
|
| 731 |
+
@media(max-width:980px){
|
| 732 |
+
.app-main-row{flex-direction:column}
|
| 733 |
+
.app-main-right{width:100%}
|
| 734 |
+
.app-main-left{border-right:none;border-bottom:1px solid var(--line)}
|
| 735 |
+
.model-switcher{flex-wrap:wrap}
|
| 736 |
+
.examples-grid{gap:8px;padding:10px 12px}
|
| 737 |
+
.example-card{width:150px}
|
| 738 |
+
.example-img-wrap img{height:92px}
|
| 739 |
+
}
|
| 740 |
+
"""
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
app_js = r"""
|
| 744 |
+
() => {
|
| 745 |
+
function init() {
|
| 746 |
+
if (window.__ocrAppInitDone) return;
|
| 747 |
+
|
| 748 |
+
const wrap = document.getElementById('vision-drop-wrap');
|
| 749 |
+
const uploadPrompt = document.getElementById('upload-prompt');
|
| 750 |
+
const uploadClickArea = document.getElementById('upload-click-area');
|
| 751 |
+
const fileInput = document.getElementById('custom-file-input');
|
| 752 |
+
const previewImg = document.getElementById('vision-preview-image');
|
| 753 |
+
|
| 754 |
+
const queryInput = document.getElementById('custom-query-input');
|
| 755 |
+
const runBtn = document.getElementById('custom-run-btn');
|
| 756 |
+
|
| 757 |
+
const rawView = document.getElementById('raw-output-view');
|
| 758 |
+
const mdView = document.getElementById('formatted-output-view');
|
| 759 |
+
|
| 760 |
+
const statusMain = document.getElementById('sb-status-label');
|
| 761 |
+
const statusModel = document.getElementById('sb-model-label');
|
| 762 |
+
const imageState = document.getElementById('sb-image-label');
|
| 763 |
+
|
| 764 |
+
const modelBtns = Array.from(document.querySelectorAll('.model-btn[data-model]'));
|
| 765 |
+
|
| 766 |
+
if (!wrap || !fileInput || !queryInput || !runBtn) {
|
| 767 |
+
setTimeout(init, 250);
|
| 768 |
+
return;
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
window.__ocrAppInitDone = true;
|
| 772 |
+
window.__currentModel = 'FireRed-OCR';
|
| 773 |
+
window.__currentImageData = '';
|
| 774 |
+
|
| 775 |
+
let toastTimer = null;
|
| 776 |
+
|
| 777 |
+
function showToast(message, type) {
|
| 778 |
+
let toast = document.getElementById('app-toast');
|
| 779 |
+
if (!toast) {
|
| 780 |
+
toast = document.createElement('div');
|
| 781 |
+
toast.id = 'app-toast';
|
| 782 |
+
toast.className = 'toast-notification';
|
| 783 |
+
toast.innerHTML = '<span class="toast-icon"></span><span class="toast-text"></span>';
|
| 784 |
+
document.body.appendChild(toast);
|
| 785 |
+
}
|
| 786 |
+
const icon = toast.querySelector('.toast-icon');
|
| 787 |
+
const text = toast.querySelector('.toast-text');
|
| 788 |
+
toast.className = 'toast-notification ' + (type || 'error');
|
| 789 |
+
if (type === 'warning') icon.textContent = '⚠';
|
| 790 |
+
else if (type === 'info') icon.textContent = 'ℹ';
|
| 791 |
+
else icon.textContent = '✕';
|
| 792 |
+
text.textContent = message;
|
| 793 |
+
if (toastTimer) clearTimeout(toastTimer);
|
| 794 |
+
void toast.offsetWidth;
|
| 795 |
+
toast.classList.add('visible');
|
| 796 |
+
toastTimer = setTimeout(function() { toast.classList.remove('visible'); }, 3500);
|
| 797 |
+
}
|
| 798 |
+
window.__showToast = showToast;
|
| 799 |
+
|
| 800 |
+
function setStatus(text) {
|
| 801 |
+
if (statusMain) statusMain.textContent = text || 'Ready';
|
| 802 |
+
}
|
| 803 |
+
|
| 804 |
+
function setGradioValue(containerId, value) {
|
| 805 |
+
var container = document.getElementById(containerId);
|
| 806 |
+
if (!container) return;
|
| 807 |
+
container.querySelectorAll('input, textarea').forEach(function(el) {
|
| 808 |
+
if (el.type === 'file' || el.type === 'range' || el.type === 'checkbox') return;
|
| 809 |
+
var proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
| 810 |
+
var ns = Object.getOwnPropertyDescriptor(proto, 'value');
|
| 811 |
+
if (ns && ns.set) {
|
| 812 |
+
ns.set.call(el, value);
|
| 813 |
+
el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
|
| 814 |
+
el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
|
| 815 |
+
}
|
| 816 |
+
});
|
| 817 |
+
}
|
| 818 |
+
window.__setGradioValue = setGradioValue;
|
| 819 |
+
|
| 820 |
+
function setSliderValue(containerId, value) {
|
| 821 |
+
var container = document.getElementById(containerId);
|
| 822 |
+
if (!container) return;
|
| 823 |
+
container.querySelectorAll('input[type="range"], input[type="number"]').forEach(function(el) {
|
| 824 |
+
var ns = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
|
| 825 |
+
if (ns && ns.set) {
|
| 826 |
+
ns.set.call(el, String(value));
|
| 827 |
+
el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));
|
| 828 |
+
el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));
|
| 829 |
+
}
|
| 830 |
+
});
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
function renderMarkdown(src) {
|
| 834 |
+
if (!mdView) return;
|
| 835 |
+
if (!src || !src.trim()) {
|
| 836 |
+
mdView.innerHTML = '<div class="out-placeholder">Formatted markdown will appear here</div>';
|
| 837 |
+
return;
|
| 838 |
+
}
|
| 839 |
+
if (window.marked && typeof window.marked.parse === 'function') {
|
| 840 |
+
mdView.innerHTML = '<div class="md-view">' + window.marked.parse(src) + '</div>';
|
| 841 |
+
} else {
|
| 842 |
+
mdView.innerHTML = '<pre class="raw-text">' + src.replace(/[&<>]/g, function(c){
|
| 843 |
+
return {'&':'&','<':'<','>':'>'}[c];
|
| 844 |
+
}) + '</pre>';
|
| 845 |
+
}
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
function setRawOutput(text) {
|
| 849 |
+
if (!rawView) return;
|
| 850 |
+
if (!text || !text.trim()) {
|
| 851 |
+
rawView.innerHTML = '<div class="out-placeholder">Raw output stream will appear here</div>';
|
| 852 |
+
return;
|
| 853 |
+
}
|
| 854 |
+
const esc = text.replace(/[&<>]/g, function(c){ return {'&':'&','<':'<','>':'>'}[c]; });
|
| 855 |
+
rawView.innerHTML = '<pre class="raw-text">' + esc + '</pre>';
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
function clearOutputs() {
|
| 859 |
+
setRawOutput('');
|
| 860 |
+
renderMarkdown('');
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
function showLoaders() {
|
| 864 |
+
var l1=document.getElementById('output-loader-raw'), l2=document.getElementById('output-loader-md');
|
| 865 |
+
if(l1)l1.classList.add('active');
|
| 866 |
+
if(l2)l2.classList.add('active');
|
| 867 |
+
setStatus('Processing...');
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
+
function hideLoaders() {
|
| 871 |
+
var l1=document.getElementById('output-loader-raw'), l2=document.getElementById('output-loader-md');
|
| 872 |
+
if(l1)l1.classList.remove('active');
|
| 873 |
+
if(l2)l2.classList.remove('active');
|
| 874 |
+
setStatus('Done');
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
window.__showLoaders = showLoaders;
|
| 878 |
+
window.__hideLoaders = hideLoaders;
|
| 879 |
+
|
| 880 |
+
function flashError(el) {
|
| 881 |
+
if (!el) return;
|
| 882 |
+
el.classList.add('error-flash');
|
| 883 |
+
setTimeout(() => el.classList.remove('error-flash'), 800);
|
| 884 |
+
}
|
| 885 |
+
|
| 886 |
+
function setModel(modelName) {
|
| 887 |
+
window.__currentModel = modelName;
|
| 888 |
+
modelBtns.forEach(btn => btn.classList.toggle('active', btn.getAttribute('data-model') === modelName));
|
| 889 |
+
setGradioValue('hidden-model-choice', modelName);
|
| 890 |
+
if (statusModel) statusModel.textContent = modelName;
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
modelBtns.forEach(btn => {
|
| 894 |
+
btn.addEventListener('click', function() {
|
| 895 |
+
const m = btn.getAttribute('data-model');
|
| 896 |
+
setModel(m);
|
| 897 |
+
});
|
| 898 |
+
});
|
| 899 |
+
|
| 900 |
+
function syncQuery() {
|
| 901 |
+
setGradioValue('hidden-query-input', queryInput.value || '');
|
| 902 |
+
}
|
| 903 |
+
queryInput.addEventListener('input', syncQuery);
|
| 904 |
+
|
| 905 |
+
function syncSelect(selectId, hiddenId) {
|
| 906 |
+
const el = document.getElementById(selectId);
|
| 907 |
+
if (!el) return;
|
| 908 |
+
el.addEventListener('change', function() {
|
| 909 |
+
setGradioValue(hiddenId, el.value);
|
| 910 |
+
});
|
| 911 |
+
}
|
| 912 |
+
|
| 913 |
+
function syncSlider(customId, gradioId) {
|
| 914 |
+
var slider = document.getElementById(customId);
|
| 915 |
+
var valSpan = document.getElementById(customId+'-val');
|
| 916 |
+
if (!slider) return;
|
| 917 |
+
slider.addEventListener('input', function() {
|
| 918 |
+
if (valSpan) valSpan.textContent = slider.value;
|
| 919 |
+
setSliderValue(gradioId, slider.value);
|
| 920 |
+
});
|
| 921 |
+
}
|
| 922 |
+
|
| 923 |
+
syncSlider('custom-max-new-tokens', 'gradio-max-new-tokens');
|
| 924 |
+
syncSlider('custom-temperature', 'gradio-temperature');
|
| 925 |
+
syncSlider('custom-top-p', 'gradio-top-p');
|
| 926 |
+
syncSlider('custom-top-k', 'gradio-top-k');
|
| 927 |
+
syncSlider('custom-repetition-penalty', 'gradio-repetition-penalty');
|
| 928 |
+
|
| 929 |
+
syncSelect('custom-gpu-duration', 'gpu-duration-input');
|
| 930 |
+
|
| 931 |
+
function loadImageFromDataUrl(dataUrl, filename) {
|
| 932 |
+
if (!dataUrl) return;
|
| 933 |
+
previewImg.src = dataUrl;
|
| 934 |
+
previewImg.style.display = 'block';
|
| 935 |
+
if (uploadPrompt) uploadPrompt.style.display = 'none';
|
| 936 |
+
window.__currentImageData = dataUrl;
|
| 937 |
+
setGradioValue('hidden-image-b64', dataUrl);
|
| 938 |
+
if (imageState) imageState.textContent = filename || 'Image loaded';
|
| 939 |
+
setStatus('Image loaded');
|
| 940 |
+
}
|
| 941 |
+
window.__loadImageFromDataUrl = loadImageFromDataUrl;
|
| 942 |
+
|
| 943 |
+
function processFiles(files) {
|
| 944 |
+
Array.from(files).forEach(function(file) {
|
| 945 |
+
if (!file.type.startsWith('image/')) return;
|
| 946 |
+
var reader = new FileReader();
|
| 947 |
+
reader.onload = function(ev) {
|
| 948 |
+
document.querySelectorAll('.example-card.example-active').forEach(function(c) { c.classList.remove('example-active'); });
|
| 949 |
+
loadImageFromDataUrl(ev.target.result, file.name);
|
| 950 |
+
showToast('Image loaded', 'info');
|
| 951 |
+
};
|
| 952 |
+
reader.readAsDataURL(file);
|
| 953 |
+
});
|
| 954 |
+
}
|
| 955 |
+
|
| 956 |
+
fileInput.addEventListener('change', function(e) { processFiles(e.target.files); e.target.value = ''; });
|
| 957 |
+
if (uploadClickArea) uploadClickArea.addEventListener('click', function() { fileInput.click(); });
|
| 958 |
+
|
| 959 |
+
wrap.addEventListener('dragover', function(e) { e.preventDefault(); wrap.classList.add('drag-over'); });
|
| 960 |
+
wrap.addEventListener('dragleave', function(e) { e.preventDefault(); wrap.classList.remove('drag-over'); });
|
| 961 |
+
wrap.addEventListener('drop', function(e) {
|
| 962 |
+
e.preventDefault(); wrap.classList.remove('drag-over');
|
| 963 |
+
if (e.dataTransfer.files.length) processFiles(e.dataTransfer.files);
|
| 964 |
+
});
|
| 965 |
+
|
| 966 |
+
document.getElementById('tb-change-img')?.addEventListener('click', function(){ fileInput.click(); });
|
| 967 |
+
document.getElementById('tb-clear-img')?.addEventListener('click', function(){
|
| 968 |
+
previewImg.removeAttribute('src');
|
| 969 |
+
previewImg.style.display = 'none';
|
| 970 |
+
if (uploadPrompt) uploadPrompt.style.display = '';
|
| 971 |
+
window.__currentImageData = '';
|
| 972 |
+
setGradioValue('hidden-image-b64', '');
|
| 973 |
+
if (imageState) imageState.textContent = 'No image';
|
| 974 |
+
setStatus('Ready');
|
| 975 |
+
document.querySelectorAll('.example-card.example-active').forEach(function(c) { c.classList.remove('example-active'); });
|
| 976 |
+
showToast('Image removed', 'info');
|
| 977 |
+
});
|
| 978 |
+
|
| 979 |
+
window.__clickGradioRunBtn = function() {
|
| 980 |
+
const query = (queryInput.value || '').trim();
|
| 981 |
+
const img = window.__currentImageData || '';
|
| 982 |
+
const model = window.__currentModel || 'FireRed-OCR';
|
| 983 |
+
const gpuDuration = document.getElementById('custom-gpu-duration')?.value || '60';
|
| 984 |
+
|
| 985 |
+
if (!img) {
|
| 986 |
+
showToast('Please upload an image first', 'error');
|
| 987 |
+
flashError(wrap);
|
| 988 |
+
return;
|
| 989 |
+
}
|
| 990 |
+
if (!query) {
|
| 991 |
+
showToast('Please enter a query', 'warning');
|
| 992 |
+
flashError(queryInput);
|
| 993 |
+
queryInput.focus();
|
| 994 |
+
return;
|
| 995 |
+
}
|
| 996 |
+
if (!model) {
|
| 997 |
+
showToast('Please select a model', 'warning');
|
| 998 |
+
return;
|
| 999 |
+
}
|
| 1000 |
+
|
| 1001 |
+
syncQuery();
|
| 1002 |
+
setGradioValue('hidden-model-choice', model);
|
| 1003 |
+
setGradioValue('gpu-duration-input', gpuDuration);
|
| 1004 |
+
|
| 1005 |
+
clearOutputs();
|
| 1006 |
+
showLoaders();
|
| 1007 |
+
|
| 1008 |
+
setTimeout(function() {
|
| 1009 |
+
var gradioBtn=document.getElementById('gradio-run-btn');
|
| 1010 |
+
if(!gradioBtn) return;
|
| 1011 |
+
var btn=gradioBtn.querySelector('button');
|
| 1012 |
+
if(btn) btn.click(); else gradioBtn.click();
|
| 1013 |
+
}, 180);
|
| 1014 |
+
};
|
| 1015 |
+
|
| 1016 |
+
runBtn.addEventListener('click', function() {
|
| 1017 |
+
window.__clickGradioRunBtn();
|
| 1018 |
+
});
|
| 1019 |
+
|
| 1020 |
+
document.querySelectorAll('.example-card[data-example-idx]').forEach(function(card) {
|
| 1021 |
+
card.addEventListener('click', function() {
|
| 1022 |
+
var idx = card.getAttribute('data-example-idx');
|
| 1023 |
+
|
| 1024 |
+
document.querySelectorAll('.example-card.example-loading').forEach(function(c) { c.classList.remove('example-loading'); });
|
| 1025 |
+
document.querySelectorAll('.example-card.example-active').forEach(function(c) { c.classList.remove('example-active'); });
|
| 1026 |
+
card.classList.add('example-loading');
|
| 1027 |
+
|
| 1028 |
+
showToast('Loading example...', 'info');
|
| 1029 |
+
|
| 1030 |
+
setGradioValue('example-result-data', '');
|
| 1031 |
+
setGradioValue('example-idx-input', idx);
|
| 1032 |
+
|
| 1033 |
+
setTimeout(function() {
|
| 1034 |
+
var btn = document.getElementById('example-load-btn');
|
| 1035 |
+
if (btn) {
|
| 1036 |
+
var b = btn.querySelector('button');
|
| 1037 |
+
if (b) b.click(); else btn.click();
|
| 1038 |
+
}
|
| 1039 |
+
}, 150);
|
| 1040 |
+
|
| 1041 |
+
setTimeout(function() { card.classList.remove('example-loading'); }, 12000);
|
| 1042 |
+
});
|
| 1043 |
+
});
|
| 1044 |
+
|
| 1045 |
+
setModel('FireRed-OCR');
|
| 1046 |
+
syncQuery();
|
| 1047 |
+
clearOutputs();
|
| 1048 |
+
setStatus('Ready');
|
| 1049 |
+
}
|
| 1050 |
+
init();
|
| 1051 |
+
}
|
| 1052 |
+
"""
|
| 1053 |
+
|
| 1054 |
+
wire_outputs_js = r"""
|
| 1055 |
+
() => {
|
| 1056 |
+
function watchOutputs() {
|
| 1057 |
+
var rawContainer = document.getElementById('gradio-raw-output');
|
| 1058 |
+
var mdContainer = document.getElementById('gradio-formatted-output');
|
| 1059 |
+
if (!rawContainer || !mdContainer) { setTimeout(watchOutputs, 500); return; }
|
| 1060 |
+
|
| 1061 |
+
var rawTarget = document.getElementById('raw-output-view');
|
| 1062 |
+
var mdTarget = document.getElementById('formatted-output-view');
|
| 1063 |
+
var lastRaw = '';
|
| 1064 |
+
var lastMd = '';
|
| 1065 |
+
|
| 1066 |
+
function esc(t){
|
| 1067 |
+
return (t || '').replace(/[&<>]/g, function(c){
|
| 1068 |
+
return {'&':'&','<':'<','>':'>'}[c];
|
| 1069 |
+
});
|
| 1070 |
+
}
|
| 1071 |
+
|
| 1072 |
+
function renderMarkdown(src) {
|
| 1073 |
+
if (!mdTarget) return;
|
| 1074 |
+
if (!src || !src.trim()) {
|
| 1075 |
+
mdTarget.innerHTML = '<div class="out-placeholder">Formatted markdown will appear here</div>';
|
| 1076 |
+
return;
|
| 1077 |
+
}
|
| 1078 |
+
if (window.marked && typeof window.marked.parse === 'function') {
|
| 1079 |
+
mdTarget.innerHTML = '<div class="md-view">' + window.marked.parse(src) + '</div>';
|
| 1080 |
+
} else {
|
| 1081 |
+
mdTarget.innerHTML = '<pre class="raw-text">' + esc(src) + '</pre>';
|
| 1082 |
+
}
|
| 1083 |
+
}
|
| 1084 |
+
|
| 1085 |
+
function syncOutputs() {
|
| 1086 |
+
var rawEl = rawContainer.querySelector('textarea, input');
|
| 1087 |
+
var mdEl = mdContainer.querySelector('textarea, input');
|
| 1088 |
+
|
| 1089 |
+
var rawVal = rawEl ? rawEl.value : '';
|
| 1090 |
+
var mdVal = mdEl ? mdEl.value : '';
|
| 1091 |
+
|
| 1092 |
+
if (rawVal !== lastRaw) {
|
| 1093 |
+
lastRaw = rawVal;
|
| 1094 |
+
if (rawTarget) {
|
| 1095 |
+
if (rawVal && rawVal.trim()) rawTarget.innerHTML = '<pre class="raw-text">' + esc(rawVal) + '</pre>';
|
| 1096 |
+
else rawTarget.innerHTML = '<div class="out-placeholder">Raw output stream will appear here</div>';
|
| 1097 |
+
}
|
| 1098 |
+
}
|
| 1099 |
+
|
| 1100 |
+
if (mdVal !== lastMd) {
|
| 1101 |
+
lastMd = mdVal;
|
| 1102 |
+
renderMarkdown(mdVal);
|
| 1103 |
+
}
|
| 1104 |
+
|
| 1105 |
+
if ((rawVal && rawVal.trim()) || (mdVal && mdVal.trim())) {
|
| 1106 |
+
if (window.__hideLoaders) window.__hideLoaders();
|
| 1107 |
+
}
|
| 1108 |
+
}
|
| 1109 |
+
|
| 1110 |
+
var obs1 = new MutationObserver(syncOutputs);
|
| 1111 |
+
var obs2 = new MutationObserver(syncOutputs);
|
| 1112 |
+
obs1.observe(rawContainer, {childList:true, subtree:true, characterData:true, attributes:true});
|
| 1113 |
+
obs2.observe(mdContainer, {childList:true, subtree:true, characterData:true, attributes:true});
|
| 1114 |
+
setInterval(syncOutputs, 500);
|
| 1115 |
+
}
|
| 1116 |
+
watchOutputs();
|
| 1117 |
+
|
| 1118 |
+
function watchExampleResults() {
|
| 1119 |
+
var container = document.getElementById('example-result-data');
|
| 1120 |
+
if (!container) { setTimeout(watchExampleResults, 500); return; }
|
| 1121 |
+
var lastProcessed = '';
|
| 1122 |
+
function checkResult() {
|
| 1123 |
+
var el = container.querySelector('textarea') || container.querySelector('input');
|
| 1124 |
+
if (!el) return;
|
| 1125 |
+
var val = el.value;
|
| 1126 |
+
if (!val || val === lastProcessed || val.length < 20) return;
|
| 1127 |
+
try {
|
| 1128 |
+
var data = JSON.parse(val);
|
| 1129 |
+
if (data.status === 'ok' && data.image) {
|
| 1130 |
+
lastProcessed = val;
|
| 1131 |
+
document.querySelectorAll('.example-card.example-active').forEach(function(c) { c.classList.remove('example-active'); });
|
| 1132 |
+
if (window.__loadImageFromDataUrl) window.__loadImageFromDataUrl(data.image, data.name || 'Example');
|
| 1133 |
+
var q = document.getElementById('custom-query-input');
|
| 1134 |
+
if (q && data.query != null) {
|
| 1135 |
+
q.value = data.query;
|
| 1136 |
+
q.dispatchEvent(new Event('input', {bubbles:true}));
|
| 1137 |
+
}
|
| 1138 |
+
document.querySelectorAll('.example-card.example-loading').forEach(function(c) {
|
| 1139 |
+
c.classList.remove('example-loading');
|
| 1140 |
+
c.classList.add('example-active');
|
| 1141 |
+
});
|
| 1142 |
+
if (window.__showToast) window.__showToast('Example loaded', 'info');
|
| 1143 |
+
} else if (data.status === 'error') {
|
| 1144 |
+
document.querySelectorAll('.example-card.example-loading').forEach(function(c) { c.classList.remove('example-loading'); });
|
| 1145 |
+
if (window.__showToast) window.__showToast('Could not load example image', 'error');
|
| 1146 |
+
}
|
| 1147 |
+
} catch(e) { console.error('Example parse error:', e); }
|
| 1148 |
+
}
|
| 1149 |
+
var obs = new MutationObserver(checkResult);
|
| 1150 |
+
obs.observe(container, {childList:true, subtree:true, characterData:true, attributes:true});
|
| 1151 |
+
setInterval(checkResult, 500);
|
| 1152 |
+
}
|
| 1153 |
+
watchExampleResults();
|
| 1154 |
+
|
| 1155 |
+
function watchSliderMirrors() {
|
| 1156 |
+
const pairs = [
|
| 1157 |
+
['gradio-max-new-tokens', 'custom-max-new-tokens', 'custom-max-new-tokens-val'],
|
| 1158 |
+
['gradio-temperature', 'custom-temperature', 'custom-temperature-val'],
|
| 1159 |
+
['gradio-top-p', 'custom-top-p', 'custom-top-p-val'],
|
| 1160 |
+
['gradio-top-k', 'custom-top-k', 'custom-top-k-val'],
|
| 1161 |
+
['gradio-repetition-penalty', 'custom-repetition-penalty', 'custom-repetition-penalty-val'],
|
| 1162 |
+
];
|
| 1163 |
+
|
| 1164 |
+
function syncOne(gradioId, customId, valId) {
|
| 1165 |
+
const g = document.getElementById(gradioId);
|
| 1166 |
+
const c = document.getElementById(customId);
|
| 1167 |
+
const v = document.getElementById(valId);
|
| 1168 |
+
if (!g || !c) return;
|
| 1169 |
+
const gi = g.querySelector('input[type="range"], input[type="number"]');
|
| 1170 |
+
if (gi && gi.value != null) {
|
| 1171 |
+
c.value = gi.value;
|
| 1172 |
+
if (v) v.textContent = gi.value;
|
| 1173 |
+
}
|
| 1174 |
+
}
|
| 1175 |
+
|
| 1176 |
+
function syncAll() {
|
| 1177 |
+
pairs.forEach(p => syncOne(...p));
|
| 1178 |
+
}
|
| 1179 |
+
|
| 1180 |
+
setInterval(syncAll, 800);
|
| 1181 |
+
}
|
| 1182 |
+
watchSliderMirrors();
|
| 1183 |
+
}
|
| 1184 |
+
"""
|
| 1185 |
+
|
| 1186 |
+
head_html = """
|
| 1187 |
+
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
| 1188 |
+
"""
|
| 1189 |
+
|
| 1190 |
+
DOWNLOAD_SVG = '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 16l-5-5h3V4h4v7h3l-5 5z"/><path d="M20 18H4v2h16v-2z"/></svg>'
|
| 1191 |
+
|
| 1192 |
|
| 1193 |
with gr.Blocks() as demo:
|
| 1194 |
+
# Hidden state / actual gradio components
|
| 1195 |
+
hidden_query = gr.Textbox(value=DEFAULT_QUERY, elem_id="hidden-query-input", elem_classes="hidden-input", container=False)
|
| 1196 |
+
hidden_image_b64 = gr.Textbox(value="", elem_id="hidden-image-b64", elem_classes="hidden-input", container=False)
|
| 1197 |
+
hidden_model_choice = gr.Textbox(value="FireRed-OCR", elem_id="hidden-model-choice", elem_classes="hidden-input", container=False)
|
| 1198 |
+
|
| 1199 |
+
max_new_tokens = gr.Slider(minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS, elem_id="gradio-max-new-tokens", elem_classes="hidden-input", container=False)
|
| 1200 |
+
temperature = gr.Slider(minimum=0.1, maximum=4.0, step=0.1, value=0.6, elem_id="gradio-temperature", elem_classes="hidden-input", container=False)
|
| 1201 |
+
top_p = gr.Slider(minimum=0.05, maximum=1.0, step=0.05, value=0.9, elem_id="gradio-top-p", elem_classes="hidden-input", container=False)
|
| 1202 |
+
top_k = gr.Slider(minimum=1, maximum=1000, step=1, value=50, elem_id="gradio-top-k", elem_classes="hidden-input", container=False)
|
| 1203 |
+
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)
|
| 1204 |
+
|
| 1205 |
+
gpu_duration_input = gr.Textbox(value="60", elem_id="gpu-duration-input", elem_classes="hidden-input", container=False)
|
| 1206 |
+
gpu_duration_state = gr.Number(value=60, visible=False)
|
| 1207 |
+
|
| 1208 |
+
raw_output = gr.Textbox(label="Raw Output Stream", elem_id="gradio-raw-output", elem_classes="hidden-input", container=False)
|
| 1209 |
+
formatted_output = gr.Textbox(label="Formatted Output", elem_id="gradio-formatted-output", elem_classes="hidden-input", container=False)
|
| 1210 |
+
|
| 1211 |
+
example_idx = gr.Textbox(value="", elem_id="example-idx-input", elem_classes="hidden-input", container=False)
|
| 1212 |
+
example_result = gr.Textbox(value="", elem_id="example-result-data", elem_classes="hidden-input", container=False)
|
| 1213 |
+
example_load_btn = gr.Button("Load Example", elem_id="example-load-btn")
|
| 1214 |
+
|
| 1215 |
+
gr.HTML(f"""
|
| 1216 |
+
<div class="app-shell">
|
| 1217 |
+
|
| 1218 |
+
<div class="app-header">
|
| 1219 |
+
<div class="app-header-left">
|
| 1220 |
+
<div class="app-logo" aria-hidden="true">
|
| 1221 |
+
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
| 1222 |
+
<path fill="white" d="M3 6.5C3 5.12 4.12 4 5.5 4h13C19.88 4 21 5.12 21 6.5v11c0 1.38-1.12 2.5-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5v-11Z" opacity=".18"/>
|
| 1223 |
+
<path fill="white" d="M5.5 5.5h13c.55 0 1 .45 1 1v7.2l-3.34-3.34a1 1 0 0 0-1.41 0l-3.1 3.1-1.66-1.66a1 1 0 0 0-1.41 0L4.5 15.88V6.5c0-.55.45-1 1-1Z"/>
|
| 1224 |
+
<circle cx="9" cy="9" r="1.7" fill="white"/>
|
| 1225 |
+
<path fill="white" d="M4.5 17.5v-.2l4.79-4.79 1.66 1.66a1 1 0 0 0 1.41 0l3.1-3.1 4.04 4.04v2.39c0 .55-.45 1-1 1h-13c-.55 0-1-.45-1-1Z"/>
|
| 1226 |
+
<path fill="white" d="M8.5 2.75a.75.75 0 0 1 .75-.75h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1-.75-.75Z" opacity=".85"/>
|
| 1227 |
+
</svg>
|
| 1228 |
+
</div>
|
| 1229 |
+
<span class="app-title">Vision OCR Studio</span>
|
| 1230 |
+
<span class="app-badge">Ruby Red</span>
|
| 1231 |
+
</div>
|
| 1232 |
+
|
| 1233 |
+
<div class="model-switcher">
|
| 1234 |
+
<button class="model-btn active" data-model="FireRed-OCR">FireRed</button>
|
| 1235 |
+
<button class="model-btn" data-model="Nanonets-OCR-s">Nanonets</button>
|
| 1236 |
+
<button class="model-btn" data-model="MonkeyOCR-Recognition">MonkeyOCR</button>
|
| 1237 |
+
<button class="model-btn" data-model="Thyme-RL">Thyme-RL</button>
|
| 1238 |
+
<button class="model-btn" data-model="Typhoon-OCR-7B">Typhoon</button>
|
| 1239 |
+
<button class="model-btn" data-model="SmolDocling-256M-preview">SmolDocling</button>
|
| 1240 |
+
</div>
|
| 1241 |
+
</div>
|
| 1242 |
+
|
| 1243 |
+
<div class="app-main-row">
|
| 1244 |
+
<div class="app-main-left">
|
| 1245 |
+
|
| 1246 |
+
<div class="app-header" style="padding:8px 16px;border-bottom:1px solid #27272a;">
|
| 1247 |
+
<div style="display:flex;gap:4px;align-items:center;flex-wrap:wrap;">
|
| 1248 |
+
<button id="tb-change-img" class="model-btn active" type="button">Upload…</button>
|
| 1249 |
+
<button id="tb-clear-img" class="model-btn" type="button">Clear</button>
|
| 1250 |
+
</div>
|
| 1251 |
+
</div>
|
| 1252 |
+
|
| 1253 |
+
<div id="vision-drop-wrap" class="image-box">
|
| 1254 |
+
<div id="upload-prompt" class="upload-prompt-modern">
|
| 1255 |
+
<div id="upload-click-area" class="upload-click-area">
|
| 1256 |
+
<svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
|
| 1257 |
+
<rect x="8" y="14" width="64" height="52" rx="6" fill="none" stroke="#E0115F" stroke-width="2" stroke-dasharray="4 3"/>
|
| 1258 |
+
<polygon points="12,62 30,40 42,50 54,34 68,62" fill="rgba(224,17,95,0.15)" stroke="#E0115F" stroke-width="1.5"/>
|
| 1259 |
+
<circle cx="28" cy="30" r="6" fill="rgba(224,17,95,0.2)" stroke="#E0115F" stroke-width="1.5"/>
|
| 1260 |
+
<path d="M55 21l4 4m0-4l-4 4" stroke="#fff" stroke-width="1.6" stroke-linecap="round"/>
|
| 1261 |
+
</svg>
|
| 1262 |
+
<span class="upload-main-text">Click or drag image here</span>
|
| 1263 |
+
<span class="upload-sub-text">Supports JPG, PNG, WebP</span>
|
| 1264 |
+
</div>
|
| 1265 |
+
</div>
|
| 1266 |
+
<input id="custom-file-input" type="file" accept="image/*" style="display:none;" />
|
| 1267 |
+
<img id="vision-preview-image" alt="Preview" />
|
| 1268 |
+
</div>
|
| 1269 |
+
|
| 1270 |
+
<div class="hint-bar" id="hint-bar-content">
|
| 1271 |
+
<b>Vision OCR:</b> Upload a document, receipt, page, chart, or screenshot ·
|
| 1272 |
+
<b>Prompt:</b> Describe the extraction task ·
|
| 1273 |
+
<kbd>Upload…</kbd> change image ·
|
| 1274 |
+
<kbd>Clear</kbd> remove image
|
| 1275 |
+
</div>
|
| 1276 |
+
|
| 1277 |
+
{examples_html_block}
|
| 1278 |
+
</div>
|
| 1279 |
+
|
| 1280 |
+
<div class="app-main-right">
|
| 1281 |
+
<div class="panel-card">
|
| 1282 |
+
<div class="panel-card-title">Instruction</div>
|
| 1283 |
+
<div class="panel-card-body">
|
| 1284 |
+
<label class="modern-label" for="custom-query-input">Query</label>
|
| 1285 |
+
<textarea id="custom-query-input" class="modern-textarea" rows="3" placeholder="Enter your query here...">{DEFAULT_QUERY}</textarea>
|
| 1286 |
+
|
| 1287 |
+
<label class="modern-label" for="custom-model-select">Model</label>
|
| 1288 |
+
<select id="custom-model-select" class="modern-select" style="display:none;">
|
| 1289 |
+
<option value="FireRed-OCR">FireRed-OCR</option>
|
| 1290 |
+
<option value="Nanonets-OCR-s">Nanonets-OCR-s</option>
|
| 1291 |
+
<option value="MonkeyOCR-Recognition">MonkeyOCR-Recognition</option>
|
| 1292 |
+
<option value="Thyme-RL">Thyme-RL</option>
|
| 1293 |
+
<option value="Typhoon-OCR-7B">Typhoon-OCR-7B</option>
|
| 1294 |
+
<option value="SmolDocling-256M-preview">SmolDocling-256M-preview</option>
|
| 1295 |
+
</select>
|
| 1296 |
+
</div>
|
| 1297 |
+
</div>
|
| 1298 |
+
|
| 1299 |
+
<div style="padding:12px 20px;">
|
| 1300 |
+
<button id="custom-run-btn" class="btn-run" type="button">
|
| 1301 |
+
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M19 7l-7 5-7-5V5l7 5 7-5v2zm0 6l-7 5-7-5v-2l7 5 7-5v2z"/></svg>
|
| 1302 |
+
<span id="run-btn-label">Run OCR</span>
|
| 1303 |
+
</button>
|
| 1304 |
+
</div>
|
| 1305 |
+
|
| 1306 |
+
<div class="output-frame" style="flex:1">
|
| 1307 |
+
<div class="out-title">
|
| 1308 |
+
<span>Raw Output Stream</span>
|
| 1309 |
+
<span id="dl-btn-output-raw" class="out-download-btn" title="Download">{DOWNLOAD_SVG} Save</span>
|
| 1310 |
+
</div>
|
| 1311 |
+
<div class="out-body" id="raw-output-view">
|
| 1312 |
+
<div class="modern-loader" id="output-loader-raw">
|
| 1313 |
+
<div class="loader-spinner"></div>
|
| 1314 |
+
<div class="loader-text">Streaming OCR output…</div>
|
| 1315 |
+
<div class="loader-bar-track"><div class="loader-bar-fill"></div></div>
|
| 1316 |
+
</div>
|
| 1317 |
+
<div class="out-placeholder">Raw output stream will appear here</div>
|
| 1318 |
+
</div>
|
| 1319 |
+
</div>
|
| 1320 |
+
|
| 1321 |
+
<div class="output-frame">
|
| 1322 |
+
<div class="out-title">
|
| 1323 |
+
<span>Formatted Result</span>
|
| 1324 |
+
<span id="dl-btn-output-md" class="out-download-btn" title="Download">{DOWNLOAD_SVG} Save</span>
|
| 1325 |
+
</div>
|
| 1326 |
+
<div class="out-body" id="formatted-output-view">
|
| 1327 |
+
<div class="modern-loader" id="output-loader-md">
|
| 1328 |
+
<div class="loader-spinner"></div>
|
| 1329 |
+
<div class="loader-text">Formatting result…</div>
|
| 1330 |
+
<div class="loader-bar-track"><div class="loader-bar-fill"></div></div>
|
| 1331 |
+
</div>
|
| 1332 |
+
<div class="out-placeholder">Formatted markdown will appear here</div>
|
| 1333 |
+
</div>
|
| 1334 |
+
</div>
|
| 1335 |
+
|
| 1336 |
+
<div class="settings-group">
|
| 1337 |
+
<div class="settings-group-title">Advanced Settings</div>
|
| 1338 |
+
<div class="settings-group-body">
|
| 1339 |
+
<div class="slider-row">
|
| 1340 |
+
<label>Max new tokens</label>
|
| 1341 |
+
<input type="range" id="custom-max-new-tokens" min="1" max="{MAX_MAX_NEW_TOKENS}" step="1" value="{DEFAULT_MAX_NEW_TOKENS}">
|
| 1342 |
+
<span class="slider-val" id="custom-max-new-tokens-val">{DEFAULT_MAX_NEW_TOKENS}</span>
|
| 1343 |
+
</div>
|
| 1344 |
+
|
| 1345 |
+
<div class="slider-row">
|
| 1346 |
+
<label>Temperature</label>
|
| 1347 |
+
<input type="range" id="custom-temperature" min="0.1" max="4.0" step="0.1" value="0.6">
|
| 1348 |
+
<span class="slider-val" id="custom-temperature-val">0.6</span>
|
| 1349 |
+
</div>
|
| 1350 |
+
|
| 1351 |
+
<div class="slider-row">
|
| 1352 |
+
<label>Top-p</label>
|
| 1353 |
+
<input type="range" id="custom-top-p" min="0.05" max="1.0" step="0.05" value="0.9">
|
| 1354 |
+
<span class="slider-val" id="custom-top-p-val">0.9</span>
|
| 1355 |
+
</div>
|
| 1356 |
+
|
| 1357 |
+
<div class="slider-row">
|
| 1358 |
+
<label>Top-k</label>
|
| 1359 |
+
<input type="range" id="custom-top-k" min="1" max="1000" step="1" value="50">
|
| 1360 |
+
<span class="slider-val" id="custom-top-k-val">50</span>
|
| 1361 |
+
</div>
|
| 1362 |
+
|
| 1363 |
+
<div class="slider-row">
|
| 1364 |
+
<label>Repetition penalty</label>
|
| 1365 |
+
<input type="range" id="custom-repetition-penalty" min="1.0" max="2.0" step="0.05" value="1.2">
|
| 1366 |
+
<span class="slider-val" id="custom-repetition-penalty-val">1.2</span>
|
| 1367 |
+
</div>
|
| 1368 |
+
|
| 1369 |
+
<div style="display:flex;flex-direction:column;gap:6px;">
|
| 1370 |
+
<label class="modern-label" for="custom-gpu-duration">GPU Duration (seconds)</label>
|
| 1371 |
+
<select id="custom-gpu-duration" class="modern-select">
|
| 1372 |
+
<option value="60" selected>60</option>
|
| 1373 |
+
<option value="90">90</option>
|
| 1374 |
+
<option value="120">120</option>
|
| 1375 |
+
<option value="180">180</option>
|
| 1376 |
+
<option value="240">240</option>
|
| 1377 |
+
<option value="300">300</option>
|
| 1378 |
+
</select>
|
| 1379 |
+
</div>
|
| 1380 |
+
</div>
|
| 1381 |
+
<div class="note-text">
|
| 1382 |
+
Note: Higher GPU duration allows for longer processing but consumes more GPU quota.
|
| 1383 |
+
</div>
|
| 1384 |
+
</div>
|
| 1385 |
+
</div>
|
| 1386 |
+
</div>
|
| 1387 |
+
|
| 1388 |
+
<div class="app-statusbar">
|
| 1389 |
+
<div class="sb-section" id="sb-image-label">No image</div>
|
| 1390 |
+
<div class="sb-section sb-model" id="sb-model-label">FireRed-OCR</div>
|
| 1391 |
+
<div class="sb-section sb-fixed" id="sb-status-label">Ready</div>
|
| 1392 |
+
</div>
|
| 1393 |
+
</div>
|
| 1394 |
+
""")
|
| 1395 |
+
|
| 1396 |
+
run_btn = gr.Button("Run", elem_id="gradio-run-btn")
|
| 1397 |
+
|
| 1398 |
+
demo.load(fn=None, js=app_js)
|
| 1399 |
+
demo.load(fn=None, js=wire_outputs_js)
|
| 1400 |
+
|
| 1401 |
+
gpu_duration_input.change(
|
| 1402 |
fn=apply_gpu_duration,
|
| 1403 |
+
inputs=gpu_duration_input,
|
| 1404 |
outputs=[gpu_duration_state],
|
| 1405 |
+
api_visibility="private",
|
| 1406 |
)
|
| 1407 |
|
| 1408 |
+
def decode_image_for_infer(image_b64):
|
| 1409 |
+
return b64_to_pil(image_b64)
|
| 1410 |
+
|
| 1411 |
+
decoded_image = gr.State()
|
| 1412 |
+
|
| 1413 |
+
hidden_image_b64.change(
|
| 1414 |
+
fn=decode_image_for_infer,
|
| 1415 |
+
inputs=[hidden_image_b64],
|
| 1416 |
+
outputs=[decoded_image],
|
| 1417 |
+
queue=False,
|
| 1418 |
+
)
|
| 1419 |
+
|
| 1420 |
+
run_btn.click(
|
| 1421 |
fn=generate_image,
|
| 1422 |
+
inputs=[
|
| 1423 |
+
hidden_model_choice,
|
| 1424 |
+
hidden_query,
|
| 1425 |
+
decoded_image,
|
| 1426 |
+
max_new_tokens,
|
| 1427 |
+
temperature,
|
| 1428 |
+
top_p,
|
| 1429 |
+
top_k,
|
| 1430 |
+
repetition_penalty,
|
| 1431 |
+
gpu_duration_state
|
| 1432 |
+
],
|
| 1433 |
+
outputs=[raw_output, formatted_output],
|
| 1434 |
+
js=r"""(model, query, img, max_new_tokens, temperature, top_p, top_k, repetition_penalty, gpu_timeout) => {
|
| 1435 |
+
return [model, query, img, max_new_tokens, temperature, top_p, top_k, repetition_penalty, gpu_timeout];
|
| 1436 |
+
}""",
|
| 1437 |
+
)
|
| 1438 |
+
|
| 1439 |
+
example_load_btn.click(
|
| 1440 |
+
fn=load_example_data,
|
| 1441 |
+
inputs=[example_idx],
|
| 1442 |
+
outputs=[example_result],
|
| 1443 |
+
queue=False,
|
| 1444 |
)
|
| 1445 |
|
| 1446 |
if __name__ == "__main__":
|
| 1447 |
+
demo.queue(max_size=50).launch(
|
| 1448 |
+
css=css,
|
| 1449 |
+
head=head_html,
|
| 1450 |
+
mcp_server=True,
|
| 1451 |
+
ssr_mode=False,
|
| 1452 |
+
show_error=True,
|
| 1453 |
+
allowed_paths=["examples"],
|
| 1454 |
+
)
|