当前位置:   article > 正文

【ModelScope】部署一个属于自己的AI服务

modelscope

前言

技术栈是Fastapi。

FastAPI 是一个现代、快速(基于 Starlette 和 Pydantic)、易于使用的 Python web 框架,主要用于构建 RESTful API。以下是 FastAPI 的一些优势:

  1. 性能卓越: FastAPI 基于 Starlette 框架,并使用 Pydantic 进行数据验证,因此具有出色的性能。它通过异步编程利用 Python 3.7+ 中的 async/await 特性,使其能够处理大量并发请求。

  2. 自动文档生成: FastAPI 自动生成交互式 API 文档(Swagger UI 和 ReDoc),让开发者能够轻松地查看和测试 API 端点,同时提供即时的反馈和文档。

  3. 强类型注解: FastAPI 使用 Python 的类型提示来定义 API,同时利用 Pydantic 模型进行请求和响应的验证,这提供了强大的静态类型检查和自动文档的支持。

  4. 自动验证: 使用 Pydantic 模型,FastAPI 自动验证请求的数据,并在数据不符合预期时返回错误。这有助于提高代码的稳健性和可维护性。

  5. 异步支持: 支持异步处理请求,可以使用异步函数来处理请求,使得 FastAPI 在处理高并发时表现出色。

  6. 便捷的依赖注入系统: FastAPI 提供了一个灵活的依赖注入系统,让你能够方便地注入和管理依赖项,使代码更加清晰和可测试。

  7. WebSocket 支持: FastAPI 提供了对 WebSocket 的原生支持,能够轻松地实现实时通信。

  8. 易于学习: FastAPI 的语法和设计理念使其易于学习和使用,特别是对于熟悉 Python 的开发者。

 

安装modelscope

  1. conda create -n modelscope python=3.8
  2. conda activate modelscope
  3. pip install modelscope

激活虚拟环境

conda activate modelscope

 

server.py代码

  1. import argparse
  2. import uvicorn
  3. from fastapi import FastAPI
  4. from modelscope.server.api.routers.router import api_router
  5. from modelscope.server.core.event_handlers import (start_app_handler,
  6. stop_app_handler)
  7. def get_app(args) -> FastAPI:
  8. app = FastAPI(
  9. title='modelscope_server',
  10. version='0.1',
  11. debug=True,
  12. swagger_ui_parameters={'tryItOutEnabled': True})
  13. app.state.args = args
  14. app.include_router(api_router)
  15. app.add_event_handler('startup', start_app_handler(app))
  16. app.add_event_handler('shutdown', stop_app_handler(app))
  17. return app
  18. def add_server_args(parser):
  19. parser.add_argument(
  20. '--model_id', required=True, type=str, help='The target model id')
  21. parser.add_argument(
  22. '--revision', required=True, type=str, help='Model revision')
  23. parser.add_argument('--host', default='0.0.0.0', help='Host to listen')
  24. parser.add_argument('--port', type=int, default=8000, help='Server port')
  25. parser.add_argument('--debug', default='debug', help='Set debug level.')
  26. parser.add_argument(
  27. '--llm_first',
  28. type=bool,
  29. default=True,
  30. help='Use LLMPipeline first for llm models.')
  31. if __name__ == '__main__':
  32. parser = argparse.ArgumentParser('modelscope_server')
  33. add_server_args(parser)
  34. args = parser.parse_args()
  35. app = get_app(args)
  36. uvicorn.run(app, host=args.host, port=args.port)

 任务一:人脸检测

命令行中虚拟环境中运行脚本

python server.py --model_id damo/cv_resnet50_face-detection_retinaface --revision v2.0.2

 

访问http://127.0.0.1:8000/docs打开文档

 

  • describe方法描述请求参数和输出形式 
  1. {
  2. "schema": {
  3. "task_name": "face-detection",
  4. "schema": {
  5. "input": {
  6. "type": "object",
  7. "properties": {
  8. "image": {
  9. "type": "string",
  10. "description": "Base64 encoded image file or url string."
  11. }
  12. }
  13. },
  14. "parameters": {},
  15. "output": {
  16. "type": "object",
  17. "properties": {
  18. "scores": {
  19. "type": "array",
  20. "items": {
  21. "type": "number"
  22. }
  23. },
  24. "boxes": {
  25. "type": "array",
  26. "items": {
  27. "type": "number"
  28. }
  29. },
  30. "keypoints": {
  31. "type": "array",
  32. "items": {
  33. "type": "number"
  34. }
  35. }
  36. }
  37. }
  38. }
  39. },
  40. "sample": null
  41. }
  • call方法(是模型推理的入口)

    • 两种请求方式(post)

    • curl方式(encode_base64表示图片转换为base64后的形式)

  • 图片转换base64的链接可以使用在线转https://tool.jisuapi.com/pic2base64.html

    curl -X 'POST' \ 'http://127.0.0.1:8000/call' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "input":{"image":"encode_base64"}'
  • face-detection_retinaface请求参数体(界面请求)直接使用fastapi界面请求或者使用apifox等

  • {"input":{"image":"encode_base64"}}

    请求结果

 返回结果解释

  1. {
  2. "scores": [
  3. 0.9998026490211487
  4. ],
  5. "boxes": [
  6. [
  7. 164.9207000732422,
  8. 82.86209106445312,
  9. 353.395263671875,
  10. 340.145263671875
  11. ]
  12. ],
  13. "keypoints": [
  14. [
  15. 214.5664520263672,
  16. 188.255859375,
  17. 303.5237121582031,
  18. 190.91671752929688,
  19. 256.9284362792969,
  20. 242.95065307617188,
  21. 223.42758178710938,
  22. 283.54241943359375,
  23. 287.28448486328125,
  24. 286.402587890625
  25. ]
  26. ]
  27. }

