国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用

這篇具有很好參考價值的文章主要介紹了[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

Gradio是一個開源的Python庫,用于構(gòu)建機(jī)器學(xué)習(xí)和數(shù)據(jù)科學(xué)演示應(yīng)用。有了Gradio,你可以圍繞你的機(jī)器學(xué)習(xí)模型或數(shù)據(jù)科學(xué)工作流程快速創(chuàng)建一個簡單漂亮的用戶界面。Gradio適用于以下情況:

  • 為客戶/合作者/用戶/學(xué)生演示你的機(jī)器學(xué)習(xí)模型。

  • 通過自動共享鏈接快速部署你的模型,并獲得對模型性能的反饋。

  • 在開發(fā)過程中使用內(nèi)置的操作和解釋工具交互式地調(diào)試你的模型。

Gradio官方倉庫為:Gradio官方倉庫。Gradio官方文檔見:Gradio官方文檔。如果在使用中遇到問題,多查查官方文檔。參考Gradio-demo可以獲得不同的Gradio應(yīng)用示例。
Gradio需要Python3.7及以上版本才能運(yùn)行,安裝指令如下:

pip install gradio

1 基礎(chǔ)使用

Gradio只需要幾行代碼就可以建立一個展示應(yīng)用,一些基礎(chǔ)應(yīng)用搭建示例將在本章進(jìn)行介紹。

1.1 快速入門

1.1.1 Interface構(gòu)建應(yīng)用

通過Interface類可以快速構(gòu)建應(yīng)用。

簡單應(yīng)用

下面的示例建立了對輸入文本進(jìn)行簡單處理的應(yīng)用。

import gradio as gr

# 輸入文本處理程序
def greet(name):
    return "Hello " + name + "!"

# 接口創(chuàng)建函數(shù)
# fn設(shè)置處理函數(shù),inputs設(shè)置輸入接口組件,outputs設(shè)置輸出接口組件
# fn,inputs,outputs都是必填函數(shù)
demo = gr.Interface(fn=greet, inputs="text", outputs="text")

demo.launch()   

運(yùn)行程序后,打開http://localhost:7860即可看到網(wǎng)頁效果。左邊是文本輸入框,右邊是結(jié)果展示框。Clear按鈕用于重置網(wǎng)頁狀態(tài),Submit按鈕用于執(zhí)行處理程序,F(xiàn)lag按鈕用于保存結(jié)果到本地。

[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用

在上面的示例中,我們看到了一個簡單的基于文本的函數(shù),但該函數(shù)可以是任何函數(shù),從音樂生成器到稅務(wù)計算器,再到機(jī)器學(xué)習(xí)模型的預(yù)測函數(shù)。核心的Interface類被初始化,有三個必要的參數(shù)。

  • fn: 圍繞用戶界面的函數(shù)
  • 輸入:用于輸入的組件(例如:“text”、"image)。
  • 輸出:用于輸出的組件(例如:“text”、"image)。

自定義輸入組件

以下代碼展示了如何自定義輸入組件。

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(
    fn=greet,
    # 自定義輸入框
    # 具體設(shè)置方法查看官方文檔
    inputs=gr.Textbox(lines=3, placeholder="Name Here...",label="my input"),
    outputs="text",
)
demo.launch()

多輸入和多輸出組件設(shè)置

對于復(fù)雜程序,輸入列表中的每個組件按順序?qū)?yīng)于函數(shù)的一個參數(shù)。輸出列表中的每個組件按順序排列對應(yīng)于函數(shù)返回的一個值。

import gradio as gr

# 該函數(shù)有3個輸入?yún)?shù)和2個輸出參數(shù)
def 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 / 9
    return greeting, round(celsius, 2)

demo = gr.Interface(
    fn=greet,
    # 按照處理程序設(shè)置輸入組件
    inputs=["text", "checkbox", gr.Slider(0, 100)],
    # 按照處理程序設(shè)置輸出組件
    outputs=["text", "number"],
)
demo.launch()

代碼運(yùn)行處理結(jié)果如下圖所示:

[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用

圖像組件

Gradio支持許多類型的組件,如image、dataframe、video。使用示例如下:

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

# shape設(shè)置輸入圖像大小
demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
demo.launch()

當(dāng)使用Image組件作為輸入時,函數(shù)將收到一個維度為(w,h,3)的numpy數(shù)組,按照RGB的通道順序排列。要注意的是,我們的輸入圖像組件帶有一個編輯按鈕??,可以對圖像進(jìn)行裁剪和放大。以這種方式處理圖像可以幫助揭示機(jī)器學(xué)習(xí)模型中的偏差或隱藏的缺陷。此外對于輸入組件有個shape參數(shù),指的設(shè)置輸入圖像大小。但是處理方式是保持長寬比的情況下,將圖像最短邊縮放為指定長度,然后按照中心裁剪方式裁剪最長邊到指定長度。當(dāng)圖像不大的情況,一種更好的方式是不設(shè)置shape,這樣直接傳入原圖。輸入組件Image也可以設(shè)置輸入類型type,比如type=filepath設(shè)置傳入處理圖像的路徑。具體可以查看官方文檔,??文檔寫的很清楚。
代碼運(yùn)行處理結(jié)果如下圖所示:

[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用

1.1.2 Blocks構(gòu)建應(yīng)用

相比Interface,Blocks提供了一個低級別的API,用于設(shè)計具有更靈活布局和數(shù)據(jù)流的網(wǎng)絡(luò)應(yīng)用。Blocks允許控制組件在頁面上出現(xiàn)的位置,處理復(fù)雜的數(shù)據(jù)流(例如,輸出可以作為其他函數(shù)的輸入),并根據(jù)用戶交互更新組件的屬性可見性。

簡單應(yīng)用

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

with gr.Blocks() as demo:
    # 設(shè)置輸入組件
    name = gr.Textbox(label="Name")
    # 設(shè)置輸出組件
    output = gr.Textbox(label="Output Box")
    # 設(shè)置按鈕
    greet_btn = gr.Button("Greet")
    # 設(shè)置按鈕點(diǎn)擊事件
    greet_btn.click(fn=greet, inputs=name, outputs=output)

demo.launch()

Blocks方式需要with語句添加組件,如果不設(shè)置布局方式,那么組件將按照創(chuàng)建的順序垂直出現(xiàn)在應(yīng)用程序中,運(yùn)行界面如下圖示:

[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用

多模塊應(yīng)用

該例子介紹了一個多模塊應(yīng)用,其中各個模塊的使用可以查看官方文檔。

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:
    # 用markdown語法編輯輸出一段話
    gr.Markdown("Flip text or image files using this demo.")
    # 設(shè)置tab選項(xiàng)卡
    with gr.Tab("Flip Text"):
        #  Blocks特有組件,設(shè)置所有子組件按垂直排列
        # 垂直排列是默認(rèn)情況,不加也沒關(guān)系
        with gr.Column():
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        # Blocks特有組件,設(shè)置所有子組件按水平排列
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    # 設(shè)置折疊內(nèi)容
    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()

1.2 關(guān)鍵特性

示例輸入

下面的代碼提供了創(chuàng)建一個簡單計算器的模板。該程序運(yùn)行后,點(diǎn)擊flag按鈕會在運(yùn)行目錄下指定flagged/logs.csv保存輸入記錄。保存目錄的修改和相關(guān)信息設(shè)置查看官方文檔flagging項(xiàng)。

import gradio as gr

# 一個簡單計算器
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:
            # 設(shè)置報錯彈窗
            raise gr.Error("Cannot divide by zero!")
        return num1 / num2

demo = gr.Interface(
    calculator,
    # 設(shè)置輸入
    [
        "number", 
        gr.Radio(["add", "subtract", "multiply", "divide"]),
        "number"
    ],
    # 設(shè)置輸出
    "number",
    # 設(shè)置輸入?yún)?shù)示例
    examples=[
        [5, "add", 3],
        [4, "divide", 2],
        [-4, "multiply", 2.5],
        [0, "subtract", 1.2],
    ],
    # 設(shè)置網(wǎng)頁標(biāo)題
    title="Toy Calculator",
    # 左上角的描述文字
    description="Here's a sample toy calculator. Enjoy!",
    # 左下角的文字
    article = "Check out the examples",
)
demo.launch()

樣式和排隊(duì)

在Gradio官方文檔,搜索不同的組件加.style(如image.style),可以獲取該組件的樣式參數(shù)設(shè)置樣例。例如image組件的設(shè)置如下:

img = gr.Image("lion.jpg").style(height='24', rounded=False)

如果函數(shù)推理時間較長,比如目標(biāo)檢測;或者應(yīng)用程序處理流量過大,則需要使用queue方法進(jìn)行排隊(duì)。queue方法使用websockets,可以防止網(wǎng)絡(luò)超時。使用方式如下:


demo = gr.Interface(...).queue()
demo.launch()

# 或
with gr.Blocks() as demo:
    #...
demo.queue()
demo.launch()

生成器

在某些情況下,你可能想顯示一連串的輸出,而不是單一的輸出。例如,你可能有一個圖像生成模型,如果你想顯示在每個步驟中生成的圖像,從而得到最終的圖像。在這種情況下,你可以向Gradio提供一個生成器函數(shù),而不是一個常規(guī)函數(shù)。下面是一個生成器的例子,每隔1秒返回1張圖片。

import gradio as gr
import numpy as np
import time

# 生成steps張圖片,每隔1秒鐘返回
def fake_diffusion(steps):
    for _ in range(steps):
        time.sleep(1)
        image = np.random.randint(255, size=(300, 600, 3))
        yield image

demo = gr.Interface(fake_diffusion, 
                    # 設(shè)置滑窗,最小值為1,最大值為10,初始值為3,每次改動增減1位
                    inputs=gr.Slider(1, 10, value=3, step=1), 
                    outputs="image")

# 生成器必須要queue函數(shù)
demo.queue()

demo.launch()

1.3 應(yīng)用分享

互聯(lián)網(wǎng)分享

如果運(yùn)行環(huán)境能夠連接互聯(lián)網(wǎng),在launch函數(shù)中設(shè)置share參數(shù)為True,那么運(yùn)行程序后。Gradio的服務(wù)器會提供XXXXX.gradio.app地址。通過其他設(shè)備,比如手機(jī)或者筆記本電腦,都可以訪問該應(yīng)用。這種方式下該鏈接只是本地服務(wù)器的代理,不會存儲通過本地應(yīng)用程序發(fā)送的任何數(shù)據(jù)。這個鏈接在有效期內(nèi)是免費(fèi)的,好處就是不需要自己搭建服務(wù)器,壞處就是太慢了,畢竟數(shù)據(jù)經(jīng)過別人的服務(wù)器。

demo.launch(share=True)

Hugging Face托管

如果想長期免費(fèi)分享應(yīng)用,可以在Hugging Face中托管應(yīng)用或者其他的一些方式,詳細(xì)使用見分享Gradio應(yīng)用。Hugging Face提供了多個基于Gradio搭建應(yīng)用的demo,詳情使用見Using Hugging Face Integrations。

局域網(wǎng)分享

通過設(shè)置server_name=‘0.0.0.0’(表示使用本機(jī)ip),server_port(可不改,默認(rèn)值是7860)。那么可以通過本機(jī)ip:端口號在局域網(wǎng)內(nèi)分享應(yīng)用。

# show_error為True表示在控制臺顯示錯誤信息。
demo.launch(server_name='0.0.0.0', server_port=8080, show_error=True)

密碼驗(yàn)證

在首次打開網(wǎng)頁前,可以設(shè)置賬戶密碼。比如auth參數(shù)為(賬戶,密碼)的元組數(shù)據(jù)。這種模式下不能夠使用queue函數(shù)。

demo.launch(auth=("admin", "pass1234"))

如果想設(shè)置更為復(fù)雜的賬戶密碼和密碼提示,可以通過函數(shù)設(shè)置校驗(yàn)規(guī)則。

# 賬戶和密碼相同就可以通過
def same_auth(username, password):
    return username == password
demo.launch(auth=same_auth,auth_message="username and password must be the same")

2 進(jìn)階使用

2.1 interface進(jìn)階使用

2.1.1 interface狀態(tài)

全局變量

全局變量的好處就是在調(diào)用函數(shù)后仍然能夠保存,例如在機(jī)器學(xué)習(xí)中通過全局變量從外部加載一個大型模型,并在函數(shù)內(nèi)部使用它,以便每次函數(shù)調(diào)用都不需要重新加載模型。下面就展示了全局變量使用的好處。

import gradio as gr

scores = []

def track_score(score):
    scores.append(score)
    # 返回分?jǐn)?shù)top3
    top_scores = sorted(scores, reverse=True)[:3]
    return top_scores

demo = gr.Interface(
    track_score, 
    gr.Number(label="Score"), 
    gr.JSON(label="Top Scores")
)
demo.launch()

會話狀態(tài)

Gradio支持的另一種數(shù)據(jù)持久性是會話狀態(tài),數(shù)據(jù)在一個頁面會話中的多次提交中持久存在。然而,數(shù)據(jù)不會在你模型的不同用戶之間共享。會話狀態(tài)的典型例子就是聊天機(jī)器人,你想訪問用戶之前提交的信息,但你不能將聊天記錄存儲在一個全局變量中,因?yàn)槟菢拥脑?,聊天記錄會在不同的用戶之間亂成一團(tuán)。注意該狀態(tài)會在每個頁面內(nèi)的提交中持續(xù)存在,但如果您在另一個標(biāo)簽頁中加載該演示(或刷新頁面),該演示將不會共享聊天歷史。

要在會話狀態(tài)下存儲數(shù)據(jù),你需要做三件事。

  • 在你的函數(shù)中傳入一個額外的參數(shù),它代表界面的狀態(tài)。
  • 在函數(shù)的最后,將狀態(tài)的更新值作為一個額外的返回值返回。
  • 在添加輸入和輸出時添加state組件。
import random
import gradio as gr

def chat(message, history):
    history = history or []
    message = message.lower()
    if message.startswith("how many"):
        response = random.randint(1, 10)
    elif message.startswith("how"):
        response = random.choice(["Great", "Good", "Okay", "Bad"])
    elif message.startswith("where"):
        response = random.choice(["Here", "There", "Somewhere"])
    else:
        response = "I don't know"
    history.append((message, response))
    return history, history

# 設(shè)置一個對話窗
chatbot = gr.Chatbot().style(color_map=("green", "pink"))
demo = gr.Interface(
    chat,
    # 添加state組件
    ["text", "state"],
    [chatbot, "state"],
    # 設(shè)置沒有保存數(shù)據(jù)的按鈕
    allow_flagging="never",
)
demo.launch()

2.1.2 interface交互

實(shí)時變化

在Interface中設(shè)置live=True,則輸出會跟隨輸入實(shí)時變化。這個時候界面不會有submit按鈕,因?yàn)椴恍枰謩犹峤惠斎搿?/p>

import gradio as gr

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":
        return num1 / num2

demo = gr.Interface(
    calculator,
    [
        "number",
        gr.Radio(["add", "subtract", "multiply", "divide"]),
        "number"
    ],
    "number",
    live=True,
)
demo.launch()

流模式

在許多情形下,我們的輸入是實(shí)時視頻流或者音頻流,那么意味這數(shù)據(jù)不停地發(fā)送到后端,這是可以采用streaming模式處理數(shù)據(jù)。

import gradio as gr
import numpy as np

def flip(im):
    return np.flipud(im)

demo = gr.Interface(
    flip, 
    gr.Image(source="webcam", streaming=True), 
    "image",
    live=True
)
demo.launch()

2.2 Blocks進(jìn)階使用

2.2.1 Blocks事件

可交互設(shè)置

任何輸入的組件內(nèi)容都是可編輯的,而輸出組件默認(rèn)是不能編輯的。如果想要使得輸出組件內(nèi)容可編輯,設(shè)置interactive=True即可。

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")
    # 可交互
    output = gr.Textbox(label="Output", interactive=True)
    greet_btn = gr.Button("Greet")
    greet_btn.click(fn=greet, inputs=name, outputs=output)

demo.launch()

事件設(shè)置

我們可以為不同的組件設(shè)置不同事件,如為輸入組件添加change事件??梢赃M(jìn)一步查看官方文檔,看看組件還有哪些事件。

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()
    # 設(shè)置change事件
    inp.change(fn = welcome, inputs = inp, outputs = out)

demo.launch()

多個數(shù)據(jù)流

如果想處理多個數(shù)據(jù)流,只要設(shè)置相應(yīng)的輸入輸出組件即可。

import gradio as gr

def increase(num):
    return num + 1

with gr.Blocks() as demo:
    a = gr.Number(label="a")
    b = gr.Number(label="b")
    # 要想b>a,則使得b = a+1
    atob = gr.Button("b > a")
    atob.click(increase, a, b)
    # 要想a>b,則使得a = b+1
    btoa = gr.Button("a > b")
    btoa.click(increase, b, a)

demo.launch()

多輸出值處理

下面的例子展示了輸出多個值時,以列表形式表現(xiàn)的處理方式。

import gradio as gr

with gr.Blocks() as demo:
    food_box = gr.Number(value=10, label="Food Count")
    status_box = gr.Textbox()
    def eat(food):
        if food > 0:
            return food - 1, "full"
        else:
            return 0, "hungry"
    gr.Button("EAT").click(
        fn=eat, 
        inputs=food_box,
        # 根據(jù)返回值改變輸入組件和輸出組件
        outputs=[food_box, status_box]
    )

demo.launch()

下面的例子展示了輸出多個值時,以字典形式表現(xiàn)的處理方式。

import gradio as gr


with gr.Blocks() as demo:
    food_box = gr.Number(value=10, label="Food Count")
    status_box = gr.Textbox()
    def eat(food):
        if food > 0:
            return {food_box: food - 1, status_box: "full"}
        else:
            return {status_box: "hungry"}
    gr.Button("EAT").click(
        fn=eat, 
        inputs=food_box,
        outputs=[food_box, status_box]
    )

demo.launch()

組件配置修改

事件監(jiān)聽器函數(shù)的返回值通常是相應(yīng)的輸出組件的更新值。有時我們也想更新組件的配置,比如說可見性。在這種情況下,我們可以通過返回update函數(shù)更新組件的配置。

import gradio as gr

def change_textbox(choice):
    # 根據(jù)不同輸入對輸出控件進(jìn)行更新
    if choice == "short":
        return gr.update(lines=2, visible=True, value="Short story: ")
    elif choice == "long":
        return gr.update(lines=8, visible=True, value="Long story...")
    else:
        return gr.update(visible=False)

with gr.Blocks() as demo:
    radio = gr.Radio(
        ["short", "long", "none"], label="Essay Length to Write?"
    )
    text = gr.Textbox(lines=2, interactive=True)
    radio.change(fn=change_textbox, inputs=radio, outputs=text)

demo.launch()

2.2.2 Blocks布局

Blocks應(yīng)用的是html中的flexbox模型布局,默認(rèn)情況下組件垂直排列。

組件水平排列

使用Row函數(shù)會將組件按照水平排列,但是在Row函數(shù)塊里面的組件都會保持同等高度。


import gradio as gr
with gr.Blocks() as demo:
    with gr.Row():
        img1 = gr.Image()
        text1 = gr.Text()
    btn1 = gr.Button("button")
demo.launch()

組件垂直排列與嵌套

組件通常是垂直排列,我們可以通過Row函數(shù)和Column函數(shù)生成不同復(fù)雜的布局。

import gradio as gr

with gr.Blocks() as demo:
    with gr.Row():
        text1 = gr.Textbox(label="t1")
        slider2 = gr.Textbox(label="s2")
        drop3 = gr.Dropdown(["a", "b", "c"], label="d3")
    with gr.Row():
        # scale與相鄰列相比的相對寬度。例如,如果列A的比例為2,列B的比例為1,則A的寬度將是B的兩倍。
        # min_width設(shè)置最小寬度,防止列太窄
        with gr.Column(scale=2, min_width=600):
            text1 = gr.Textbox(label="prompt 1")
            text2 = gr.Textbox(label="prompt 2")
            inbtw = gr.Button("Between")
            text4 = gr.Textbox(label="prompt 1")
            text5 = gr.Textbox(label="prompt 2")
        with gr.Column(scale=1, min_width=600):
            img1 = gr.Image("test.jpg")
            btn = gr.Button("Go")

demo.launch()

組件可視化

如下所示,我們可以通過visible和update函數(shù)構(gòu)建更為復(fù)雜的應(yīng)用。

import gradio as gr

with gr.Blocks() as demo:
    # 出錯提示框
    error_box = gr.Textbox(label="Error", visible=False)

    # 輸入框
    name_box = gr.Textbox(label="Name")
    age_box = gr.Number(label="Age")
    symptoms_box = gr.CheckboxGroup(["Cough", "Fever", "Runny Nose"])
    submit_btn = gr.Button("Submit")

    # 輸出不可見
    with gr.Column(visible=False) as output_col:
        diagnosis_box = gr.Textbox(label="Diagnosis")
        patient_summary_box = gr.Textbox(label="Patient Summary")

    def submit(name, age, symptoms):
        if len(name) == 0:
            return {error_box: gr.update(value="Enter name", visible=True)}
        if age < 0 or age > 200:
            return {error_box: gr.update(value="Enter valid age", visible=True)}
        return {
            output_col: gr.update(visible=True),
            diagnosis_box: "covid" if "Cough" in symptoms else "flu",
            patient_summary_box: f"{name}, {age} y/o"
        }

    submit_btn.click(
        submit,
        [name_box, age_box, symptoms_box],
        [error_box, diagnosis_box, patient_summary_box, output_col],
    )

demo.launch()

組件渲染

在某些情況下,您可能希望在實(shí)際在UI中呈現(xiàn)組件之前定義組件。例如,您可能希望在相應(yīng)的gr.Textbox輸入上方顯示使用gr.examples的示例部分。由于gr.Examples需要輸入組件對象作為參數(shù),因此您需要先定義輸入組件,然后在定義gr.Exmples對象后再進(jìn)行渲染。解決方法是在gr.Blocks()范圍外定義gr.Textbox,并在UI中希望放置的任何位置使用組件的.render()方法。

import gradio as gr

input_textbox = gr.Textbox()

with gr.Blocks() as demo:
    # 提供示例輸入給input_textbox,示例輸入以嵌套列表形式設(shè)置
    gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
    # render函數(shù)渲染input_textbox
    input_textbox.render()
demo.launch()

2.2.3 樣式修改

自定義css

要獲得額外的樣式功能,您可以設(shè)置行內(nèi)css屬性將任何樣式給應(yīng)用程序。如下所示。

import gradio as gr

# 修改blocks的背景顏色
with gr.Blocks(css=".gradio-container {background-color: red}") as demo:
    box1 = gr.Textbox(value="Good Job")
    box2 = gr.Textbox(value="Failure")
demo.launch()

元素選擇

您可以向任何組件添加HTML元素。通過elem_id選擇對應(yīng)的css元素。文章來源地址http://www.zghlxwxcb.cn/news/detail-405799.html

import gradio as gr

# 這里用的是id屬性設(shè)置
with gr.Blocks(css="#warning {background-color: red}") as demo:
    box1 = gr.Textbox(value="Good Job", elem_id="warning")
    box2 = gr.Textbox(value="Failure")
    box3 = gr.Textbox(value="None", elem_id="warning")
demo.launch()

3 參考

  • Gradio官方倉庫
  • Gradio官方文檔
  • 分享Gradio應(yīng)用
  • Gradio-demo
  • Using Hugging Face Integrations

到了這里,關(guān)于[python] 基于Gradio可視化部署機(jī)器學(xué)習(xí)應(yīng)用的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包