Spaces:
Runtime error
Runtime error
File size: 6,957 Bytes
9c6c4fb aa50c63 9c6c4fb aa50c63 9c6c4fb aa50c63 9c6c4fb aa50c63 9c6c4fb aa50c63 9c6c4fb |
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 |
import gradio as gr
import gradio.themes
import numpy as np
from style import js_func, css_func
import tempfile
import pandas as pd
def greet(name="Stranger", intensity=1, exclaim=False):
greeting = f"Hello, {name}{'!' * int(intensity)}"
if exclaim:
greeting = greeting.upper()
return greeting
def calculator(num1, operation, num2):
if operation == "add":
result = num1 + num2
elif operation == "subtract":
result = num1 - num2
elif operation == "multiply":
result = num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
result = num1 / num2
return result
def sepia(input_img):
sepia_filter = np.array([
[0.393, 0.769, 0.189],
[0.349, 0.686, 0.168],
[0.272, 0.534, 0.131]
])
sepia_img = input_img @ sepia_filter.T
sepia_img = np.clip(sepia_img, 0, 255).astype(np.uint8)
return sepia_img
def download_text(text):
if not text:
text = ""
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as f:
f.write(text)
return f.name
def download_csv(result):
if result is None:
result = ""
df = pd.DataFrame({"Result": [result]})
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as f:
df.to_csv(f, index=False)
return f.name
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)
with gr.Sidebar(width="25vw"):
gr.Image("logo.png", width=80, show_label=False)
gr.Markdown("""
# 🤖 Gradio API Demo
_Build, test, and share AI tools instantly!_
---
**Navigation**
- [Greeting](#greeting)
- [Calculator](#calculator)
- [Sepia Image](#sepia-image)
---
### [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")
with gr.Tab("Greeting"):
gr.Markdown("## Greeting Generator")
with gr.Row():
with gr.Column():
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")
with gr.Column():
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
)
greet_btn.click(greet, [name, intensity, exclaim], greet_output)
with gr.Tab("Calculator"):
gr.Markdown("## Toy Calculator")
with gr.Row():
with gr.Column():
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")
with gr.Column():
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
)
calc_btn.click(calculator, [num1, operation, num2], calc_output)
with gr.Tab("Sepia Image"):
gr.Markdown("## Sepia Image Filter")
image_input = gr.Image(label="Input Image", type="numpy")
sepia_btn = gr.Button("Apply Sepia")
image_output = gr.Image(label="Sepia Image")
sepia_btn.click(sepia, image_input, image_output)
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>')
with gr.Tab("SAM2.1 Masking Tool (gr.load)", visible=False) as sam_tab:
gr.Markdown("## LPX55/SAM2_1-Image-Predictor-Masking-Tool-CPU (gr.load)")
sam_interface = gr.load("LPX55/SAM2_1-Image-Predictor-Masking-Tool-CPU", src="spaces")
with gr.Tab("SAM2.1 Masking Tool (iframe)", visible=False) as sam_iframe_tab:
gr.Markdown("## LPX55/SAM2_1-Image-Predictor-Masking-Tool-CPU (iframe)")
sam_iframe = gr.HTML(visible=True)
def show_tab():
return gr.Tab(visible=True)
load_space_btn.click(fn=show_tab, outputs=[extra_space_tab])
def show_sam_tab():
return gr.Tab(visible=True)
load_sam_btn.click(fn=show_sam_tab, outputs=[sam_tab])
def show_sam_iframe_tab():
iframe_html = '<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), iframe_html
load_sam_iframe_btn.click(fn=show_sam_iframe_tab, outputs=[sam_iframe_tab, sam_iframe])
gr.Markdown("""
---
## 📡 API Usage
- Every function in this demo is automatically available as a REST API!
- View the [OpenAPI schema](./openapi.json) or click "Use via API" in the footer.
- Try the [gradio_client](https://www.gradio.app/guides/getting-started-with-the-python-client) or [@gradio/client](https://www.gradio.app/guides/getting-started-with-the-js-client) to call these endpoints programmatically.
""")
demo.launch(mcp_server=True)
|