文章目录
- 关于 Gradio
- 安装
- Interface
- ChatInterface
- Text
- Blocks
- Sentence Builder
- Diff Texts
- Media
- Sepia Filter
- Video Identity
- Iterative Output
- Generate Tone
- Tabular
- Filter Records
- Video Identity
- Iterative Output
- Generate Tone
- Tabular
- Filter Records
- Transpose Matrix
- Tax Calculator
- Kinematics
- Stock Forecast
- Other
- Tabbed Interface
- Chatbot
- Streaming Chatbot
- Layouts
- Error
- Chained Events
- Change Listener
关于 Gradio
- 官网:https://www.gradio.app/
- 官方文档:https://www.gradio.app/docs/
- github : https://github.com/gradio-app/gradio
- playground : https://www.gradio.app/playground
安装
pip install gradio
import gradio as gr
def greet(name, intensity):
return "Hello " * intensity + name + "!"
demo = gr.Interface(
fn=greet,
inputs=["text", "slider"],
outputs=["text"],
)
demo.launch()
Interface
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label")
demo.launch()
ChatInterface
import gradio as gr
def echo(message, history):
return message
demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot")
demo.launch()
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
if __name__ == "__main__":
demo.launch()
Text
Blocks
import gradio as gr
def greet(name):
return "Hello " + name + "!"
with gr.Blocks() as demo:
name = gr.Textbox(label="Name")
output = gr.Textbox(label="Output Box")
greet_btn = gr.Button("Greet")
greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet")
if __name__ == "__main__":
demo.launch()
Sentence Builder
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Diff Texts
from difflib import Differ
import gradio as gr
def diff_texts(text1, text2):
d = Differ()
return [
(token[2:], token[0] if token[0] != " " else None)
for token in d.compare(text1, text2)
]
demo = gr.Interface(
diff_texts,
[
gr.Textbox(
label="Text 1",
info="Initial text",
lines=3,
value="The quick brown fox jumped over the lazy dogs.",
),
gr.Textbox(
label="Text 2",
info="Text to compare",
lines=3,
value="The fast brown fox jumps over lazy dogs.",
),
],
gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
color_map={"+": "red", "-": "green"}),
theme=gr.themes.Base()
)
if __name__ == "__main__":
demo.launch()
Media
Sepia Filter
import numpy as np
import gradio as gr
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.dot(sepia_filter.T)
sepia_img /= sepia_img.max()
return sepia_img
demo = gr.Interface(sepia, gr.Image(), "image")
if __name__ == "__main__":
demo.launch()
Video Identity
import gradio as gr
def video_identity(video):
return video
demo = gr.Interface(video_identity,
gr.Video(),
"playable_video",
)
if __name__ == "__main__":
demo.launch()
Iterative Output
import gradio as gr
import numpy as np
import time
def fake_diffusion(steps):
rng = np.random.default_rng()
for i in range(steps):
time.sleep(1)
image = rng.random(size=(600, 600, 3))
yield image
image = np.ones((1000,1000,3), np.uint8)
image[:] = [255, 124, 0]
yield image
demo = gr.Interface(fake_diffusion,
inputs=gr.Slider(1, 10, 3, step=1),
outputs="image")
if __name__ == "__main__":
demo.launch()
Generate Tone
import numpy as np
import gradio as gr
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def generate_tone(note, octave, duration):
sr = 48000
a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)
frequency = a4_freq * 2 ** (tones_from_a4 / 12)
duration = int(duration)
audio = np.linspace(0, duration, duration * sr)
audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)
return sr, audio
demo = gr.Interface(
generate_tone,
[
gr.Dropdown(notes, type="index"),
gr.Slider(4, 6, step=1),
gr.Textbox(value=1, label="Duration in seconds"),
],
"audio",
)
if __name__ == "__main__":
demo.launch()
Tabular
Filter Records
import gradio as gr
def filter_records(records, gender):
return records[records["gender"] == gender]
demo = gr.Interface(
filter_records,
[
gr.Dataframe(
headers=["name", "age", "gender"],
datatype=["str", "number", "str"],
row_count=5,
col_count=(3, "fixed"),
),
gr.Dropdown(["M", "F", "O"]),
],
"dataframe",
description="Enter gender as 'M', 'F', or 'O' for other.",
)
if __name__ == "__main__":
demo.launch()
Video Identity
import gradio as gr
def video_identity(video):
return video
demo = gr.Interface(video_identity,
gr.Video(),
"playable_video",
)
if __name__ == "__main__":
demo.launch()
Iterative Output
import gradio as gr
import numpy as np
import time
def fake_diffusion(steps):
rng = np.random.default_rng()
for i in range(steps):
time.sleep(1)
image = rng.random(size=(600, 600, 3))
yield image
image = np.ones((1000,1000,3), np.uint8)
image[:] = [255, 124, 0]
yield image
demo = gr.Interface(fake_diffusion,
inputs=gr.Slider(1, 10, 3, step=1),
outputs="image")
if __name__ == "__main__":
demo.launch()
Generate Tone
import numpy as np
import gradio as gr
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def generate_tone(note, octave, duration):
sr = 48000
a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)
frequency = a4_freq * 2 ** (tones_from_a4 / 12)
duration = int(duration)
audio = np.linspace(0, duration, duration * sr)
audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)
return sr, audio
demo = gr.Interface(
generate_tone,
[
gr.Dropdown(notes, type="index"),
gr.Slider(4, 6, step=1),
gr.Textbox(value=1, label="Duration in seconds"),
],
"audio",
)
if __name__ == "__main__":
demo.launch()
Tabular
Filter Records
import gradio as gr
def filter_records(records, gender):
return records[records["gender"] == gender]
demo = gr.Interface(
filter_records,
[
gr.Dataframe(
headers=["name", "age", "gender"],
datatype=["str", "number", "str"],
row_count=5,
col_count=(3, "fixed"),
),
gr.Dropdown(["M", "F", "O"]),
],
"dataframe",
description="Enter gender as 'M', 'F', or 'O' for other.",
)
if __name__ == "__main__":
demo.launch()
Transpose Matrix
import numpy as np
import gradio as gr
def transpose(matrix):
return matrix.T
demo = gr.Interface(
transpose,
gr.Dataframe(type="numpy", datatype="number", row_count=5, col_count=3),
"numpy",
examples=[
[np.zeros((3, 3)).tolist()],
[np.ones((2, 2)).tolist()],
[np.random.randint(0, 10, (3, 10)).tolist()],
[np.random.randint(0, 10, (10, 3)).tolist()],
[np.random.randint(0, 10, (10, 10)).tolist()],
],
cache_examples=False
)
if __name__ == "__main__":
demo.launch()
Tax Calculator
import gradio as gr
def tax_calculator(income, marital_status, assets):
tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
total_deductible = sum(assets["Cost"])
taxable_income = income - total_deductible
total_tax = 0
for bracket, rate in tax_brackets:
if taxable_income > bracket:
total_tax += (taxable_income - bracket) * rate / 100
if marital_status == "Married":
total_tax *= 0.75
elif marital_status == "Divorced":
total_tax *= 0.8
return round(total_tax)
demo = gr.Interface(
tax_calculator,
[
"number",
gr.Radio(["Single", "Married", "Divorced"]),
gr.Dataframe(
headers=["Item", "Cost"],
datatype=["str", "number"],
label="Assets Purchased this Year",
),
],
"number",
examples=[
[10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
[80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
],
)
demo.launch()
Kinematics
import pandas as pd
import numpy as np
import gradio as gr
def plot(v, a):
g = 9.81
theta = a / 180 * 3.14
tmax = ((2 * v) * np.sin(theta)) / g
timemat = tmax * np.linspace(0, 1, 40)
x = (v * timemat) * np.cos(theta)
y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
df = pd.DataFrame({"x": x, "y": y})
return df
demo = gr.Blocks()
with demo:
gr.Markdown(
r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
)
with gr.Row():
speed = gr.Slider(1, 30, 25, label="Speed")
angle = gr.Slider(0, 90, 45, label="Angle")
output = gr.LinePlot(
x="x",
y="y",
overlay_point=True,
tooltip=["x", "y"],
x_lim=[0, 100],
y_lim=[0, 60],
width=350,
height=300,
)
btn = gr.Button(value="Run")
btn.click(plot, [speed, angle], output)
if __name__ == "__main__":
demo.launch()
Stock Forecast
import matplotlib.pyplot as plt
import numpy as np
import gradio as gr
def plot_forecast(final_year, companies, noise, show_legend, point_style):
start_year = 2020
x = np.arange(start_year, final_year + 1)
year_count = x.shape[0]
plt_format = ({"cross": "X", "line": "-", "circle": "o--"})[point_style]
fig = plt.figure()
ax = fig.add_subplot(111)
for i, company in enumerate(companies):
series = np.arange(0, year_count, dtype=float)
series = series**2 * (i + 1)
series += np.random.rand(year_count) * noise
ax.plot(x, series, plt_format)
if show_legend:
plt.legend(companies)
return fig
demo = gr.Interface(
plot_forecast,
[
gr.Radio([2025, 2030, 2035, 2040], label="Project to:"),
gr.CheckboxGroup(["Google", "Microsoft", "Gradio"], label="Company Selection"),
gr.Slider(1, 100, label="Noise Level"),
gr.Checkbox(label="Show Legend"),
gr.Dropdown(["cross", "line", "circle"], label="Style"),
],
gr.Plot(label="forecast"),
)
if __name__ == "__main__":
demo.launch()
Other
Tabbed Interface
import gradio as gr
hello_world = gr.Interface(lambda name: "Hello " + name, "text", "text")
bye_world = gr.Interface(lambda name: "Bye " + name, "text", "text")
demo = gr.TabbedInterface([hello_world, bye_world], ["Hello World", "Bye World"])
if __name__ == "__main__":
demo.launch()
Chatbot
import random
import gradio as gr
def random_response(message, history):
return random.choice(["Yes", "No"])
demo = gr.ChatInterface(random_response)
if __name__ == "__main__":
demo.launch()
Streaming Chatbot
import time
import gradio as gr
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(0.05)
yield "You typed: " + message[: i + 1]
demo = gr.ChatInterface(slow_echo).queue()
if __name__ == "__main__":
demo.launch()
Layouts
import numpy as np
import gradio as gr
def flip_text(x):
return x[::-1]
def flip_image(x):
return np.fliplr(x)
with gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.")
with gr.Tab("Flip Text"):
text_input = gr.Textbox()
text_output = gr.Textbox()
text_button = gr.Button("Flip")
with gr.Tab("Flip Image"):
with gr.Row():
image_input = gr.Image()
image_output = gr.Image()
image_button = gr.Button("Flip")
with gr.Accordion("Open for More!", open=False):
gr.Markdown("Look at me...")
temp_slider = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.1,
step=0.1,
interactive=True,
label="Slide me",
)
temp_slider.change(lambda x: x, [temp_slider])
text_button.click(flip_text, inputs=text_input, outputs=text_output)
image_button.click(flip_image, inputs=image_input, outputs=image_output)
if __name__ == "__main__":
demo.launch()
Error
import gradio as gr
#from foo import BAR
#
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
examples=[
[45, "add", 3],
[3.14, "divide", 2],
[144, "multiply", 2.5],
[0, "subtract", 1.2],
],
title="Toy Calculator",
description="Here's a sample toy calculator. Allows you to calculate things like $2+2=4$",
)
if __name__ == "__main__":
demo.launch()
Chained Events
import gradio as gr
import time
def failure():
raise gr.Error("This should fail!")
def exception():
raise ValueError("Something went wrong")
def success():
return True
def warning_fn():
gr.Warning("This is a warning!")
def info_fn():
gr.Info("This is some info")
with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests."
" Also testing that the status modals show up.")
with gr.Row():
result = gr.Textbox(label="Result")
result_2 = gr.Textbox(label="Consecutive Event")
with gr.Row():
success_btn = gr.Button(value="Trigger Success")
success_btn_2 = gr.Button(value="Trigger Consecutive Success")
failure_btn = gr.Button(value="Trigger Failure")
failure_exception = gr.Button(value="Trigger Failure With ValueError")
with gr.Row():
trigger_warning = gr.Button(value="Trigger Warning")
trigger_info = gr.Button(value="Trigger Info")
success_btn_2.click(success, None, None).success(lambda: "First Event Trigered", None, result).success(lambda: "Consecutive Event Triggered", None, result_2)
success_btn.click(success, None, None).success(lambda: "Success event triggered", inputs=None, outputs=result)
failure_btn.click(failure, None, None).success(lambda: "Should not be triggered", inputs=None, outputs=result)
failure_exception.click(exception, None, None)
trigger_warning.click(warning_fn, None, None)
trigger_info.click(info_fn, None, None)
demo.queue()
if __name__ == "__main__":
demo.launch(show_error=True)
Change Listener
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
# Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
2024-05-15(三)