返回图像中人脸的分数,越大表示有人脸的可能性越大,boxes表示人脸的矩形框,左上角x,y坐标和右下角x,y坐标,keypoints返回左眼、右眼、鼻尖、左嘴角、右嘴角的坐标值x,y。 

输入图片

 根据boxes和keypoints画图

 

  1. import cv2
  2. # 读取图像
  3. image = cv2.imread('0.png')
  4. # 定义矩形框的坐标和大小
  5. x, y, x1, y1 = 164,82,353,340
  6. w = 353-164
  7. h = 340-82
  8. # 画矩形框
  9. cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
  10. # 显示结果
  11. # cv2.imshow('Rectangle', image)
  12. # cv2.waitKey(0)
  13. # cv2.destroyAllWindows()
  14. cv2.imwrite('0_rectangle.png', image)

 

  1. import cv2
  2. # 读取图像
  3. image = cv2.imread('0.png')
  4. radius = 5 # 点的半径
  5. color = (0, 0, 255) # 点的颜色,通常使用BGR格式
  6. thickness = -1 # 为了画一个实心圆,线条宽度设置为-1
  7. keypoints = [214.5664520263672,
  8. 188.255859375,
  9. 303.5237121582031,
  10. 190.91671752929688,
  11. 256.9284362792969,
  12. 242.95065307617188,
  13. 223.42758178710938,
  14. 283.54241943359375,
  15. 287.28448486328125,
  16. 286.402587890625]
  17. print(len(keypoints))
  18. for i in range(0,len(keypoints),2):
  19. cv2.circle(image, (int(keypoints[i]),int(keypoints[i+1])), radius, color, thickness)
  20. # 显示结果
  21. # cv2.imshow('Point', image)
  22. # cv2.waitKey(0)
  23. # cv2.destroyAllWindows()
  24. cv2.imwrite('0_keypoints.png', image)

 

 需要注意的是不同的任务请求体的内容不一样,需要明确每个任务的请求参数具体有哪些。

 任务二:人脸融合

 第二种任务,人脸融合,需要重启服务,将model_id和revision替换。

 

python server.py --model_id damo/cv_unet-image-face-fusion_damo --revision v1.3

此时访问http://127.0.0.1/docs 

执行一下describe方法 

 

  1. {
  2. "schema": {
  3. "task_name": "image-face-fusion",
  4. "schema": {
  5. "input": {
  6. "type": "object",
  7. "properties": {
  8. "template": {
  9. "type": "string",
  10. "description": "Base64 encoded image file or url string."
  11. },
  12. "user": {
  13. "type": "string",
  14. "description": "Base64 encoded image file or url string."
  15. }
  16. }
  17. },
  18. "parameters": {
  19. "type": "object",
  20. "properties": {
  21. "user": {
  22. "type": "object",
  23. "default": null
  24. }
  25. }
  26. },
  27. "output": {
  28. "type": "object",
  29. "properties": {
  30. "output_img": {
  31. "type": "string",
  32. "description": "The base64 encoded image."
  33. }
  34. }
  35. }
  36. }
  37. },
  38. "sample": null
  39. }

input有两个参数,第一个是template,表示模版;第二个参数是user,表示用户的图片,最终的目的就是将用户的图片的脸替换到模版上

parameters参数一般使用默认的就行,不填,如果有特殊需求可自行尝试

output会返回一个换好脸图像的base64编码

请求体

  1. {
  2. "input": {
  3. "template": "base64_template",
  4. "user":"bas64_user"
  5. }
  6. }

 template

 User

 

 Ourput

参考链接:

https://github.com/modelscope/modelscope/blob/master/modelscope/server/api_server.py 

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

闽ICP备14008679号