本地部署bert-base-chinese模型交互式问答,gradio

首先下载bert-base-chinese,可以在 Huggingface, modelscope, github下载

pip install gradio torch transformers

python 复制代码
import gradio as gr
import torch
from transformers import BertTokenizer, BertForQuestionAnswering

# 加载bert-base-chinese模型和分词器
model_name = "D:/dev/php/magook/trunk/server/learn-python/models/bert-base-chinese"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForQuestionAnswering.from_pretrained(model_name)


def question_answering(context, question):
    # 使用分词器对输入进行处理
    inputs = tokenizer(question, context, return_tensors="pt")
    # 调用模型进行问答
    outputs = model(**inputs)
    # 获取答案的起始和结束位置
    start_scores = outputs.start_logits
    end_scores = outputs.end_logits
    # 获取最佳答案
    answer_start = torch.argmax(start_scores)
    answer_end = torch.argmax(end_scores) + 1
    answer = tokenizer.decode(inputs["input_ids"][0][answer_start:answer_end])
    return answer


# 创建Gradio界面
interface = gr.Interface(
    fn=question_answering,
    inputs=["text", "text"],  # 输入分别为context和question
    outputs="text",  # 输出为答案
)

interface.launch()

运行

bash 复制代码
> python llm_and_transformer/bert/use_bert-base-chinese4.py
Some weights of BertForQuestionAnswering were not initialized from the model checkpoint at D:/dev/php/magook/trunk/server/learn-python/models/bert-base-chinese and are
newly initialized: ['qa_outputs.bias', 'qa_outputs.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
Running on local URL:  http://127.0.0.1:7860

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

访问 http://127.0.0.1:7860

相关推荐
未来和明天6 分钟前
领嵌4G/5GAI边缘计算盒子多路视频算力高达10.4Tops兼容Modbus、DLT645、OPC UA等多种行业协议
人工智能·5g·边缘计算
万联WANFLOW8 分钟前
Meta开源了能本地跑的agent
运维·服务器·网络·人工智能·业界资讯
Bruce_Liuxiaowei9 分钟前
安全意识培训——大模型在安全培训中的创新应用
人工智能·安全·ai·智能体
2601_9563198810 分钟前
2026年用示例、拆解和练习提升量化理解效率
人工智能·python
飞哥数智坊13 分钟前
WorkBuddy 帮我把吃灰的 ima 收藏,变成了每日知识速览
人工智能·agent
学习中.........17 分钟前
Karpathy nanoGPT 教程到底讲了什么
人工智能·算法·语言模型
ZYJCSZKJ22 分钟前
AI数字人直播系统的技术架构与多方言交互实现方案——基于广西区域商业场景的工程实践
人工智能·架构·交互
珐恩AI-人工智能29 分钟前
大模型意图召回偏差分析:GEO如何解决“有收录却不触发问答曝光”的难题
大数据·前端·人工智能·html·流量运营·geo优化
Java小白笔记35 分钟前
Windows系统免软件命令激活
java·网络·人工智能·windows·ai·ai编程
王志来1379447300835 分钟前
从分散到集成:工控服务器机箱采购如何实现“一站式”破局
运维·服务器·人工智能·python