Gemini 模型可處理影片,因此開發人員可利用許多前衛的開發案例,而這些案例在過去需要專門的領域模型。Gemini 的視覺功能包括:
- 描述、分割及擷取長達 90 分鐘的影片資訊
- 回答影片內容相關問題
- 參照影片中的特定時間戳記
Gemini 從一開始就以多模態為設計宗旨,我們會持續突破 AI 技術的極限。本指南說明如何使用 Gemini API,根據影片輸入內容產生文字回應。
事前準備
呼叫 Gemini API 前,請確認您已安裝所選 SDK,並設定 Gemini API 金鑰,以便使用。
視訊輸入裝置
您可以透過下列方式,將影片做為 Gemini 的輸入內容:
- 請先使用 File API 上傳影片檔案,再向
generateContent
提出要求。請在檔案大小超過 20 MB、影片長度超過約 1 分鐘,或您想在多個要求中重複使用檔案時,使用這項方法。 - 透過請求傳遞內嵌式影片資料至
generateContent
。請將這個方法用於較小的檔案 (小於 20 MB) 和較短的時間。 - 直接在提示中加入 YouTube 網址。
上傳影片檔案
您可以使用 Files API 上傳影片檔案。如果總要求大小 (包括檔案、文字提示、系統指示等) 超過 20 MB、影片長度相當長,或您打算在多個提示中使用相同的影片,請一律使用 Files API。
File API 可直接接受影片檔案格式。本範例使用 NASA 的短片「Jupiter's Great Red Spot Shrinks and Grows」。圖片來源:Goddard Space Flight Center (GSFC)/David Ladd (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)
JavaScript
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
。這類影片的總要求大小應低於 20 MB,
以下是提供內嵌影片資料的範例:
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.')
]
)
)
JavaScript
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 網址
Gemini API 和 AI Studio 支援 YouTube 網址做為檔案資料 Part
。您可以加入 YouTube 網址,並在提示中要求模型摘要、翻譯或以其他方式與影片內容互動。
限制:
- 每天最多只能上傳 8 小時的 YouTube 影片。
- 每次提出要求只能上傳 1 部影片。
- 你只能上傳公開影片 (不得為私人或不公開影片)。
以下範例說明如何在提示中加入 YouTube 網址:
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.')
]
)
)
JavaScript
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
JavaScript
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."
JavaScript
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) 的速度取樣影片,並以 1 Kbps (單一頻道) 的速度處理音訊。每秒會新增一個時間戳記。
- 這些費率日後可能會因推論功能的改善而有所變動。
- 符記計算:每秒的影片會以以下方式轉為符記:
- 個別影格 (以 1 FPS 取樣):每影格 258 個符記。
- 音訊:每秒 32 個符記。
- 中繼資料也包含在內。
- 總數:每秒影片約 300 個符記。
- 時間戳記格式:在提示中提及影片中的特定片段時,請使用
MM:SS
格式 (例如01:15
代表 1 分 15 秒)。 - 最佳做法:
- 為取得最佳結果,請每個提示請求只使用一支影片。
- 如果要結合文字和單一影片,請將文字提示放在
contents
陣列中的影片部分後方。 - 請注意,由於 1 FPS 取樣率,快速動作序列可能會遺失細節。如有需要,請考慮放慢這類短片的速度。
後續步驟
本指南說明如何上傳影片檔案,以及從影片輸入內容產生文字輸出內容。如要進一步瞭解相關內容,請參閱下列資源: