当前位置:   article > 正文

基于FastAPI构造一个AI模型部署应用_使用fastapi构建ai推理框架

使用fastapi构建ai推理框架
前言

fastapi是目前一个比较流行的python web框架,在大模型日益流行的今天,其云端部署和应用大多数都是基于fastapi框架。所以掌握和理解fastapi框架基本代码和用法尤显重要。

   需要注意的是,fastapi主要是通过app对象提供了web服务端的实现代码,对于一个完整应用来说,还需要uvicorn组件来启动web服务,如果想要可视化UI的话,可以考虑使用streamlit前端。

代码

   大家可以基于下面这个简单代码例子(参考GitHub - markthink/streamlit-fastapi-model,稍有修改)来加深理解。一共三个python源文件: segmentation.py(获取pytorch deeplabv3模型和推理该模型实现图像分割), ui.py(基于streamlit构造webUI供用户来选择图片并显示结果)和server.py(基于fastapi编写服务端函数来响应前端UI发来的/segmentation消息)。

segmentation.py:

  1. import io, torch
  2. from PIL import Image
  3. from torchvision import transforms
  4. def get_segmentator():
  5. model = torch.hub.load('pytorch/vision:v0.10.0', 'deeplabv3_mobilenet_v3_large', pretrained=True)
  6. model.eval()
  7. return model
  8. def get_segments(model, binary_image, max_size=512):
  9. input_image = Image.open(io.BytesIO(binary_image)).convert("RGB")
  10. width, height = input_image.size
  11. resize_factor = min(max_size/width,max_size/height)
  12. resize_image = input_image.resize((int(input_image.width * resize_factor),int(input_image.height*resize_factor)))
  13. preprocess = transforms.Compose(
  14. [
  15. transforms.ToTensor(),
  16. transforms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225])
  17. ]
  18. )
  19. input_tensor = preprocess(resize_image)
  20. input_batch = input_tensor.unsqueeze(0)
  21. with torch.no_grad():
  22. output = model(input_batch)['out'][0]
  23. output_predictions = output.argmax(0)
  24. # create a color pallette, selecting a color for each class
  25. palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
  26. colors = torch.as_tensor([i for i in range(21)])[:, None] * palette
  27. colors = (colors % 255).numpy().astype("uint8")
  28. r = Image.fromarray(output_predictions.byte().cpu().numpy()).resize(
  29. input_image.size
  30. )
  31. r.putpalette(colors)
  32. return r

ui.py:

  1. import io, requests
  2. import streamlit as st
  3. from PIL import Image
  4. from requests_toolbelt.multipart.encoder import MultipartEncoder
  5. #backend = "http://fastapi:8000/segmentation"
  6. backend = "http://0.0.0.0:8000/segmentation"
  7. def process(image, server_url:str):
  8. m = MultipartEncoder(fields={"file": ("filename", image, "image/jpeg")})
  9. r = requests.post(server_url, data=m, headers={"Content-Type":m.content_type}, timeout=8000)
  10. return r
  11. st.title("DeepLabV3 image segmentation")
  12. st.write("AI inference demo for fastapi calling pytorch model")
  13. input_image = st.file_uploader("pls input one image")
  14. if st.button("get image segmentation"):
  15. col1, col2 = st.columns(2)
  16. if input_image:
  17. segments = process(input_image, backend)
  18. original_image = Image.open(input_image).convert("RGB")
  19. segmented_image = Image.open(io.BytesIO(segments.content)).convert("RGB")
  20. col1.header("original version")
  21. col1.image(original_image, use_column_width=True)
  22. col2.header("segmentation version")
  23. col2.image(segmented_image, use_column_width=True)
  24. else:
  25. st.write("pls input one image")

server.py:

  1. import io
  2. from segmentation import get_segmentator, get_segments
  3. from starlette.responses import Response
  4. from fastapi import FastAPI, File
  5. model = get_segmentator()
  6. app = FastAPI(
  7. title="Deeplabv3 image segmentation",
  8. description="demo for deploying pytorch models with fastapi",
  9. version="0.1.0"
  10. )
  11. @app.post('/segmentation')
  12. def get_segmentation(file:bytes=File(...)):
  13. print("hello post")
  14. segmented_img = get_segments(model, file)
  15. bytes_io = io.BytesIO()
  16. segmented_img.save(bytes_io, format='PNG')
  17. return Response(bytes_io.getvalue(), media_type='image/png')

这三个文件放在一个目录下面,启动两个terminal窗口分别输入命令: 

uvicorn server:app --host 0.0.0.0 --port 8000
streamlit run ui.py

 

全部代码在CPU+ubuntu20.04上运行成功,无需GPU加速。

webui如下图所示

首先点击Browse file按钮,选择待分割图片,然后点击get image segmentation按钮就可以看到原始图片和分割结果。

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/787351
推荐阅读
相关标签
  

闽ICP备14008679号