GPT4o는 텍스트, 오디오, 비디오 입력을 통합적으로 처리하고, 텍스트, 오디오, 이미지 형식으로 출력을 생성하도록 설계된 강력한 AI 모델입니다. 단일 모델로 다양한 모달리티를 처리함으로써, GPT-4o는 사용자와의 상호작용을 한 차원 높은 수준으로 끌어올립니다.
이 글에서는 GPT-4o API를 활용하여 대화, 이미지 처리, 영상 요약 등 다양한 작업을 수행하는 방법을 단계별로 살펴보겠습니다. 실제 사용 예시와 함께 GPT-4o의 강력한 기능을 경험해 볼 수 있을 것입니다.
GPT-4o API 시작하기
OpenAI SDK 설치
GPT-4o API를 사용하기 위해서는 먼저 OpenAI SDK를 설치해야 합니다.
pip install --upgrade openai
API 키 설정 API 키를 발급받아 환경 변수로 설정합니다.
import os
os.environ["OPENAI_API_KEY"] = "<your OpenAI API key>"
간단한 수학 문제 풀이
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
  model="gpt-4o",
  messages=[
    {"role": "system", "content": "You are a helpful math tuton. Help me with my math homework!"},
    {"role": "user", "content": "Hello! Could you solve 2+2?"}  
  ]
)
print("Assistant: " + completion.choices[0].message.content)
Assistant: Of course! 
\[ 2 + 2 = 4 \]
If you have any other questions, feel free to ask!
이미지 처리
GPT-4o는 이미지를 직접 처리하고 이미지 기반으로 지능적인 작업을 수행할 수 있습니다. Base64로 인코딩된 이미지나 URL을 통해 이미지를 입력으로 제공할 수 있습니다.
Base64 인코딩 이미지 처리
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("triangle.png")
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with my math homework!"},
        {"role": "user", "content": [
            {"type": "text", "text": "What's the area of the triangle?"},
            {"type": "image_url", "image_url": {
                "url": f"data:image/png;base64,{base64_image}"}
            }  
        ]}
    ],
    temperature=0.0,
)
print(response.choices[0].message.content)
URL 이미지 처리
URL을 통해서도 이미지를 입력으로 제공할 수 있습니다.
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant that responds in Markdown. Help me with explain images!"},
        {"role": "user", "content": [
            {"type": "text", "text": "How is the cat looks like?"},
            {"type": "image_url", "image_url": {
                "url": "https://www.developerfastlane.com/img/blog/streamlit/cat.webp"}
            }
        ]}
    ],
    temperature=0.0,
)
print(response.choices[0].message.content)
영상 처리
GPT-4o API는 현재 오디오 입력을 직접 지원하지 않기 때문에, 영상 처리를 위해서는 프레임을 샘플링하여 이미지로 제공하는 방식을 사용합니다. 영상의 오디오와 비주얼을 모두 처리하기 위해 GPT-4o와 Whisper를 함께 활용하는 방법을 알아보겠습니다.
영상 처리를 위한 프레임 추출 및 오디오 분리
def process_video(video_path, seconds_per_frame=2):  
    base64Frames = []
    base_video_path, _ = os.path.splitext(video_path)
    video = cv2.VideoCapture(video_path)
    total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = video.get(cv2.CAP_PROP_FPS)   
    frames_to_skip = int(fps * seconds_per_frame)
    curr_frame=0
    while curr_frame < total_frames - 1:
        video.set(cv2.CAP_PROP_POS_FRAMES, curr_frame)
        success, frame = video.read()
        if not success:
            break  
        _, buffer = cv2.imencode(".jpg", frame)
        base64Frames.append(base64.b64encode(buffer).decode("utf-8")) 
        curr_frame += frames_to_skip
    video.release()
    
    audio_path = f"{base_video_path}.mp3"
    clip = VideoFileClip(video_path)
    clip.audio.write_audiofile(audio_path, bitrate="32k")
    clip.audio.close()  
    clip.close()
    return base64Frames, audio_path
사례 1: 영상 요약
비주얼 요약
response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content": "You are generating a video summary. Please provide a summary of the video. Respond in Markdown."},    
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames)
        ],  
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)
오디오 요약
transcription = client.audio.transcriptions.create(
    model="whisper-1",
    file=open(audio_path, "rb"),  
)
response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a transcript summary. Create a summary of the provided transcription. Respond in Markdown."""},
    {"role": "user", "content": [
        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],  
    }
    ],
    temperature=0,
)
print(response.choices[0].message.content)
비주얼 + 오디오 요약
response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":"""You are generating a video summary. Create a summary of the provided video and its transcript. Respond in Markdown"""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),  
        {"type": "text", "text": f"The audio transcription is: {transcription.text}"}
        ],
    }  
],
    temperature=0,
)
print(response.choices[0].message.content)
사례 2: 질의 응답
비주얼 기반 질의 응답
qa_visual_response = client.chat.completions.create(
    model=MODEL,
    messages=[  
    {"role": "system", "content": "Use the video to answer the provided question. Respond in Markdown."},
    {"role": "user", "content": [
        "These are the frames from the video.",  
        *map(lambda x: {"type": "image_url", "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
        QUESTION
        ],  
    }
    ],
    temperature=0,
)
print("Visual QA:\n" + qa_visual_response.choices[0].message.content)
오디오 기반 질의 응답
qa_audio_response = client.chat.completions.create(
    model=MODEL,
    messages=[
    {"role": "system", "content":""""Use the transcription to answer the provided question. Respond in Markdown."""},
    {"role": "user", "content": f"The audio transcription is: {transcription.text}. \n\n {QUESTION}"},  
    ],
    temperature=0,
)  
print("Audio QA:\n" + qa_audio_response.choices[0].message.content)
비주얼 + 오디오 기반 질의 응답
qa_both_response = client.chat.completions.create(
    model=MODEL,
    messages=[  
    {"role": "system", "content":""""Use the video and transcription to answer the provided question."""},
    {"role": "user", "content": [
        "These are the frames from the video.",
        *map(lambda x: {"type": "image_url", 
                        "image_url": {"url": f'data:image/jpg;base64,{x}', "detail": "low"}}, base64Frames),
                        {"type": "text", "text": f"The audio transcription is: {transcription.text}"},  
        QUESTION
        ],
    }  
    ],
    temperature=0,
)
print("Both QA:\n" + qa_both_response.choices[0].message.content)
텍스트, 이미지, 오디오 등 다양한 입력 모달리티를 통합하는 것은 모델의 성능을 크게 향상시킵니다. 이러한 멀티모달 접근 방식은 인간이 정보를 인지하고 처리하는 방식과 유사하게 작동하여 더욱 포괄적인 이해와 상호작용을 가능하게 합니다. 현재 GPT-4o API는 텍스트와 이미지 입력을 지원하며, 오디오 기능도 곧 추가될 예정입니다. 다양한 작업에 GPT-4o를 활용해 보시고, 더 강력해진 멀티모달 AI의 가능성을 경험해 보시기 바랍니다.