详细内容见:开源AIGC学习—文生图模型本地运行
当前算法模型采用Python + Flask 方式进行Rest API方式进行服务封装,对应封装代码说明如下:
from gevent import pywsgi
from flask import Flask
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
import torch
import cv2
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
task = Tasks.text_to_image_synthesis
model_id = '/mnt/d/aigc_model/modelscope/damo/multi-modal_chinese_stable_diffusion_v1'
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app)
task = Tasks.text_to_image_synthesis
model_id = '/mnt/d/aigc_model/modelscope/damo/multi-modal_chinese_stable_diffusion_v1'
pipe = pipeline(task=task, model=model_id)
parser = reqparse.RequestParser()
parser.add_argument('prompts', type=str, help='Inputs for text to image', location='form')
class TextToImag(Resource):
def post(self):
args = parser.parse_args()
text = args['prompts']
output = pipe({'text': text})
result = cv2.imwrite('/mnt/d/aigc_result/result.png', output['output_imgs'][0])
return {'response': result}
api.add_resource(TextToImag, '/api/text2imag')
if __name__ == '__main__':
server = pywsgi.WSGIServer(('0.0.0.0', 2000), app)
server.serve_forever()
也可以直接返回图片,但是文生图模型推理耗时比较长,选择异步方案比较好,然后图片生成后在消息知会用户。
# -- utf-8 ---
from gevent import pywsgi
from flask import Flask, send_file
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
import torch
import cv2
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
task = Tasks.text_to_image_synthesis
model_id = '/mnt/d/aigc_model/modelscope/damo/multi-modal_chinese_stable_diffusion_v1'
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
api = Api(app)
task = Tasks.text_to_image_synthesis
model_id = '/mnt/d/aigc_model/modelscope/damo/multi-modal_chinese_stable_diffusion_v1'
pipe = pipeline(task=task, model=model_id)
parser = reqparse.RequestParser()
parser.add_argument('prompts', type=str, help='Inputs for text to image', location='form')
class TextToImag(Resource):
def post(self):
args = parser.parse_args()
text = args['prompts']
output = pipe({'text': text})
output_path = '/mnt/d/aigc_result/result.png'
cv2.imwrite(output_path, output['output_imgs'][0])
return send_file(output_path, mimetype='image/jpeg')
api.add_resource(TextToImag, '/api/text2imag')
if __name__ == '__main__':
server = pywsgi.WSGIServer(('0.0.0.0', 2000), app)
server.serve_forever()
返回效果展示
因为多数AIGC服务背后是任务方式运行,按照工作流方式处理架构。算法模型需要上传到对于文件,结果生成需要下载文件,系统设计考虑异步调用方案。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。