【通义实验室】开源【文本生成图片】大模型

文本生成图片效果

文本为一首古诗:孤帆远影碧空尽,唯见长江天际流。 不同风格生成的图片

模型地址

中文StableDiffusion-通用领域

初始化pipeline

python 复制代码
task = Tasks.text_to_image_synthesis
model_id = 'damo/multi-modal_chinese_stable_diffusion_v1.0'
pipe = pipeline(task=task, model=model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)

生成图片

python 复制代码
# 反向提示词
negative_prompt = (
        "blood, gore, violence, murder, kill, dead, corpse, "
        "horrible, frightening, scary, monster, ghost, skeleton, zombie, "
        "sex, nudity, pornography, adult, erotic, mature, "
        "drugs, alcohol, smoking, tobacco, illegal, "
        "dark, night, storm, thunder, lightning, apocalypse, disaster, "
        "gun, knife, sword, bomb, explosion, firearm, "
        "mean, angry, sadistic, hostile, aggressive, bullying, "
        "dangerous, unsafe, hazardous, poison, toxic, pollution"
    )
output = pipe(
        {
            'text': '孤帆远影碧空尽,唯见长江天际流。中国画',
            'num_inference_steps': 120,
            'guidance_scale': 11,
            'negative_prompt': negative_prompt
        }
    )
cv2.imwrite('result1.png', output['output_imgs'][0])
# 输出为opencv numpy格式,转为PIL.Image
img = output['output_imgs'][0]
img = Image.fromarray(img[:,:,::-1])
img.save('result1.png')

封装为http接口的完整代码

python 复制代码
from flask import Flask, request, send_file
import io
import torch
import cv2
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from PIL import Image

app = Flask(__name__)

# 初始化pipeline
task = Tasks.text_to_image_synthesis
model_id = 'damo/multi-modal_chinese_stable_diffusion_v1.0'
pipe = pipeline(task=task, model=model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)

@app.route('/generate', methods=['POST'])
def generate_image():
    data = request.json
    text = data.get('text', '')
    guidance_scale = data.get('guidance_scale', 9)

    if not text:
        return {'error': 'No text provided'}, 400

    negative_prompt = (
        "blood, gore, violence, murder, kill, dead, corpse, "
        "horrible, frightening, scary, monster, ghost, skeleton, zombie, "
        "sex, nudity, pornography, adult, erotic, mature, "
        "drugs, alcohol, smoking, tobacco, illegal, "
        "dark, night, storm, thunder, lightning, apocalypse, disaster, "
        "gun, knife, sword, bomb, explosion, firearm, "
        "mean, angry, sadistic, hostile, aggressive, bullying, "
        "dangerous, unsafe, hazardous, poison, toxic, pollution"
    )

    output = pipe(
        {
            'text': text,
            'num_inference_steps': 120,
            'guidance_scale': guidance_scale,
            'negative_prompt': negative_prompt
        }
    )

    img = output['output_imgs'][0]
    img = Image.fromarray(img[:, :, ::-1])  # Convert BGR to RGB

    # Save image to bytes
    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format='PNG')
    img_byte_arr.seek(0)

    return send_file(img_byte_arr, mimetype='image/png')


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=5000)

在python环境下运行代码

第一次运行会下载大模型文件,需要等待一段时间 启动成功会有如下提示

csharp 复制代码
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://10.10.10.132:5000

使用postman测试

源码下载地址

相关推荐
源码之家4 分钟前
计算机毕业设计:Python城市天气数据挖掘与预测系统 Flask框架 随机森林 K-Means 可视化 数据分析 大数据 机器学习 深度学习(建议收藏)✅
人工智能·爬虫·python·深度学习·机器学习·数据挖掘·课程设计
Dxy12393102166 分钟前
Python在图片上画多边形:从简单轮廓到复杂区域标注
开发语言·python
数智化管理手记6 分钟前
零基础认知精益生产——核心本质与必避误区
大数据·数据库·人工智能·低代码·制造
weixin_381288188 分钟前
MongoDB备节点无法读取数据怎么解决_rs.slaveOk()与Secondary读取权限
jvm·数据库·python
南尘NCA86668 分钟前
如何解决企业微信防封行业高封号率痛点
python·企业微信
dyxal9 分钟前
内网 Windows 离线安装 uv:极速 Python 包管理器的部署实战
windows·python·uv
qq_6543669811 分钟前
Vue 3 中集成 Three.js 场景的完整实践指南
jvm·数据库·python
人邮异步社区13 分钟前
文科生零基础学 Python 难吗?真不难,难的是找对书!
开发语言·python
用户51914958484513 分钟前
Kubernetes kubeadm 集群部署与 CKA 实战指南
人工智能·aigc
qq_4240985616 分钟前
JavaScript中箭头函数在类方法定义中的this绑定优势
jvm·数据库·python