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

文本生成图片效果

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

模型地址

中文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测试

源码下载地址

相关推荐
想名字好难啊竟然不止我一个3 分钟前
清除 Pip 缓存, 释放磁盘空间
python·缓存·pip
Eiceblue8 分钟前
Python 快速提取扫描件 PDF 中的文本:OCR 实操教程
vscode·python·ocr·1024程序员节
拓端研究室9 分钟前
专题:2025中国汽车行业Data+AI数智化转型与全球化白皮书|附340+份报告PDF、数据仪表盘汇总下载
人工智能
APIshop11 分钟前
淘宝/天猫 API 接口深度解析:商品详情获取与按图搜索商品(拍立淘)实战指南
python·1024程序员节
九年义务漏网鲨鱼13 分钟前
BLIP2 工业实战(一):从零实现 LAVIS 跌倒检测 (微调与“踩坑”指南)
人工智能·pytorch·深度学习·语言模型
WangYan202214 分钟前
ArcGIS Pro与Python下空间数据采集与管理——涵盖矢量、栅格、GPS、点云、多维数据与遥感云平台等
python·arcgis pro·空间数据采集与管理
gddkxc22 分钟前
悟空AI CRM15版本 自定义字段功能
人工智能
浔川python社24 分钟前
浔川社团总访问量超 13 万:数据见证成长,热爱铸就辉煌
python
大千AI助手24 分钟前
Netflix Prize竞赛:推荐系统的里程碑与机器学习革命的催化剂
人工智能·机器学习·推荐系统·netflix·竞赛·电影推荐·冷启动
Lab4AI大模型实验室29 分钟前
【每日Arxiv热文】北大新框架 Edit-R1 炸场!破解图像编辑 3 大难题,双榜刷 SOTA
人工智能·计算机视觉