蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python AI 绘画:云端任务与本地工作流

分清云端文生图任务、本地模型运行和图片保存,实测请求、状态和文件的边界。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

选择云端 API 或本地模型

云端文生图把提示词和生成设置发给服务,服务可直接返回结果,也可先给任务 ID。本地 Stable Diffusion 需要安装前端、推理依赖与兼容权重,运行条件由所选版本、操作系统及 GPU 决定。

百炼提供 Qwen-Image 与万相系列。需要文字排版可从支持文本渲染的 Qwen-Image 型号查起,想做特定画风或写实任务时再看各型号能力。模型名、支持的尺寸和返回结构取决于选定版本。

用当前虚拟环境的 python -m pip 安装 dashscope 和 requests。真实调用前在百炼对应工作空间和区域申请 API Key,从服务端环境变量 DASHSCOPE_API_KEY 读取。计费按具体模型与用法确认,部分文生图按成功图片张数计费。先确认额度和规则,再发真实请求。

提交任务并安全保存图片

历史示例采用 ImageSynthesis.call 和 qwen-image。对采用任务接口的型号,SDK 可以提交任务并轮询。分别检查 HTTP 状态、任务状态及结果列表。HTTP 200 时任务仍可能失败。记录请求 ID 和错误码,给等待设上限。

提示词可写为 “雨后的书店门口,玻璃上有‘晚灯’两字”,使用成对的引号。n 控制请求图片数量,size 常用 宽*高,prompt_extend 控制提示词改写,watermark 请求添加水印。参数是否生效、可选范围及默认值以模型文档为准。

使用同步多模态接口时,可按对应指南发送带角色和文本内容的 messages,再从 output.choices 的消息内容中读取图片地址。任务式接口则常从 output.results 取 URL。结果链接可能短期有效,下载时检查 HTTP 状态和图片字节,再用自己指定的文件名保存。

按版本安装本地 WebUI 和权重

AUTOMATIC1111 文档的 Windows 自动安装示例以 Python 3.10.6 为基线。可从官方仓库克隆或下载官方发行包,按所选版本文档安装。Windows 常用 webui-user.bat 并以普通用户运行,Linux 常用 ./webui.sh。macOS 依照单独的安装说明与硬件要求操作。

Stable Diffusion v1.4 是历史模型。下载前核对模型卡、许可、发行版本与文件哈希。使用支持的模型文件类型,将检查过的 checkpoint 放进 models/Stable-diffusion。社区国风 3 是历史例子的第三方权重,使用前也要核实发布者、版本、基础模型和许可。

WebUI 启动后按控制台实际地址打开,本机常见端口为 7860。把界面留在回环地址。导入新权重后刷新模型列表,选择对应 checkpoint,填写提示词和宽高。尺寸减小可能降低显存消耗,也会改变画面细节。依赖下载卡住时先查启动日志和官方安装说明。

用本地实验核对两种返回格式

如果启动的 WebUI 支持 --api,txt2img 路径通常是 /sdapi/v1/txt2img。典型响应含 Base64 图片。可在本机 Swagger 页面确认当前实例的请求结构。模型文件的路径、参数传递和实际推理分别验证。

本站实验只访问本机测试服务。真实 DashScope SDK 发送任务与多模态请求,WebUI 分支核对本机 HTTP 载荷及 Base64 图片保存。测试返回程序生成的色块,供检查编码和下载,生成效果与硬件表现需要真实模型另行验证。

本机测试服务返回的 160 × 96 像素蓝色色块
本站本机 HTTP 实验保存的 PNG 色块,用于核对字节和实际尺寸。

解压实验 ZIP 后,在 Python 3.12 隔离环境安装 dashscope==2.0.4 和 requests==2.34.2,运行 python python-ai-draw.py。脚本使用固定测试密钥,核对任务失败、超时、无效图片和有效图片分别产生的结果。

下载本站 AI 绘画接口实验 ZIP

所需环境:Python 3.12;DashScope 和 Requests

