Spaces:
Runtime error
Runtime error
File size: 8,734 Bytes
9c6c4fb 4cc700d 4478d67 4cc700d 9c6c4fb 4cc700d 63ebafe 9c6c4fb e22d5ca aa50c63 4cc700d 9c6c4fb b3c00c0 9c6c4fb b3c00c0 9c6c4fb b3c00c0 4cc700d 9c6c4fb aa50c63 9c6c4fb aa50c63 b3c00c0 4cc700d 9c6c4fb 4cc700d 9c6c4fb 4cc700d 9c6c4fb 4478d67 4cc700d 9c6c4fb 2680f30 aa50c63 b3c00c0 4cc700d 9c6c4fb e22d5ca |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
import gradio as gr
import gradio.themes
import numpy as np
from style import js_func, css_func
import tempfile
import pandas as pd
from shared_functions import greet, calculator, sepia, download_text, download_csv
from greeting_tab import greeting_tab
from calculator_tab import calculator_tab
from sepia_tab import sepia_tab
from space_loader_tab import gr_load_tab, iframe_loader_tab
import json
print("Gradio version:", gradio.__version__)
theme = gr.Theme.from_hub("LPX55/modal_ai")
with gr.Blocks(theme=theme, js=js_func, css=css_func) as demo:
show_space_tab = gr.State(False)
# Iframe lazy load pattern
heavy_iframe_src = gr.State("")
with gr.Tab("Heavy Space (iframe - lazy load)", visible=False) as heavy_iframe_tab:
iframe_html = gr.HTML("")
close_btn = gr.Button("Close Tab")
def close_heavy_iframe_tab():
return gr.Tab(visible=False), ""
close_btn.click(fn=close_heavy_iframe_tab, outputs=[heavy_iframe_tab, iframe_html])
def open_heavy_iframe_tab():
src = '<iframe src="https://lpx55-sam2-1-image-predictor-masking-tool-cpu.hf.space" width="100%" height="800" style="border:none;"></iframe>'
return gr.Tab(visible=True), src
# Iframe always loaded pattern
with gr.Tab("Heavy Space (iframe - always loaded)", visible=False) as heavy_iframe_always_tab:
gr.HTML('<iframe src="https://lpx55-sam2-1-image-predictor-masking-tool-cpu.hf.space" width="100%" height="800" style="border:none;"></iframe>')
close_btn2 = gr.Button("Close Tab")
def close_heavy_iframe_always_tab():
return gr.Tab(visible=False)
close_btn2.click(fn=close_heavy_iframe_always_tab, outputs=heavy_iframe_always_tab)
def open_heavy_iframe_always_tab():
return gr.Tab(visible=True)
with gr.Sidebar(width="25vw"):
gr.Markdown("""
# 🤖 API + MCP Demo
_Dynamically load tabs 🤫_
---
**Ways to load the remote SAM2.1 Masking Tool:**
- **gr.load()**: Loads the remote interface at startup, just hidden until shown.
- **iframe**: Loads the remote UI only when you click the button (no API integration).
- **API Proxy**: Upload an image, and the backend will call the remote Space's API and show the result.
- **Open in New Tab**: Opens the remote Space in a new browser tab.
---
**Navigation**
- [Greeting](#greeting)
- [Calculator](#calculator)
- [Sepia Image](#sepia-image)
- [Custom IFrame Loader](#custom-iframe-loader)
- [Space Loader](#space-loader)
---
### [GitHub Repo](https://github.com/yourrepo) | [Docs](https://yourdocs)
---
**Tips:**
- Try the examples in each tab!
- Download your results with the button on the right.
""")
gr.Code(
"""from gradio_client import Client
client = Client("YOUR_URL")
print(client.predict("Alex", 5, False, api_name="/greet"))
""", language="python", label="**API Example:**"
)
gr.Button("Reset All", elem_id="reset-btn")
load_space_btn = gr.Button("Load Extra Space", elem_id="load-space-btn")
load_sam_btn = gr.Button("Load SAM2.1 Masking Tool (gr.load)", elem_id="load-sam-btn")
load_sam_iframe_btn = gr.Button("Load SAM2.1 Masking Tool (iframe)", elem_id="load-sam-iframe-btn")
load_sam_api_btn = gr.Button("Load SAM2.1 Masking Tool (API Proxy)", elem_id="load-sam-api-btn")
open_sam_tab_btn = gr.Button("Open SAM2.1 Masking Tool in New Tab", elem_id="open-sam-tab-btn")
open_heavy_iframe_btn = gr.Button("Open Heavy Space (iframe - lazy load)")
open_heavy_iframe_btn.click(fn=open_heavy_iframe_tab, outputs=[heavy_iframe_tab, iframe_html])
open_heavy_iframe_always_btn = gr.Button("Open Heavy Space (iframe - always loaded)")
open_heavy_iframe_always_btn.click(fn=open_heavy_iframe_always_tab, outputs=heavy_iframe_always_tab)
# All tabs grouped together for a unified tab bar
shared_state = gr.State({"greeting": None, "calculation": None})
shared_state_box = gr.JSON(label="Shared Data Between Tabs")
def pretty_json(state):
return json.dumps(state, indent=2, ensure_ascii=False)
with gr.Tab("Greeting"):
name = gr.Textbox(label="Name", info="Enter your name", placeholder="e.g. Alex")
intensity = gr.Slider(1, 20, value=3, step=1, label="Intensity", info="How excited should the greeting be?")
with gr.Accordion("Advanced Options", open=False):
exclaim = gr.Checkbox(label="Shout (all caps)", info="Make the greeting all uppercase and add exclamations")
greet_btn = gr.Button("Greet")
greet_output = gr.Textbox(label="Greeting", lines=2)
download_greet_btn = gr.DownloadButton(label="Download Greeting", value=download_text, inputs=greet_output)
gr.Examples(
[["Jill", 1, False], ["Sam", 3, True], ["Alex", 5, False]],
inputs=[name, intensity, exclaim],
outputs=greet_output,
fn=greet
)
def update_greeting_state(greeting, state):
state = dict(state)
state["greeting"] = greeting
return state
greet_btn.click(greet, [name, intensity, exclaim], greet_output).then(update_greeting_state, [greet_output, shared_state], shared_state)
with gr.Tab("Calculator"):
num1 = gr.Number(label="Number 1", info="First number")
operation = gr.Radio(["add", "subtract", "multiply", "divide"], label="Operation", info="Choose the operation")
num2 = gr.Number(label="Number 2", info="Second number")
calc_btn = gr.Button("Calculate")
calc_output = gr.Number(label="Result")
download_calc_btn = gr.DownloadButton(label="Download Result", value=download_csv, inputs=calc_output)
gr.Examples(
[[45, "add", 3], [3.14, "divide", 2], [144, "multiply", 2.5], [0, "subtract", 1.2]],
inputs=[num1, operation, num2],
outputs=calc_output,
fn=calculator
)
def update_calc_state(result, state):
state = dict(state)
state["calculation"] = result
return state
calc_btn.click(calculator, [num1, operation, num2], calc_output).then(update_calc_state, [calc_output, shared_state], shared_state)
with gr.Tab("Sepia Image"):
sepia_tab()
with gr.Tab("Space Loader (gr.load)"):
gr_load_tab()
with gr.Tab("Space Loader (iframe)"):
iframe_loader_tab()
with gr.Tab("Extra Space", visible=False) as extra_space_tab:
gr.Markdown("## External Gradio Space")
gr.HTML('<iframe src="https://huggingface.co/spaces/gradio/calculator" width="100%" height="600" style="border:none;"></iframe>')
close_btn = gr.Button("Close Tab")
def close_tab():
return gr.Tab(visible=False)
close_btn.click(fn=close_tab, outputs=extra_space_tab)
with gr.Tab("Custom IFrame Loader") as custom_iframe_tab:
gr.Markdown("## Load Any IFrame URL")
custom_url = gr.Textbox(label="IFrame URL", placeholder="https://example.com")
load_custom_iframe_btn = gr.Button("Load IFrame")
custom_iframe = gr.HTML(visible=True)
def load_custom_iframe(url):
if not url:
return "<div style='color:red'>Please enter a URL.</div>"
return f'<iframe src="{url}" width="100%" height="800" style="border:none;"></iframe>'
load_custom_iframe_btn.click(fn=load_custom_iframe, inputs=custom_url, outputs=custom_iframe)
close_btn = gr.Button("Close Tab")
def close_tab_custom():
return gr.Tab(visible=False)
close_btn.click(fn=close_tab_custom, outputs=custom_iframe_tab)
# Add state variables for each dynamic tab
extra_space_open = gr.State(True)
sam_tab_open = gr.State(True)
sam_iframe_tab_open = gr.State(True)
sam_api_tab_open = gr.State(True)
custom_iframe_tab_open = gr.State(True)
def show_tab():
return gr.Tab(visible=True)
load_space_btn.click(fn=show_tab, outputs=[extra_space_tab])
def show_sam_api_tab():
return gr.Tab(visible=True)
def open_in_new_tab():
# This function does nothing server-side, but the button will have a link
pass
open_sam_tab_btn.click(fn=open_in_new_tab, inputs=None, outputs=None, js="window.open('https://lpx55-sam2-1-image-predictor-masking-tool-cpu.hf.space', '_blank')")
shared_state.change(pretty_json, shared_state, shared_state_box)
demo.queue(default_concurrency_limit=2, max_size=10).launch(mcp_server=True) |