Spaces:
Running on Zero
Running on Zero
update app
Browse files66 unmodified lines676869707172732 unmodified lines76777879808152 unmodified lines13413513613713813914014114214314414514614714814915015115215315415510 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225321 unmodified lines27527627727827928028133 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363372 unmodified lines3403413423433443453463473483493503513523533543553563573583593603613623633643653 unmodified lines3693703713723733743753763773783793803813821 unmodified line3843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264 unmodified lines4314324334344354364374384394404 unmodified lines4454464474484494504514524534544554564574584594601 unmodified line46246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755815 unmodified lines57457557657757857958013 unmodified lines59459559659759859960020 unmodified lines6216226236246256266277 unmodified lines63563663763863964064164216 unmodified lines65966066166266366466566666766866967067167267367467567667767867968068114 unmodified lines6966976986997007017027037047057067077087097107117127138 unmodified lines72272372472572672772829 unmodified lines75875976076176276330 unmodified lines7947957967977987998008011 unmodified line80380480580680780880981081181281312 unmodified lines82682782882983083183245 unmodified lines87887988088188288388488588688788888989089189289389489589689789889910 unmodified lines9109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419421 unmodified line94494594694794894995095195295395495595695716 unmodified lines9749759769779789792 unmodified lines98298398498598698798868 unmodified lines105710581059106010611062106311 unmodified lines107510761077107810791080108110827 unmodified lines109010911092109310941095109610971098109962 unmodified lines11621163116411651166116711689 unmodified lines117811791180118111821183118431 unmodified lines121612171218121912201221122266 unmodified lines"Captioner-7B-Qwen2.5VL": (processor_z, model_z),"visionOCR-3B": (processor_v, model_v),}MODEL_CHOICES = list(MODEL_MAP.keys())image_examples = [2 unmodified lines]def pil_to_data_url(img: Image.Image, fmt="PNG"):buf = BytesIO()img.save(buf, format=fmt)52 unmodified linesdef load_example_data(idx_str):try:idx = int(float(idx_str))except Exception:return json.dumps({"status": "error", "message": "Invalid example index"})if idx < 0 or idx >= len(image_examples):return json.dumps({"status": "error", "message": "Example index out of range"})ex = image_examples[idx]media_b64 = file_to_data_url(ex["media"])if not media_b64:return json.dumps({"status": "error", "message": "Could not load example image"})return json.dumps({"status": "ok","query": ex["query"],"media": media_b64,"model": ex["model"],"name": os.path.basename(ex["media"]),})def b64_to_pil(b64_str):10 unmodified linesreturn Nonedef calc_timeout_image(model_name, text, image, max_new_tokens, temperature, top_p, top_k, repetition_penalty, gpu_timeout):try:return int(gpu_timeout)except Exception:return 60@spaces.GPU(duration=calc_timeout_image)def generate_image(model_name, text, image, max_new_tokens=1024, temperature=0.6, top_p=0.9, top_k=50, repetition_penalty=1.2, gpu_timeout=60):if not model_name or model_name not in MODEL_MAP:raise gr.Error("Please select a valid model.")if image is None:raise gr.Error("Please upload an image.")if not text or not str(text).strip():raise gr.Error("Please enter your instruction.")if len(str(text)) > MAX_INPUT_TOKEN_LENGTH * 8:raise gr.Error("Query is too long. Please shorten your input.")processor, model = MODEL_MAP[model_name]messages = [{"role": "user","content": [{"type": "image"},{"type": "text", "text": text},]}]prompt_full = processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)inputs = processor(text=[prompt_full],images=[image],return_tensors="pt",padding=True,truncation=True,max_length=MAX_INPUT_TOKEN_LENGTH).to(device)streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)generation_kwargs = {**inputs,"streamer": streamer,"max_new_tokens": int(max_new_tokens),"do_sample": True,"temperature": float(temperature),"top_p": float(top_p),"top_k": int(top_k),"repetition_penalty": float(repetition_penalty),}thread = Thread(target=model.generate, kwargs=generation_kwargs)thread.start()buffer = ""for new_text in streamer:buffer += new_text.replace("<|im_end|>", "")time.sleep(0.01)yield buffergc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()def run_inference(model_name, text, image_b64, max_new_tokens_v, temperature_v, top_p_v, top_k_v, repetition_penalty_v, gpu_timeout_v):image = b64_to_pil(image_b64)yield from generate_image(model_name=model_name,text=text,image=image,max_new_tokens=max_new_tokens_v,temperature=temperature_v,top_p=top_p_v,top_k=top_k_v,repetition_penalty=repetition_penalty_v,gpu_timeout=gpu_timeout_v,)def noop():21 unmodified lines.app-shell{background:#18181b;border:1px solid #27272a;border-radius:16px;margin:12px auto;max-width:1400px;overflow:hidden;box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03);}.app-header{33 unmodified lines.app-main-row{display:flex;gap:0;flex:1;overflow:hidden}.app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid #27272a}.app-main-right{width:470px;display:flex;flex-direction:column;flex-shrink:0;background:#18181b}#media-drop-zone{position:relative;background:#09090b;height:440px;min-height:440px;max-height:440px;overflow:hidden;}#media-drop-zone.drag-over{outline:2px solid #FF1493;outline-offset:-2px;background:rgba(255,20,147,.04)}.upload-prompt-modern{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:20px;z-index:20;overflow:hidden;}.upload-click-area{display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;padding:28px 36px;max-width:92%;max-height:92%;border:2px dashed #3f3f46;border-radius:16px;background:rgba(255,20,147,.03);transition:all .2s ease;gap:8px;text-align:center;overflow:hidden;}.upload-click-area:hover{background:rgba(255,20,147,.08);border-color:#FF1493;transform:scale(1.02)}.upload-click-area:active{background:rgba(255,20,147,.12);transform:scale(.99)}2 unmodified lines.upload-sub-text{color:#71717a;font-size:12px}.single-preview-wrap{width:100%;height:100%;display:none;align-items:center;justify-content:center;padding:16px;overflow:hidden;}.single-preview-card{width:100%;height:100%;max-width:100%;max-height:100%;border-radius:14px;overflow:hidden;border:1px solid #27272a;background:#111114;display:flex;align-items:center;justify-content:center;position:relative;}.single-preview-card img{width:100%;height:100%;max-width:100%;max-height:100%;object-fit:contain;display:block;background:#000;}.preview-overlay-actions{position:absolute;top:12px;right:12px;display:flex;gap:8px;z-index:5;}.preview-action-btn{display:inline-flex;align-items:center;justify-content:center;min-width:34px;height:34px;padding:0 12px;background:rgba(0,0,0,.65);border:1px solid rgba(255,255,255,.14);border-radius:10px;cursor:pointer;color:#fff!important;font-size:12px;font-weight:600;transition:all .15s ease;}.preview-action-btn:hover{background:#FF1493;border-color:#FF1493}3 unmodified lines}.hint-bar b{color:#ff7ac7;font-weight:600}.hint-bar kbd{display:inline-block;padding:1px 6px;background:#27272a;border:1px solid #3f3f46;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa;}.examples-section{border-top:1px solid #27272a;padding:12px 16px}.examples-title{font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;margin-bottom:10px;}.examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}.examples-scroll::-webkit-scrollbar{height:6px}1 unmodified line.examples-scroll::-webkit-scrollbar-thumb{background:#27272a;border-radius:3px}.examples-scroll::-webkit-scrollbar-thumb:hover{background:#3f3f46}.example-card{position:relative;flex-shrink:0;width:220px;background:#09090b;border:1px solid #27272a;border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease;}.example-card:hover{border-color:#FF1493;transform:translateY(-2px);box-shadow:0 4px 12px rgba(255,20,147,.15)}.example-card.loading{opacity:.5;pointer-events:none}.example-thumb-wrap{height:120px;overflow:hidden;background:#18181b;position:relative}.example-thumb-wrap img{width:100%;height:100%;object-fit:cover}.example-media-chip{position:absolute;top:8px;left:8px;display:inline-flex;padding:3px 7px;background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.12);border-radius:999px;font-size:10px;font-weight:700;color:#fff;letter-spacing:.5px;}.example-thumb-placeholder{width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:#18181b;color:#3f3f46;font-size:11px;}.example-meta-row{padding:6px 10px;display:flex;align-items:center;gap:6px}.example-badge{display:inline-flex;padding:2px 7px;background:rgba(255,20,147,.12);border-radius:4px;font-size:10px;font-weight:600;color:#ff7ac7;font-family:'JetBrains Mono',monospace;white-space:nowrap;}.example-prompt-text{padding:0 10px 8px;font-size:11px;color:#a1a1aa;line-height:1.4;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}.panel-card{border-bottom:1px solid #27272a}.panel-card-title{padding:12px 20px;font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);}.panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px}.modern-label{font-size:13px;font-weight:500;color:#a1a1aa;margin-bottom:4px;display:block}.modern-textarea{width:100%;background:#09090b;border:1px solid #27272a;border-radius:8px;padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#e4e4e7;resize:none;outline:none;min-height:100px;transition:border-color .2s;}.modern-textarea:focus{border-color:#FF1493;box-shadow:0 0 0 3px rgba(255,20,147,.15)}4 unmodified lines@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}.toast-notification{position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none;}.toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}4 unmodified lines.toast-notification .toast-text{line-height:1.3}.btn-run{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;background:linear-gradient(135deg,#FF1493,#D10073);border:none;border-radius:10px;padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px;box-shadow:0 4px 16px rgba(255,20,147,.3),inset 0 1px 0 rgba(255,255,255,.1);}.btn-run:hover{background:linear-gradient(135deg,#ff4db2,#FF1493);transform:translateY(-1px);box-shadow:0 6px 24px rgba(255,20,147,.45),inset 0 1px 0 rgba(255,255,255,.15);}.btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(255,20,147,.3)}#custom-run-btn,#custom-run-btn *,#run-btn-label,.btn-run,.btn-run *{1 unmodified line}.output-frame{border-bottom:1px solid #27272a;display:flex;flex-direction:column;position:relative}.output-frame .out-title,.output-frame .out-title *,#output-title-label{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;}.output-frame .out-title{padding:10px 20px;font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;}.out-title-right{display:flex;gap:8px;align-items:center}.out-action-btn{display:inline-flex;align-items:center;justify-content:center;background:rgba(255,20,147,.1);border:1px solid rgba(255,20,147,.2);border-radius:6px;cursor:pointer;padding:3px 10px;font-size:11px;font-weight:500;color:#ff7ac7!important;gap:4px;height:24px;transition:all .15s;}.out-action-btn:hover{background:rgba(255,20,147,.2);border-color:rgba(255,20,147,.35);color:#ffffff!important}.out-action-btn svg{width:12px;height:12px;fill:#ff7ac7}.output-frame .out-body{flex:1;background:#09090b;display:flex;align-items:stretch;justify-content:stretch;overflow:hidden;min-height:320px;position:relative;}.output-scroll-wrap{width:100%;height:100%;padding:0;overflow:hidden;}.output-textarea{width:100%;height:320px;min-height:320px;max-height:320px;background:#09090b;color:#e4e4e7;border:none;outline:none;padding:16px 18px;font-size:13px;line-height:1.6;font-family:'JetBrains Mono',monospace;overflow:auto;resize:none;white-space:pre-wrap;}.output-textarea::placeholder{color:#52525b}.output-textarea.error-flash{box-shadow:inset 0 0 0 2px rgba(239,68,68,.6);}.modern-loader{display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);}.modern-loader.active{display:flex}.modern-loader .loader-spinner{width:36px;height:36px;border:3px solid #27272a;border-top-color:#FF1493;border-radius:50%;animation:spin .8s linear infinite;}@keyframes spin{to{transform:rotate(360deg)}}.modern-loader .loader-text{font-size:13px;color:#a1a1aa;font-weight:500}.loader-bar-track{width:200px;height:4px;background:#27272a;border-radius:2px;overflow:hidden}.loader-bar-fill{height:100%;background:linear-gradient(90deg,#FF1493,#FF69C8,#FF1493);background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;}@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}.settings-group{border:1px solid #27272a;border-radius:10px;margin:12px 16px;padding:0;overflow:hidden}.settings-group-title{font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;padding:10px 16px;border-bottom:1px solid #27272a;background:rgba(24,24,27,.5);}.settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}.slider-row{display:flex;align-items:center;gap:10px;min-height:28px}.slider-row label{font-size:13px;font-weight:500;color:#a1a1aa;min-width:118px;flex-shrink:0}.slider-row input[type="range"]{flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#27272a;border-radius:3px;outline:none;min-width:0;}.slider-row input[type="range"]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#FF1493,#D10073);border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(255,20,147,.4);transition:transform .15s;}.slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}.slider-row input[type="range"]::-moz-range-thumb{width:16px;height:16px;background:linear-gradient(135deg,#FF1493,#D10073);border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(255,20,147,.4);}.slider-row .slider-val{min-width:58px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;font-weight:500;padding:3px 8px;background:#09090b;border:1px solid #27272a;border-radius:6px;color:#a1a1aa;flex-shrink:0;}.app-statusbar{background:#18181b;border-top:1px solid #27272a;padding:6px 20px;display:flex;gap:12px;height:34px;align-items:center;font-size:12px;}.app-statusbar .sb-section{padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap;}.app-statusbar .sb-section.sb-fixed{flex:0 0 auto;min-width:110px;text-align:center;justify-content:center;padding:3px 12px;background:rgba(255,20,147,.08);border-radius:6px;color:#ff7ac7;font-weight:500;}.exp-note{padding:10px 20px;font-size:12px;color:#52525b;border-top:1px solid #27272a;text-align:center}15 unmodified linesgallery_js = r"""() => {function init() {if (window.__docScopeInitDone) return;const dropZone = document.getElementById('media-drop-zone');const uploadPrompt = document.getElementById('upload-prompt');13 unmodified linesreturn;}window.__docScopeInitDone = true;let mediaState = null;let toastTimer = null;let examplePoller = null;20 unmodified linestoast.classList.add('visible');toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500);}window.__showToast = showToast;function showLoader() {const l = document.getElementById('output-loader');7 unmodified linesconst sb = document.getElementById('sb-run-state');if (sb) sb.textContent = 'Done';}window.__showLoader = showLoader;window.__hideLoader = hideLoader;function flashPromptError() {promptInput.classList.add('error-flash');16 unmodified linesfunction setGradioValue(containerId, value) {const container = document.getElementById(containerId);if (!container) return;container.querySelectorAll('input, textarea').forEach(el => {if (el.type === 'file' || el.type === 'range' || el.type === 'checkbox') return;const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;const ns = Object.getOwnPropertyDescriptor(proto, 'value');if (ns && ns.set) {ns.set.call(el, value);el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));}});}function syncImageToGradio() {setGradioValue('hidden-image-b64', mediaState ? mediaState.b64 : '');const txt = mediaState ? '1 image uploaded' : 'No image uploaded';if (mediaStatus) mediaStatus.textContent = txt;}function syncPromptToGradio() {14 unmodified linesreturn;}previewImg.src = mediaState.b64;previewImg.style.display = 'block';previewWrap.style.display = 'flex';if (uploadPrompt) uploadPrompt.style.display = 'none';syncImageToGradio();}function setPreview(b64, name) {mediaState = {b64, name: name || 'file'};renderPreview();}window.__setPreview = setPreview;function clearPreview() {mediaState = null;8 unmodified linesreturn;}const reader = new FileReader();reader.onload = (e) => setPreview(e.target.result, file.name);reader.readAsDataURL(file);}29 unmodified lines});syncModelToGradio(name);}window.__activateModelTab = activateModelTab;document.querySelectorAll('.model-tab[data-model]').forEach(btn => {30 unmodified linesfunction validateBeforeRun() {const promptVal = promptInput.value.trim();if (!mediaState && !promptVal) {showToast('Please upload an image and enter your instruction', 'error');flashPromptError();return false;}1 unmodified lineshowToast('Please upload an image', 'error');return false;}if (!promptVal) {showToast('Please enter your instruction', 'warning');flashPromptError();return false;}const currentModel = (document.querySelector('.model-tab.active') || {}).dataset?.model;if (!currentModel) {showToast('Please select a model', 'error');12 unmodified linesshowLoader();setTimeout(() => {const gradioBtn = document.getElementById('gradio-run-btn');if (!gradioBtn) return;const btn = gradioBtn.querySelector('button');if (btn) btn.click(); else gradioBtn.click();}, 180);45 unmodified linesfunction applyExamplePayload(raw) {try {const data = JSON.parse(raw);if (data.status === 'ok') {if (data.media) setPreview(data.media, data.name || 'example_file');if (data.query) {promptInput.value = data.query;syncPromptToGradio();}if (data.model) activateModelTab(data.model);document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Example loaded', 'info');} else if (data.status === 'error') {document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast(data.message || 'Failed to load example', 'error');}} catch (e) {document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Failed to parse example data', 'error');}}10 unmodified linesapplyExamplePayload(current);return;}if (attempts >= 80) {clearInterval(examplePoller);examplePoller = null;document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Example load timed out', 'error');}}, 150);}document.querySelectorAll('.example-card[data-idx]').forEach(card => {card.addEventListener('click', () => {const idx = card.getAttribute('data-idx');document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));card.classList.add('loading');showToast('Loading example...', 'info');setGradioValue('example-result-data', '');setGradioValue('example-idx-input', idx);setTimeout(() => {const btn = document.getElementById('example-load-btn');if (btn) {const b = btn.querySelector('button');if (b) b.click(); else btn.click();}startExamplePolling();}, 220);});});1 unmodified lineif (observerTarget) {const obs = new MutationObserver(() => {const current = getValueFromContainer('example-result-data');if (current && current !== lastSeenExamplePayload) {lastSeenExamplePayload = current;if (examplePoller) {clearInterval(examplePoller);examplePoller = null;}applyExamplePayload(current);}});obs.observe(observerTarget, {childList:true, subtree:true, characterData:true, attributes:true});}16 unmodified lineslet lastText = '';function syncOutput() {const el = resultContainer.querySelector('textarea') || resultContainer.querySelector('input');if (!el) return;2 unmodified lineslastText = val;outArea.value = val;outArea.scrollTop = outArea.scrollHeight;if (window.__hideLoader && val.trim()) window.__hideLoader();}}68 unmodified lines<div id="upload-click-area" class="upload-click-area">{UPLOAD_PREVIEW_SVG}<span id="upload-main-text" class="upload-main-text">Click or drag an image here</span><span id="upload-sub-text" class="upload-sub-text">Upload one document, page, screenshot, receipt, or scene image for OCR and reasoning</span></div></div>11 unmodified lines</div><div class="hint-bar"><b>Upload:</b> Click or drag an image into the panel · <b>Model:</b> Change models from the header · <kbd>Clear</kbd> removes the current image</div>7 unmodified lines<div class="app-main-right"><div class="panel-card"><div class="panel-card-title">Vision / OCR Instruction</div><div class="panel-card-body"><label class="modern-label" for="custom-query-input">Query Input</label><textarea id="custom-query-input" class="modern-textarea" rows="4" placeholder="e.g., perform OCR on this image, describe the document, identify visible text, analyze the scene..."></textarea></div></div>62 unmodified lines</div><div class="exp-note">Experimental document vision suite · Open on <a href="https://github.com/PRITHIVSAKTHIUR/DocScope-R1" target="_blank">GitHub</a></div><div class="app-statusbar">9 unmodified linesdemo.load(fn=noop, inputs=None, outputs=None, js=wire_outputs_js)run_btn.click(fn=run_inference,inputs=[hidden_model_name,prompt,31 unmodified lines)if __name__ == "__main__":demo.queue(max_size=30).launch(css=css,mcp_server=True,ssr_mode=False,66 unmodified lines6768697071722 unmodified lines75767778798081828384858652 unmodified lines13914014114214314414514614714814915015115215315415515615715815916016116216310 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430521 unmodified lines32732832933033133233333 unmodified lines3673683693703713723733743753763773783793803813823833843852 unmodified lines3883893903913923933943953963973983994004014024034044054064074083 unmodified lines4124134144154164174184194204214224234241 unmodified line4264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614 unmodified lines4664674684694704714724734 unmodified lines4784794804814824834844854864874884891 unmodified line49149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356415 unmodified lines58058158258358458558613 unmodified lines60060160260360460560620 unmodified lines6276286296306316327 unmodified lines64064164264364464564664764864965065165265365465516 unmodified lines67267367467567667767867968068168268368468568668768868969069169269369414 unmodified lines7097107117127137147157167177187197207217227237247258 unmodified lines73473573673773873974029 unmodified lines77077177277377477577630 unmodified lines8078088098108118128138141 unmodified line81681781881982082112 unmodified lines83483583683783883984084184284384484545 unmodified lines89189289389489589689789889990090190290390490590690790890991091191291391491591610 unmodified lines9279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799801 unmodified line98298398498598698798898999099199299399416 unmodified lines10111012101310141015101610171018101910202 unmodified lines10231024102510261027102810291030103110321033103410351036103768 unmodified lines110611071108110911101111111211 unmodified lines112411251126112711281129113011317 unmodified lines113911401141114211431144114511461147114862 unmodified lines12111212121312141215121612179 unmodified lines122712281229123012311232123331 unmodified lines126512661267126812691270127166 unmodified lines"Captioner-7B-Qwen2.5VL": (processor_z, model_z),"visionOCR-3B": (processor_v, model_v),}MODEL_CHOICES = list(MODEL_MAP.keys())image_examples = [2 unmodified lines]def select_model(model_name: str):if model_name not in MODEL_MAP:raise ValueError("Invalid model selected.")return MODEL_MAP[model_name]def pil_to_data_url(img: Image.Image, fmt="PNG"):buf = BytesIO()img.save(buf, format=fmt)52 unmodified linesdef load_example_data(idx_str):try:idx = int(str(idx_str).strip())except Exception:return gr.update(value="")if idx < 0 or idx >= len(image_examples):return gr.update(value="")ex = image_examples[idx]media_b64 = file_to_data_url(ex["media"])if not media_b64:return gr.update(value=json.dumps({"status": "error", "message": "Could not load example image"}))return gr.update(value=json.dumps({"status": "ok","query": ex["query"],"media": media_b64,"model": ex["model"],"name": os.path.basename(ex["media"]),}))def b64_to_pil(b64_str):10 unmodified linesreturn Nonedef calc_timeout_generic(*args, **kwargs):gpu_timeout = kwargs.get("gpu_timeout", None)if gpu_timeout is None and args:gpu_timeout = args[-1]try:return int(gpu_timeout)except Exception:return 60@spaces.GPU(duration=calc_timeout_generic)def generate_image(model_name, text, image, max_new_tokens=1024, temperature=0.6, top_p=0.9, top_k=50, repetition_penalty=1.2, gpu_timeout=60):try:if not model_name or model_name not in MODEL_MAP:yield "[ERROR] Please select a valid model."returnif image is None:yield "[ERROR] Please upload an image."returnif not text or not str(text).strip():yield "[ERROR] Please enter your instruction."returnif len(str(text)) > MAX_INPUT_TOKEN_LENGTH * 8:yield "[ERROR] Query is too long. Please shorten your input."returnprocessor, model = select_model(model_name)messages = [{"role": "user","content": [{"type": "image"},{"type": "text", "text": text},]}]prompt_full = processor.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)inputs = processor(text=[prompt_full],images=[image],return_tensors="pt",padding=True,truncation=True,max_length=MAX_INPUT_TOKEN_LENGTH).to(device)streamer = TextIteratorStreamer(processor.tokenizer if hasattr(processor, "tokenizer") else processor,skip_prompt=True,skip_special_tokens=True)generation_error = {"error": None}generation_kwargs = {**inputs,"streamer": streamer,"max_new_tokens": int(max_new_tokens),"do_sample": True,"temperature": float(temperature),"top_p": float(top_p),"top_k": int(top_k),"repetition_penalty": float(repetition_penalty),}def _run_generation():try:model.generate(**generation_kwargs)except Exception as e:generation_error["error"] = etry:streamer.end()except Exception:passthread = Thread(target=_run_generation, daemon=True)thread.start()buffer = ""for new_text in streamer:buffer += new_text.replace("<|im_end|>", "")time.sleep(0.01)yield bufferthread.join(timeout=1.0)if generation_error["error"] is not None:err_msg = f"[ERROR] Inference failed: {str(generation_error['error'])}"if buffer.strip():yield buffer + "\n\n" + err_msgelse:yield err_msgreturnif not buffer.strip():yield "[ERROR] No output was generated."except Exception as e:yield f"[ERROR] {str(e)}"finally:gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()def run_router(model_name, text, image_b64, max_new_tokens_v, temperature_v, top_p_v, top_k_v, repetition_penalty_v, gpu_timeout_v):try:image = b64_to_pil(image_b64)yield from generate_image(model_name=model_name,text=text,image=image,max_new_tokens=max_new_tokens_v,temperature=temperature_v,top_p=top_p_v,top_k=top_k_v,repetition_penalty=repetition_penalty_v,gpu_timeout=gpu_timeout_v,)except Exception as e:yield f"[ERROR] {str(e)}"def noop():21 unmodified lines.app-shell{background:#18181b;border:1px solid #27272a;border-radius:16px;margin:12px auto;max-width:1450px;overflow:hidden;box-shadow:0 25px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(255,255,255,.03);}.app-header{33 unmodified lines.app-main-row{display:flex;gap:0;flex:1;overflow:hidden}.app-main-left{flex:1;display:flex;flex-direction:column;min-width:0;border-right:1px solid #27272a}.app-main-right{width:500px;display:flex;flex-direction:column;flex-shrink:0;background:#18181b}#media-drop-zone{position:relative;background:#09090b;height:440px;min-height:440px;max-height:440px;overflow:hidden;}#media-drop-zone.drag-over{outline:2px solid #FF1493;outline-offset:-2px;background:rgba(255,20,147,.04)}.upload-prompt-modern{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:20px;z-index:20;overflow:hidden;}.upload-click-area{display:flex;flex-direction:column;align-items:center;justify-content:center;cursor:pointer;padding:28px 36px;max-width:92%;max-height:92%;border:2px dashed #3f3f46;border-radius:16px;background:rgba(255,20,147,.03);transition:all .2s ease;gap:8px;text-align:center;overflow:hidden;}.upload-click-area:hover{background:rgba(255,20,147,.08);border-color:#FF1493;transform:scale(1.02)}.upload-click-area:active{background:rgba(255,20,147,.12);transform:scale(.99)}2 unmodified lines.upload-sub-text{color:#71717a;font-size:12px}.single-preview-wrap{width:100%;height:100%;display:none;align-items:center;justify-content:center;padding:16px;overflow:hidden;}.single-preview-card{width:100%;height:100%;max-width:100%;max-height:100%;border-radius:14px;overflow:hidden;border:1px solid #27272a;background:#111114;display:flex;align-items:center;justify-content:center;position:relative;}.single-preview-card img{width:100%;height:100%;max-width:100%;max-height:100%;object-fit:contain;display:block;background:#000;border:none;}.preview-overlay-actions{position:absolute;top:12px;right:12px;display:flex;gap:8px;z-index:5;}.preview-action-btn{display:inline-flex;align-items:center;justify-content:center;min-width:34px;height:34px;padding:0 12px;background:rgba(0,0,0,.65);border:1px solid rgba(255,255,255,.14);border-radius:10px;cursor:pointer;color:#fff!important;font-size:12px;font-weight:600;transition:all .15s ease;}.preview-action-btn:hover{background:#FF1493;border-color:#FF1493}3 unmodified lines}.hint-bar b{color:#ff7ac7;font-weight:600}.hint-bar kbd{display:inline-block;padding:1px 6px;background:#27272a;border:1px solid #3f3f46;border-radius:4px;font-family:'JetBrains Mono',monospace;font-size:11px;color:#a1a1aa;}.examples-section{border-top:1px solid #27272a;padding:12px 16px}.examples-title{font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;margin-bottom:10px;}.examples-scroll{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px}.examples-scroll::-webkit-scrollbar{height:6px}1 unmodified line.examples-scroll::-webkit-scrollbar-thumb{background:#27272a;border-radius:3px}.examples-scroll::-webkit-scrollbar-thumb:hover{background:#3f3f46}.example-card{position:relative;flex-shrink:0;width:220px;background:#09090b;border:1px solid #27272a;border-radius:10px;overflow:hidden;cursor:pointer;transition:all .2s ease;}.example-card:hover{border-color:#FF1493;transform:translateY(-2px);box-shadow:0 4px 12px rgba(255,20,147,.15)}.example-card.loading{opacity:.5;pointer-events:none}.example-thumb-wrap{height:120px;overflow:hidden;background:#18181b;position:relative}.example-thumb-wrap img{width:100%;height:100%;object-fit:cover}.example-media-chip{position:absolute;top:8px;left:8px;display:inline-flex;padding:3px 7px;background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.12);border-radius:999px;font-size:10px;font-weight:700;color:#fff;letter-spacing:.5px;}.example-thumb-placeholder{width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:#18181b;color:#3f3f46;font-size:11px;}.example-meta-row{padding:6px 10px;display:flex;align-items:center;gap:6px}.example-badge{display:inline-flex;padding:2px 7px;background:rgba(255,20,147,.12);border-radius:4px;font-size:10px;font-weight:600;color:#ff7ac7;font-family:'JetBrains Mono',monospace;white-space:nowrap;}.example-prompt-text{padding:0 10px 8px;font-size:11px;color:#a1a1aa;line-height:1.4;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}.panel-card{border-bottom:1px solid #27272a}.panel-card-title{padding:12px 20px;font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);}.panel-card-body{padding:16px 20px;display:flex;flex-direction:column;gap:8px}.modern-label{font-size:13px;font-weight:500;color:#a1a1aa;margin-bottom:4px;display:block}.modern-textarea{width:100%;background:#09090b;border:1px solid #27272a;border-radius:8px;padding:10px 14px;font-family:'Inter',sans-serif;font-size:14px;color:#e4e4e7;resize:none;outline:none;min-height:100px;transition:border-color .2s;}.modern-textarea:focus{border-color:#FF1493;box-shadow:0 0 0 3px rgba(255,20,147,.15)}4 unmodified lines@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}}.toast-notification{position:fixed;top:24px;left:50%;transform:translateX(-50%) translateY(-120%);z-index:9999;padding:10px 24px;border-radius:10px;font-family:'Inter',sans-serif;font-size:14px;font-weight:600;display:flex;align-items:center;gap:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);transition:transform .35s cubic-bezier(.34,1.56,.64,1),opacity .35s ease;opacity:0;pointer-events:none;}.toast-notification.visible{transform:translateX(-50%) translateY(0);opacity:1;pointer-events:auto}4 unmodified lines.toast-notification .toast-text{line-height:1.3}.btn-run{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;background:linear-gradient(135deg,#FF1493,#D10073);border:none;border-radius:10px;padding:12px 24px;cursor:pointer;font-size:15px;font-weight:600;font-family:'Inter',sans-serif;color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;transition:all .2s ease;letter-spacing:-.2px;box-shadow:0 4px 16px rgba(255,20,147,.3),inset 0 1px 0 rgba(255,255,255,.1);}.btn-run:hover{background:linear-gradient(135deg,#ff4db2,#FF1493);transform:translateY(-1px);box-shadow:0 6px 24px rgba(255,20,147,.45),inset 0 1px 0 rgba(255,255,255,.15);}.btn-run:active{transform:translateY(0);box-shadow:0 2px 8px rgba(255,20,147,.3)}#custom-run-btn,#custom-run-btn *,#run-btn-label,.btn-run,.btn-run *{1 unmodified line}.output-frame{border-bottom:1px solid #27272a;display:flex;flex-direction:column;position:relative}.output-frame .out-title,.output-frame .out-title *,#output-title-label{color:#ffffff!important;-webkit-text-fill-color:#ffffff!important;}.output-frame .out-title{padding:10px 20px;font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;border-bottom:1px solid rgba(39,39,42,.6);display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;}.out-title-right{display:flex;gap:8px;align-items:center}.out-action-btn{display:inline-flex;align-items:center;justify-content:center;background:rgba(255,20,147,.1);border:1px solid rgba(255,20,147,.2);border-radius:6px;cursor:pointer;padding:3px 10px;font-size:11px;font-weight:500;color:#ff7ac7!important;gap:4px;height:24px;transition:all .15s;}.out-action-btn:hover{background:rgba(255,20,147,.2);border-color:rgba(255,20,147,.35);color:#ffffff!important}.out-action-btn svg{width:12px;height:12px;fill:#ff7ac7}.output-frame .out-body{flex:1;background:#09090b;display:flex;align-items:stretch;justify-content:stretch;overflow:hidden;min-height:320px;position:relative;}.output-scroll-wrap{width:100%;height:100%;padding:0;overflow:hidden}.output-textarea{width:100%;height:320px;min-height:320px;max-height:320px;background:#09090b;color:#e4e4e7;border:none;outline:none;padding:16px 18px;font-size:13px;line-height:1.6;font-family:'JetBrains Mono',monospace;overflow:auto;resize:none;white-space:pre-wrap;}.output-textarea::placeholder{color:#52525b}.output-textarea.error-flash{box-shadow:inset 0 0 0 2px rgba(239,68,68,.6)}.modern-loader{display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(9,9,11,.92);z-index:15;flex-direction:column;align-items:center;justify-content:center;gap:16px;backdrop-filter:blur(4px);}.modern-loader.active{display:flex}.modern-loader .loader-spinner{width:36px;height:36px;border:3px solid #27272a;border-top-color:#FF1493;border-radius:50%;animation:spin .8s linear infinite;}@keyframes spin{to{transform:rotate(360deg)}}.modern-loader .loader-text{font-size:13px;color:#a1a1aa;font-weight:500}.loader-bar-track{width:200px;height:4px;background:#27272a;border-radius:2px;overflow:hidden}.loader-bar-fill{height:100%;background:linear-gradient(90deg,#FF1493,#FF69C8,#FF1493);background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:2px;}@keyframes shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}.settings-group{border:1px solid #27272a;border-radius:10px;margin:12px 16px;padding:0;overflow:hidden}.settings-group-title{font-size:12px;font-weight:600;color:#71717a;text-transform:uppercase;letter-spacing:.8px;padding:10px 16px;border-bottom:1px solid #27272a;background:rgba(24,24,27,.5);}.settings-group-body{padding:14px 16px;display:flex;flex-direction:column;gap:12px}.slider-row{display:flex;align-items:center;gap:10px;min-height:28px}.slider-row label{font-size:13px;font-weight:500;color:#a1a1aa;min-width:118px;flex-shrink:0}.slider-row input[type="range"]{flex:1;-webkit-appearance:none;appearance:none;height:6px;background:#27272a;border-radius:3px;outline:none;min-width:0;}.slider-row input[type="range"]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;background:linear-gradient(135deg,#FF1493,#D10073);border-radius:50%;cursor:pointer;box-shadow:0 2px 6px rgba(255,20,147,.4);transition:transform .15s;}.slider-row input[type="range"]::-webkit-slider-thumb:hover{transform:scale(1.2)}.slider-row input[type="range"]::-moz-range-thumb{width:16px;height:16px;background:linear-gradient(135deg,#FF1493,#D10073);border-radius:50%;cursor:pointer;border:none;box-shadow:0 2px 6px rgba(255,20,147,.4);}.slider-row .slider-val{min-width:58px;text-align:right;font-family:'JetBrains Mono',monospace;font-size:12px;font-weight:500;padding:3px 8px;background:#09090b;border:1px solid #27272a;border-radius:6px;color:#a1a1aa;flex-shrink:0;}.app-statusbar{background:#18181b;border-top:1px solid #27272a;padding:6px 20px;display:flex;gap:12px;height:34px;align-items:center;font-size:12px;}.app-statusbar .sb-section{padding:0 12px;flex:1;display:flex;align-items:center;font-family:'JetBrains Mono',monospace;font-size:12px;color:#52525b;overflow:hidden;white-space:nowrap;}.app-statusbar .sb-section.sb-fixed{flex:0 0 auto;min-width:110px;text-align:center;justify-content:center;padding:3px 12px;background:rgba(255,20,147,.08);border-radius:6px;color:#ff7ac7;font-weight:500;}.exp-note{padding:10px 20px;font-size:12px;color:#52525b;border-top:1px solid #27272a;text-align:center}15 unmodified linesgallery_js = r"""() => {function init() {if (window.__outpostInitDone) return;const dropZone = document.getElementById('media-drop-zone');const uploadPrompt = document.getElementById('upload-prompt');13 unmodified linesreturn;}window.__outpostInitDone = true;let mediaState = null;let toastTimer = null;let examplePoller = null;20 unmodified linestoast.classList.add('visible');toastTimer = setTimeout(() => toast.classList.remove('visible'), 3500);}function showLoader() {const l = document.getElementById('output-loader');7 unmodified linesconst sb = document.getElementById('sb-run-state');if (sb) sb.textContent = 'Done';}function setRunErrorState() {const l = document.getElementById('output-loader');if (l) l.classList.remove('active');const sb = document.getElementById('sb-run-state');if (sb) sb.textContent = 'Error';}window.__hideLoader = hideLoader;window.__setRunErrorState = setRunErrorState;window.__showToast = showToast;function flashPromptError() {promptInput.classList.add('error-flash');16 unmodified linesfunction setGradioValue(containerId, value) {const container = document.getElementById(containerId);if (!container) return false;const el = container.querySelector('textarea, input');if (!el) return false;const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;const ns = Object.getOwnPropertyDescriptor(proto, 'value');if (ns && ns.set) {ns.set.call(el, value);el.dispatchEvent(new Event('input', {bubbles:true, composed:true}));el.dispatchEvent(new Event('change', {bubbles:true, composed:true}));return true;}return false;}function syncImageToGradio() {setGradioValue('hidden-image-b64', mediaState ? mediaState.b64 : '');if (mediaStatus) mediaStatus.textContent = mediaState ? '1 image uploaded' : 'No image uploaded';}function syncPromptToGradio() {14 unmodified linesreturn;}previewWrap.style.display = 'flex';if (uploadPrompt) uploadPrompt.style.display = 'none';previewImg.src = mediaState.preview || mediaState.b64;previewImg.style.display = 'block';syncImageToGradio();}function setPreviewFromFileReader(b64, name) {mediaState = {b64, name: name || 'file', mode: 'image'};renderPreview();}function clearPreview() {mediaState = null;8 unmodified linesreturn;}const reader = new FileReader();reader.onload = (e) => setPreviewFromFileReader(e.target.result, file.name);reader.readAsDataURL(file);}29 unmodified lines});syncModelToGradio(name);}window.__activateModelTab = activateModelTab;document.querySelectorAll('.model-tab[data-model]').forEach(btn => {30 unmodified linesfunction validateBeforeRun() {const promptVal = promptInput.value.trim();if (!promptVal) {showToast('Please enter your instruction', 'warning');flashPromptError();return false;}1 unmodified lineshowToast('Please upload an image', 'error');return false;}const currentModel = (document.querySelector('.model-tab.active') || {}).dataset?.model;if (!currentModel) {showToast('Please select a model', 'error');12 unmodified linesshowLoader();setTimeout(() => {const gradioBtn = document.getElementById('gradio-run-btn');if (!gradioBtn) {setRunErrorState();if (outputArea) outputArea.value = '[ERROR] Run button not found.';showToast('Run button not found', 'error');return;}const btn = gradioBtn.querySelector('button');if (btn) btn.click(); else gradioBtn.click();}, 180);45 unmodified linesfunction applyExamplePayload(raw) {try {const data = JSON.parse(raw);if (data.status !== 'ok') return;if (data.model) activateModelTab(data.model);if (data.query) {promptInput.value = data.query;syncPromptToGradio();}mediaState = {b64: data.media || '',preview: data.media || '',name: data.name || 'example_file',mode: 'image'};renderPreview();document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Example loaded', 'info');} catch (e) {document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));}}10 unmodified linesapplyExamplePayload(current);return;}if (attempts >= 100) {clearInterval(examplePoller);examplePoller = null;document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Example load timed out', 'error');}}, 120);}function triggerExampleLoad(idx) {const btnWrap = document.getElementById('example-load-btn');const btn = btnWrap ? (btnWrap.querySelector('button') || btnWrap) : null;if (!btn) return;let attempts = 0;function writeIdxAndClick() {attempts += 1;const ok1 = setGradioValue('example-idx-input', String(idx));setGradioValue('example-result-data', '');const currentVal = getValueFromContainer('example-idx-input');if (ok1 && currentVal === String(idx)) {btn.click();startExamplePolling();return;}if (attempts < 30) {setTimeout(writeIdxAndClick, 100);} else {document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));showToast('Failed to initialize example loader', 'error');}}writeIdxAndClick();}document.querySelectorAll('.example-card[data-idx]').forEach(card => {card.addEventListener('click', () => {const idx = card.getAttribute('data-idx');if (idx === null || idx === undefined || idx === '') return;document.querySelectorAll('.example-card.loading').forEach(c => c.classList.remove('loading'));card.classList.add('loading');showToast('Loading example...', 'info');triggerExampleLoad(idx);});});1 unmodified lineif (observerTarget) {const obs = new MutationObserver(() => {const current = getValueFromContainer('example-result-data');if (!current || current === lastSeenExamplePayload) return;lastSeenExamplePayload = current;if (examplePoller) {clearInterval(examplePoller);examplePoller = null;}applyExamplePayload(current);});obs.observe(observerTarget, {childList:true, subtree:true, characterData:true, attributes:true});}16 unmodified lineslet lastText = '';function isErrorText(val) {return typeof val === 'string' && val.trim().startsWith('[ERROR]');}function syncOutput() {const el = resultContainer.querySelector('textarea') || resultContainer.querySelector('input');if (!el) return;2 unmodified lineslastText = val;outArea.value = val;outArea.scrollTop = outArea.scrollHeight;if (val.trim()) {if (isErrorText(val)) {if (window.__setRunErrorState) window.__setRunErrorState();if (window.__showToast) window.__showToast('Inference failed', 'error');} else {if (window.__hideLoader) window.__hideLoader();}}}}68 unmodified lines<div id="upload-click-area" class="upload-click-area">{UPLOAD_PREVIEW_SVG}<span id="upload-main-text" class="upload-main-text">Click or drag an image here</span><span id="upload-sub-text" class="upload-sub-text">Upload one image for OCR and multimodal reasoning</span></div></div>11 unmodified lines</div><div class="hint-bar"><b>Mode:</b> Image inference only · <b>Model:</b> Switch between OCR, captioning, and reasoning variants · <kbd>Clear</kbd> removes the current image</div>7 unmodified lines<div class="app-main-right"><div class="panel-card"><div id="instruction-title" class="panel-card-title">Vision / OCR Instruction</div><div class="panel-card-body"><label id="query-label" class="modern-label" for="custom-query-input">Query Input</label><textarea id="custom-query-input" class="modern-textarea" rows="4" placeholder="e.g., perform OCR, describe the image, analyze the scene, extract visible text..."></textarea></div></div>62 unmodified lines</div><div class="exp-note">Experimental document vision workspace</div><div class="app-statusbar">9 unmodified linesdemo.load(fn=noop, inputs=None, outputs=None, js=wire_outputs_js)run_btn.click(fn=run_router,inputs=[hidden_model_name,prompt,31 unmodified lines)if __name__ == "__main__":demo.queue(max_size=50).launch(css=css,mcp_server=True,ssr_mode=False,
app.py+298-249