一、Gradio基本使用方式:
Gradio是一个开源的Python包,允许您快速为您的机器学习模型、API或任意Python函数构建演示或Web应用程序。然后,您可以使用Gradio内置的分享功能在几秒钟内分享您的演示或Web应用程序链接。无需JavaScript、CSS或Web主机经验。
基本使用:
import gradio as gr
#参数名直接就是界面显示的参数名,无需再次定义界面head名称
def greet(name, intensity):
return "Hello, " + name + "!" * int(intensity)
demo = gr.Interface(
fn=greet, #按钮submit链接的函数
inputs=["text", "slider"], # 函数输入类型text为文字框,slider为拖拉框(需要和函数定义吻合)
outputs=["text"], # 函数输出,也需要和函数输出吻合
#以下是非必需
title="Toy Calculator", #标题
description="Here's a sample toy calculator. Allows you to calculate things like $2+2=4$" #说明
)
# 也可以采用这个方式
demo = gr.Interface(
fn=greet,
inputs=["text", gr.Slider(value=2, minimum=1, maximum=10, step=1)],
outputs=[gr.Textbox(label="greeting", lines=3)] #将“text”改为一个组件gr.Textbox的格式,自定义label和长度。
)
#而对于单个输入输出,简化可以为:
demo = gr.Interface(sepia, gr.Image(), "image")#输入图像(默认为array格式)和输出图像
#如果想让输入图片为‘路径格式’,只需要将gr.Image()修改为
gr.Image(type="filepath", shape=...)
demo.launch()
二、examples(输入建议)
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!"