공부/AI

최신 업그레이드된 인공지능(AI) 그림을 코드 붙여넣기만으로 몇 분만에 구현하여 그리기 (Stable Diffusion v2)

우주관리자 2022. 11. 28.

Stable Diffusion v2로 33초만에 생성한 이미지

Stable Diffusion v2

이전 포스팅에서 다뤘던 Stable Diffusion이 최근 v2로 업그레이드 되었습니다.

 

아래 사이트를 참고하여 빠르게 구현해보겠습니다.

https://huggingface.co/stabilityai/stable-diffusion-2

 

stabilityai/stable-diffusion-2 · Hugging Face

Stable Diffusion v2 Model Card This model card focuses on the model associated with the Stable Diffusion v2 model, available here. This stable-diffusion-2 model is resumed from stable-diffusion-2-base (512-base-ema.ckpt) and trained for 150k steps using a

huggingface.co

 

구글 코랩을 사용한 환경 구성은 이전 포스팅을 참고해주세요.

2022.11.20 - [AI] - 인공지능(AI) 그림을 라이센스 없이 무제한으로 1분만에 생성하는 방법 (Stable Diffusion + 구글 Colab 사용)

 

인공지능(AI) 그림을 라이센스 없이 무제한으로 1분만에 생성하는 방법 (Stable Diffusion + 구글 Colab

최근 텍스트를 이미지로 만들어주는 Stable diffusion이라는 모델이 공개되어 다양한 활용 및 응용이 되고 있습니다. 그러나 모델과 소스가 공개되었다고 하더라도 일반인들이 접근하기에는 아직

ourhertz.com

 

핵심 코드

코랩에 아래 코드를 복사한 뒤 실행해주세요.

런타임 - 런타임 유형 변경에서 하드웨어 가속기가 GPU로 설정되어있는지 확인해야합니다.

 

!pip install --upgrade git+https://github.com/huggingface/diffusers.git transformers accelerate scipy 
!pip install xformers translate gradio

import torch

from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler

model_id = "stabilityai/stable-diffusion-2"

# Use the Euler scheduler here instead
scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
pipe = StableDiffusionPipeline.from_pretrained(model_id, scheduler=scheduler, revision="fp16", torch_dtype=torch.float16)
pipe = pipe.to("cuda")

# 원본 코드
#prompt = "a photo of an astronaut riding a horse on mars"
#image = pipe(prompt, height=768, width=768).images[0]

#image.save("astronaut_rides_horse.png")
#image

from translate import Translator
translator = Translator(from_lang="ko", to_lang="en")

def generate_images(text):
    print("입력한 한글 문장 : " + text)
    translated = translator.translate(text)
    print("번역된 영어 문장 : " + translated)

    image = pipe(translated, height=768, width=768).images[0]

    return image

import gradio

def inference(text):
    image = generate_images(text)
    return image

gradio = gradio.Interface(fn=inference, inputs="text", outputs="image")

 

정상적으로 완료가 되면 다음과 같이 재생 아이콘 좌측에 실행 시간이 녹색으로 표시됩니다.

 

만약 위 코드 실행 중 아래와 같은 오류가 발생된다면 huggingface 서버 문제이므로 시간이 지난 뒤 재시도해보시기 바랍니다.

---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/huggingface_hub/utils/_errors.py in hf_raise_for_status(response, endpoint_name)
    238     try:
--> 239         response.raise_for_status()
    240     except HTTPError as e:

10 frames
HTTPError: 504 Server Error: Gateway Time-out for url: https://huggingface.co/api/models/stabilityai/stable-diffusion-2/revision/fp16

The above exception was the direct cause of the following exception:

HfHubHTTPError                            Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/huggingface_hub/utils/_errors.py in hf_raise_for_status(response, endpoint_name)
    278         # Convert `HTTPError` into a `HfHubHTTPError` to display request information
    279         # as well (request id and/or server error message)
--> 280         raise HfHubHTTPError(str(e), response=response) from e
    281 
    282 

HfHubHTTPError: 504 Server Error: Gateway Time-out for url: https://huggingface.co/api/models/stabilityai/stable-diffusion-2/revision/fp16

 

Hugging Face 사이트의 Login 페이지에 접속 시도를 해보시면 서버 상태를 확인할 수 있습니다.

https://huggingface.co/login

 

Hugging Face – The AI community building the future.

 

huggingface.co

 

서버가 죽어있는 상태에서는 위의 오류와 동일한 504 오류가 표시되는 것을 확인할 수 있습니다.

 

AI 이미지를 생성해보자#1 (Gradio 사용)

+ 코드를 눌러서 아래 코드 한줄을 입력 후 실행합니다.

gradio.launch(debug=True)

 

위와 같은 화면이 나오면 성공입니다.

text 란에 한글로 원하는 문장을 입력하고 제출하기 버튼을 누르면 됩니다.

업그레이드된 인공지능의 그림 그리는 실력

 

위에 나온 https://localhost:7860/ 을 클릭하면 인터넷에서도 접속할 수 있는 웹페이지가 열립니다 (당연히 런타임 유지가 되어있는동안만 사용 가능합니다)

 

외부 웹페이지를 사용해서 실행을 해도 코랩 내 실행 결과에는 다음과 같이 실행된 내역을 볼 수 있습니다.

 

AI 이미지를 생성해보자#2 (코랩 내 명령어를 통해)

+ 코드를 눌러서 아래 코드 한줄을 입력 후,

큰 따옴표 내의 문장을 원하는 문장으로 변경한 뒤 실행합니다.

 

generate_images("사람과 개의 달리기 시합")

실행이 되고 있습니다.

33초만에 결과가 나왔습니다.

사람과 개의 달리기 시합

 

Stable Diffusion v2는 이전 v1에 비해 해상도 향상(512x512에서 768x768로)과 속도 개선이 있었다고 하는데 이전 포스팅의 v1 이미지 생성 시간을 보면 약 1분 정도가 소요된 것을 보면 상당히 빨라진 것을 알 수 있습니다.


 

v2로도 많이 시도해보시고 재밌는 그림이 나오면 댓글로 공유해주시기 바랍니다.

반응형