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

相关推荐
yenggd9 小时前
华为批量下发配置命令使用telnetlib模块
网络·python·华为
不惑_9 小时前
通俗理解感知机(Perceptron)
人工智能·python
Everybody_up9 小时前
pycharm中编译环境配置
ide·python·pycharm
零小陈上(shouhou6668889)9 小时前
YOLOv8+PyQt5输电线路缺陷检测(目前最全面的类别检测,可以从图像、视频和摄像头三种路径检测)
python·qt·yolo
luoluoal9 小时前
基于python的爬虫的贵州菜价可视化系统(源码+文档)
python·mysql·django·毕业设计·源码
2501_9216494910 小时前
股票 API 对接,接入美国纳斯达克交易所(Nasdaq)实现缠论回测
开发语言·后端·python·websocket·金融
2401_8414956410 小时前
【LeetCode刷题】打家劫舍
数据结构·python·算法·leetcode·动态规划·数组·传统dp数组
李昊哲小课10 小时前
简化版天气爬虫教程
爬虫·python
38242782710 小时前
python:Ajax爬取电影详情实战
开发语言·python·ajax
天呐草莓10 小时前
集成学习 (ensemble learning)
人工智能·python·深度学习·算法·机器学习·数据挖掘·集成学习