gradio 合集

发布于:2025-02-10 ⋅ 阅读:(68) ⋅ 点赞:(0)

知识点 1:基本 Chatbot 创建

import gradio as gr

定义历史记录

history = [gr.ChatMessage(role=“assistant”, content=“How can I help you?”),
gr.ChatMessage(role=“user”, content=“What is the weather today?”)]

使用历史记录创建 Chatbot 组件

chatbot = gr.Chatbot(history=history)

启动演示应用

if name == “main”:
gr.Interface(chatbot, []).launch()
知识点 2:自定义消息格式

import gradio as gr

自定义消息格式

custom_history = [{“role”: “user”, “content”: “Greet me!”},
{“role”: “assistant”, “content”: “Hello! How may I assist you?”}]

创建 Chatbot 并设置自定义历史记录

chatbot_custom = gr.Chatbot(history=custom_history)

启动演示应用

if name == “main”:
gr.Interface(chatbot_custom, []).launch()
知识点 3:使用 Markdown 渲染文本

import gradio as gr

包含 Markdown 文本的示例消息

markdown_message = [“## Welcome to Gradio!”,
“- Use the Chatbot to interact with your models.”,
“- You can add images, videos, and more.”]

创建 Chatbot 并传入 Markdown 消息

chatbot_md = gr.Chatbot(history=markdown_message)

启动演示应用

if name == “main”:
gr.Interface(chatbot_md, []).launch()
知识点 4:多媒体文件处理

import gradio as gr

假设有一个图片路径

image_path = “path/to/image.jpg”

创建 Chatbot 并上传图片作为消息

chatbot_media = gr.Chatbot(history=[{“role”: “user”, “content”: f"Uploaded Image"}])

启动演示应用

if name == “main”:
gr.Interface(chatbot_media, []).launch()
知识点 5:事件监听器

import gradio as gr

用户喜欢消息的事件监听器

def like_listener(event_data):
print(f"User {event_data[‘index’]} liked message {event_data[‘value’]}")

创建 Chatbot 并附加事件监听器

chatbot_likes = gr.Chatbot(like=like_listener)

启动演示应用

if name == “main”:
gr.Interface(chatbot_likes, []).launch()
请确保您已经安装了 Gradio 库才能运行上面的代码示例。可以使用 pip 安装:

pip install gradio
这些代码示例展示了如何在 Gradio 中创建基础的 Chatbot 应用程序,处理不同的消息格式,以及在 Chatbot 上设置事件监听器。


网站公告

今日签到

点亮在社区的每一天
去签到