当前位置:   article > 正文

【Gradio快速入门】构建交互式界面的简单而强大的Python库_import gradio as gr

import gradio as gr

嗨,你好哈,今天介绍一个可以快速搭建一套 UI 界面 Python 库,为快速搭建一个有界面的聊天机器人做准备。

Gradio 是什么

上一次分享中,我们创建了一个对话机器人,但是只能通过终端的方式进行交互。今天介绍一个 Python 库,可以快速搭建一套 UI 界面,不需要去学习 JavaScript、TypeScript 以及相关的前端技术了。并且,Gradio 渲染出来的界面可以直接在 Jupyter Notebook 里面显示出来,适合场景相对简单,想要快速部署应用的开发者快速体验产品效果。

如果你已经在 AI 领域深入多年,可以略过哈。

Hello World

安装 gradio 库

pip install gradio

图片

 

  1. import gradio as gr
  2. def greet(name):
  3.     return "Hello " + name + "!"
  4. demo = gr.Interface(fn=greet, inputs="text", outputs="text")
  5. demo.launch()   

图片

 

创建了两个文本框,输入一个 name,输出内容为:Hello xxx !如下图:

图片

 

从上面例子我们看到,简单的基于文本创建的 demo。但这个函数还可以处理很多类型。

Interface 类通过以下三个参数进行初始化:

  • fn:包装的函数

  • inputs:输入组件类型,(例如:“text”、"image)

  • ouputs:输出组件类型,(例如:“text”、"image)

组件介绍

最常用的基础模块由以下几部分构成:

  • 应用界面:gr.Interface(简易场景), gr.Blocks(定制化场景)

  • 输入输出:gr.Image(图像), gr.Textbox(文本框), gr.DataFrame(数据框), gr.Dropdown(下拉选项),,gr.Number(数字), gr.Markdown, gr.Files

  • 控制组件:gr.Button(按钮)

  • 布局组件:gr.Tab(标签页), gr.Row(行布局),,gr.Column(列布局)

Textbox 组件

输入框为多行,使用占位符提示用户输入,并且设置了输入框的标签名称。

  1. import gradio as gr
  2. def greet(name):
  3.     return "Hello " + name + "!"
  4. demo = gr.Interface(
  5.     fn=greet,
  6.     inputs=gr.Textbox(lines=2, placeholder="Name Here...", label="Input Your Name"),
  7.     outputs="text",
  8. )
  9. demo.launch()

图片

多个输入和输出

对于复杂程序,输入列表中的每个组件按顺序对应于函数的一个参数。输出列表中的每个组件按顺序排列对应于函数返回的一个值。

  1. import gradio as gr
  2. def greet(name, is_morning, temperature):
  3.     salutation = "Good morning" if is_morning else "Good evening"
  4.     greeting = f"{salutation} {name}. It is {temperature} degrees today"
  5.     celsius = (temperature - 32* 5 / 9
  6.     return greeting, round(celsius, 2)
  7. demo = gr.Interface(
  8.     fn=greet,
  9.     inputs=["text""checkbox", gr.Slider(0100)],
  10.     outputs=["text""number"],
  11. )
  12. demo.launch(debug=True)

图片

 

greet 函数有3个输入参数和2个输出参数,与 inputs 、 outputs 相对应。

图像组件

用图像生成图像的功能

  1. import numpy as np
  2. import gradio as gr
  3. def sepia(input_img):
  4.     sepia_filter = np.array([
  5.         [0.3930.7690.189], 
  6.         [0.3490.6860.168], 
  7.         [0.2720.5340.131]
  8.     ])
  9.     sepia_img = input_img.dot(sepia_filter.T)
  10.     sepia_img /= sepia_img.max()
  11.     return sepia_img
  12. demo = gr.Interface(sepia, gr.Image(shape=(200200)), "image")
  13. demo.launch()

图片

 

更多的灵活性和控制

Grdio 提供了两个类来构建应用程序:

  1. Interface,一个高级抽象的 API,我们到目前为止一直在用它在演示。

  2. Blocks,用于设计具有更灵活布局和数据流的 Web 应用程序的低级 API。Blocks 可以让我们做一些事情,比如提供多个数据流和演示,控制组件出现在页面的哪个位置,处理复杂的数据流(例如输出可以作为其他函数的输入) ,以及基于用户交互更新组件的属性/可见性ーー仍然全部使用 Python。

如果您需要这种可定制性,请尝试使用 Block!

相对复杂点的示例
  1. import numpy as np
  2. import gradio as gr
  3. def flip_text(x):
  4.     return x[::-1]
  5. def flip_image(x):
  6.     return np.fliplr(x)
  7. with gr.Blocks() as demo:
  8.     gr.Markdown("Flip text or image files using this demo.")
  9.     with gr.Tab("Flip Text"):
  10.         text_input = gr.Textbox()
  11.         text_output = gr.Textbox()
  12.         text_button = gr.Button("Flip")
  13.     with gr.Tab("Flip Image"):
  14.         with gr.Row():
  15.             image_input = gr.Image()
  16.             image_output = gr.Image()
  17.         image_button = gr.Button("Flip")
  18.     with gr.Accordion("Open for More!"):
  19.         gr.Markdown("Look at me...")
  20.     text_button.click(flip_text, inputs=text_input, outputs=text_output)
  21.     image_button.click(flip_image, inputs=image_input, outputs=image_output)
  22. demo.launch()

图片

 

  • Blocks 是用 with 子句创建的,在这个子句中创建的任何组件都会自动添加到应用程序中。

  • 组件按照创建的顺序垂直出现在应用程序中。

  • 创建了一个 Button,然后向该按钮添加了一个 click 事件监听器。这个 API 应该看起来很熟悉!与 Interface 类似,click 方法接受 Python 函数、输入组件和输出组件。

  • 任何输入的组件内容都是可编辑的,而输出组件默认是不能编辑的。如果想要使得输出组件内容可编辑,设置interactive=True 即可。

布局

Blocks 默认情况下组件垂直排列。

组件水平排列:使用 Row 函数会将组件按照水平排列,但是在Row函数块里面的组件都会保持同等高度。

  1. import gradio as gr
  2. with gr.Blocks() as demo:
  3.     with gr.Row():
  4.         img1 = gr.Image()
  5.         text1 = gr.Text()
  6.     btn1 = gr.Button("button")
  7. demo.launch()

图片

 

组件垂直排列与嵌套:组件通常是垂直排列,可以通过 Row 函数和 Column 函数生成不同复杂的布局。

  1. import gradio as gr
  2. with gr.Blocks() as demo:
  3.     with gr.Row():
  4.         text1 = gr.Textbox(label="Textbox1")
  5.         slider2 = gr.Textbox(label="Textbox2")
  6.         drop3 = gr.Dropdown(["选项一""选项二""选项三"], label="Dropdown")
  7.     with gr.Row():
  8.         # scale与相邻列相比的相对宽度。例如,如果列A的比例为2,列B的比例为1,则A的宽度将是B的两倍。
  9.         # min_width设置最小宽度,防止列太窄
  10.         with gr.Column(scale=2, min_width=600):
  11.             text1 = gr.Textbox(label="prompt 1")
  12.             text2 = gr.Textbox(label="prompt 2")
  13.             inbtw = gr.Button("Between")
  14.             text4 = gr.Textbox(label="prompt 4")
  15.             text5 = gr.Textbox(label="prompt 5")
  16.         with gr.Column(scale=1, min_width=600):
  17.             img1 = gr.Image()
  18.             btn = gr.Button("Go")
  19. demo.launch()

图片

 

修改样式

可以设置行内 css 属性将任何样式给应用程序

  1. import gradio as gr
  2. #修改blocks的背景颜色
  3. with gr.Blocks(css=".gradio-container {background-color: black}"as demo:
  4.     box1 = gr.Textbox(value="Good Job")
  5. demo.launch()

图片

 

可以向任何组件添加HTML元素。通过 elem_id 选择对应的 css 元素。

  1. import gradio as gr
  2. # 这里用的是id属性设置
  3. with gr.Blocks(css="#warning{background-color: yellow} #sucess{background-color: green} #failure{background-color: red}"as demo:
  4.     box1 = gr.Textbox(value="Good Job", elem_id="sucess")
  5.     box2 = gr.Textbox(value="Failure", elem_id="failure")
  6.     box3 = gr.Textbox(value="None", elem_id="warning")
  7. demo.launch()

图片

以上就是本次分享的内容,感谢大家支持。您的关注、点赞、收藏是我创作的动力。

万水千山总是情,点个 声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】

推荐阅读
相关标签