1. 소개
최종 업데이트: 2023년 10월 12일
Imagegen 이미지 생성
Google Imagen은 텍스트 설명에서 사실적이고 창의적인 이미지를 생성할 수 있는 강력한 Google의 대규모 언어 모델입니다. Vertex AI의 Imagen을 사용하면 사용자가 상상력을 몇 초 만에 고품질 시각적 애셋으로 변환하는 차세대 AI 제품을 빌드할 수 있습니다. 텍스트 기반 이미지 생성 외에도 텍스트 프롬프트를 통한 이미지 편집, 이미지 캡셔닝, 시각적 Q&A, 주제 및 스타일 기반 이미지 모델 미세 조정을 지원합니다.
프롬프트 생성
Imagen을 사용하여 이미지를 만들려면 이미지를 생성하는 데 사용되는 프롬프트라는 이미지의 텍스트 설명을 제공해야 합니다. 그러나 고품질의 사실적인 이미지를 생성하려면 프롬프트 전문 지식이 필요합니다. 소매, 제조 등 특정 비즈니스 도메인과 관련된 이미지를 생성하려는 경우 도메인에 따라 달라질 수도 있습니다. 프롬프트를 설계하는 더 쉬운 방법은 Text Bison 모델에 키워드 집합을 제공하는 것입니다.
전반적인 접근 방식은 다음과 같습니다.

Gradio UI
Gradio는 몇 줄의 코드를 사용하여 머신러닝 모델, API 또는 임의의 Python 함수를 위한 사용하기 쉽고 맞춤설정 가능한 UI 구성요소를 빠르게 만들 수 있는 오픈소스 Python 라이브러리입니다. Gradio GUI를 Jupyter 노트북에 직접 통합하거나 링크로 공유할 수 있습니다. Gradio는 텍스트, 이미지, 동영상, 오디오를 비롯한 다양한 미디어 유형을 지원합니다. 또한 입력란, 버튼, 슬라이더, 드롭다운 메뉴와 같은 여러 사전 빌드된 UI 구성요소를 제공합니다.
빌드할 항목
이 Codelab에서는 다음 작업을 실행하는 Gradio 앱을 배포합니다.
- 키워드 또는 구문을 사용하여 텍스트 프롬프트를 생성합니다. 생성된 프롬프트는 수동으로 수정할 수도 있습니다.
- UI에서 생성된 프롬프트로 이미지를 생성합니다.
학습할 내용
- 텍스트-바이슨 모델을 사용하여 이미지 생성을 위한 Imagen 관련 프롬프트를 프로그래매틱 방식으로 생성하는 방법
- API 및 프롬프트를 통해 Imagen 모델을 사용하여 이미지를 생성하는 방법
- Vertex AI Workbench 노트북에서 Gradio 애플리케이션을 빌드, 배포, 테스트하는 방법
필요한 항목
- GCP 프로젝트에 대한 액세스 권한(예: 'Cloud-llm-preview4')
- Vertex AI Workbench를 만들 수 있는 액세스 권한
- Vertex AI API 사용 설정됨
- Gradio의 네트워킹 요구사항: 노트북 인스턴스 액세스 공개 URL
2. 설정
노트북 만들기
- 프로젝트에 로그인합니다.
- 왼쪽 탐색 메뉴에서 Workbench 로 이동합니다.
- "사용자 관리 노트북"에서 기본 옵션으로 새 노트북을 만듭니다.
- 인스턴스가 프로비저닝되면 "JupyterLab 열기"를 클릭합니다.
참고: 노트북이 중지된 상태인 경우 노트북을 시작하는 데 몇 분 정도 걸릴 수 있습니다.
코드 가져오기
코드 파일은 여기에 있습니다. 이 노트북은 환경으로 가져와서 그대로 실행할 수 있습니다 (프로젝트 세부정보 변경 제외).
3. 코드 실행
필요한 종속 항목 및 라이브러리 설치/가져오기
- Gradio 앱 설치
- 텍스트-바이슨 및 이미지 생성을 위한 Vertex AI API를 가져옵니다.
- 기타 필요한 라이브러리를 모두 가져옵니다.
텍스트-바이슨을 사용한 프롬프트 생성
키워드 및/또는 구문이 포함된 사용자 입력을 사용합니다. 즉, 생성할 필요한 이미지를 설명하는 문장을 구성하는 데 사용할 수 있는 쉼표로 구분된 키워드 또는 구문 목록입니다.
예: 페르소나, 주제, 배경, 조명 및 기타 설명
프롬프트를 생성하는 함수는 다음과 같습니다.
def prompt_generation(persona,signal,theme, lighting, quality, extra_desc):
model = TextGenerationModel.from_pretrained("text-bison")
response_few_shot = model.predict(
few_shot_prompt,
**parameters
)
response_single_shot = model.predict(
prompt,
**parameters
)
퓨샷 및 제로샷 프롬프트
제로샷 프롬프트는 모델에 텍스트를 생성할 컨텍스트나 예가 제공되지 않는 텍스트 생성 기법입니다. 모델이 일관되고 유익한 텍스트를 생성하기 위해 자체 지식에 의존해야 하므로 어려울 수 있습니다.
그러나 제로샷 프롬프트는 모델이 기존 예에 의해 제한되지 않으므로 매우 창의적일 수도 있습니다.
퓨샷 프롬프트는 모델에 텍스트를 생성할 몇 가지 예가 제공되는 텍스트 생성 기법입니다. 모델에 생성할 항목에 대한 안내가 있으므로 제로샷 프롬프트보다 쉬울 수 있습니다. 그러나 퓨샷 프롬프트는 모델이 제공된 예와 유사한 텍스트만 생성할 수 있으므로 제한적일 수도 있습니다.
다음은 퓨샷 및 제로샷 프롬프트의 샘플 코드입니다.
**# 코드에 사용된 퓨샷 프롬프트**
few_shot_prompt = f"""You are an expert in writing prompts for Image Generation Models. Using the provided phrases and keywords, concatenate them and add on some realistic details to generate logical and Meaningful prompt that can be used for image generation.
input: people, gardening, house garden, colorful plants, Real, HD image, Photo.
output: A Photo of people gardening in a house garden landscape with few coloured flowering plants. Realistic FULL HD Images, Elegant and natural facial and eye features taken by professional photographer
input: plumber, faucet, kitchen, high quality, natural lighting, Photo
output: A Photo of a plumber fixing a faucet in the kitchen. High quality image with natural indoor lighting.
input: house and garden, halloween, warm lighting, high quality image, Sketch
output: A Sketch of Beautiful House and Garden with Halloween Decorations. Warm lighting, High Quality, 4K photograph taken by professional photographer from front.
input: nice living room, warm lighting,Professional Photographer from far, Photo
output: A photo of a Well designed Living Room. Warm lighting, High Quality, 4K photograph taken by Professional Photographer from far
input: {params_list_str}
output:
"""
# 코드에 사용된 제로샷 프롬프트
prompt = f"""You are an expert in writing prompts for Image Generation Models. Help me write a list of meaningful prompts for Image Generation Model specifically including the words: "{params_list_str}". Remember to include these words in the prompt and make the prompt meaningful."""
Imagen을 사용한 이미지 생성
사용자 입력 프롬프트 및 부정적 프롬프트(선택사항)를 사용하고 모델 (imagegeneration@002)에 제공합니다.
def image_generation_completion(input, negative_prompt):
input_prompt = input
model = ImageGenerationModel.from_pretrained("imagegeneration@002")
response = model.generate_images(
prompt=input_prompt,
number_of_images=4, #kept to static value of 4
negative_prompt=negative_prompt
)
다음 코드는 사용자 입력 프롬프트 및 부정적 프롬프트에서 이미지를 생성하기 위해 포함됩니다. 최종 코드는 텍스트-바이슨 모델에서 생성된 프롬프트를 사용합니다.
from vertexai.preview.vision_models import ImageGenerationModel
def image_generation(input, negative_prompt):
input_prompt = input
model = ImageGenerationModel.from_pretrained("imagegeneration@002")
response = model.generate_images(
prompt=input_prompt,
number_of_images=4, #kept to static value of 4.. can be a max value of 8
negative_prompt=negative_prompt
)
images = response.images
return images
user_prompt = "Prompt: A Young Woman Showcasing and selling an undecorated Fresh Christmas Tree from A bunch of trees. Cold Lighting, High Quality and detailed Image Taken By Professional Photographer from far."
negative_prompt = "Distorted and unattractive faces"
generated_images_list = image_generation(user_prompt,negative_prompt)
#생성된 이미지 중 하나 표시
generated_images_list[0].show()
출력 -

