การทำความเข้าใจวิดีโอ

โมเดล Gemini สามารถประมวลผลวิดีโอได้ ซึ่งทำให้นักพัฒนาแอปจำนวนมากสามารถใช้ Use Case ใหม่ๆ ได้ ซึ่งในอดีตต้องใช้โมเดลเฉพาะโดเมน ความสามารถบางอย่างของ Gemini ด้านภาพ ได้แก่

  • อธิบาย แบ่งกลุ่ม และดึงข้อมูลจากวิดีโอที่มีความยาวไม่เกิน 90 นาที
  • ตอบคำถามเกี่ยวกับเนื้อหาวิดีโอ
  • อ้างอิงการประทับเวลาที่ต้องการภายในวิดีโอ

Gemini สร้างขึ้นใหม่ทั้งหมดให้ทำงานได้หลายรูปแบบ และเราจะพัฒนาขีดความสามารถของโมเดลนี้ต่อไป คู่มือนี้จะแสดงวิธีใช้ Gemini API เพื่อสร้างคำตอบแบบข้อความตามอินพุตวิดีโอ

ก่อนเริ่มต้น

ก่อนเรียกใช้ Gemini API โปรดตรวจสอบว่าคุณได้ติดตั้ง SDK ที่ต้องการ รวมถึงกําหนดค่าคีย์ API ของ Gemini ให้พร้อมใช้งานแล้ว

วิดีโออินพุต

คุณส่งวิดีโอเป็นอินพุตให้ Gemini ได้ดังนี้

  • อัปโหลดไฟล์วิดีโอโดยใช้ File API ก่อนส่งคำขอไปยัง generateContent ใช้วิธีนี้กับไฟล์ที่มีขนาดใหญ่กว่า 20 MB, วิดีโอที่มีความยาวมากกว่า 1 นาทีโดยประมาณ หรือเมื่อคุณต้องการใช้ไฟล์ซ้ำในคำขอหลายรายการ
  • ส่งข้อมูลวิดีโอในบรรทัดพร้อมกับคำขอไปยัง generateContent ใช้วิธีนี้กับไฟล์ขนาดเล็ก (<20 MB) และระยะเวลาที่สั้นลง
  • ใส่ URL ของ YouTube โดยตรงในพรอมต์

อัปโหลดไฟล์วิดีโอ

คุณสามารถใช้ Files API เพื่ออัปโหลดไฟล์วิดีโอ ใช้ Files API เสมอเมื่อขนาดคำขอทั้งหมด (รวมถึงไฟล์ พรอมต์ข้อความ คำสั่งของระบบ ฯลฯ) มากกว่า 20 MB, ระยะเวลาของวิดีโอนานมาก หรือคุณตั้งใจจะใช้วิดีโอเดียวกันในพรอมต์หลายรายการ

File API ยอมรับรูปแบบไฟล์วิดีโอโดยตรง ตัวอย่างนี้ใช้ภาพยนตร์สั้นของ NASA เรื่อง"จุดแดงใหญ่ของดาวพฤหัสบดีหดเล็กและขยายใหญ่ขึ้น" เครดิต: ศูนย์การบินอวกาศก็อดดาร์ด (GSFC)/David Ladd (2018)

"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

ส่งข้อมูลวิดีโอในบรรทัด

คุณสามารถส่งวิดีโอขนาดเล็กในคำขอไปยัง generateContent ได้โดยตรงแทนการอัปโหลดไฟล์วิดีโอโดยใช้ File API ตัวเลือกนี้เหมาะสำหรับวิดีโอที่สั้นกว่าและมีขนาดคำขอรวมไม่เกิน 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

ใส่ URL ของ YouTube

Gemini API และ AI Studio รองรับ URL ของ YouTube เป็นข้อมูลไฟล์ Part คุณสามารถใส่ URL ของ YouTube พร้อมพรอมต์ที่ขอให้โมเดลสรุป แปล หรือโต้ตอบกับเนื้อหาวิดีโอ

ข้อจํากัด:

  • คุณอัปโหลดวิดีโอ YouTube ได้ไม่เกิน 8 ชั่วโมงต่อวัน
  • คุณอัปโหลดวิดีโอได้เพียง 1 รายการต่อคำขอ
  • คุณอัปโหลดได้เฉพาะวิดีโอสาธารณะ (ไม่ใช่วิดีโอส่วนตัวหรือที่ไม่เป็นสาธารณะ)