ZIP SHA256:c1252a431e2e022ebba659e188e1d1c1745b7a46b8fd0b291f73880393724b98

图像工作流的请求和结果

字段或动作如何使用需要检查
model、prompt选择模型,提交文本描述当前端点是否支持模型及内容格式
n、size设置数量和尺寸模型限制、返回数量及实际像素
prompt_extend、watermark设置提示词改写与水印模型参数适用性及返回结果
task_id、task_status按任务 ID 查询状态成功、失败、取消或超时
图片 URL / Base64按接口返回结构读取并解码HTTP 状态、图片签名、文件名和尺寸
checkpoint、width、height选权重,设置输出宽高模型兼容性、显存、许可和版本

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com · 本机图像 API 工作流实验。"""
from argparse import ArgumentParser
import base64
from contextlib import contextmanager
from hashlib import sha256
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from importlib.metadata import version
import json
from pathlib import Path
import platform
import struct
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from urllib.parse import urlsplit
import zlib

parser = ArgumentParser()
parser.add_argument("--sdk-dir", type=Path)
arguments = parser.parse_args()
sys.path.insert(0, str(Path(__file__).resolve().parent))
if arguments.sdk_dir:
    sys.path.insert(0, str(arguments.sdk_dir.resolve()))

import dashscope
from dashscope import ImageSynthesis, MultiModalConversation
import requests

from mbsky_pychecks import Checks

TOKEN = "mbsky-local-fixture-key"
PROMPT = "雨后书店,玻璃上写着“晚灯”"
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"


def chunk(kind, data):
    return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))


def swatch(width, height):
    row = b"\0" + b"\x45\x91\xda"*width
    return (PNG_SIGNATURE + chunk(b"IHDR", struct.pack(">IIBBBBB", width,height,8,2,0,0,0))
            + chunk(b"IDAT", zlib.compress(row*height)) + chunk(b"IEND", b""))


IMAGE = swatch(160, 96)


def save_fixture_png(data, path):
    if len(data) < 33 or not data.startswith(PNG_SIGNATURE) or data[12:16] != b"IHDR":
        raise ValueError("expected PNG with IHDR")
    if zlib.crc32(data[12:29]) != struct.unpack_from(">I", data, 29)[0]:
        raise ValueError("PNG header checksum mismatch")
    width, height = struct.unpack_from(">II", data, 16)
    with path.open("xb") as output:
        output.write(data)
    return width, height


class Fixture(BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def reply(self, status, body, mime="application/json"):
        if mime == "application/json":
            body = json.dumps(body, ensure_ascii=False).encode()
        self.send_response(status)
        self.send_header("Content-Type", mime)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        path = urlsplit(self.path).path
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        self.server.posts.append((path, body, self.headers.get("Authorization"), self.headers.get("X-DashScope-Async")))
        if path == "/api/v1/services/aigc/text2image/image-synthesis":
            prompt = body["input"]["prompt"]
            if prompt == "reject before task":
                self.reply(401,dict(code="InvalidApiKey",message="fixture denied",request_id="request-reject"))
                return
            task = {"fixture fails":"failed","fixture never completes":"waiting"}.get(prompt,"done")
            self.reply(200,dict(request_id="request-submit",output=dict(task_id=task,task_status="PENDING")))
        elif path == "/api/v1/services/aigc/multimodal-generation/generation":
            picture = dict(image=self.server.base+"/artifact.png")
            message = dict(role="assistant",content=[picture])
            self.reply(200,dict(request_id="request-sync",output=dict(choices=[dict(message=message,finish_reason="stop")]),
                                usage=dict(image_count=1)))
        elif path == "/sdapi/v1/txt2img":
            self.reply(200,dict(images=[base64.b64encode(IMAGE).decode("ascii")],parameters=body,info="fixture"))
        else:
            self.reply(404,dict(code="NotFound"))

    def do_GET(self):
        path = urlsplit(self.path).path
        if path.startswith("/api/v1/tasks/"):
            task = path.rsplit("/",1)[-1]
            self.server.polls.append(task)
            status = {"failed":"FAILED","waiting":"RUNNING"}.get(task,"SUCCEEDED")
            if task=="done" and self.server.polls.count(task)==1:
                status = "RUNNING"
            output = dict(task_id=task,task_status=status)
            if status=="SUCCEEDED":
                output["results"]=[dict(url=self.server.base+"/artifact.png?fixture=1")]
            if status=="FAILED":
                output.update(code="FixtureError",message="controlled task failure")
            self.reply(200,dict(request_id="request-poll",output=output))
        elif path == "/artifact.png":
            self.reply(200, IMAGE, "image/png")
        elif path == "/not-image":
            self.reply(200,b"not a PNG","text/plain")
        else:
            self.reply(404,dict(code="NotFound"))


@contextmanager
def fixture_service():
    with ThreadingHTTPServer(("127.0.0.1",0), Fixture) as server:
        server.base = f"http://127.0.0.1:{server.server_port}"
        server.posts, server.polls = [], []
        worker = Thread(target=server.serve_forever,daemon=True)
        worker.start()
        previous = dashscope.base_http_api_url
        dashscope.base_http_api_url = server.base + "/api/v1"
        try:
            yield server
        finally:
            dashscope.base_http_api_url = previous
            server.shutdown()
            worker.join()


def fetch_fixture_png(session, base, url, path):
    expected, actual = urlsplit(base), urlsplit(url)
    if (actual.scheme, actual.netloc) != (expected.scheme, expected.netloc):
        raise ValueError("test URL is not this fixture origin")
    response = session.get(url,timeout=3,allow_redirects=False)
    if response.status_code != 200:
        response.raise_for_status()
        raise ValueError("unexpected redirect")
    return save_fixture_png(response.content, path)


def legacy(check, server, session, folder):
    opts = dict(model="qwen-image",api_key=TOKEN,n=1,size="1328*1328",prompt_extend=True,watermark=True)
    result = ImageSynthesis.call(prompt=PROMPT,wait_timeout=5,**opts)
    path, body, auth, asynchronous = server.posts[-1]
    params = body["parameters"]
    check.eq("legacy request and options",(path,body["model"],body["input"]["prompt"],
             params["n"],params["size"],params["prompt_extend"],params["watermark"],auth==f"Bearer {TOKEN}",asynchronous),
             ("/api/v1/services/aigc/text2image/image-synthesis","qwen-image",PROMPT,1,"1328*1328",True,True,True,"enable"))
    check.eq("legacy wait and terminal status",(server.polls,result.status_code==HTTPStatus.OK,
             result.request_id,result.output.task_status,len(result.output.results)),
             (["done","done"],True,"request-poll","SUCCEEDED",1))
    image_path = folder/"legacy-result.png"
    size = fetch_fixture_png(session, server.base, result.output.results[0].url, image_path)
    check.eq("downloaded PNG and dimensions",(image_path.read_bytes(),size),(IMAGE,(160,96)))

    denied = ImageSynthesis.async_call(prompt="reject before task",**opts)
    check.eq("submission HTTP error",(denied.status_code,denied.code,denied.request_id),(401,"InvalidApiKey","request-reject"))
    failed = ImageSynthesis.call(prompt="fixture fails",wait_timeout=5,**opts)
    check.eq("terminal failure under HTTP 200",(failed.status_code==HTTPStatus.OK,failed.output.task_status),(True,"FAILED"))
    waited = ImageSynthesis.call(prompt="fixture never completes",wait_timeout=1,**opts)
    check.eq("bounded poll timeout",(waited.status_code==HTTPStatus.REQUEST_TIMEOUT,waited.code),(True,"WaitTaskTimeout"))
    check.raises("foreign URL refused without request",ValueError,
                 lambda:fetch_fixture_png(session,server.base,"https://example.invalid/image.png",folder/"foreign.png"))
    check.raises("HTTP download error",requests.HTTPError,
                 lambda:fetch_fixture_png(session,server.base,server.base+"/missing.png",folder/"missing.png"))
    check.raises("invalid image does not write a file",ValueError,
                 lambda:fetch_fixture_png(session,server.base,server.base+"/not-image",folder/"bad.png"))
    check.raises("existing image is not overwritten",FileExistsError,
                 lambda:fetch_fixture_png(session,server.base,result.output.results[0].url,image_path))
    damaged = bytearray(IMAGE)
    damaged[29] ^= 1
    check.raises("PNG header checksum error",ValueError,lambda:save_fixture_png(damaged,folder/"damaged.png"))
    check.eq("invalid output paths not created",list(sorted(p.name for p in folder.iterdir())),["legacy-result.png"])


def modern(check, server, session, folder):
    messages = [dict(role="user",content=[dict(text=PROMPT)])]
    result = MultiModalConversation.call(model="qwen-image-2.0-pro",messages=messages,
                 api_key=TOKEN,size="1024*1024",n=1,prompt_extend=False,watermark=False)
    path, body, auth, _ = server.posts[-1]
    check.eq("multimodal message request",(path,body["model"],body["input"]["messages"],auth==f"Bearer {TOKEN}"),
             ("/api/v1/services/aigc/multimodal-generation/generation","qwen-image-2.0-pro",messages,True))
    url = result.output.choices[0].message.content[0]["image"]
    check.eq("multimodal result structure",(result.status_code==HTTPStatus.OK,urlsplit(url).path),
             (True,"/artifact.png"))
    image_path = folder/"multimodal-result.png"
    check.eq("multimodal output saved",fetch_fixture_png(session,server.base,url,image_path),(160,96))


def webui(check, server, session, folder):
    checkpoints = folder/"models"/"Stable-diffusion"
    checkpoints.mkdir(parents=True)
    fixture = checkpoints/"mbsky-test.safetensors"
    fixture.write_bytes(b"placeholder only; never load as weights")
    check.eq("model directory relative to WebUI root",fixture.relative_to(folder).as_posix(),
             "models/Stable-diffusion/mbsky-test.safetensors")
    check.eq("fixture checkpoint hash",sha256(fixture.read_bytes()).hexdigest(),"d072b11677e47be3af5b103bae3ad85023ec8100fdf2bef8aa71d1079ff13069")
    for width, height in [(512, 384),(256,192)]:
        body = dict(prompt=PROMPT,negative_prompt="模糊",width=width,height=height,seed=123,steps=12,
                    override_settings={"sd_model_checkpoint":fixture.name})
        result = session.post(server.base+"/sdapi/v1/txt2img",json=body,timeout=3)
        result.raise_for_status()
        path, sent, _, _ = server.posts[-1]
        check.eq(f"WebUI request {width}x{height}",(path,sent,result.json()["parameters"]),
                 ("/sdapi/v1/txt2img",body,body))
        decoded = base64.b64decode(result.json()["images"][0],validate=True)
        check.eq(f"WebUI fixture PNG {width}x{height}",(decoded,save_fixture_png(decoded,folder/f"webui-{width}.png")),
                 (IMAGE,(160,96)))


def main():
    check = Checks()
    with TemporaryDirectory(prefix="mbsky-ai-draw-") as directory, fixture_service() as server, requests.Session() as session:
        session.trust_env = False
        folder = Path(directory)
        legacy(check,server,session,folder)
        modern(check,server,session,folder)
        webui(check,server,session,folder)
    check.finish("python-ai-draw",python=platform.python_version(),platform=platform.platform(),
                 dashscope=version("dashscope"),requests=requests.__version__,
                 scope="Actual SDK and loopback HTTP; locally authored PNG, no model inference")


if __name__ == "__main__":
    main()

运行本章核心实例

所需环境:Actual SDK and loopback HTTP; locally authored PNG, no model inference

当前源码 SHA256:ef208fb63a14417ecc2f2e1fb62aa9445e6b503cc93b9d5a1066e12be25ba1f3

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据