解读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,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
东莞市云毅网络有限公司3 小时前
用 Node 做收录快照的周对比:差集、阈值与告警
python·sqlite·自动化运维·geo·数据监测
山楂树の4 小时前
Python Pandas 数据处理:数据读取、筛选、清洗、排序与分组
开发语言·python·pandas
Logintern094 小时前
langgraph 图编译的聊天机器人
python·langgraph
xurileidian5 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
钱栈up7 小时前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu7 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
Agent世界7 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维
用户298698530149 小时前
Python 自动化处理 Word:按规则查找并高亮关键文本
python·api·编程语言
人工智能技术咨询.10 小时前
什么才算高质量数据集
python
DanCheng-studio10 小时前
毕业设计项目 机器视觉指纹识别特征对比算法(源码+论文)
python·毕业设计·毕设