Gemini 模型可處理影片,因此開發人員能運用許多前所未有的功能,這些功能過去需要使用特定領域的模型。Gemini 的部分影像功能包括:
- 描述、區隔影片並從中擷取資訊
- 回答影片內容相關問題
- 參照影片中的特定時間戳記
Gemini 從一開始就建構於多模態的基礎上,我們也持續拓展多模態技術的極限。本指南說明如何使用 Gemini API,根據影片輸入內容生成文字回覆。
視訊輸入裝置
你可以透過下列方式將影片提供給 Gemini:
- 使用 File API 上傳影片檔,然後再向
generateContent
發出要求。如果檔案大於 20 MB、影片長度超過約 1 分鐘,或您想在多個要求中重複使用檔案,請使用這個方法。 - 在對
generateContent
的要求中傳遞內嵌影片資料。如果檔案較小 (小於 20 MB) 且時間較短,請使用這個方法。 - 在
generateContent
要求中傳遞 YouTube 網址。
上傳影片檔案
你可以使用 Files API 上傳影片檔案。 如果要求總大小 (包括檔案、文字提示、系統指令等) 超過 20 MB、影片時間長度較長,或您打算在多個提示中使用相同影片,請一律使用 Files API。File API 可直接接受影片檔案格式。
下列程式碼會下載範例影片、使用 File API 上傳影片、等待處理完成,然後在 generateContent
要求中使用檔案參照。
Python
from google import genai
client = genai.Client()
myfile = client.files.upload(file="path/to/sample.mp4")
response = client.models.generate_content(
model="gemini-2.5-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({});
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.5-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
uploadedFile, _ := client.Files.UploadFromPath(ctx, "path/to/sample.mp4", nil)
parts := []*genai.Part{
genai.NewPartFromText("Summarize this video. Then create a quiz with an answer key based on the information in this video."),
genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
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" \
-H "x-goog-api-key: $GEMINI_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.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_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
from google import genai
from google.genai import types
# Only for videos of size <20Mb
video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()
client = genai.Client()
response = client.models.generate_content(
model='models/gemini-2.5-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({});
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.5-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.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_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 網址
您可以將 YouTube 網址直接傳遞至 Gemini API,做為generateContent
要求的一部分,如下所示:
Python
response = client.models.generate_content(
model='models/gemini-2.5-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-2.5-flash" });
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
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
parts := []*genai.Part{
genai.NewPartFromText("Please summarize the video in 3 sentences."),
genai.NewPartFromURI("https://www.youtube.com/watch?v=9hE5-98ZeCg","video/mp4"),
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_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
限制:
- 免費方案每天最多只能上傳 8 小時的 YouTube 影片。
- 付費方案則沒有影片長度限制。
- 如果是 Gemini 2.5 之前的模型,每次要求只能上傳 1 部影片。如果是 Gemini 2.5 以上版本,每個要求最多可上傳 10 部影片。
- 你只能上傳公開影片,無法上傳私人或不公開影片。
參考內容中的時間戳記
你可以使用 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.NewPartFromURI(currentVideoFile.URI, currentVideoFile.MIMEType),
// Adjusted timestamps for the NASA video
genai.NewPartFromText("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.NewPartFromURI(currentVideoFile.URI, currentVideoFile.MIMEType),
genai.NewPartFromText("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 API 中自訂影片處理作業。
設定剪輯間隔
您可以指定 videoMetadata
,並設定開始和結束偏移,即可剪輯影片。
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model='models/gemini-2.5-flash',
contents=types.Content(
parts=[
types.Part(
file_data=types.FileData(file_uri='https://www.youtube.com/watch?v=XEzRZ35urlk'),
video_metadata=types.VideoMetadata(
start_offset='1250s',
end_offset='1570s'
)
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
JavaScript
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({});
const model = 'gemini-2.5-flash';
async function main() {
const contents = [
{
role: 'user',
parts: [
{
fileData: {
fileUri: 'https://www.youtube.com/watch?v=9hE5-98ZeCg',
mimeType: 'video/*',
},
videoMetadata: {
startOffset: '40s',
endOffset: '80s',
}
},
{
text: 'Please summarize the video in 3 sentences.',
},
],
},
];
const response = await ai.models.generateContent({
model,
contents,
});
console.log(response.text)
}
await main();
設定自訂影格速率
您可以將 fps
引數傳遞至 videoMetadata
,藉此設定自訂影格速率取樣。
Python
from google import genai
from google.genai import types
# Only for videos of size <20Mb
video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()
client = genai.Client()
response = client.models.generate_content(
model='models/gemini-2.5-flash',
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(
data=video_bytes,
mime_type='video/mp4'),
video_metadata=types.VideoMetadata(fps=5)
),
types.Part(text='Please summarize the video in 3 sentences.')
]
)
)
系統預設會從影片中取樣每秒 1 個影格。如果是長片,建議將 FPS 設為低於 1。這項功能特別適合大部分為靜態的影片 (例如講座)。如要擷取快速變化的影像細節,建議設定較高的 FPS 值。
支援的影片格式
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 小時的影片 (預設媒體解析度),或長達 6 小時的影片 (低媒體解析度)。支援 100 萬個詞元的模型可以處理長達 1 小時的影片 (預設媒體解析度),或長達 3 小時的影片 (低媒體解析度)。
- File API 處理:使用 File API 時,影片會以每秒 1 個影格 (FPS) 的速度儲存,音訊則會以 1 Kbps (單一聲道) 的速度處理。系統每秒都會新增時間戳記。
- 為提升推論品質,這些費率日後可能會有所變動。
- 如要覆寫 1 FPS 的取樣率,請設定自訂影格速率。
- 符記計算:每秒影片會依下列方式轉換為符記:
- 個別影格 (以 1 FPS 取樣):
- 如果
mediaResolution
設為低,每個影格會產生 66 個權杖。 - 否則,每個影格會產生 258 個權杖。
- 如果
- 音訊:每秒 32 個權杖。
- 也包含中繼資料。
- 總計:預設媒體解析度下,每秒影片約 300 個權杖;低媒體解析度下,每秒影片約 100 個權杖。
- 個別影格 (以 1 FPS 取樣):
- 時間戳記格式:在提示中提及影片的特定時間點時,請使用
MM:SS
格式 (例如01:15
1 分 15 秒)。 - 最佳做法:
- 為求最佳效果,每個提示要求只能使用一部影片。
- 如果結合文字和單一影片,請將文字提示詞放在
contents
陣列的影片部分之後。 - 請注意,由於取樣率為每秒 1 幀,快速動作序列可能會遺失細節。如有需要,請考慮放慢這類片段的速度。
後續步驟
本指南說明如何上傳影片檔案,並從影片輸入內容生成文字輸出內容。如要進一步瞭解相關內容,請參閱下列資源: