Detailed tutorial for getting started with Gradio

Comparison of two commonly used AI visualization interactive applications:

  • Gradio
    The advantage of Gradio lies in its ease of use. The code structure is simpler than Streamlit. It can be quickly constructed by simply defining the input and output interfaces. Simple interactive page makes it easier to deploy models. It is suitable for developers who have relatively simple scenarios and want to quickly deploy applications. Easy to share: Gradio can set theshare=True parameters when starting the application to create an external sharing link, which can be shared directly with users in WeChat.

  • The advantage of Streamlit
    Streamlit is that可扩展性 is more complicated than Gradio, and it takes some time to be fully proficient in using it. You can use Python to write complete interactive applications including front and back ends. It is suitable for developers who have relatively complex scenarios and want to build rich and diverse interactive pages.

Gradio official website link:https://gradio.app/
Streamlit official website link:https: //streamlit.io/

1. Installation & Basic Usage

Python third-party libraryGradioGet started quickly, current versionV3.27.0

  • Python version requires 3.7 and above
pip install gradio

#为了更快安装,可以使用清华镜像源
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gradio

After installation, start quickly on the IDE directly.

1.1 Quick Start

import gradio as gr
#输入文本处理程序
def greet(name):
    return "Hello " + name + "!"
#接口创建函数
#fn设置处理函数,inputs设置输入接口组件,outputs设置输出接口组件
#fn,inputs,outputs都是必填函数
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

After running the program, open http://localhost:7860 to see the web page effect. On the left is the text input box, and on the right is the result display box. The Clear button is used to reset the web page state, the Submit button is used to execute the handler, and the Flag button is used to save the results locally.

#执行结果
Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.

Just open your browser and use:

Insert image description here

When developing locally, if you want to run the code as a Python script, you can useGradio CLI to launch the application in reload mode, which will provide seamless and fast development .

gradio app.py

Note: You can also do python app.py, but it will not provide automatic reloading mechanism.

2.Basic parameters|Supported interfaces

2.1 Interface class and basic modules

Gradio can wrap almost any Python function into an easy-to-use user interface. From the above example we see a simple text-based function. But this function can also handle many types.

The Interface class is initialized with the following three parameters:

  • fn: wrapped function
  • inputs: Input component type, (for example: "text", "image")
  • ouputs: Output component type, (for example: "text", "image")

With these three parameters, we can quickly create an interface and publish them.

The most commonly used basic module composition.

  • Application interface: gr.Interface (simple scenario), gr.Blocks (customized scenario)

  • Input and output: gr.Image (image), gr.Textbox (text box), gr.DataFrame (data frame), gr.Dropdown (drop-down option), gr.Number (number), gr.Markdown, gr.Files

  • Control component: gr.Button (button)

  • Layout components: gr.Tab (tab page), gr.Row (row layout), gr.Column (column layout)

1.2.1 Custom input components

import gradio as gr
def greet(name):
    return "Hello " + name + "!"
demo = gr.Interface(
    fn=greet,
    # 自定义输入框
    # 具体设置方法查看官方文档
    inputs=gr.Textbox(lines=3, placeholder="Name Here...",label="my input"),
    outputs="text",
)
demo.launch()

Insert image description here

The Interface.launch() method returns three values

  • app, the FastAPI application powering the Gradio demo
    l- ocal_url, local address
  • share_url, public address, generated when share=True
import gradio as gr

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

iface = gr.Interface(
    fn=greet,
    inputs=gr.inputs.Textbox(lines=2, placeholder="Name Here..."),
    outputs="text",
)
if __name__ == "__main__":
    app, local_url, share_url = iface.launch()

1.2.2 Multiple inputs and outputs

For complex programs, each component in the input list corresponds in sequence to one parameter of the function. Each component in the output list corresponds, in order, to a value returned by the function.

import gradio as gr
#该函数有3个输入参数和2个输出参数
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,
    #按照处理程序设置输入组件
    inputs=["text", "checkbox", gr.Slider(0, 100)],
    #按照处理程序设置输出组件
    outputs=["text", "number"],
)
demo.launch()

Insert image description here

Each field in the inputs list corresponds to each parameter of the function in order, and the same applies to outputs.

1.2.3 Image component

Gradio supports many types of components, such as image, dataframe, and video. Usage examples are as follows:

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设置输入图像大小
demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
demo.launch()

Insert image description here

When using the Image component as input, the function will receive a numpy array with dimensions (w, h, 3), arranged in RGB channel order. Note that our input image component comes with an edit button that allows the image to be cropped and enlarged. Processing images in this way can help reveal biases or hidden flaws in machine learning models.

In addition, there is a shape parameter for the input component, which refers to setting the input image size. However, the processing method is to maintain the aspect ratio, scale the shortest side of the image to the specified length, and then crop the longest side to the specified length according to the center cropping method.

When the image is not large, a better way is not to set the shape and directly pass in the original image. The input component Image can also set the input type type. For example, type=filepath sets the path to pass in the processed image. For details, you can check the official documentation, which is very clear.

1.2.4 Dynamic interface interface: simple calculator template changes in real time

Add parameters in Interface. As long as the input changes, the result will change immediately. live=True

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

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

iface.launch()

Insert image description here

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:
            # 设置报错弹窗
            raise gr.Error("Cannot divide by zero!")
        return num1 / num2
demo = gr.Interface(
    calculator,
    # 设置输入
    [
        "number",
        gr.Radio(["add", "subtract", "multiply", "divide"]),
        "number"
    ],
    # 设置输出
    "number",
    # 设置输入参数示例
    examples=[
        [5, "add", 3],
        [4, "divide", 2],
        [-4, "multiply", 2.5],
        [0, "subtract", 1.2],
    ],
    # 设置网页标题
    title="Toy Calculator",
    # 左上角的描述文字
    description="Here's a sample toy calculator. Enjoy!",
    # 左下角的文字
    article = "Check out the examples",
)
demo.launch()

Insert image description here

2.2 Advanced use of interface

2.2.1 interface status

global variables

The advantage of global variables is that they can still be saved after calling the function. For example, in machine learning, a large model can be loaded from the outside through global variables and used inside the function so that the model does not need to be reloaded every time the function is called. The following shows the benefits of using global variables.

import gradio as gr
scores = []
def track_score(score):
    scores.append(score)
    #返回分数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()

Insert image description here

session state

Another type of data persistence supported by Gradio is session state, where data is persisted across multiple submissions within a page session. However, the data is not shared between different users of your model. A classic example of session state is a chatbot, where you want to access the information previously submitted by the user, but you can't store the chat history in a global variable because then the chat history will be jumbled up between different users. Note that this state persists across commits within each page, but if you load the demo in another tab (or refresh the page), the demo will not share the chat history.

To store data in session state, you need to do three things:

  • Pass in an extra parameter in your function, which represents the state of the interface.
  • At the end of the function, return the updated value of the state as an additional return value.
  • Add state components when adding inputs and outputs.
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
#设置一个对话窗
chatbot = gr.Chatbot().style(color_map=("green", "pink"))
demo = gr.Interface(
    chat,
    # 添加state组件
    ["text", "state"],
    [chatbot, "state"],
    # 设置没有保存数据的按钮
    allow_flagging="never",
)
demo.launch()

Insert image description here

2.2.2 interface interaction

real-time changes

Set live=True in the Interface, and the output will change in real time following the input. There will be no submit button on the interface at this time because there is no need to manually submit input.

Same as 1.2.4

streaming mode

In many cases, our input is a real-time video stream or audio stream, which means that the data is continuously sent to the backend, which can be processed in streaming mode.

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.3 Customized components: Building applications with Blocks

Compared with Interface, Blocks provides a low-level API for designing network applications with more flexible layout and data flow. Blocks allow you to control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update a component's property visibility based on user interaction. More components can be customized, and more detailed customization canview the documentation

2.3.1 Simple demonstration

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")
    #设置按钮
    greet_btn = gr.Button("Greet")
    #设置按钮点击事件
    greet_btn.click(fn=greet, inputs=name, outputs=output)
demo.launch()

Insert image description here

The Blocks method requires the with statement to add components. If the layout method is not set, the components will appear vertically in the application in the order of creation. The running interface

2.3.2 Multi-module application☆

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.")
    # 设置tab选项卡
    with gr.Tab("Flip Text"):
        #Blocks特有组件,设置所有子组件按垂直排列
        #垂直排列是默认情况,不加也没关系
        with gr.Column():
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        #Blocks特有组件,设置所有子组件按水平排列
        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()

Insert image description here

Insert image description here

2.3.3 Flagging mark

I believe some friends have noticed that there is a Flag button under the output box. When users testing your model see an input that causes output errors or unexpected model behavior, they can flag the input to let developers know.

This folder is specified by the parameter of Interface, and the default is . Save these error-causing inputs to afile. Ifcontains file data, a folder is also created to hold this tag data. flagging_dir’flagged’csvInterface

Openlog.csvDisplay as follows:

Insert image description here

2.3.4 Styles, queues, generators

style

In theGradio official documentation, search for different components and add.style(如image.style) to get the style parameter setting examples of the component. For example, the settings of theimage component are as follows:

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

If the function inference takes a long time, such as target detection; or the application processing traffic is too large, you need to use the queue method for queuing. queueUse websockets to prevent network timeout. Here's how to use it:

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

In some cases, you may want to display a sequence of output rather than a single output. For example, you might have an image generation model and you want to display the images generated at each step leading to the final image. In this case, you can provide Gradio with a generator function instead of a regular function. Below is an example of a generator that returns an image every 1 second.

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,
                    #设置滑窗,最小值为1,最大值为10,初始值为3,每次改动增减1位
                    inputs=gr.Slider(1, 10, value=3, step=1),
                    outputs="image")
#生成器必须要queue函数
demo.queue()
demo.launch()

2.4 Advanced use of Blocks

2.4.1 Blocks event

Interactive settings

The content of any input component is editable, while the output component is not editable by default. If you want to make the output component content editable, set 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()
Event settings

We can set different events for different components, such as adding change events for input components. You can further check the official documentation to see what other events the component has.

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()
    #设置change事件
    inp.change(fn = welcome, inputs = inp, outputs = out)
demo.launch()
Multiple data streams

If you want to handle multiple data streams, just set the corresponding input and output components.

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()

Insert image description here

Multiple output value processing

The following example shows how to output multiple values ​​in list form.

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,
        #根据返回值改变输入组件和输出组件
        outputs=[food_box, status_box]
    )
demo.launch()

The following example shows how to output multiple values ​​in dictionary form.

Component configuration modification

The return value of an event listener function is usually the updated value of the corresponding output component. Sometimes we also want to update a component's configuration, such as its visibility. In this case, we can update the component's configuration by returning the update function.

import gradio as gr
def change_textbox(choice):
    #根据不同输入对输出控件进行更新
    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()

Insert image description here

2.4.2 Blocks layout

Blocks applies the model layout in html, and the components are arranged vertically by default. flexbox

Components arranged horizontally

Using the Row function will arrange the components horizontally, but the components in the Row function block will maintain the same height.

import gradio as gr
with gr.Blocks() as demo:
    with gr.Row():
        img1 = gr.Image()
        text1 = gr.Text()
    btn1 = gr.Button("button")
demo.launch()
Vertical arrangement and nesting of components

components are usually arranged vertically, and we can generate different complex layouts through Row函数 and Column函数.

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设置最小宽度,防止列太窄
        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()
Component visualization: Output visualization from scratch

As shown below, we can build more complex applications through visible and update函数.

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()

Insert image description here

Component rendering: click as input

In some cases, you may want to define a component before actually rendering it in the UI.

For example, you might want to display an example section using above the corresponding gr.Textbox input. Sincerequires input component objects as parameters, you need to define the input component first and then render after defining. The solution is to and use the component's wherever you want it to be placed in the UI. gr.examplesgr.Examplesgr.Exmples对象在gr.Blocks()范围外定义gr.Textbox.render()方法

import gradio as gr
input_textbox = gr.Textbox()
with gr.Blocks() as demo:
    #提供示例输入给input_textbox,示例输入以嵌套列表形式设置
    gr.Examples(["hello", "bonjour", "merhaba"], input_textbox)
    # render函数渲染input_textbox
    input_textbox.render()
demo.launch()

Insert image description here

2.4.3 Style modification

Custom css

For additional styling capabilities, you can set inline CSS properties to apply any style to your application. As follows.

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()

Insert image description here

Element selection

You can add HTML elements to any component. Select the corresponding via elem_id. css元素

import gradio as gr
# 这里用的是id属性设置
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()

Insert image description here

3. Application sharing

3.1 Internet sharing

If the running environment can connect to the Internet, inlaunch函数中设置share参数为True, then after running the program. Gradio's server will provide XXXXX.gradio.app地址. The app can be accessed through other devices, such as mobile phones or laptops. This way the link is just a proxy for the local server and does not store any data sent through the local application. This link is free within the validity period. The advantage is that you do not need to build a server yourself. The disadvantage is that it is too slow. After all, the data passes through someone else's server.

demo.launch(share=True)

3.2 huggingface hosting

In order to permanently display our model App to partners, you can gradio的模型部署到 HuggingFace的 Space托管空间中 for free.

Methods as below:

  1. 注册huggingface账号https://huggingface.co/join

  2. Create project inspace空间:https://huggingface.co/spaces

  3. The created project has oneReadme文档. You can follow the instructions or manually edit the app.py and requirements.txt files.

3.3 LAN sharing

By settingserver_name=‘0.0.0.0’(表示使用本机ip),server_port(可不改,默认值是7860). Then you can share the application within the LAN through the local ip:port number.

#show_error为True表示在控制台显示错误信息。
demo.launch(server_name='0.0.0.0', server_port=8080, show_error=True)

The host address here can be queried on the computer by yourself. Just modify C:\Windows\System32\drivers\etc\hosts to 127.0.0.1 and then specify the port number.

3.4 Password verification

Before opening the webpage for the first time, you can set an account password. For example, the auth parameter is tuple data of (account, password). The queue function cannot be used in this mode.

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

If you want to set more complex account passwords and password prompts, you can set verification rules through functions.

#账户和密码相同就可以通过
def same_auth(username, password):
    return username == password
demo.launch(auth=same_auth,auth_message="username and password must be the same")

4. Case upgrade display

4.1 Text classification

#!pip install gradio, ultralytics, transformers, torchkeras
import gradio as gr 
from transformers import pipeline
 
pipe = pipeline("text-classification")
 
def clf(text):
    result = pipe(text)
    label = result[0]['label']
    score = result[0]['score']
    res = {
    
    label:score,'POSITIVE' if label=='NEGATIVE' else 'NEGATIVE': 1-score}
    return res 
 
demo = gr.Interface(fn=clf, inputs="text", outputs="label")
gr.close_all()
demo.launch(share=True)

4.2 Image classification

import gradio as gr 
import pandas as pd 
from ultralytics import YOLO
from skimage import data
from PIL import Image
 
model = YOLO('yolov8n-cls.pt')
def predict(img):
    result = model.predict(source=img)
    df = pd.Series(result[0].names).to_frame()
    df.columns = ['names']
    df['probs'] = result[0].probs
    df = df.sort_values('probs',ascending=False)
    res = dict(zip(df['names'],df['probs']))
    return res
gr.close_all() 
demo = gr.Interface(fn = predict,inputs = gr.Image(type='pil'), outputs = gr.Label(num_top_classes=5), 
                    examples = ['cat.jpeg','people.jpeg','coffee.jpeg'])
demo.launch()

4.3 Target detection

import gradio as gr 
import pandas as pd 
from skimage import data
from ultralytics.yolo.data import utils 
 
model = YOLO('yolov8n.pt')
 
#load class_names
yaml_path = str(Path(ultralytics.__file__).parent/'datasets/coco128.yaml') 
class_names = utils.yaml_load(yaml_path)['names']

def detect(img):
    if isinstance(img,str):
        img = get_url_img(img) if img.startswith('http') else Image.open(img).convert('RGB')
    result = model.predict(source=img)
    if len(result[0].boxes.boxes)>0:
        vis = plots.plot_detection(img,boxes=result[0].boxes.boxes,
                     class_names=class_names, min_score=0.2)
    else:
        vis = img
    return vis
    
with gr.Blocks() as demo:
    gr.Markdown("# yolov8目标检测演示")
 
    with gr.Tab("捕捉摄像头喔"):
        in_img = gr.Image(source='webcam',type='pil')
        button = gr.Button("执行检测",variant="primary")
 
        gr.Markdown("## 预测输出")
        out_img = gr.Image(type='pil')
 
        button.click(detect,
                     inputs=in_img, 
                     outputs=out_img)
        
    
gr.close_all() 
demo.queue(concurrency_count=5)
demo.launch()

4.4 Image filter

Although Gradio is designed to quickly create machine learning user interaction pages. But in fact, by combining various components of Gradio, users can easily implement various application gadgets that are very practical.

For example: data analysis display dashboard, data annotation tool, making a small game interface, etc.

In this example, we will use grario to build an image filter and select some of the cat emoticons we like from a bunch of cat emoticons crawled by Baidu.

#!pip install -U torchkeras
import torchkeras 
from torchkeras.data import download_baidu_pictures 
download_baidu_pictures('猫咪表情包',100)

import gradio as gr
from PIL import Image
import time,os
from pathlib import Path 
base_dir = '猫咪表情包'
selected_dir = 'selected'
files = [str(x) for x in 
         Path(base_dir).rglob('*.jp*g') 
         if 'checkpoint' not in str(x)]
def show_img(path):
    return Image.open(path)
def fn_before(done,todo):
    ...
    return done,todo,path,img
def fn_next(done,todo):
    ...
    return done,todo,path,img
def save_selected(img_path):
    ...
    return msg 
def get_default_msg():
    ...
    return msg
    
    
with gr.Blocks() as demo:
    with gr.Row():
        total = gr.Number(len(files),label='总数量')
        with gr.Row(scale = 1):
            bn_before = gr.Button("上一张")
            bn_next = gr.Button("下一张")
        with gr.Row(scale = 2):
            done = gr.Number(0,label='已完成')
            todo = gr.Number(len(files),label='待完成')
    path = gr.Text(files[0],lines=1, label='当前图片路径')
    feedback_button = gr.Button("选择图片",variant="primary")
    msg = gr.TextArea(value=get_default_msg,lines=3,max_lines = 5)
    img = gr.Image(value = show_img(files[0]),type='pil')
    
    bn_before.click(fn_before,
                 inputs= [done,todo], 
                 outputs=[done,todo,path,img])
    bn_next.click(fn_next,
                 inputs= [done,todo], 
                 outputs=[done,todo,path,img])
    feedback_button.click(save_selected,
                         inputs = path,
                         outputs = msg
                         )

demo.launch()

Reference link:
Gradio official warehouse

Deploy machine learning applications based on Gradio visualization

Gradio official documentation

Gradio makes your machine learning models sexy

Gradio builds a demonstration system

Gradio Getting Started Tutorial

Gradio: Easily implement visual deployment of AI algorithms

Guess you like

Origin blog.csdn.net/weixin_45277161/article/details/134998849