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

相关推荐
程序员敲代码吗23 分钟前
提升Python编程效率的五大特性
开发语言·python
List<String> error_P1 小时前
Python蓝桥杯常考知识点-模拟
开发语言·python·蓝桥杯
比奇堡鱼贩1 小时前
python第五次作业
开发语言·前端·python
码农小韩2 小时前
AIAgent应用开发——DeepSeek分析(二)
人工智能·python·深度学习·agent·强化学习·deepseek
喵手2 小时前
Python爬虫实战:构建一个高健壮性的图书数据采集器!
爬虫·python·爬虫实战·零基础python爬虫教学·构建图书数据·采集图书数据·图书数据采集
张3蜂3 小时前
Python venv 详解:为什么要用、怎么用、怎么用好
开发语言·python
老赵全栈实战4 小时前
《从零搭建RAG系统第3天:文档加载+文本向量化+向量存入Milvus》
python
火龙果研究院4 小时前
在CentOS上安装Python 3.13需要从源码编译
开发语言·python·centos
龙山云仓4 小时前
No156:AI中国故事-对话司马迁——史家绝唱与AI记忆:时间叙事与因果之链
大数据·开发语言·人工智能·python·机器学习
niuniudengdeng4 小时前
一种基于高维物理张量与XRF实景复刻的一步闭式解工业级3D打印品生成模型
人工智能·python·数学·算法·3d