# Python文生图API应用 **Repository Path**: KcanyueL/Python-stable-diffusion-api ## Basic Information - **Project Name**: Python文生图API应用 - **Description**: 基于stable-diffusion-webui的Liunx平台搭建与Python简单API使用 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-05-22 - **Last Updated**: 2023-06-03 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Python文生图应用 ### 介绍 基于stable-diffusion-webui的搭建与使用 Stable diffusion是一个基于Latent Diffusion Models(潜在扩散模型,LDMs)的文图生成(text-to-image)模型。具体来说,得益于Stability AI的计算资源支持和LAION的数据资源支持,Stable Diffusion在LAION-5B的一个子集上训练了一个Latent Diffusion Models,该模型专门用于文图生成 简单来说就是支持你输入文字描述,生成一张图片给你,本文主讲Liunx的上的使用: ### 安装: 首先打开 Stable diffusion WebUI项目地址:https://github.com/AUTOMATIC1111/stable-diffusion-webui 一个基于Gradio库的Web封装了Stable diffusion 然后你需要一台Liunx计算机, 当然配置要求较高:**16GB运行内存与具有至少6GB以上的Nvidia显卡**. 这里测试环境为:(**Ubantu**) ![输入图片说明](.idea/md/image.png) 服务器上得先安装git,才能拉取git上的项目包: ``` sudo apt install -y git ``` 新建一个目录作为主目录cd进去并执行拉取项目:(当然需要服务器配置科学上网) ``` git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git ``` 然后这个是一个基于**python的项目**所以还得有python环境且版本不低于**3.10.6**, 这里使用Anconda进行创建并激活 ``` conda create -n py python=3.10.6 //创建环境 conda activate py //激活环境 ``` 由于Stable Diffusion需要用到**torch**核心模块,然而pytorch对显卡的**cuda版本**有限制要求,程序默认安装pytorch2.0版本,我们需要根据显卡的**cuda版本**进行修改: 首先通过以下指令查询**cuda版本**是多少 ``` nvidia-smi ``` ![输入图片说明](.idea/image1.png) 查询到版本**10.2**,所以我们就需要去寻找对应可使用的最新版本https://download.pytorch.org/whl/torch_stable.html ![输入图片说明](.idea/image2.png) 开启程序的时候会默认开始安装依赖,所以我们需要修改**launch.py**启动文件,让它安装我们需要的版本 打开**launch.py**文件来到这个部分 ![输入图片说明](.idea/image3.png) 安装对应版本torch ``` torch_command = os.environ.get('TORCH_COMMAND', "pip install torch==1.12.1 torchvision==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu102") ``` 还有配置git加速镜像,因为有的仓库即使你科学上网都速度慢的很 ``` git+https://ghdl.feizhuqwq.cf/https://github.com/mlfoundations/open_clip.git@bb6e834e9c70d9c27d0dc3ecedeebeaeb1ffad6b //加https://ghdl.feizhuqwq.cf/前缀 ``` 完整需要配置的项 ``` torch_command = os.environ.get('TORCH_COMMAND', "pip install torch==1.12.1 torchvision==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu102") requirements_file = os.environ.get('REQS_FILE', "requirements_versions.txt") xformers_package = os.environ.get('XFORMERS_PACKAGE', 'xformers==0.0.17') gfpgan_package = os.environ.get('GFPGAN_PACKAGE', "git+https://ghdl.feizhuqwq.cf/https://github.com/TencentARC/GFPGAN.git@8d2447a2d918f8eba5a4a01463fd48e45126a379") clip_package = os.environ.get('CLIP_PACKAGE', "git+https://ghdl.feizhuqwq.cf/https://github.com/openai/CLIP.git@d50d76daa670286dd6cacf3bcd80b5e4823fc8e1") openclip_package = os.environ.get('OPENCLIP_PACKAGE', "git+https://ghdl.feizhuqwq.cf/https://github.com/mlfoundations/open_clip.git@bb6e834e9c70d9c27d0dc3ecedeebeaeb1ffad6b") stable_diffusion_repo = os.environ.get('STABLE_DIFFUSION_REPO', "https://ghdl.feizhuqwq.cf/https://github.com/Stability-AI/stablediffusion.git") taming_transformers_repo = os.environ.get('TAMING_TRANSFORMERS_REPO', "https://ghdl.feizhuqwq.cf/https://github.com/CompVis/taming-transformers.git") k_diffusion_repo = os.environ.get('K_DIFFUSION_REPO', 'https://ghdl.feizhuqwq.cf/https://github.com/crowsonkb/k-diffusion.git') codeformer_repo = os.environ.get('CODEFORMER_REPO', 'https://ghdl.feizhuqwq.cf/https://github.com/sczhou/CodeFormer.git') blip_repo = os.environ.get('BLIP_REPO', 'https://ghdl.feizhuqwq.cf/https://github.com/salesforce/BLIP.git') stable_diffusion_commit_hash = os.environ.get('STABLE_DIFFUSION_COMMIT_HASH', "cf1d67a6fd5ea1aa600c4df58e5b47da45f6bdbf") taming_transformers_commit_hash = os.environ.get('TAMING_TRANSFORMERS_COMMIT_HASH', "24268930bf1dce879235a7fddd0b2355b84d7ea6") k_diffusion_commit_hash = os.environ.get('K_DIFFUSION_COMMIT_HASH', "5b3af030dd83e0297272d861c19477735d0317ec") codeformer_commit_hash = os.environ.get('CODEFORMER_COMMIT_HASH', "c5b4593074ba6214284d6acd5f1719b6c5d739af") blip_commit_hash = os.environ.get('BLIP_COMMIT_HASH', "48211a1594f1321b00f14c9f7a5b4813144b2fb9") ``` 再打开**webui.py**配置 ![输入图片说明](.idea/imagea.png) 配置这两个,否则还是会下载高版本,从而导致运行不了 ``` expected_torch_version = "1.12.1" expected_xformers_version = "0.0.17" ``` 运行中可能会出现卡 ``` Installing gfpgan Installing open_clip ``` 这是因为镜像问题导致速度慢,可以选择在github上直接寻找仓库并下载 ![输入图片说明](.idea/imageb.png) 解压并进行python build install安装,但是要注意,程序在运行的时候会创建**venv**虚拟环境,所以**python解释器**目录要选对 我们的路径是**/home/xxx/xx/StableDiffusion/stable-diffusion-webui/venv/bin/python**, 所以编译的时候应该是先cd进去目录,然后执行: ``` "/home/xxx/xx/StableDiffusion/stable-diffusion-webui/venv/bin/python" xxx build install ``` 这样就不会出现卡死的情况 接下来我们需要下载模型文件 可以在以下网站免费下载 ``` https://aituzhan.com/ http://www.liandange.com/models ``` ![输入图片说明](.idea/imagec.png) 下载完毕之后保存到这个位置 /xxx/xxx/xx/StableDiffusion/stable-diffusion-webui/models/Stable-diffusion ![输入图片说明](.idea/imaged.png) 以上工作准备好后我们最终修改启动**weibu.sh**脚本 先给脚本赋予**777权限**,否则无法识别.sh脚本 vim编译器修改类型,因为模式是**dos**类型,我们需要:set ff=unix修改类型并保存 然后启动命令也要配置 ``` nohup ./webui.sh --listen --api --port 9000 --enable-insecure-extension-access & ``` 首先**nohup**启动信息不可见, **--listen**改变主机为0.0.0.0方便防火墙映射, **--api**开启自带的API请求接口, **--port**设置启动访问端口, **--enable-insecure-extension-access**关闭插件扩展安装限制 如果是**没配nohup**那么启动成功的信息应该是这样 ![输入图片说明](.idea/imagee.png) 当然我们修改过使用Url并不是上面这个 **ps:端口需要Liunx防火墙进行开放映射才可以访问** 如此就完成了Stable diffusion WebUI的安装启动,现在通过浏览器进入 界面默认英文可以下载插件进行汉化:https://baijiahao.baidu.com/s?id=1761750555164890926&wfr=spider&for=pc 也可以直接github下载插件存放到此处会自动加载 ![输入图片说明](.idea/imagef.png) 效果: ![输入图片说明](.idea/imageg.png) 这里可以切换下载的模型,模型不同生成出来的图片风格也不同 ![输入图片说明](.idea/imageh.png) 让我们尝试文生图操作 ![输入图片说明](.idea/imagei.png) 生成的图片会输出保存在这个目录 ``` /xxx/xxx/xxxStableDiffusion/stable-diffusion-webui/outputs/txt2img-images/xxx ``` ![输入图片说明](.idea/imagej.png) 至此,Stable diffusion WebUI搭建成功. ### API使用: 我们使用 **--api* 开启了**API**可以在底部进入调试 ![输入图片说明](.idea/imagek.png) 有许多的**API接口**,我们选择文生图接口进行调试: ![输入图片说明](.idea/imagel.png) 详情: ![输入图片说明](.idea/imagem.png) 请求体里有一个关键字段**prompt**,这个字段是输入的文生图的提示词,响应给我们的图片是**base64**的格式,需要进行转码才可以查看,这里我们可以写一个**python**程序来使用接口. ### Python程序: ``` import json import base64 import uuid import cv2 import requests def post(url: str, datas: dict): return requests.post(url, data=json.dumps(datas)) def save(b64_image: str, output_path: str): with open(output_path, "wb") as image_file: image_file.write(base64.b64decode(b64_image)) if __name__ == '__main__': text = input('请输入提示词:') print("构造中,请稍后...") txt2img_url = 'http://x.x.x.x:9000/sdapi/v1/txt2img' response = post(txt2img_url, {'prompt': text}) filename = str(uuid.uuid1()) + '.png' b64 = response.json()['images'][0] print("构造成功!") print(b64) print("转换中...") save(b64, filename) print("转换完毕!") image = cv2.imread(filename) cv2.imshow(filename, image) cv2.waitKey(0) ``` **post**方法用来发送**post请求** **save**方法用来接收**base64数据**进行转码输出图片 **main**方法首先控制台接收提示词,再由**response参数**进行配置发送获取**响应信息** **b64**获取**响应**被转换为**json对象**并获取**图片base64**的**base64数据** 进行方法**save**转化后进行保存 使用**OpenCV**打开保存的图片进行显示 然后我们使用**auto-py-to-exe包**讲其打包成**exe**文件,注意这里只能在**内网**使用 ![输入图片说明](.idea/imagen.png) 接下来进行使用测试,打开程序进行使用 ![输入图片说明](.idea/imageo.png) ![输入图片说明](.idea/imagep.png) 关闭图片,会同时关闭窗口. **当然模型目前只能手动在web页面切换** 至此简单程序的实验成功. ### 下文: Stable diffusion WebUI支持其他的功能 ![输入图片说明](.idea/imageq.png) 项目更新可以使用**git pull**获取