ตัวอย่างต่อไปนี้แสดงวิธีใส่ URL ของ 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 ทั้งหมดสามารถประมวลผลข้อมูลวิดีโอได้
    • โมเดลที่มีกรอบเวลาบริบท 2 ล้านรายการจะประมวลผลวิดีโอได้สูงสุด 2 ชั่วโมง ส่วนโมเดลที่มีกรอบเวลาบริบท 1 ล้านรายการจะประมวลผลวิดีโอได้สูงสุด 1 ชั่วโมง
  • การประมวลผล File API: เมื่อใช้ File API ระบบจะสุ่มตัวอย่างวิดีโอที่ 1 เฟรมต่อวินาที (FPS) และประมวลผลเสียงที่ 1 Kbps (ช่องเดียว) ระบบจะเพิ่มการประทับเวลาทุกวินาที
    • อัตราเหล่านี้อาจมีการเปลี่ยนแปลงในอนาคตเพื่อปรับปรุงการอนุมาน
  • การคํานวณโทเค็น: ระบบจะแบ่งวิดีโอแต่ละวินาทีออกเป็นโทเค็นดังนี้
    • เฟรมแต่ละเฟรม (สุ่มตัวอย่างที่ 1 FPS): โทเค็น 258 รายการต่อเฟรม
    • เสียง: 32 โทเค็นต่อวินาที
    • รวมถึงข้อมูลเมตาด้วย
    • รวม: ประมาณ 300 โทเค็นต่อวินาทีของวิดีโอ
  • รูปแบบการประทับเวลา: เมื่ออ้างอิงถึงช่วงเวลาที่เฉพาะเจาะจงในวิดีโอภายในพรอมต์ ให้ใช้รูปแบบ MM:SS (เช่น 01:15 เป็นเวลา 1 นาที 15 วินาที)
  • แนวทางปฏิบัติแนะนำ
    • ใช้วิดีโอเพียงรายการเดียวต่อคำขอพรอมต์เพื่อให้ได้ผลลัพธ์ที่ดีที่สุด
    • หากรวมข้อความและวิดีโอรายการเดียว ให้วางพรอมต์ข้อความหลังส่วนวิดีโอในอาร์เรย์ contents
    • โปรดทราบว่าซีเควนซ์การเคลื่อนไหวที่รวดเร็วอาจสูญเสียรายละเอียดเนื่องจากอัตราการสุ่มตัวอย่าง 1 FPS พิจารณาที่จะเล่นคลิปดังกล่าวช้าลงหากจำเป็น

ขั้นตอนถัดไป

คู่มือนี้จะแสดงวิธีอัปโหลดไฟล์วิดีโอและสร้างเอาต์พุตข้อความจากอินพุตวิดีโอ ดูข้อมูลเพิ่มเติมได้ที่แหล่งข้อมูลต่อไปนี้

  • คำสั่งของระบบ: คำสั่งของระบบช่วยให้คุณควบคุมลักษณะการทํางานของโมเดลตามความต้องการและกรณีการใช้งานที่เฉพาะเจาะจงได้
  • Files API: ดูข้อมูลเพิ่มเติมเกี่ยวกับการอัปโหลดและจัดการไฟล์เพื่อใช้กับ Gemini
  • กลยุทธ์การแจ้งไฟล์: Gemini API รองรับการแจ้งด้วยข้อมูลข้อความ รูปภาพ เสียง และวิดีโอ หรือที่เรียกว่าการแจ้งแบบหลายสื่อ
  • คำแนะนำด้านความปลอดภัย: บางครั้งโมเดล Generative AI อาจให้ผลลัพธ์ที่ไม่คาดคิด เช่น ผลลัพธ์ที่ไม่ถูกต้อง มีอคติ หรือไม่เหมาะสม ขั้นตอนหลังการประมวลผลและการประเมินจากเจ้าหน้าที่เป็นสิ่งจําเป็นในการจำกัดความเสี่ยงของอันตรายจากเอาต์พุตดังกล่าว