Gemini 모델은 동영상을 처리할 수 있으므로 이전에는 도메인별 모델이 필요했던 많은 첨단 개발자 사용 사례를 지원할 수 있습니다. Gemini의 비전 기능에는 다음과 같은 기능이 포함됩니다.
- 최대 90분 길이의 동영상을 설명, 세분화, 정보 추출
- 동영상 콘텐츠에 관한 질문에 답변하기
- 동영상 내 특정 타임스탬프 참조
Gemini는 처음부터 멀티모달로 빌드되었으며 Google은 계속해서 가능한 한계를 넓혀 나가고 있습니다. 이 가이드에서는 Gemini API를 사용하여 동영상 입력을 기반으로 텍스트 응답을 생성하는 방법을 보여줍니다.
시작하기 전에
Gemini API를 호출하기 전에 선택한 SDK가 설치되어 있고 Gemini API 키가 구성되어 있고 사용할 준비가 되었는지 확인합니다.
비디오 입력 장치
다음과 같은 방법으로 동영상을 Gemini에 입력으로 제공할 수 있습니다.
generateContent
에 요청하기 전에 File API를 사용하여 동영상 파일을 업로드합니다. 이 메서드는 20MB를 초과하는 파일, 약 1분을 초과하는 동영상 또는 여러 요청에서 파일을 재사용하려는 경우에 사용하세요.generateContent
에 대한 요청과 함께 인라인 동영상 데이터를 전달합니다. 이 방법은 파일 크기가 작고(20MB 미만) 기간이 짧은 경우에 사용합니다.- 프롬프트에 YouTube URL을 포함합니다.
동영상 파일 업로드
Files API를 사용하여 동영상 파일을 업로드할 수 있습니다. 총 요청 크기 (파일, 텍스트 프롬프트, 시스템 안내 등 포함)가 20MB를 초과하거나 동영상 길이가 상당하거나 여러 프롬프트에서 동일한 동영상을 사용할 계획인 경우 항상 Files API를 사용하세요.
File API는 동영상 파일 형식을 직접 허용합니다. 이 예에서는 NASA의 짧은 영화인 'Jupiter's Great Red Spot Shrinks and Grows'를 사용합니다. 저작자: 고다드 우주 비행 센터 (GSFC)/데이비드 래드 (2018)
'Jupiter's Great Red Spot Shrinks and Grows'는 공개 도메인이며 식별 가능한 사람이 표시되지 않습니다. (NASA 이미지 및 미디어 사용 가이드라인)
다음 코드는 샘플 동영상을 다운로드하고 File API를 사용하여 업로드한 후 처리될 때까지 기다린 다음 generateContent
요청에서 파일 참조를 사용합니다.
Python
from google import genai
client = genai.Client(api_key="GOOGLE_API_KEY")
myfile = client.files.upload(file="path/to/sample.mp4")
response = client.models.generate_content(
model="gemini-2.0-flash", contents=[myfile, "Summarize this video. Then create a quiz with an answer key based on the information in this video."]
)
print(response.text)
자바스크립트
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
async function main() {
const myfile = await ai.files.upload({
file: "path/to/sample.mp4",
config: { mimeType: "video/mp4" },
});
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: createUserContent([
createPartFromUri(myfile.uri, myfile.mimeType),
"Summarize this video. Then create a quiz with an answer key based on the information in this video.",
]),
});
console.log(response.text);
}
await main();
Go
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp4", nil)
if err != nil {
log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
genai.FileData{URI: file.URI},
genai.Text("Summarize this video. Then create a quiz with an answer key based on the information in this video."))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
REST
VIDEO_PATH="path/to/sample.mp4"
MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO
tmp_header_file=upload-header.tmp
echo "Starting file upload..."
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
-D ${tmp_header_file} \
-H "X-Goog-Upload-Protocol: resumable" \
-H "X-Goog-Upload-Command: start" \
-H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
-H "Content-Type: application/json" \
-d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null
upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"
echo "Uploading video data..."
curl "${upload_url}" \
-H "Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Offset: 0" \
-H "X-Goog-Upload-Command: upload, finalize" \
--data-binary "@${VIDEO_PATH}" 2> /dev/null > file_info.json
file_uri=$(jq -r ".file.uri" file_info.json)
echo file_uri=$file_uri
echo "File uploaded successfully. File URI: ${file_uri}"
# --- 3. Generate content using the uploaded video file ---
echo "Generating content from video..."
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"file_data":{"mime_type": "'"${MIME_TYPE}"'", "file_uri": "'"${file_uri}"'"}},
{"text": "Summarize this video. Then create a quiz with an answer key based on the information in this video."}]
}]
}' 2> /dev/null > response.json
jq -r ".candidates[].content.parts[].text" response.json
미디어 파일 작업에 관한 자세한 내용은 Files API를 참고하세요.
인라인으로 동영상 데이터 전달
File API를 사용하여 동영상 파일을 업로드하는 대신 generateContent
에 대한 요청에서 더 작은 동영상을 직접 전달할 수 있습니다. 총 요청 크기가 20MB 미만인 짧은 동영상에 적합합니다.
다음은 인라인 동영상 데이터를 제공하는 예입니다.
Python
# Only for videos of size <20Mb
video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()
response = client.models.generate_content(
model='models/gemini-2.0-flash',
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(data=video_bytes, mime_type='video/mp4')
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
자바스크립트
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const base64VideoFile = fs.readFileSync("path/to/small-sample.mp4", {
encoding: "base64",
});
const contents = [
{
inlineData: {
mimeType: "video/mp4",
data: base64VideoFile,
},
},
{ text: "Please summarize the video in 3 sentences." }
];
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: contents,
});
console.log(response.text);
REST
VIDEO_PATH=/path/to/your/video.mp4
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{
"inline_data": {
"mime_type":"video/mp4",
"data": "'$(base64 $B64FLAGS $VIDEO_PATH)'"
}
},
{"text": "Please summarize the video in 3 sentences."}
]
}]
}' 2> /dev/null
YouTube URL 포함
Gemini API 및 AI 스튜디오는 YouTube URL을 파일 데이터 Part
로 지원합니다. 모델에 동영상 콘텐츠를 요약하거나 번역하거나 다른 방식으로 상호작용하도록 요청하는 프롬프트와 함께 YouTube URL을 포함할 수 있습니다.
제한사항:
- 하루에 YouTube 동영상을 8시간 넘게 업로드할 수 없습니다.
- 요청당 동영상을 1개만 업로드할 수 있습니다.
- 비공개 또는 일부 공개 동영상이 아닌 공개 동영상만 업로드할 수 있습니다.
다음 예는 프롬프트에 YouTube URL을 포함하는 방법을 보여줍니다.
Python
response = client.models.generate_content(
model='models/gemini-2.0-flash',
contents=types.Content(
parts=[
types.Part(
file_data=types.FileData(file_uri='https://www.youtube.com/watch?v=9hE5-98ZeCg')
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
자바스크립트
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro" });
const result = await model.generateContent([
"Please summarize the video in 3 sentences.",
{
fileData: {
fileUri: "https://www.youtube.com/watch?v=9hE5-98ZeCg",
},
},
]);
console.log(result.response.text());
Go
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GOOGLE_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
genai.FileData{URI: "https://www.youtube.com/watch?v=9hE5-98ZeCg"},
genai.Text("Please summarize the video in 3 sentences."))
if err != nil {
log.Fatal(err)
}
// Handle the response of generated text.
for _, c := range resp.Candidates {
if c.Content != nil {
fmt.Println(*c.Content)
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "Please summarize the video in 3 sentences."},
{
"file_data": {
"file_uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
}
}
]
}]
}' 2> /dev/null
콘텐츠의 타임스탬프 참조
MM:SS
형식의 타임스탬프를 사용하여 동영상 내 특정 시점에 관해 질문할 수 있습니다.
Python
prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?" # Adjusted timestamps for the NASA video
자바스크립트
const prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?";
Go
prompt := []genai.Part{
genai.FileData{URI: currentVideoFile.URI, MIMEType: currentVideoFile.MIMEType},
// Adjusted timestamps for the NASA video
genai.Text("What are the examples given at 00:05 and " +
"00:10 supposed to show us?"),
}
REST
PROMPT="What are the examples given at 00:05 and 00:10 supposed to show us?"
동영상 스크립트 작성 및 시각적 설명 제공
Gemini 모델은 오디오 트랙과 시각적 프레임을 모두 처리하여 동영상 콘텐츠의 스크립트를 작성하고 시각적 설명을 제공할 수 있습니다. 시각적 설명의 경우 모델은 초당 1프레임의 속도로 동영상을 샘플링합니다. 이 샘플링 레이트는 특히 시각적 요소가 빠르게 변화하는 동영상의 경우 설명의 세부정보 수준에 영향을 줄 수 있습니다.
Python
prompt = "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."
자바스크립트
const prompt = "Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions.";
Go
prompt := []genai.Part{
genai.FileData{URI: currentVideoFile.URI, MIMEType: currentVideoFile.MIMEType},
genai.Text("Transcribe the audio from this video, giving timestamps for salient events in the video. Also " +
"provide visual descriptions."),
}
REST
PROMPT="Transcribe the audio from this video, giving timestamps for salient events in the video. Also provide visual descriptions."
지원되는 동영상 형식
Gemini는 다음과 같은 동영상 형식 MIME 유형을 지원합니다.
video/mp4
video/mpeg
video/mov
video/avi
video/x-flv
video/mpg
video/webm
video/wmv
video/3gpp
동영상에 관한 기술 세부정보
- 지원되는 모델 및 컨텍스트: 모든 Gemini 2.0 및 2.5 모델은 동영상 데이터를 처리할 수 있습니다.
- 컨텍스트 윈도우가 200만 개인 모델은 최대 2시간 길이의 동영상을 처리할 수 있고, 컨텍스트 윈도우가 100만 개인 모델은 최대 1시간 길이의 동영상을 처리할 수 있습니다.
- File API 처리: File API를 사용하면 동영상이 1프레임/초 (FPS)로 샘플링되고 오디오는 1Kbps (단일 채널)로 처리됩니다.
타임스탬프는 1초마다 추가됩니다.
- 이러한 비율은 추론 개선을 위해 향후 변경될 수 있습니다.
- 토큰 계산: 동영상의 각 초는 다음과 같이 토큰화됩니다.
- 개별 프레임 (1FPS로 샘플링됨): 프레임당 258개 토큰
- 오디오: 초당 32개 토큰
- 메타데이터도 포함됩니다.
- 총액: 동영상 1초당 약 300개의 토큰
- 타임스탬프 형식: 프롬프트 내에서 동영상의 특정 순간을 언급할 때는
MM:SS
형식을 사용하세요 (예:01:15
: 1분 15초 - 권장사항:
- 최적의 결과를 얻으려면 프롬프트 요청당 동영상을 하나만 사용하세요.
- 텍스트와 단일 동영상을 결합하는 경우
contents
배열에서 동영상 부분 뒤에 텍스트 프롬프트를 배치합니다. - 빠른 액션 시퀀스는 1FPS 샘플링 레이트로 인해 세부정보가 손실될 수 있습니다. 필요한 경우 이러한 클립의 속도를 늦추는 것이 좋습니다.
다음 단계
이 가이드에서는 동영상 파일을 업로드하고 동영상 입력에서 텍스트 출력을 생성하는 방법을 보여줍니다. 자세한 내용은 다음 리소스를 참고하세요.
- 시스템 안내: 시스템 안내를 사용하면 특정 요구사항 및 사용 사례에 따라 모델의 동작을 조정할 수 있습니다.
- Files API: Gemini에서 사용할 파일을 업로드하고 관리하는 방법을 자세히 알아보세요.
- 파일 프롬프트 전략: Gemini API는 텍스트, 이미지, 오디오, 동영상 데이터를 사용한 프롬프트(다중 모달 프롬프트라고도 함)를 지원합니다.
- 안전 가이드: 생성형 AI 모델이 부정확하거나 편향되거나 불쾌감을 주는 출력과 같이 예상치 못한 출력을 생성하는 경우가 있습니다. 이러한 출력으로 인한 피해 위험을 제한하려면 후처리 및 인간 평가가 필수적입니다.