1. 설치
1.1 Automatic1111
설치는 이 블로그를 참고했다.
https://www.internetmap.kr/entry/Installing-Stable-Diffusion-AUTOMATIC1111
Stable Diffusion 대표 UI - AUTOMATIC1111 설치방법
그림 생성형 인공지능 중 하나인 Stable Diffusion은 다양한 방법으로 사용할 수 있습니다. 오픈 소스이기 때문에 원하는 누구나 조금씩 수정하여 프로그램을 만들 수 있기 때문입니다. 며칠전 소개
www.internetmap.kr
설치시 주의 할 점
-Python 3.10.6 설치 (다른 버전을 사용하면 지원되지 않는 모듈이 있다는 에러가 발생 할 수 있다.)
-Git을 사용하면 쉽게 다운받을 수 있음.
1.2 Nodejs 설치
구글에 검색하면 공식 사이트에서 다운받을 수 있다.
2.머신
허깅페이스나 Civitai에 오픈소스 모델들이 많이 있다.
우선 나는 허깅페이스 모델을 다운받았다.
https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/tree/main
stabilityai/stable-diffusion-xl-base-1.0 at main
StableDiffusionXLPipeline
huggingface.co
그리고 아래 모델을 다운받았다.
다운 받은 모델을 모델 폴더( sd\webui\models\Stable-diffusion )에 옮겨준다.
(내 경로는 C:\Users\KIM\sd\webui\models\Stable-diffusion)
(단, 모델유형이 체크포인트가 아닌 경우 다른 폴더에 넣어야한다. 위 모델을 체크포인트)
3.실행 및 설정
기본적으로 웹 브라우저에서 실행된다.
......\sd\webui 이 폴더 안에 webui-user.bat 라는 파일이 있는데 이 파일을 통해 실행시킬수 있다.
나는 API통신을 할 것이므로 따로 설정해야할 것이 있다. (초기 세팅은 api를 사용하지 못하도록 해놨음)
우선 webui-user.bat 을 메모장으로 연다.
@echo off
set PYTHON=
set GIT=
set VENV_DIR=
set COMMANDLINE_ARGS=
call webui.bat
이렇게 쓰여 있을 탠데 COMMANDLINE_ARGS 부분을 아래처럼 바꾼다.
set COMMANDLINE_ARGS=--api
이제 api통신이 가능해졌다.
webui-user.bat 파일을 실행시켜보면
처럼 나올 탠데 이 url뒤에 /docs를 붙이면 문서가 나오는데 api 설정이 정상적으로 되었다면 아래 사진 처럼 나올것이다.
(POST : /sdapi/v1/txt2img 가 보여야한다.)
4. Nodejs API통신
이제 .bat 을 실행시키고 아래의 코드를 실행시켜보자.
const axios = require('axios');
const fs = require('fs');
//sd_xl_base_1.0
const url = "http://127.0.0.1:7860";
payload = {
"prompt": "A majestic lion jumping from a big stone at night",
"negative_prompt": "low quality",
"steps": 20,
"cfg_scale": 11,
"width": 512,
"height": 512,
"override_settings": {
"sd_model_checkpoint": "sd_xl_base_1.0"
}
}
// Send
axios.post(`${url}/sdapi/v1/txt2img`, payload)
.then(response => {
const imageBase64 = response.data.images[0];
// Decode and save the image.
const imageBuffer = Buffer.from(imageBase64, 'base64');
fs.writeFile('output.png', imageBuffer, err => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('File saved successfully!');
}
});
})
.catch(error => {
console.error('Error making request:', error);
});
/*
sd_xl_base_1.0 프롬프트 작성 순서
https://blog.segmind.com/prompt-guide-for-stable-diffusion-xl-crafting-textual-descriptions-for-image-generation/
[1] Subject, [2] Detailed Imagery, [3] Environment Description, [4] Mood/Atmosphere Description, [5] Style, [6] Style Execution
예시 :
Prompt: "Model in layered street style, standing against a vibrant graffiti wall, Vivid colors, Mirrorless, 28mm lens, f/2.5 aperture, ISO 400, natural daylight"
Style: Photographic
Negative Prompt: out of frame, lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature.
Steps:27
Guidance Scale: 7
Strength: 1
Seed: 68420
*/
/*
페이로드 예시
{
"prompt": "",
"negative_prompt": "",
"styles": [
"string"
],
"seed": -1,
"subseed": -1,
"subseed_strength": 0,
"seed_resize_from_h": -1,
"seed_resize_from_w": -1,
"sampler_name": "string",
"scheduler": "string",
"batch_size": 1,
"n_iter": 1,
"steps": 50,
"cfg_scale": 7,
"width": 512,
"height": 512,
"restore_faces": true,
"tiling": true,
"do_not_save_samples": false,
"do_not_save_grid": false,
"eta": 0,
"denoising_strength": 0,
"s_min_uncond": 0,
"s_churn": 0,
"s_tmax": 0,
"s_tmin": 0,
"s_noise": 0,
"override_settings": {},
"override_settings_restore_afterwards": true,
"refiner_checkpoint": "string",
"refiner_switch_at": 0,
"disable_extra_networks": false,
"firstpass_image": "string",
"comments": {},
"enable_hr": false,
"firstphase_width": 0,
"firstphase_height": 0,
"hr_scale": 2,
"hr_upscaler": "string",
"hr_second_pass_steps": 0,
"hr_resize_x": 0,
"hr_resize_y": 0,
"hr_checkpoint_name": "string",
"hr_sampler_name": "string",
"hr_scheduler": "string",
"hr_prompt": "",
"hr_negative_prompt": "",
"force_task_id": "string",
"sampler_index": "Euler",
"script_name": "string",
"script_args": [],
"send_images": true,
"save_images": false,
"alwayson_scripts": {},
"infotext": "string"
}
*/
이 스크립트의 맨 아래 주석을 보면 많은 항목을 설정할 수 있는데, 전부 보내줄 필요는 없다. 필요한 요소를 골라서 보내면 된다.
payload = {
"prompt": "A majestic lion jumping from a big stone at night",
"negative_prompt": "low quality",
"steps": 20,
"cfg_scale": 11,
"width": 512,
"height": 512,
"override_settings": {
"sd_model_checkpoint": "sd_xl_base_1.0"
}
}
이 항목들은 거의 핵심이므로 꼭 포함 하도록하자.