gradio入门示例

    随着chat-gpt等机器人对话框架的流行,让一个名为gradio的框架也火热起来,这个框架可以开启一个http服务,并且带输入输出界面,可以让对话类的人工智能项目快速运行。

    gradio号称可以快速部署ai可视化项目。

    下面通过两个示例来感受一下,首先我们需要安装gradio库。

pip install gradio

    接着编写如下的代码,用户输入一个字符串xxx,提交之后,输出一个hello,xxx 。

import gradio as gr


def hello(name):
    return "hello," + name + "!"


def launch():
    demo = gr.Interface(fn=hello, inputs='text', outputs='text')
    demo.launch()


if __name__ == '__main__':
    launch()

    运行这段代码,可以开启7860端口监听http服务, 浏览器访问http://localhost:7860,可以打开如下界面:

     再编写一个示例,是关于图像识别的,代码如下:

import torch
from PIL import Image
from torchvision import transforms
import gradio as gr
import jso
### Gradio 示例案例与使用教程 #### 安装 Gradio 为了开始构建 Gradio 应用程序,首先需要安装 `gradio` 库。可以通过以下命令完成安装[^2]: ```bash pip install gradio ``` #### 创建简单的 “Hello World” 示例 以下是 Gradio 的基本入门示例,展示了如何创建一个简单的文本输入和输出界面: ```python import gradio as gr def greet(name): return f"Hello {name}!" with gr.Blocks() as demo: name_input = gr.Textbox(label="Enter your name") greeting_output = gr.Textbox(label="Greeting") submit_button = gr.Button("Submit") submit_button.click(greet, inputs=name_input, outputs=greeting_output) demo.launch() ``` 此代码定义了一个函数 `greet()`,该函数接收用户的姓名作为参数并返回问候语。通过 Gradio 的 `Blocks` API 构建了一个带有文本框和按钮的用户界面[^1]。 #### 更复杂的 NLP 模型集成示例 下面是一个更高级的例子,展示如何将预训练的语言模型(如 Hugging Face Transformers 中的 BERT)与 Gradio 结合起来,实现情感分析功能: ```python from transformers import pipeline import gradio as gr sentiment_pipeline = pipeline("sentiment-analysis") def analyze_sentiment(text): result = sentiment_pipeline(text)[0] return {"label": result["label"], "score": round(result["score"], 2)} with gr.Blocks() as demo: input_text = gr.Textbox(lines=5, label="Input Text") output_result = gr.JSON(label="Sentiment Analysis Result") input_text.submit(analyze_sentiment, inputs=input_text, outputs=output_result) demo.launch(share=True) ``` 在此示例中,我们利用了 Hugging Face 的 `pipeline` 工具加载了一个现成的情感分析器,并将其封装在一个 Gradio 接口中。最终生成的应用允许用户提交一段文字并查看其情绪分类及其置信度得分[^3]。 #### 图像识别示例 对于计算机视觉任务,比如图像分类,也可以借助 Gradio 来快速建立原型。这里提供了一种方式来预测上传图片中的对象类别: ```python import torch from torchvision import models, transforms from PIL import Image import gradio as gr device = 'cuda' if torch.cuda.is_available() else 'cpu' model = models.resnet18(pretrained=True).to(device) model.eval() preprocess = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), ]) labels_map = { 0: "Ant", 1: "Bee" } def predict_image(img_path): img = Image.open(img_path).convert('RGB') tensor = preprocess(img).unsqueeze(0).to(device) with torch.no_grad(): predictions = model(tensor) _, index = torch.max(predictions, 1) percentage = torch.nn.functional.softmax(predictions, dim=1)[0] * 100 return labels_map[index.item()], float(percentage[index].item()) with gr.Blocks() as demo: image_input = gr.Image(type='filepath', label="Upload an image of ant or bee.") prediction_output = gr.Label(num_top_classes=1, label="Prediction") image_input.change(predict_image, inputs=image_input, outputs=prediction_output) demo.launch(debug=True) ``` 上述脚本实现了 ResNet-18 对抗蚁类或蜜蜂照片进行二元分类的功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值