赞
踩
$ pip install gradio==4.29 -i "https://pypi.doubanio.com/simple/"
Successfully installed aiofiles-23.2.1 altair-5.3.0 attrs-23.2.0 contourpy-1.2.1 cycler-0.12.1 ffmpy-0.3.2 filelock-3.14.0 fonttools-4.51.0 fsspec-2024.3.1 gradio-4.29.0 gradio-client-0.16.1 httpcore-1.0.5 httpx-0.27.0 huggingface-hub-0.23.0 importlib-resources-6.4.0 jsonschema-4.22.0 jsonschema-specifications-2023.12.1 kiwisolver-1.4.5 markdown-it-py-3.0.0 matplotlib-3.8.4 mdurl-0.1.2 orjson-3.10.3 pillow-10.3.0 pydub-0.25.1 pygments-2.18.0 pyparsing-3.1.2 python-multipart-0.0.9 referencing-0.35.1 requests-2.31.0 rich-13.7.1 rpds-py-0.18.1 ruff-0.4.3 semantic-version-2.10.0 shellingham-1.5.4 tomlkit-0.12.0 typer-0.12.3 urllib3-2.2.1 websockets-11.0.3
import gradio as gr print(gr.__version__) def process_data(text, image, filter_type): print(type(image)) # 数据处理逻辑 processed_text = text.upper() if filter_type: image = image.convert(filter_type) return processed_text, image iface = gr.Interface( fn=process_data, inputs=[ gr.Textbox(label="输入文本"), gr.Image(label="上传图片", type="pil"), gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), ], outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")], title="文本、图像处理", description="输入文本、图像,以获得处理。", ) iface.launch()
# 设置启动端口 iface.launch(server_name='127.0.0.1', server_port=8080, show_error=True) # 当把server_name设置为'0.0.0.0'时,局域网内的电脑皆可通过服务器IP访问该服务 iface.launch(server_name='0.0.0.0') # 在互联网分享(Gradio的服务器会提供XXX.gradio.app地址) iface.launch(share=True) # 设置用户、密码 iface.launch(auth=("admin", "admin12345")) # 更复杂的用户、密码校验 def my_auth(username, password): # 例如可以连接到外部系统校验登录 return username == "admin" and password == "admin12345" iface.launch(auth=my_auth, auth_message="login error") # 启动服务时,自动打开默认浏览器 face.launch(inbrowser=True)
yield
,可以实现流式响应 Streaming outputsimport gradio as gr
import time
print(gr.__version__)
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(0.05)
yield "机器人回复: " + message[: i+1]
iface = gr.ChatInterface(slow_echo).queue()
iface.launch()
import gradio as gr
import time
def function1(input1):
return f"处理结果: {input1}"
def function2(input2):
return f"分析结果: {input2}"
iface1 = gr.Interface(function1, "text", "text")
iface2 = gr.Interface(function2, "text", "text")
tabbed_interface = gr.TabbedInterface([iface1, iface2], ["界面1", "界面2"])
tabbed_interface.launch()
import gradio as gr import time def process_data(text, image, filter_type): print(type(image)) # 数据处理逻辑 processed_text = text.upper() if filter_type: image = image.convert(filter_type) return processed_text, image base_iface = gr.Interface( fn=process_data, inputs=[ gr.Textbox(label="输入文本"), gr.Image(label="上传图片", type="pil"), gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), ], outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")], title="文本、图像处理", description="输入文本、图像,以获得处理。", ) def slow_echo(message, history): for i in range(len(message)): time.sleep(0.05) yield "机器人回复: " + message[: i+1] chat_iface = gr.ChatInterface(slow_echo).queue() tabbed_interface = gr.TabbedInterface([base_iface, chat_iface], ["基础界面", "聊天界面"]) tabbed_interface.launch()
import gradio as gr import time def process_data(text, image, filter_type): print(type(image)) # 数据处理逻辑 processed_text = text.upper() if filter_type: image = image.convert(filter_type) return processed_text, image base_iface = gr.Interface( fn=process_data, inputs=[ gr.Textbox(label="输入文本"), gr.Image(label="上传图片", type="pil"), gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L"), ], outputs=[gr.Text(label="处理后的文本"), gr.Image(label="处理后的图片")], title="文本、图像处理", description="输入文本、图像,以获得处理。", ) def slow_echo(message, history): for i in range(len(message)): time.sleep(0.05) yield "机器人回复: " + message[: i+1] chat_iface = gr.ChatInterface(slow_echo).queue() with gr.Blocks() as block1_iface: # 多个Row,均分纵轴 with gr.Row(): # 多个Column,则均分横纵 with gr.Column(): input_text = gr.Textbox(label="输入") submit_button = gr.Button("提交") with gr.Column(): output_text = gr.Label(label="输出") submit_button.click(fn=lambda x: f"你输入了: {x}", inputs=input_text, outputs=output_text) with gr.Blocks() as block2_iface: # Group 连接2个组件 with gr.Group(): input1 = gr.Textbox() input2 = gr.Slider() # Accordion 连接2个组件,并包含,并有标题提示 with gr.Accordion("详细设置"): checkbox = gr.Checkbox(label="选项") dropdown = gr.Dropdown(choices=["选项1", "选项2"]) submit_button = gr.Button("提交") output_label = gr.Label() submit_button.click(fn=lambda x, y, z: f"{x}, {y}, {z}", inputs=[input1, input2, checkbox], outputs=output_label) with gr.Blocks() as block3_iface: with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="输入文本") with gr.Group(): input_image = gr.Image(label="上传图片", type="pil") input_mode = gr.Radio(label="图像转换模式", info="参考 https://blog.csdn.net/u012977885/article/details/105733554", choices=["1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "I", "F"], value="L") submit_button = gr.Button("提交") with gr.Column(): output_text = gr.Text(label="处理后的文本") output_image = gr.Image(label="处理后的图片") submit_button.click(fn=process_data, inputs=[input_text, input_image, input_mode], outputs=[output_text, output_image]) tabbed_interface = gr.TabbedInterface( [base_iface, chat_iface, block1_iface, block2_iface, block3_iface], ["基础界面", "聊天界面", "Block1界面", "Block2界面", "Block3界面"] ) tabbed_interface.launch()
import gradio as gr import pandas as pd # pip install plotly import plotly.express as px import matplotlib.pyplot as plt def explore_data(dataset, columns): df = pd.read_csv(dataset) # plotly库,自带功能更多 # fig = px.scatter(df, x=columns[0], y=columns[1]) # matplotlib库 fig = plt.figure() plt.scatter(df[columns[0]], df[columns[1]]) plt.xlabel(columns[0]) plt.ylabel(columns[1]) return fig demo = gr.Interface( fn=explore_data, inputs=[ gr.File(label="上传CSV文件"), gr.CheckboxGroup(choices=["num", "age", "tall"], label="选择列"), ], outputs=gr.Plot(), ) demo.launch()
import gradio as gr import pandas as pd # pip install seaborn import seaborn as sns import matplotlib.pyplot as plt def plot_data(file, chart_type): df = pd.read_csv(file) if chart_type == "柱状图": plt.figure(figsize=(10, 6)) sns.barplot(data=df) elif chart_type == "折线图": plt.figure(figsize=(10, 6)) sns.lineplot(data=df) plt.tight_layout() return plt iface = gr.Interface( plot_data, inputs=[gr.File(), gr.Dropdown(["柱状图", "折线图"])], outputs="plot" ) iface.launch()
import gradio as gr
def update_output(input_text, state_obj):
state_obj = state_obj or 0
state_obj += 1
return f"您输入了:{input_text}", f"状态值:{state_obj}", state_obj
# gr.State() 是会话级状态
# 全局状态,直接在代码里面定义一个state_obj变量即可
iface = gr.Interface(
fn=update_output,
inputs=[gr.Textbox(), gr.State()],
outputs=[gr.Textbox(), gr.Label(), gr.State()]
)
iface.launch()
def start_process(name):
gr.Info("Starting process")
if name is None:
gr.Warning("Name is empty")
...
if success == False:
raise gr.Error("Process failed")
import gradio as gr import time def slowly_reverse(word, progress=gr.Progress()): progress(0, desc="Starting") time.sleep(1) progress(0.05) new_string = "" for letter in progress.tqdm(word, desc="Reversing"): time.sleep(0.25) new_string = letter + new_string return new_string demo = gr.Interface(slowly_reverse, gr.Text(), gr.Text()) demo.launch()
gr.Progress(track_tqdm=True)
,自动追踪tqdm
,显示进度)import gradio as gr import time import tqdm # gr.Progress(track_tqdm=True) 必须写在方法入参这里 def slowly_reverse2(word, progress=gr.Progress(track_tqdm=True)): time.sleep(1) new_string = "" tqdm_progress = tqdm.tqdm(word, desc="Reversing") for letter in tqdm_progress: time.sleep(0.25) new_string = letter + new_string return new_string demo = gr.Interface(slowly_reverse2, gr.Text(), gr.Text()) demo.launch()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。