本地部署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

相关推荐
johnsong4 小时前
AI前沿日报 2026-10-07:信任崩塌
人工智能
菩提树下的凡夫4 小时前
多线程是加载一个复用推理模型还是用多个独立的推理模型
人工智能·深度学习
冯一川4 小时前
使用 Python 实现支持多轮对话的 CLI 聊天机器人(基于 Ollama)
人工智能
武子康4 小时前
LingBot-Video 怎么选推理路径?8 步 DMD 不等于小显存
人工智能·后端
Febrie4 小时前
Codex插件推荐:Local Figma Agent MCP,不购买付费套餐,也能让 Agent 读懂并修改Figma设计稿
人工智能
edtoplort4 小时前
OpenAI紧急叫停GPT-6.1 Astra训练,奥尔特曼为何踩刹车
人工智能·gpt·算法
打工仔折腾 AI5 小时前
Docker镜像分层与卷挂载到底怎么工作:一次文件系统层面的实测分析
运维·人工智能·后端·python·docker·容器·性能优化
墨染天姬5 小时前
【人工智能训练师】python语法二
开发语言·人工智能·python
深蓝AI5 小时前
748GB 统一内存装进桌面:英伟达 DGX Station 本地跑万亿参数模型,瓶颈不在算力在插座
人工智能·agent
成旭先生6 小时前
AI 文本审核 API:一段中文文本判风险等级、命中标签与处置建议
java·前端·人工智能·api接口·内容风控·文本审核·ugc审核