最近玩 Agent 或機器學習模型時,你可能會想要一個簡單的方式把它 變成網頁互動介面。
這時候,Python 的 Gradio 就派上用場啦~
今天我們來看看什麼是 Gradio q(≧▽≦q)
Gradio 是一個 Python 函式庫,專門用來快速把模型或函數包裝成 可互動的網頁 UI。
它的設計理念就是:簡單、快速、直接就能看到效果。
你只要幾行程式碼,就可以把模型從命令列工具變成任何人都能在線使用的 Web App。
幾行 Python 就能搞定互動式網頁,不需要寫 HTML、CSS 或 JS。
import gradio as gr
def greet(name):
return f"哈囉,{name}!"
iface = gr.Interface(fn=greet, inputs="text", outputs="text")
iface.launch()
文字、圖片、音訊、影片、滑桿、下拉選單…幾乎所有常見輸入輸出都支援。
不用部署伺服器,直接在瀏覽器互動,立即看到模型的輸出結果。
不懂前端也沒關係,純 Python 就能做出漂亮的 Demo。
內建 share=True
,可生成臨時公開網址,朋友或同事也能立即使用你的應用。
最簡單的單一函式介面:
gr.Interface(fn=greet, inputs="text", outputs="text")
可組合多個元件,建立複雜介面:
with gr.Blocks() as demo:
with gr.Row():
gr.Textbox(label="輸入1")
gr.Textbox(label="輸入2")
with gr.Column():
btn = gr.Button("提交")
out = gr.Textbox(label="回應")
demo.launch()
建立多分頁畫面:
with gr.Blocks() as demo:
with gr.Tab("登入"):
gr.Textbox(label="帳號")
gr.Textbox(label="密碼", type="password")
with gr.Tab("註冊"):
gr.Textbox(label="姓名")
gr.Textbox(label="Email")
demo.launch()
快速做聊天機器人介面:
import gradio as gr
def simple_chat(message, history):
return message
demo = gr.ChatInterface(fn=simple_chat,
title="簡易聊天機器人",
description="回傳你輸入的文字")
demo.launch()
優點:
缺點:
看完這篇,你應該就知道 Gradio 是 Python 開發者快速做模型互動 Demo 的最佳利器啦!
下次,我們可以試試把 Gradio + Agent 整合
下一篇再見o( ̄︶ ̄)o