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

相关推荐
j .3 分钟前
Java 集合的核心概念笔记
开发语言·python
宸津-代码粉碎机20 分钟前
Spring 6.0+Boot 3.0实战避坑全指南:5大类高频问题与解决方案(附代码示例)
java·数据仓库·hive·hadoop·python·技术文档编写
傻啦嘿哟20 分钟前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
数据库·python·分类
weixin_4624462325 分钟前
基于 Flask + lunar-python 的农历转换 API 实战(公历 ↔ 农历 / 干支 / 生肖 / 节日)
python·flask·节日
weixin_5795996638 分钟前
编写一个程序,输入两个数字的加减乘除余数(Python版)
开发语言·python
liu****41 分钟前
02_Pandas_数据结构
数据结构·python·pandas·python基础
RFCEO1 小时前
用手机写 Python程序解决方案
开发语言·python·智能手机·qpython环境安装
0思必得01 小时前
[Web自动化] Requests模块基本使用
运维·前端·python·自动化·html·web自动化
AAA简单玩转程序设计1 小时前
救命!Python 这些基础操作居然能省一半工作量
python
Brduino脑机接口技术答疑1 小时前
TDCA 算法在 SSVEP 场景中:Padding 的应用对象与工程实践指南
人工智能·python·算法·数据分析·脑机接口·eeg