Spaces:
Running
Running
initial commit
Browse files
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# pip install -U gradio transformers pillow matplotlib
|
2 |
+
|
3 |
+
import io
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
from PIL import Image
|
9 |
+
|
10 |
+
from transformers.utils.processor_visualizer_utils import ImageVisualizer
|
11 |
+
|
12 |
+
|
13 |
+
def _fig_to_pil(fig) -> Image.Image:
|
14 |
+
buf = io.BytesIO()
|
15 |
+
fig.savefig(buf, format="png", bbox_inches="tight", dpi=160)
|
16 |
+
buf.seek(0)
|
17 |
+
return Image.open(buf).convert("RGB")
|
18 |
+
|
19 |
+
|
20 |
+
def _run(model_id: str, image: Optional[Image.Image], use_sample: bool, add_grid: bool):
|
21 |
+
viz = ImageVisualizer(model_id)
|
22 |
+
|
23 |
+
# Capture all matplotlib figures the visualizer produces without changing the utility.
|
24 |
+
captured = []
|
25 |
+
orig_show = plt.show
|
26 |
+
|
27 |
+
def _capture_show(*_, **__):
|
28 |
+
# collect the current figure then do not actually display
|
29 |
+
fig = plt.gcf()
|
30 |
+
captured.append(fig)
|
31 |
+
|
32 |
+
try:
|
33 |
+
plt.show = _capture_show
|
34 |
+
viz.visualize(images=None if use_sample else image, add_grid=add_grid)
|
35 |
+
finally:
|
36 |
+
plt.show = orig_show
|
37 |
+
|
38 |
+
# Convert figures to PIL for Gradio
|
39 |
+
imgs = [_fig_to_pil(fig) for fig in captured] if captured else []
|
40 |
+
prompt_preview = viz.default_message(full_output=False)
|
41 |
+
return imgs, prompt_preview
|
42 |
+
|
43 |
+
|
44 |
+
with gr.Blocks(title="Transformers Processor Visualizer") as demo:
|
45 |
+
gr.Markdown("Switch models and see what the processor actually feeds them (uses the existing `ImageVisualizer`).")
|
46 |
+
|
47 |
+
with gr.Row():
|
48 |
+
model_id = gr.Textbox(
|
49 |
+
label="Model repo_id",
|
50 |
+
value="openai/clip-vit-base-patch32",
|
51 |
+
placeholder="owner/repo (e.g., llava-hf/llava-1.5-7b-hf)",
|
52 |
+
)
|
53 |
+
add_grid = gr.Checkbox(label="Show patch grid", value=True)
|
54 |
+
use_sample = gr.Checkbox(label="Use HF logo sample", value=True)
|
55 |
+
|
56 |
+
image = gr.Image(label="Or upload an image", type="pil")
|
57 |
+
|
58 |
+
run_btn = gr.Button("Render")
|
59 |
+
|
60 |
+
gallery = gr.Gallery(label="Processor output").style(grid=2, height=600)
|
61 |
+
prompt = gr.Code(label="Compact chat template preview", language="text")
|
62 |
+
|
63 |
+
run_btn.click(_run, inputs=[model_id, image, use_sample, add_grid], outputs=[gallery, prompt])
|
64 |
+
|
65 |
+
if __name__ == "__main__":
|
66 |
+
demo.launch()
|