解读FastAPI异步化为transformers模型打造高性能接口解析

bash 复制代码
from fastapi import FastAPI
from transformers import AutoModel, AutoTokenizer
import numpy as np
from starlette.responses import JSONResponse
 
 app = FastAPI()

加载模型和分词器

bash 复制代码
model = AutoModel.from_pretrained("distilbert-base-uncased")
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")

异步函数用于将输入文本转换为模型需要的格式

bash 复制代码
  async def prepare_input_for_model(text: str):
       inputs = tokenizer.encode(text, return_tensors='pt')
           return inputs

异步函数用于模型预测

bash 复制代码
 async def get_prediction(inputs):
        outputs = model(inputs)
        return outputs.logits

异步接口用于处理HTTP请求并返回预测结果

bash 复制代码
   @app.post("/predict")
   async def predict(text: str):
             inputs = await prepare_input_for_model(text)
             outputs = await get_prediction(inputs)
             predictions = np.argmax(outputs.numpy(), axis=-1)
             return JSONResponse(content={"prediction": predictions[0]})

这段代码展示了如何使用FastAPI框架的异步功能来提高性能。通过异步函数prepare_input_for_model和get_prediction,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
小呀小萝卜儿1 小时前
2025-11-15 学习记录--Python-LSTM模型定义(PyTorch)
python·学习·lstm
百锦再2 小时前
第15章 并发编程
android·java·开发语言·python·rust·django·go
laufing2 小时前
pyinstaller 介绍
python·构建打包
谅望者2 小时前
数据分析笔记09:Python条件语循环
笔记·python·数据分析
Auspemak-Derafru3 小时前
从U盘损坏中恢复视频文件并修复修改日期的完整解决方案
python
techzhi3 小时前
Intellij idea 注释模版
java·python·intellij-idea
李昊哲小课3 小时前
wsl ubuntu24.04 cuda13 cudnn9 pytorch 显卡加速
人工智能·pytorch·python·cuda·cudnn
温暖名字3 小时前
调用qwen3-omni的api对本地文件生成视频文本描述(批量生成)
python·音视频·qwen·qa问答
一眼万里*e4 小时前
搭建个人知识库
python
程序员小远5 小时前
软件测试之bug分析定位技巧
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·bug