4. Gradio 앱 배포
Gradio는 사용자가 키워드를 입력하고 구조화된 프롬프트를 생성할 수 있는 프런트엔드에 사용되며 이러한 프롬프트는 직접 사용하거나 사용자가 추가로 편집한 후 Imagen에 제공하여 입력에 따라 이미지를 생성할 수 있습니다. Gradio는 머신러닝 모델의 사용자 인터페이스를 만드는 데 사용할 수 있는 Python 라이브러리입니다. 이 애플리케이션에서는 블록을 사용하여 이 애플리케이션에 유연성과 복잡한 데이터 흐름을 추가합니다. 블록은 행과 열을 사용하여 애플리케이션 레이아웃 관리를 제공합니다.
with gr.Blocks() as demo:
#Prompt Generation Part
with gr.Row():
with gr.Column(scale=1):
Persona = gr.Textbox(label="Persona", info = "Customer segment such as Plumber, Electrician etc.")
with gr.Column(scale=1):
Signals = gr.Textbox(label="Signals", info = "Main content of banner such as Faucet, Lamp etc.")
with gr.Column(scale=1):
Theme = gr.Textbox(label="Theme", info = "Context of the banner such as Halloween, Kitchen etc.")
with gr.Row():
with gr.Column(scale=1):
photo_modifiers = gr.Textbox(label="Photography Modifiers", info = "Photography specific modifiers and parameters such as Lighting(Dramatic/Natural/Warm/Cold), Camera Proximity etc.")
with gr.Column(scale=1):
quality_modifiers = gr.Textbox(label="Image Quality Modifier", info = "Quality Modifiers like high-quality, beautiful, stylized. 4K, HDR, By a professional etc")
with gr.Column(scale=1):
other_desc = gr.Textbox(label="Any Other Description", info = "Other Descriptions for Image such as Style (Painting/Photo/Sketch), Bakground/Foreground Context")
with gr.Row():
btn = gr.Button("Submit")
with gr.Row():
returned_prompts = gr.Textbox(label="Result Prompts", interactive = True)
btn.click(fn=prompt_generation, inputs=[Persona, Signals,Theme, photo_modifiers, quality_modifiers, other_desc], outputs = returned_prompts)
사용자 입력 및 출력을 처리하기 위해 Gradio는 이미지, 동영상, 슬라이더, 드롭다운, 텍스트 상자, 라디오 및 기타 옵션과 같은 여러 구성요소를 제공합니다. 이러한 구성요소를 통해 개발자는 사용자로부터 입력을 수락하고 이를 테스트-바이슨, Imagen 또는 기타 ML 모델에 제공하는 방법을 유연하게 제어할 수 있습니다.
이 프로젝트에서는 블록을 사용하여 애플리케이션에 유연성과 복잡성을 추가하여 애플리케이션을 만듭니다.
애플리케이션에 데이터 흐름을 추가합니다. 블록 외에도 여러 Gradio 구성요소가
다음과 같이 사용됩니다.
- 적절한 레이아웃을 위한 행, 열
- 버튼, 텍스트 상자, 드롭다운, 슬라이더를 사용하여 필요한 기능과 사용 편의성을 달성
- 이미지 구성요소로 결과를 표시합니다.
- UI의 동적 변경을 지원하기 위한 EventData, 업데이트와 같은 기타 도우미
다음은 입력 및 부정적 프롬프트에서 이미지를 생성하는 데 사용되는 코드 스니펫입니다.
#이미지 생성 부분
with gr.Row():
with gr.Column(scale=1):
image_prompt = gr.Textbox(label="Image Generation Prompt")
with gr.Accordion("Advanced options", open=False): #Let's hide the advanced options!
with gr.Row():
negative_prompt = gr.Textbox(label="Negative prompt", info = "Specify What not to Include in Image ex. Bad Quality Image")
with gr.Row():
with gr.Column(scale=1):
img_btn = gr.Button("Generate Images")
with gr.Row():
with gr.Column():
output_image_1 = gr.Image(label = "Result Image 1", visible = False)
with gr.Column():
output_image_2 = gr.Image(label = "Result Image 2", visible = False)
with gr.Row():
with gr.Column():
output_image_3 = gr.Image(label = "Result Image 3", visible = False)
with gr.Column():
output_image_4 = gr.Image(label = "Result Image 4", visible = False)
returned_prompts.select(populate_image_prompt, inputs = [returned_prompts], outputs = image_prompt)
img_btn.click(fn=image_generation_completion, inputs=[image_prompt,negative_prompt], outputs = [output_image_1,output_image_2,output_image_3,output_image_4])
Gradio 애플리케이션을 실행하고 테스트하려면 텍스트 프롬프트를 입력하고 생성 버튼을 클릭하면 됩니다. Imagen은 프롬프트에 따라 이미지를 생성합니다. 다양한 프롬프트를 시도하여 Imagen이 생성할 수 있는 이미지 유형을 확인할 수 있습니다.
다음은 Gradio 앱의 프롬프트 생성 스크린샷입니다.

