Python AI Painting
In this article we will show you how to build your own AI image generation tool based on some developer APIs or open-source libraries.
Via a text-to-image API
With a text-to-image API, you can create entirely new original images from text descriptions.
Alibaba Cloud Model Studio provides two major series of models:
- Tongyi Qianwen (Qwen-Image): good at rendering complex Chinese and English text; this chapter uses it as the example.
- Tongyi Wanxiang (Wan series): used to generate realistic images and photographic-quality visual effects.
Install the DashScope Python SDK by running the following command:
# 如果运行失败,您可以将pip替换成pip3再运行
pip install -U requests dashscope
We need to activate the Alibaba Cloud Model Studio service and obtain an API key.
We can first use the Alibaba Cloud main account to visit the Model Studio platform:https://bailian.console.aliyun.com/, then click Log in in the upper right corner. After logging in, click the gear ⚙️ icon in the upper right corner, select API key, and copy the API key. If you do not have one, you can create one:


Activating Alibaba Cloud Model Studio is free of charge; only model calls (after exceeding the free quota), model deployment and model tuning are billed.
Using the API is now billed by token, and fortunately it is not expensive; we can start by buying the cheapest package:Alibaba Cloud Model Studio large model platform。
Next we generate an image by setting a prompt:
Example
from
http
import
HTTPStatus
from
urllib
.
parse
import
urlparse
,
unquote
from
pathlib
import
PurePosixPath
import
requests
from
dashscope
import
ImageSynthesis
import
os
prompt
=
"An elegant and dignified couplet hangs in the hall; the room has a quiet, classical Chinese layout with some blue-and-white porcelain on the table. The left scroll of the couplet reads 'Yi Ben Sheng Zhi Ren Ji Tong Dao Shan Si Xin' and the right reads 'Tong Yun Fu Zhi Qian Kun Qi Shu Gao Zhi Yuan', with the horizontal scroll 'Zhi Qi Tong Yi' (all romanized Chinese). The calligraphy is graceful, and in the middle hangs a Chinese-style painting of the Yueyang Tower."
Please use the Model Studio API Key
api_key
=
"sk-xxx"
(
'----synchronous call, please wait for the task to finish----'
)
rsp
=
ImageSynthesis.
call
(
api_key
=
api_key
,
model
=
"qwen-image"
,
prompt
=
prompt
,
n
=
1
,
size
=
'1328*1328'
,
prompt_extend
=
True
,
watermark
=
True
)
(
'response: %s'
% rsp
)
if
rsp.
status_code
==
HTTPStatus.
OK
:
Save the image in the current directory
for
result
in
rsp.
output
.
results
:
file_name
=
PurePosixPath
(
unquote
(
urlparse
(
result.
url
)
.
path
)
)
.
parts
[
1
]
with
open
(
'./%s'
% file_name
,
'wb+'
)
as
f:
f.
write
(
requests.
get
(
result.
url
)
.
content
)
else
:
(
'Synchronous call failed, status_code: %s, code: %s, message: %s'
%
(
rsp.
status_code
,
rsp.
code
,
rsp.
message
)
)
The output is similar to the following; you will see a url parameter, and visiting it lets you download the image described by the prompt:
----Synchronous call, please wait for the task to execute----
response: {"status_code": 200, "request_id": "1968746e-f434-4f77-9f8c-9b1adb80e8d7", "code": null, "message": "", "output": {"task_id": "d85c65d9-c4ff-4d66-a895-7c7746620b0c", "task_status": "SUCCEEDED", "results": [{"url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/7d/05/20250916/8d68e658/d85c65d9-c4ff-4d66-a895-7c7746620b0c-1.png?xxxxxxxxx",
...
The image generated by the above example is as follows:

For more information, refer to the official documentation:https://help.aliyun.com/zh/model-studio/text-to-image
Stable Diffusion
The open-source library to use is Stable Diffusion web UI, a browser interface for Stable Diffusion built on the Gradio library
Stable Diffusion web UI GitHub address:https://github.com/AUTOMATIC1111/stable-diffusion-webui
Running Stable Diffusion requires fairly high-end hardware and consumes considerable resources during operation, especially the graphics card.
Installation on Windows
The local environment requires Python 3.10.6 or later, added to the machine's environment variables.
Download the Stable Diffusion web UI source code from GitHub https://github.com/AUTOMATIC1111/stable-diffusion-webui。
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git
If Git is not installed, you can download the zip archive from the upper right corner.

Extract stable-diffusion-webui and enter the stable-diffusion-webui directory.
Next we need to download a model; download address:https://huggingface.co/CompVis/stable-diffusion-v-1-4-original

Move the downloaded model into the stable-diffusion-webui/models/Stable-diffusion directory.
Enter the stable-diffusion-webui directory:
Running on Windows as a non-administrator:
webui-user.bat
On Linux and macOS, run the following command:
./webui.sh
The program will then install and start automatically; when it starts successfully you will see an accessible URL, http://127.0.0.1:7860:

Visit http://127.0.0.1:7860; the interface is as follows:

Note: If the installation hangs, it is most likely a problem downloading the GitHub source. You can use some GitHub mirrors; there is no very stable mirror at present, so searching on Google is recommended. On April 6, 2023 I used the mirror address https://hub.fgit.ml; open the launch.py file in the stable-diffusion-webui directory and replace the GitHub addresses in the following portion of code (around lines 230-240):
Introduction to Civitai
Civitai has many customized models that can be downloaded for free. We use theGuofeng 3model for testing; download address:https://civitai.com/models/10415/3-guofeng3?modelVersionId=36644

After downloading, move the model into the stable-diffusion-webui/models/Stable-diffusion directory and restart stable-diffusion-webui:
./webui.sh
Now we can select theGuofeng 3model in the model list:

After selecting it, we can copy some prompts and test parameters from the model's introduction page:



To generate quickly, I halved both the height and the width, then clicked the Generate button:

For the full generation process, follow our WeChat Channels account:


