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

相关推荐
Tianwen_Burning2 分钟前
pycharm下配置halcon
python
汉堡go4 分钟前
python_chapter6
前端·数据库·python
摘星编程11 分钟前
React Native鸿蒙:Geolocation持续定位更新
python
小二·29 分钟前
Python Web 开发进阶实战:数字孪生平台 —— 在 Flask + Vue 中构建实时物理世界镜像
前端·vue.js·python
2501_9421584333 分钟前
服务设计从成本到利润引擎的重构
大数据·python·重构
23124_8037 分钟前
热身签到-ctfshow
开发语言·python
小白学大数据1 小时前
移动端Temu App数据抓包与商品爬取方案
开发语言·爬虫·python
2501_944526421 小时前
Flutter for OpenHarmony 万能游戏库App实战 - 知识问答游戏实现
android·开发语言·javascript·python·flutter·游戏·harmonyos
人工智能AI技术1 小时前
【Agent从入门到实践】21 Prompt工程基础:为Agent设计“思考指令”,简单有效即可
人工智能·python
2501_941322031 小时前
铆钉表面缺陷检测:YOLO13-BiFPN模型实现与性能优化_1
python