다음은 Gradio 앱의 이미지 생성 스크린샷입니다.

몇 가지 예
예 1 -
[왼쪽 이미지] 프롬프트 (간단한 키워드를 프롬프트로 사용) : 보트를 타는 친구 커플
[오른쪽 이미지] 프롬프트 (텍스트-바이슨에서 생성된 프롬프트 사용) : 숲의 어두운 나무로 둘러싸인 보트에서 낚시하는 두 젊은 남자의 사진 남자는 셔츠를 입고 보트에 서 있습니다. 자연 조명, 고품질, 전문 사진작가가 촬영한 4K 사진

예 2 -
[왼쪽 이미지] 프롬프트(간단한 키워드를 프롬프트로 사용) : 크리스마스 트리
[오른쪽 이미지] 프롬프트 (텍스트-바이슨에서 생성된 프롬프트 사용) : 램프와 가구가 있는 방의 크리스마스 트리 트리는 조명과 장식으로 장식되어 있습니다. 창문 근처에 있으며 배경에 벽이 보입니다. 따뜻한 조명, 고품질, 전문 사진작가가 멀리서 촬영한 HDR 사진

5. 삭제
리소스를 삭제하려면 다음 단계를 따르세요.
- Gradio 앱을 중지합니다.
- Workbench 노트북을 중지/삭제합니다.
6. 축하합니다
축하합니다. Google Text-Bison API 및 Imagen API를 사용하여 프롬프트와 이미지를 만드는 Gradio 애플리케이션을 배포했습니다.