Spaces:
Runtime error
Rename to OneVision Patch Inspector + presets, charts, UI polish
Browse files- Rename title in README and Hero block to "OneVision Patch Inspector".
- Run info JSON moved into a default-collapsed Accordion to keep the
output area tidy; a small summary blurb sits above it.
- Visualization mode and saliency signal Radios now use (label, value)
pairs so the meaning of "sbs" / "frame_diff" / etc. is visible.
- Quick presets: three buttons (Detail / Motion / Balanced) wire through
to atomically set saliency_signal + log + percentile + viz_mode.
- Charts panel: matplotlib gr.Plot with a log-y patch-score histogram
and a per-frame selected-count line, refreshed each run.
- CSS pass: bigger hero with subtle radial glow, accent-bullet card
headers, larger gradient Run button with hover lift, soft-gradient
preset chips, footer divider. Container widened to 1320px.
- requirements: matplotlib added (used for the charts panel).
Files changed (3)
- README.md+2-2
- app.py+219-54
- requirements.txt+1
123453 unmodified lines9101112131415---title: OneVision Encoder Codec Viewemoji: 🏆colorFrom: bluecolorTo: indigo3 unmodified linesapp_file: app.pypinned: falselicense: apache-2.0short_description: For online video codec testing---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123453 unmodified lines9101112131415---title: OneVision Patch Inspectoremoji: 🏆colorFrom: bluecolorTo: indigo3 unmodified linesapp_file: app.pypinned: falselicense: apache-2.0short_description: Inspect which video patches a codec-style saliency picks---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
31 unmodified lines323334353637277 unmodified lines31531631731831932011 unmodified lines3323333343353363373383 unmodified lines34234334434534634734823 unmodified lines37237337437537637737876 unmodified lines45545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853910 unmodified lines5505515525535545555565575585595605615625635645652 unmodified lines5685695705715725735743 unmodified lines5785795805815825837 unmodified lines5915925935945955965976 unmodified lines6046056066076086094 unmodified lines61461561661761861962062162262362462562662762862963063120 unmodified lines6526536546556566573 unmodified lines6616626636646656666676686696703 unmodified lines6746756766776786792 unmodified lines68268368468568668768831 unmodified linesimport cv2import gradio as grimport imageio_ffmpegimport numpy as np277 unmodified linesreturn canvas, ndef process(video_path,sample_frames: int,11 unmodified linesprogress=gr.Progress(track_tqdm=False),):if not video_path:return None, None, "Please upload a video."t0 = time.time()progress(0.05, desc="Reading metadata")3 unmodified linesreturn None, None, json.dumps({"error": "Could not read frame count.", "metadata": meta},indent=2, ensure_ascii=False,)progress(0.10, desc="Sampling frames")fps = float(meta.get("fps") or 0.0)23 unmodified linesreturn None, None, json.dumps({"error": "Failed to decode frames.", "metadata": meta},indent=2, ensure_ascii=False,)progress(0.25, desc="smart_resize")resized = [smart_resize(f, int(max_pixels), int(patch_size)) for f in raw]76 unmodified lines+ (" (log1p applied)" if score_log_scale else ""),"elapsed_sec": round(time.time() - t0, 2),}progress(1.0, desc="Done")return vis_path, canvas_path, json.dumps(info, indent=2, ensure_ascii=False)CUSTOM_CSS = """:root, .gradio-container, .gradio-container.dark {--ovc-grad: linear-gradient(135deg, #4f46e5 0%, #2563eb 50%, #06b6d4 100%);}.gradio-container { max-width: 1280px !important; margin: 0 auto !important; }#ovc-hero {text-align: center;padding: 28px 16px 8px;border-radius: 16px;background: linear-gradient(180deg, rgba(79,70,229,0.08), rgba(6,182,212,0.04));margin-bottom: 8px;}#ovc-hero h1 {font-size: 2.1rem;font-weight: 700;background: var(--ovc-grad);-webkit-background-clip: text;background-clip: text;color: transparent;margin: 0 0 6px;letter-spacing: -0.02em;}#ovc-hero p.tagline {font-size: 1.02rem;color: var(--body-text-color-subdued);margin: 0 auto 12px;max-width: 720px;line-height: 1.55;}#ovc-hero .pills { display:flex; flex-wrap:wrap; gap:6px; justify-content:center; margin-top:6px; }#ovc-hero .pill {font-size: 0.78rem;font-weight: 600;padding: 4px 10px;border-radius: 999px;color: #fff;background: var(--ovc-grad);opacity: 0.92;}.ovc-card {border-radius: 14px !important;padding: 14px 16px !important;border: 1px solid var(--border-color-primary) !important;background: var(--background-fill-primary) !important;box-shadow: 0 1px 2px rgba(0,0,0,0.04);}.ovc-card h3 {font-size: 0.86rem !important;font-weight: 700 !important;text-transform: uppercase;letter-spacing: 0.06em;color: var(--body-text-color-subdued) !important;margin: 0 0 8px !important;}#ovc-run button {width: 100%;height: 48px !important;font-size: 1.02rem !important;font-weight: 600 !important;background: var(--ovc-grad) !important;border: none !important;color: #fff !important;border-radius: 12px !important;box-shadow: 0 4px 14px rgba(37, 99, 235, 0.35);transition: transform 0.05s ease;}#ovc-run button:hover { transform: translateY(-1px); }#ovc-run button:active { transform: translateY(0); }#ovc-footer {text-align: center;color: var(--body-text-color-subdued);font-size: 0.78rem;padding: 18px 8px 8px;margin-top: 10px;}"""THEME = gr.themes.Soft(10 unmodified linesHERO_HTML = """<div id="ovc-hero"><h1>OneVision Encoder Codec View</h1><p class="tagline">Visualize which patches a codec-style saliency picks from your video,then pack them into the canvas LLaVA-OneVision2 consumes.Use it to inspect <i>where</i> the model is actually looking.</p><div class="pills"><span class="pill">selection · heatmap · sbs</span><span class="pill">gradient + motion signals</span><span class="pill">canvas export</span></div></div>"""2 unmodified lines_GR_MAJOR = int(gr.__version__.split(".")[0])except Exception:_GR_MAJOR = 4_BLOCK_KW: dict = {"title": "OneVision Encoder Codec View"}_LAUNCH_KW: dict = {}if _GR_MAJOR >= 6:# In Gradio 6.0 these moved off Blocks(...) onto launch(...).3 unmodified lines_BLOCK_KW["theme"] = THEME_BLOCK_KW["css"] = CUSTOM_CSSwith gr.Blocks(**_BLOCK_KW) as demo:gr.HTML(HERO_HTML)7 unmodified lineswith gr.Group(elem_classes="ovc-card"):gr.Markdown("### Pipeline")viz_mode = gr.Radio(["selection", "heatmap", "sbs"], value="selection",label="Visualization mode",)sample_frames = gr.Slider(6 unmodified linesPATCH_CHOICES, value=14, label="Patch size (px)",)with gr.Accordion("Time window", open=False):with gr.Row():start_sec = gr.Number(value=0.0, precision=2, label="Start (s)")4 unmodified lineswith gr.Accordion("Saliency", open=False):saliency_signal = gr.Radio(["gradient", "frame_diff", "combined"], value="gradient",label="Scoring signal",info="gradient = intra-frame Sobel · ""frame_diff = inter-frame motion · ""combined = 0.5 each.",)score_log_scale = gr.Checkbox(value=False, label="Apply log1p to scores",)bitcost_pct = gr.Slider(80.0, 99.9, value=99.0, step=0.1,label="Heatmap normalization percentile",)with gr.Accordion("Visual style", open=False):20 unmodified linesvis_out = gr.Video(label="", show_label=False, autoplay=True, height=420,)with gr.Row():with gr.Column(scale=1):with gr.Group(elem_classes="ovc-card"):3 unmodified lines)with gr.Column(scale=1):with gr.Group(elem_classes="ovc-card"):gr.Markdown("### Run info")info_out = gr.Code(label="", language="json", lines=14,)gr.HTML('<div id="ovc-footer">'3 unmodified lines'</div>')run_btn.click(process,inputs=[2 unmodified linesstart_sec, end_sec,saliency_signal, score_log_scale, bitcost_pct, fade_strength,],outputs=[vis_out, canvas_out, info_out],)31 unmodified lines323334353637383940277 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835911 unmodified lines3713723733743753763773 unmodified lines38138238338438538638723 unmodified lines41141241341441541641776 unmodified lines49449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665710 unmodified lines6686696706716726736746756766776786796806816826832 unmodified lines6866876886896906916923 unmodified lines6966976986997007017027037047057067077087097107117127137147 unmodified lines7227237247257267277286 unmodified lines7357367377387397407417427437447457467477487497507517524 unmodified lines75775875976076176276376476576676776876977077177277377420 unmodified lines7957967977987998008018028038048053 unmodified lines8098108118128138148158168178188198208218228233 unmodified lines8278288298308318328338348358368378388398408418428438442 unmodified lines84784884985085185285331 unmodified linesimport cv2import gradio as grimport imageio_ffmpegimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as np277 unmodified linesreturn canvas, ndef make_charts(grids: List[np.ndarray], masks: List[np.ndarray], saliency_signal: str,):"""Two side-by-side panels:- patch score histogram across all sampled frames (log-y)- selected patch count per sampled frame index"""fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8.6, 3.0), constrained_layout=True)all_scores = np.concatenate([g.flatten().astype(np.float32) for g in grids])ax1.hist(all_scores, bins=40, color="#4f46e5", alpha=0.85,edgecolor="#312e81", linewidth=0.4)ax1.set_yscale("log")ax1.set_title(f"Patch score distribution · {saliency_signal}",fontsize=10, color="#1e293b")ax1.set_xlabel("score", fontsize=9)ax1.set_ylabel("patches (log)", fontsize=9)ax1.tick_params(axis="both", which="both", labelsize=8)ax1.grid(True, alpha=0.25, linestyle="--")ax1.spines[["top", "right"]].set_visible(False)counts = [int(m.sum()) for m in masks]xs = list(range(len(counts)))ax2.plot(xs, counts, "o-", color="#06b6d4", linewidth=2.0,markersize=5, markeredgecolor="#0e7490")ax2.fill_between(xs, counts, alpha=0.15, color="#06b6d4")ax2.set_title("Selected patches per sampled frame",fontsize=10, color="#1e293b")ax2.set_xlabel("sampled frame index", fontsize=9)ax2.set_ylabel("# selected", fontsize=9)ax2.tick_params(axis="both", which="both", labelsize=8)ax2.grid(True, alpha=0.25, linestyle="--")ax2.spines[["top", "right"]].set_visible(False)fig.patch.set_facecolor("white")return figdef process(video_path,sample_frames: int,11 unmodified linesprogress=gr.Progress(track_tqdm=False),):if not video_path:return None, None, "Please upload a video.", Nonet0 = time.time()progress(0.05, desc="Reading metadata")3 unmodified linesreturn None, None, json.dumps({"error": "Could not read frame count.", "metadata": meta},indent=2, ensure_ascii=False,), Noneprogress(0.10, desc="Sampling frames")fps = float(meta.get("fps") or 0.0)23 unmodified linesreturn None, None, json.dumps({"error": "Failed to decode frames.", "metadata": meta},indent=2, ensure_ascii=False,), Noneprogress(0.25, desc="smart_resize")resized = [smart_resize(f, int(max_pixels), int(patch_size)) for f in raw]76 unmodified lines+ (" (log1p applied)" if score_log_scale else ""),"elapsed_sec": round(time.time() - t0, 2),}progress(0.95, desc="Building charts")chart_fig = make_charts(grids, masks, saliency_signal)progress(1.0, desc="Done")return (vis_path, canvas_path,json.dumps(info, indent=2, ensure_ascii=False),chart_fig,)PRESETS = {# (saliency_signal, score_log_scale, bitcost_pct, viz_mode)"detail": ("gradient", False, 99.0, "heatmap"),"motion": ("frame_diff", False, 95.0, "heatmap"),"balanced": ("combined", True, 96.0, "sbs"),}def apply_preset(name: str):sig, log_, pct, mode = PRESETS[name]return sig, log_, pct, modeCUSTOM_CSS = """:root, .gradio-container, .gradio-container.dark {--ovc-grad: linear-gradient(135deg, #4f46e5 0%, #2563eb 50%, #06b6d4 100%);--ovc-grad-soft: linear-gradient(135deg, rgba(79,70,229,0.10), rgba(6,182,212,0.10));}.gradio-container { max-width: 1320px !important; margin: 0 auto !important; }/* Hero */#ovc-hero {text-align: center;padding: 36px 16px 18px;border-radius: 18px;background:radial-gradient(120% 80% at 50% -10%, rgba(79,70,229,0.18), transparent 60%),linear-gradient(180deg, rgba(79,70,229,0.06), rgba(6,182,212,0.03));border: 1px solid rgba(99,102,241,0.18);margin-bottom: 14px;position: relative;overflow: hidden;}#ovc-hero::after {content: "";position: absolute; inset: auto -20% -40% -20%;height: 60%;background: radial-gradient(60% 80% at 50% 0%, rgba(6,182,212,0.18), transparent 70%);pointer-events: none;}#ovc-hero h1 {font-size: 2.4rem;font-weight: 800;background: var(--ovc-grad);-webkit-background-clip: text;background-clip: text;color: transparent;margin: 0 0 8px;letter-spacing: -0.025em;line-height: 1.05;}#ovc-hero p.tagline {font-size: 1.04rem;color: var(--body-text-color-subdued);margin: 0 auto 14px;max-width: 760px;line-height: 1.6;}#ovc-hero .pills { display:flex; flex-wrap:wrap; gap:8px; justify-content:center; margin-top:8px; }#ovc-hero .pill {font-size: 0.78rem;font-weight: 600;padding: 5px 12px;border-radius: 999px;color: #fff;background: var(--ovc-grad);opacity: 0.94;box-shadow: 0 1px 6px rgba(79,70,229,0.25);}/* Cards */.ovc-card {border-radius: 16px !important;padding: 14px 16px !important;border: 1px solid rgba(148,163,184,0.30) !important;background: var(--background-fill-primary) !important;box-shadow: 0 1px 3px rgba(15,23,42,0.04);}.ovc-card h3 {font-size: 0.78rem !important;font-weight: 700 !important;text-transform: uppercase;letter-spacing: 0.08em;color: #4f46e5 !important;margin: 0 0 10px !important;}.ovc-card h3::before {content: "";display: inline-block;width: 6px; height: 6px; border-radius: 50%;background: var(--ovc-grad);margin-right: 8px; vertical-align: middle;transform: translateY(-1px);}/* Run button */#ovc-run button {width: 100%;height: 52px !important;font-size: 1.05rem !important;font-weight: 700 !important;letter-spacing: 0.01em;background: var(--ovc-grad) !important;border: none !important;color: #fff !important;border-radius: 14px !important;box-shadow: 0 6px 18px rgba(37, 99, 235, 0.32);transition: transform 0.06s ease, box-shadow 0.2s ease;}#ovc-run button:hover {transform: translateY(-1px);box-shadow: 0 8px 22px rgba(37, 99, 235, 0.40);}#ovc-run button:active { transform: translateY(0); }/* Preset buttons */.ovc-preset button {background: var(--ovc-grad-soft) !important;color: #4338ca !important;border: 1px solid rgba(79,70,229,0.25) !important;border-radius: 10px !important;font-weight: 600 !important;transition: all 0.15s ease;}.ovc-preset button:hover {background: var(--ovc-grad) !important;color: #fff !important;border-color: transparent !important;}/* Footer */#ovc-footer {text-align: center;color: var(--body-text-color-subdued);font-size: 0.80rem;padding: 22px 8px 10px;margin-top: 14px;border-top: 1px solid rgba(148,163,184,0.18);}#ovc-footer code {background: rgba(79,70,229,0.08);padding: 1px 6px;border-radius: 4px;}/* Tighter spacing for sliders inside cards */.ovc-card .gradio-slider { margin-bottom: 4px !important; }"""THEME = gr.themes.Soft(10 unmodified linesHERO_HTML = """<div id="ovc-hero"><h1>OneVision Patch Inspector</h1><p class="tagline">See which patches a codec-style saliency picks from your video,then pack them into the canvas LLaVA-OneVision2 consumes.A visual lab for inspecting <i>where</i> the encoder — and the model — is actually looking.</p><div class="pills"><span class="pill">selection · heatmap · side-by-side</span><span class="pill">gradient + motion saliency</span><span class="pill">presets · charts · canvas export</span></div></div>"""2 unmodified lines_GR_MAJOR = int(gr.__version__.split(".")[0])except Exception:_GR_MAJOR = 4_BLOCK_KW: dict = {"title": "OneVision Patch Inspector"}_LAUNCH_KW: dict = {}if _GR_MAJOR >= 6:# In Gradio 6.0 these moved off Blocks(...) onto launch(...).3 unmodified lines_BLOCK_KW["theme"] = THEME_BLOCK_KW["css"] = CUSTOM_CSSVIZ_CHOICES = [("Selection — kept patches in color, others fade to gray-white", "selection"),("Heatmap — full-frame JET overlay (blue=low, red=high)", "heatmap"),("Side-by-side — selection on the left, heatmap on the right", "sbs"),]SIGNAL_CHOICES = [("Gradient — intra-frame Sobel (sharp edges, textures, text)", "gradient"),("Frame diff — inter-frame motion (movers, action)", "frame_diff"),("Combined — 0.5·gradient + 0.5·frame_diff (general purpose)", "combined"),]with gr.Blocks(**_BLOCK_KW) as demo:gr.HTML(HERO_HTML)7 unmodified lineswith gr.Group(elem_classes="ovc-card"):gr.Markdown("### Pipeline")viz_mode = gr.Radio(VIZ_CHOICES, value="selection",label="Visualization mode",)sample_frames = gr.Slider(6 unmodified linesPATCH_CHOICES, value=14, label="Patch size (px)",)with gr.Group(elem_classes="ovc-card"):gr.Markdown("### Quick presets")with gr.Row(elem_classes="ovc-preset"):btn_detail = gr.Button("Detail", size="sm")btn_motion = gr.Button("Motion", size="sm")btn_balanced = gr.Button("Balanced", size="sm")gr.Markdown("<small><b>Detail</b>: gradient · pct=99 · heatmap | ""<b>Motion</b>: frame_diff · pct=95 · heatmap | ""<b>Balanced</b>: combined · log · pct=96 · sbs</small>")with gr.Accordion("Time window", open=False):with gr.Row():start_sec = gr.Number(value=0.0, precision=2, label="Start (s)")4 unmodified lineswith gr.Accordion("Saliency", open=False):saliency_signal = gr.Radio(SIGNAL_CHOICES, value="gradient",label="Scoring signal",)score_log_scale = gr.Checkbox(value=False,label="Apply log1p to scores",info="Compresses dynamic range — brings up mid-energy patches.",)bitcost_pct = gr.Slider(80.0, 99.9, value=99.0, step=0.1,label="Heatmap normalization percentile",info="Higher = harder to saturate red; lower = more vivid.",)with gr.Accordion("Visual style", open=False):20 unmodified linesvis_out = gr.Video(label="", show_label=False, autoplay=True, height=420,)with gr.Group(elem_classes="ovc-card"):gr.Markdown("### Score distribution & per-frame patch count")chart_out = gr.Plot(label="", show_label=False)with gr.Row():with gr.Column(scale=1):with gr.Group(elem_classes="ovc-card"):3 unmodified lines)with gr.Column(scale=1):with gr.Group(elem_classes="ovc-card"):gr.Markdown("### Run summary")gr.Markdown("<small>The full per-run JSON is collapsed below ""to keep things tidy. Click to expand.</small>")with gr.Accordion("Show full run info (JSON)", open=False):info_out = gr.Code(label="", language="json", lines=18,)gr.HTML('<div id="ovc-footer">'3 unmodified lines'</div>')# Preset wiring: each updates 4 controls atomically.for btn, key in [(btn_detail, "detail"),(btn_motion, "motion"),(btn_balanced, "balanced"),]:btn.click(lambda k=key: apply_preset(k),inputs=None,outputs=[saliency_signal, score_log_scale, bitcost_pct, viz_mode],)run_btn.click(process,inputs=[2 unmodified linesstart_sec, end_sec,saliency_signal, score_log_scale, bitcost_pct, fade_strength,],outputs=[vis_out, canvas_out, info_out, chart_out],)
1 unmodified line23451 unmodified linenumpy>=1.24imageio>=2.34imageio-ffmpeg>=0.5Pillow>=10.01 unmodified line234561 unmodified linenumpy>=1.24imageio>=2.34imageio-ffmpeg>=0.5matplotlib>=3.7Pillow>=10.0