核心内容包括:
熟悉AI产品开发的基本流程
学会选择技术路线、给 AI 分配任务并拆解复杂任务
从产品功能角度进行简单优化
通过这些学习,我们建立了对AI项目从无到有的全面理解,并掌握了如何将复杂的项目分解为更易管理的任务,以实现有效的开发和迭代。
接下来,在本节课里,我们将把焦点转向一个具体的AI工具——Gradio。
Step1:先看一遍视频教程,对本节课程内容有一个整体的了解
Step2:然后根据下方图文版教程和demo示例动手实践,学以致用
本节课偏向实战,会提供以下用于辅助的在线 ipynb 文档:
01-Gradio 的简单使用.ipynb
02-Gradio 的 Interface.ipynb
https://modelscope.cn/notebook/share/ipynb/7d460a55/02-Gradio%20%E7%9A%84%20Interface.ipynb
03-使用 ChatInterface 生成对话界面.ipynb
04-自定义界面与复杂布局.ipynb
05-Gradio 的组件与运行机制.ipynb
06-自定义组件与三方组件.ipynb
Gradio简介
Gradio (https://www.gradio.app/) 是一个用于快速创建和部署机器学习模型界面的 Python 库,允许用户通过 Python 代码来构建交互式的 Web 界面。
安装 Gradio
开始之前,请确保你的环境中已安装了 Gradio。可以通过 pip 来安装:
pip install gradio如果你正在 ModelScope 的 Notebook 中,还需要在 Python 中运行下面这段代码来适配 Notebook 中的路由转发问题:
# 如果你正在 ModelScope 的 Notebook 中,还需要运行下面这段代码:import osos.environ['GRADIO_ROOT_PATH'] = f"/{os.environ['JUPYTER_NAME']}/proxy/7860"
1、创建第一个 Gradio 应用
让我们从一个非常简单的例子开始:一个接收文本输入并返回该文本倒序输出的应用。
步骤 1: 定义函数
首先,定义一个 Python 函数,这个函数将会是 Gradio 界面的核心逻辑。
def reverse_text(text):return text[::-1]
步骤 2: 使用 Gradio 构建接口
接下来,利用 Gradio 的组件来构建用户界面。这里我们需要一个文本输入框和一个用于显示结果的文本输出区域。
import gradio as grdemo = gr.Interface(fn=reverse_text, inputs="text", outputs="text")
上面的代码中:
fn 参数指定了处理输入输出数据的函数。
inputs 指定输入类型,在这里是文本。
outputs 设置了期望的输出格式,同样为文本。
步骤 3: 启动服务
最后一步是启动 Gradio 提供的服务,我们可以通过浏览器访问到我们刚才创建的界面。
demo.launch()执行上述代码后,你可以在控制台看到一条在 7860 端口打开的 URL,打开指定的 URL 即可查看效果。
完整代码
import gradio as grdef reverse_text(text):return text[::-1]demo = gr.Interface(fn=reverse_text, inputs="text", outputs="text")demo.launch()
2、Gradio 的 Interface
Gradio 的 Interface是 Gradio 中高度封装的一种布局方式,比较适合面向小白用户,允许用户通过几行代码就可以生成 WebUI。
Interface 的核心是在上一节中提到的三个参数:
fn:指定了处理输入数据的函数,并将结果进行输出。
inputs:指定输入类型。
outputs:设置了期望的输出格式。
除了核心的参数之外,其余参数大多和整体的界面布局有关。
更新 Gradio 界面
我们更新上一节的 Gradio 界面,假设我们想要构建一个应用,该应用不仅能够反转文本,还能计算给定字符串的长度。
import gradio as gr# 这是修改后的函数def reverse_and_count(text):reversed_text = text[::-1]length = len(text)return reversed_text, lengthdemo = gr.Interface(fn=reverse_and_count,inputs="text",# flagging_mode="never",outputs=["text", "number"], # 第一个输出是文本,第二个输出是一个数字title="文本处理工具", # 设置页面标题description="输入一段文字,查看其倒序形式及字符数。", # 添加简短说明examples=[["你好,世界"], ["Hello World"]])demo.launch()
这里 outputs 参数被设置为列表,允许同时显示两个不同类型的输出结果。
更改组件初始值
Interface的输入输出除了可以接收字符串外,还可以接收由 Gradio 导出的任意其他组件实例,我们可以为这些实例添加初始值和配置项,来实现更定制化的需求:
import gradio as gr# 下面的示例中,我们可以通过输入文字,将其输出到 output 侧,并最终通过 Slider 选择的值为后面添加不同个数的 !def greet(name, intensity):return "Hello, " + name + "!" * intensitydemo = gr.Interface(fn=greet,inputs=["text", gr.Slider(value=2, minimum=1, maximum=10, step=1)],outputs=[gr.Text(label="greeting", lines=3)],)demo.launch()
其他组件示例
绘制函数
使用 Number 组件输入函数的参数范围和点数,使用 Plot 组件绘制正弦波图。
import gradio as grimport numpy as npimport matplotlib.pyplot as pltdef plot_function(x_min, x_max, n_points):x = np.linspace(x_min, x_max, n_points)y = np.sin(x)plt.figure()plt.plot(x, y)plt.title("Sine Wave")plt.xlabel("x")plt.ylabel("sin(x)")return pltdemo = gr.Interface(fn=plot_function,inputs=[gr.Number(label="X Min"),gr.Number(label="X Max"),gr.Number(label="Number of Points")],outputs=[gr.Plot()],title="Function Plotter",description="Plot a sine wave function based on the given parameters.")demo.launch()
图像处理
使用 Image 组件输入图像,并将其转换为铅笔素描。
import gradio as grimport numpy as npimport cv2def image_to_sketch(image):gray_image = image.convert('L')inverted_image = 255 - np.array(gray_image)blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)inverted_blurred = 255 - blurredpencil_sketch = cv2.divide(np.array(gray_image), inverted_blurred, scale=256.0)return pencil_sketchdemo = gr.Interface(fn=image_to_sketch,inputs=[gr.Image(label="Input Image", type="pil")],outputs=[gr.Image(label="Pencil Sketch")],title="Image to Pencil Sketch",description="Convert an input image to a pencil sketch.")demo.launch()
音频处理
使用 Audio 组件输入音频文件,并生成频谱图。
import gradio as grimport matplotlib.pyplot as pltdef audio_to_spectrogram(audio):sr, data = audioplt.figure(figsize=(10, 5))plt.specgram(data, Fs=sr)plt.title("Spectrogram")plt.xlabel("Time")plt.ylabel("Frequency")return pltdemo = gr.Interface(fn=audio_to_spectrogram,inputs=[gr.Audio(label="Input Audio")],outputs=[gr.Plot()],title="Audio to Spectrogram",description="Convert an input audio file to a spectrogram.")demo.launch()
视频处理
使用 Video 组件输入视频,并提取第一帧。
import gradio as grimport cv2def video_to_frame(video):cap = cv2.VideoCapture(video)ret, frame = cap.read()if ret:return frameelse:return Nonedemo = gr.Interface(fn=video_to_frame,inputs=[gr.Video(label="Input Video")],outputs=[gr.Image(label="First Frame")],title="Video to First Frame",description="Extract the first frame from an input video.")demo.launch()
3、使用 ChatInterface 生成对话界面
Gradio 的 ChatInterface 同样是 Gradio 中高度封装的一种布局方式,但主要用于创建聊天机器人的 UI 界面。
与 Interface 不同,ChatInterface 只有一个核心参数:
fn:根据用户输入和聊天历史记录来控制聊天机器人的响应值
import gradio as grdef echo(message, history):# message 为用户当次输入,return 的返回结果为当次的 bot 输出return messagedemo = gr.ChatInterface(fn=echo, type="messages", examples=["hello", "hola", "merhaba"], title="Echo Bot")demo.launch()
流式返回值
import timeimport gradio as grdef slow_echo(message, history):for i in range(len(message)):time.sleep(0.1) # 模拟间隔yield "You typed: " + message[: i + 1]demo = gr.ChatInterface(slow_echo, type="messages")demo.launch()
4、自定义界面与复杂布局
Gradio 除了提供Interface与ChatInterface等高级封装方式来快速实现界面布局外,还支持我们自定义地控制页面布局。
Blocks是 Gradio 的低阶 API,使用它我们可以像搭建积木一样装饰页面,并对一些函数的触发时机与数据流的输入输出提供更强大的灵活性。Interface与ChatInterface本质上也是基于它来二次封装的。
更改布局方式
现在让我们更新一下前面的使用Interface创建的反转文本应用。
import gradio as gr# 这是修改后的函数def reverse_and_count(text):reversed_text = text[::-1]length = len(text)return reversed_text, lengthwith gr.Blocks() as demo:gr.Markdown("<h1><center>文本处理工具<center/></h1>")gr.Markdown("输入一段文字,查看其倒序形式及字符数。")with gr.Row(): # 水平排列with gr.Column():input_text = gr.Textbox(label="请输入一些文字")with gr.Column():output_reversed = gr.Textbox(label="倒序结果")btn = gr.Button("提交")output_length = gr.Number(label="字符总数")gr.Examples([["你好,世界"], ["Hello World"]], inputs=[input_text])# 组件支持的事件,这里代表着页面上的按钮被点击时会触发 reverse_and_count 这个函数btn.click(fn=reverse_and_count,inputs=[input_text],outputs=[output_reversed, output_length])demo.launch()
现在,我们将之前Interface构建的界面拆成了几个不同的模块,然后再用不同的方式将其拼接了起来。基于Blocks的方式,我们可以构建出更多定制化的应用,ModelScope 创空间中的大部分应用都是基于此种方式构建而成的。
结合 ChatInterface 构建 Code Artifacts
下面为 Gradio 的官方示例,Blocks作为 Gradio 最基础的界面构建方式,还支持与其它的方式混用。
import gradio as grpython_code = """def fib(n):if n <= 0:return 0elif n == 1:return 1else:return fib(n-1) + fib(n-2)"""js_code = """function fib(n) {if (n <= 0) return 0;if (n === 1) return 1;return fib(n - 1) + fib(n - 2);}"""def chat(message, history):if "python" in message.lower():return "Type Python or JavaScript to see the code.", gr.Code(language="python", value=python_code)elif "javascript" in message.lower():return "Type Python or JavaScript to see the code.", gr.Code(language="javascript", value=js_code)else:return "Please ask about Python or JavaScript.", Nonewith gr.Blocks() as demo:code = gr.Code(render=False)with gr.Row():with gr.Column():gr.Markdown("<center><h1>Write Python or JavaScript</h1></center>")gr.ChatInterface(chat,examples=["Python", "JavaScript"],additional_outputs=[code],type="messages")with gr.Column():gr.Markdown("<center><h1>Code Artifacts</h1></center>")code.render()demo.launch()
5、Gradio 的组件与运行机制
Gradio 的组件是 Gradio 中的基本单元,它不仅可以映射到前端作为页面显示元素,还可以在 Python 端绑定事件,运行用户的实际推理函数。
Gradio 整体的运行机制如下:
通常在一个应用中,我们会遇到下面几种概念:
Components:组件本身,此概念下它只是作为构成界面的基本元素,如文本框、按钮等。
Events:用户与界面交互时触发的事件,如点击按钮、输入文本等行为。
Functions:用户输入并生成输出的函数。
本质上,Gradio 是一个基于事件监听机制的应用框架,它通常由前端发送事件信号,然后在 Python 端由对应绑定了事件的组件进行接收,传递给用户的输入输出函数,最后又由 Gradio 将用户的返回结果传递给前端界面。
前端:用户在界面上进行操作(例如输入文本或点击按钮)时,这些操作会由前端组件发送到后端。
Python 端:Python 端接收到用户的请求后,会调用相应的函数来处理输入数据,并将结果返回给前端。
更新界面:前端接收到后端返回的结果后,会更新相应的组件(如文本框的内容)。
6、自定义组件与三方组件
之前小节中提到的一些组件示例和很多没讲到的 Gradio 组件都可以在官方文档中找到。
除此之外,Gradio 支持自定义组件,自定义组件底层与 Gradio 原始组件的实现机制一致,在使用时一般不会有其他特殊限制(除了某些自定义组件本身有特殊要求),你可以查看这里来获取更多如何制作自定义组件的信息。
三方组件
Gradio 原始组件之外的组件都是三方组件,它们通常用于支持一些 Gradio 原始组件无法实现的功能,你可以在这里查看目前所有已反馈给官方的三方组件。
modelscope-studio
modelscope-studio是一个基于 Gradio 的三方组件库,它可以为开发者提供更定制化的界面搭建能力和更丰富的组件使用形式。
在原有 Gradio 组件之上,modelscope-studio提供了多种基础组件来辅助开发者优化界面布局,如div、span、text等前端的基本元素,并且还集成了Ant Design等著名的前端组件库来帮助开发者快速构建更加美观的界面。
pip install modelscope_studioimport gradio as grimport modelscope_studio.components.antd as antdimport modelscope_studio.components.base as mswith gr.Blocks() as demo:with ms.Application():with antd.ConfigProvider(locale="zh_CN"):with ms.AutoLoading():with antd.Flex(vertical=True, gap="small"):antd.Alert(type="info",message="Welcome",closable=True,description="Welcome to modelscope-studio")with antd.Card(title="ModelScope"):with ms.Slot("title"):antd.Typography.Text("ModelScope",strong=True,copyable=True)with ms.Slot("extra"):with antd.Button(href="https://github.com/modelscope/modelscope-studio",href_target="_blank"):ms.Text("GitHub")with ms.Slot("icon"):antd.Icon("GithubOutlined")antd.Tag("modelscope", color="purple")antd.Tag("ms-swift", color="magenta")antd.Tag("modelscope-studio", color="geekblue")demo.launch()
附加项、使用 AI 辅助编码
由于 AI 的普及,现在 Gradio 界面同样也可以使用 AI 进行辅助编码实现,你可以基于通义千问等代码工具来帮助你生成合适的应用雏形,并在此基础上进行完善。
Step3:反馈学习需求
预设课程大纲如下
✔️课程一:全栈产品经理启发课:AI加持后,从想法到落地,就是这么简单!
✔️课程二:Gradio组件学习:应用UI界面可无限DIY(本次内容)
✔️课程三:AI模型部署与推理:应用功能可无限拓展
✔️课程四:前后端联调及应用发布:打通前后端的任督二脉,就是完整的AI应用!
✔️课程五:案例学习:通过AI应用案例来实践,用微调的思路先做出你自己的第一个AI应用!
无论是对课程内容的疑问、对教学方式的建议,还是对未来课程主题的期待,都请不吝赐教。你可以通过公众号留言或是直接加入我们学习群的方式,分享你的想法。
课程学习群:
我们会从公众号留言中选取有用的建议来赠送魔搭周边小礼品哦!
?点击关注ModelScope公众号获取
更多技术信息~
