import os
from openai import OpenAI
from PIL import Image
from io import BytesIO
import base64
client = OpenAI(
api_key="sk-***", # 🔑 AiHubMix에서 생성한 키로 교체하세요
base_url="https://aihubmix.com/v1",
)
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "filled.jpg")
if not os.path.exists(image_path):
raise FileNotFoundError(f"이미지 {image_path}가 존재하지 않습니다")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image(image_path)
response = client.chat.completions.create(
model="gemini-2.0-flash-preview-image-generation",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "describe the image with a concise and engaging paragraph, then fill color as children's crayon style",
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
modalities=["text", "image"],
temperature=0.7,
)
try:
# base64 데이터 없이 기본 응답 정보 출력
print(f"생성 시간: {response.created}")
print(f"토큰 사용량: {response.usage.total_tokens}")
# multi_mod_content 필드가 존재하는지 확인
if (
hasattr(response.choices[0].message, "multi_mod_content")
and response.choices[0].message.multi_mod_content is not None
):
print("\n응답 내용:")
for part in response.choices[0].message.multi_mod_content:
if "text" in part and part["text"] is not None:
print(part["text"])
# 이미지 내용 처리
elif "inline_data" in part and part["inline_data"] is not None:
print("\n🖼️ [이미지 내용 수신됨]")
image_data = base64.b64decode(part["inline_data"]["data"])
mime_type = part["inline_data"].get("mime_type", "image/png")
print(f"이미지 유형: {mime_type}")
image = Image.open(BytesIO(image_data))
image.show()
# 이미지 저장
output_dir = os.path.join(os.path.dirname(image_path), "output")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "edited_image.jpg")
image.save(output_path)
print(f"✅ 이미지가 저장되었습니다: {output_path}")
else:
print("유효한 멀티모달 응답을 받지 못했습니다. 응답 구조를 확인하세요")
except Exception as e:
print(f"응답 처리 중 오류 발생: {str(e)}")