LPX55
Update .gitignore to exclude .pyc files, modify app.py to use demo.queue().launch for improved functionality, and add rebase.sh script for automated git rebase operations with branch detection.
38c0d61
raw
history blame
8.65 kB
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
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().launch(mcp_server=True)