文章目錄
- 1、簡介
- 2、安裝
- 3、基本測試
- 3.1 入門代碼
- 3.2 組件屬性
- 3.3 多個輸入和輸出組件
- 3.4 圖像示例
- 3.5 聊天機器人
- 3.6 模塊:更靈活、更可控
- 3.7 進度條
- 結語
1、簡介
https://www.gradio.app/
Gradio是用友好的網絡界面演示機器學習模型的最快方法,因此任何人都可以在任何地方使用它!
Gradio與他人共享機器學習模型、API或數據科學工作流程的最佳方法之一是創建一個交互式應用程序,允許您的用戶或同事在瀏覽器中嘗試演示。
Gradio允許您構建演示并共享它們,所有這些都使用Python。通常只需幾行代碼!讓我們開始吧。
使用gradio,只需在原有的代碼中增加幾行,就能自動化生成交互式web頁面,并支持多種輸入輸出格式,比如圖像分類中的圖>>標簽,超分辨率中的圖>>圖等。
2、安裝
Gradio requires Python 3.8 or higher, that’s all!
pip install gradio
3、基本測試
3.1 入門代碼
Run the code below as a Python script or in a Jupyter Notebook (or Google Colab):
import gradio as grdef greet(name):return "小沐: " + name + "!"demo = gr.Interface(fn=greet, inputs="text", outputs="text")if __name__ == "__main__":demo.launch(show_api=False)
瀏覽器訪問:
http://127.0.0.1:7860/
在本地開發時,如果要將代碼作為 Python 腳本運行,可以使用 Gradio CLI 以重新加載模式啟動應用程序,這將提供無縫和快速的開發。
gradio test.py
注意:你也可以這樣做,但它不會提供自動重新加載機制。python test.py
3.2 組件屬性
假設您要自定義輸入文本字段,例如,您希望它更大并具有文本占位符。
import gradio as grdef greet(name):return "小沐: " + name + "!"demo = gr.Interface(fn=greet,inputs=gr.Textbox(lines=2, placeholder="Name Here..."),outputs="text",
)
demo.launch()
3.3 多個輸入和輸出組件
假設您有一個更復雜的函數,具有多個輸入和輸出。在下面的示例中,我們定義了一個函數,該函數接受字符串、布爾值和數字,并返回字符串和數字。看看如何傳遞輸入和輸出組件列表。
import gradio as grdef greet(name, is_morning, temperature):salutation = "Good morning" if is_morning else "Good evening"greeting = f"{salutation} {name}. It is {temperature} degrees today"celsius = (temperature - 32) * 5 / 9return greeting, round(celsius, 2)demo = gr.Interface(fn=greet,inputs=["text", "checkbox", gr.Slider(0, 100)],outputs=["text", "number"],
)
demo.launch()
3.4 圖像示例
Gradio 支持多種類型的組件,例如 、 、 或 。讓我們嘗試一個圖像到圖像功能來感受這些!
import numpy as np
import gradio as grdef 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_imgdemo = gr.Interface(sepia, gr.Image(), "image")
demo.launch()
3.5 聊天機器人
Gradio 包含一個高級類,它類似于 ,但專為聊天機器人 UI 設計。該類還包裝一個函數,但此函數必須具有特定的簽名。該函數應該接受兩個參數:然后(參數可以命名為任何名稱,但必須按此順序命名).
gr.ChatInterfacegr.Interfacegr.ChatInterfacemessagehistory:
- message:a 表示用戶的輸入str
- history:a 表示在此之前的對話。每個內部列表由兩個表示一對組成:。listliststr[user input, bot response]
import random
import gradio as grdef random_response(message, history):return random.choice(["Yes", "No"])demo = gr.ChatInterface(random_response)demo.launch()
3.6 模塊:更靈活、更可控
Gradio提供了兩種構建應用程序的方法:
- Interface 和 ChatInterface,它們為創建我們目前一直在討論的演示提供了高級抽象。
- Blocks,一個低級 API,用于設計具有更靈活布局和數據流的 Web 應用程序。Blocks 允許您執行諸如具有多個數據流和演示、控制組件在頁面上的顯示位置、處理復雜的數據流(例如,輸出可以作為其他函數的輸入)以及基于用戶交互更新組件的屬性/可見性等操作——所有這些都在 Python 中。
import gradio as grdef 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")demo.launch()
這里有一個應用程序,可以讓你體驗到什么是可能的:Blocks
import numpy as np
import gradio as grdef 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!"):gr.Markdown("Look at me...")text_button.click(flip_text, inputs=text_input, outputs=text_output)image_button.click(flip_image, inputs=image_input, outputs=image_output)demo.launch()
3.7 進度條
import gradio as gr
import timedef 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_stringreturn new_stringdemo = gr.Interface(slowly_reverse, gr.Text(), gr.Text())demo.launch()
結語
如果您覺得該方法或代碼有一點點用處,可以給作者點個贊,或打賞杯咖啡;
╮( ̄▽ ̄)╭
如果您感覺方法或代碼不咋地
//(ㄒoㄒ)//,就在評論處留言,作者繼續改進;
o_O???
如果您需要相關功能的代碼定制化開發,可以留言私信作者;
(????)
感謝各位大佬童鞋們的支持!
( ′ ▽′ )ノ ( ′ ▽′)っ!!!