본문 바로가기
카테고리 없음

ChatGPT - Dall-e API 연결하여 이미지 상세 그리기(바닷가 집 디자인)

by 스마트파베르 2024. 3. 10.
반응형

ㅇ OpenAI 가입, API key 발급, 모델 선택 등에 대한 설명은 앞에서 만든 티스토리 글을 참조해 주세요. 

  https://ai-democracy.tistory.com/18

 

ChatGPT API 연동 (파이썬) 방법 - 텍스트 응답 처리 방식 2가지

ㅇ OpenAI 가입하고, API key를 발급받는다. - 아래 사이트에서 +Create new secret key를 눌러서 키 발급 받음 : https://platform.openai.com/api-keys ㅇ openAI 에서 API 사용 레퍼런스를 제공한다. 기본적인 text를 만

ai-democracy.tistory.com

 

ㅇ Dalle API 연동으로 이미지 생성 방법은  앞에서 만든 티스토리 글을 참조해 주세요. 

https://ai-democracy.tistory.com/19

 

OpenAI Dall-e 이미지 API 연동 (파이썬) 방법

ㅇ OpenAI 가입, API key 발급, 모델 선택 등에 대한 설명은 이전에 만든 티스토리 글을 참조해 주세요. https://ai-democracy.tistory.com/18 ChatGPT API 연동 (파이썬) 방법 - 텍스트 응답 처리 방식 2가지 ㅇ OpenAI

ai-democracy.tistory.com

 

 

 

1. ChatGPT API로 그리고자 하는 이미지에 대한 설명 프롬프트를 입력하여 응답을 받는다.

from openai import OpenAI

client = OpenAI(api_key = "발급받은 api key")

completion_assign = client.chat.completions.create(
  model="gpt-4-0125-preview",
  messages=[
    {"role": "system", "content": "You are a helpful assistant who is an artchitect."}, #role 필드 : ['system', 'assistant', 'user', 'function'] 중 하나  
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Hi, I am an architect. What do you want?"},
  ],
  temperature=0.7,
  max_tokens=500,
  n=1,
  stop=None  
)
answer = completion_assign.choices[0].message.content
print(answer)

prompt = "나는 노후에 바닷가에 작은 건물을 짓고, 텃밭에는 과일나무와 채소를 키우고, 지인들이 모여서 마당에서 파티를 하면서 즐겁게 이야기하는 것을 바란다. 바닷가의 지중해 풍의 집과 외형을 묘사해주세요."

messages=[
    {"role": "user", "content": prompt}  
]
    
completion_prompt = client.chat.completions.create(
  model="gpt-4-0125-preview",
  messages=messages,  
  temperature=0.7,
  max_tokens=1000,
  n=1,
  stop=None  
)

answer1 = completion_prompt.choices[0].message.content
print(answer1)

ㅇ answer1 응답

Hello! How can I assist you today?
당신의 꿈은 평화롭고 아름다운 삶을 향한 열망을 반영합니다. 바닷가에 위치한 지중해 풍의 집은 그림 같은 풍경과 어우러져 완벽한 휴식처를 제공합니다. 이상적인 집의 모습을 그려보겠습니다.

외형은 전통적인 지중해 스타일을 따릅니다. 흰색 또는 밝은 베이지색 페인트로 칠해진 벽은

 

2. 응답받은 설명을 프롬프트로 입력하여 ChatGPT에게 좀 더 상세한 설명을 요청한다.

# 이전 어시스턴트 응답 메시지 추가
messages.append(
    {"role": "assistant","content": answer1},
)

# 사용자 메시지 추가
messages.append(
    {"role": "user", "content": "위 내용을 바탕으로 건물의 외형적인 모습을 더 자세히 상상해서 묘사해주세요."}
)
print()

#print("messages", messages)
print("\n-------------------------")

# ChatGPT API 호출하기
completion_prompt = client.chat.completions.create(
  model="gpt-4-0125-preview",
  messages=messages,  
  temperature=0.7,
  max_tokens=500,
  n=1,
  stop=None  
)
answer2 = completion_prompt.choices[0].message.content
print(answer2)

ㅇ answer2 응답

-------------------------
당신이 꿈꾸는 바닷가의 지중해 풍 건물은 자연과 조화를 이루며, 휴식과 평화의 상징처럼 바다를 마주하고 있습니다. 이 아름다운 건물은 전통과 현대성이 어우러진 디자인으로, 그 자체만으로도 한 폭의 그림 같은 풍경을 연출합니다.

건물의 외벽은 태양의 빛을 반사하는 

 

3. 응답받은 상세 설명을 ChatGPT에게 영어로 번역을 요청한다.


# 영어 번역 요청 새 메시지 구성
messages =  [
    {"role": "system", "content": "You are a helpful assistant who is good at translating."},
    {"role": "user", "content": answer2 + " 이 설명을 영어로 번역해주세요."}
]

print("messages", messages)
print("\n-------------------------")

# ChatGPT API 호출하기
completion_prompt = client.chat.completions.create(
  model="gpt-4-0125-preview",
  messages=messages,  
  temperature=0.7,
  max_tokens=1000,
  n=1,
  stop=None  
)

answer3 = completion_prompt.choices[0].message.content
print(answer3)

ㅇ answer3 응답

-------------------------
The Mediterranean-style building you dream of harmonizes with nature and stands as a symbol of rest and peace, facing the sea. This beautiful building blends tradition with modernity in its design, creating a picturesque landscape in itself.

The exterior walls are finished with bright white lime walls

 

4. 응답받은 영어 설명을  Dall-e에게 입력할 핵심 문장으로 요약을

ChatGPT에게 요청한다.

# 이미지 생성을 위한 요약 프롬프트 작성 요청하기
messages =  [
    {"role": "system", "content": "You are an assistant who is good at creating prompts for image creation."},
    {"role": "user", "content": answer3 + " 위 설명문을 명사와 형용사에 초점을 맞춰 최대 6개까지 요약해서 콤마(,) 로 구분해주세요."} 
     #"Condense up to 6 outward description to focus on nouns and adjectives separated by ,"}
]

print("messages", messages)
print("\n-------------------------")

# ChatGPT API 호출하기
completion_prompt = client.chat.completions.create(
  model="gpt-4-0125-preview",
  messages=messages,  
  temperature=0.7,
  max_tokens=1000,
  n=1,
  stop=None  
)

answer4 = completion_prompt.choices[0].message.content
print(answer4)

 

ㅇ answer4 응답

-------------------------
Mediterranean-style, bright white lime walls, large arched windows, red terracotta tiles, wooden roof beams, U-shape design

 

5. 요약한 영어 설명을  Dall-e에게 입력하여 이미지를 생성한다.

  - 이미지 생성을 위한 그림 형태나 디자인 요소를 추가해본다.

 - model은 달리를 사용 : "dall-e-3"

import requests
from PIL import Image
from io import BytesIO

#이미지 생성에 추가할 설명 넣기
params = " realistic lighting, ultra-detailed, 4K, photorealism, digital art"  # 그림 형태 설명
prompt = f"Cozy seaside home with beach garden, {answer4}{params}"  # 추가할 디자인
print(prompt)

#이미지 모델 구성
response = client.images.generate(
  model="dall-e-3",
  prompt= prompt,
  n=1,
  size="1024x1024"
)

#image_url = response['data'][0]['url']
image_url = response.data[0].url

res = requests.get(image_url)
img = Image.open(BytesIO(res.content))
img

ㅇ 응답 이미지 

반응형