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

相关推荐
追风少年ii13 分钟前
多组学扩展---分子对接pyrosetta
python·数据分析·空间·单细胞
2301_8213696131 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
m0_5613596735 分钟前
使用Kivy开发跨平台的移动应用
jvm·数据库·python
编程火箭车1 小时前
04.第一个 Python 程序:Hello World 从编写到运行全解析
python·python第一个程序·python入门报错解决·python新手教程·hello world 程序·python终端运行·pycharm运行代码
qq_423233901 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
疯狂踩坑人2 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
HDO清风2 小时前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
weixin_499771552 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
weixin_452159552 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
多米Domi0112 小时前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试