درک ویدیو

برای آشنایی با تولید ویدیو، راهنمای Gemini Omni Flash را ببینید.

مدل‌های Gemini می‌توانند ویدیوها را پردازش کنند و امکان استفاده از موارد کاربرد توسعه‌دهندگان پیشرو را فراهم کنند که در گذشته نیازمند مدل‌های خاص دامنه بودند. برخی‌از قابلیت‌های دیداری Gemini عبارت‌اند از: توانایی توصیف، بخش‌بندی، و استخراج اطلاعات از ویدیوها، پاسخ به سؤالات درباره محتوای ویدیو، و ارجاع به مُهرهای زمانی خاص در یک ویدیو.

می‌توانید به روش‌های زیر ویدیو را به‌عنوان ورودی به Gemini ارائه دهید:

روش ورودی حداکثر اندازه مورد استفاده توصیه‌شده
File API ‫۲۰ گیگابایت (پولی) / ۲ گیگابایت (رایگان) فایل‌های بزرگ (بیش‌از ۱۰۰ مگابایت)، ویدیوهای طولانی (بیش‌از ۱۰ دقیقه)، فایل‌های قابل‌استفاده مجدد.
ثبت فضای ذخیره‌سازی ابری ‫۲ گیگابایت (برای هر فایل، بدون محدودیت فضای ذخیره‌سازی) فایل‌های بزرگ (بیش‌از ۱۰۰ مگابایت)، ویدیوهای طولانی (بیش‌از ۱۰ دقیقه)، فایل‌های ماندگار و قابل‌استفاده مجدد.
داده‌های درون‌خطی ‫< ۱۰۰ مگابایت فایل‌های کوچک (کمتر از ۱۰۰ مگابایت)، مدت کوتاه (کمتر از ۱ دقیقه)، ورودی‌های یک‌باره.
نشانی‌های وب YouTube موجود نیست ویدیوهای عمومی YouTube.

توجه: File API برای اکثر موارد استفاده توصیه می‌شود، به‌ویژه برای فایل‌های بزرگ‌تر از ۱۰۰ مگابایت یا زمانی که می‌خواهید از فایل در چندین درخواست مجدداً استفاده کنید.

برای آشنایی با دیگر روش‌های ورودی فایل، مثل استفاده از نشانی‌های وب خارجی یا فایل‌های ذخیره‌شده در Google Cloud، به راهنمای روش‌های ورودی فایل مراجعه کنید.

بارگذاری فایل ویدیویی

کد زیر یک ویدیو نمونه را بارگیری می‌کند، آن را بااستفاده از Files API بارگذاری می‌کند، منتظر می‌ماند تا پردازش شود، و سپس از مرجع فایل بارگذاری‌شده برای خلاصه کردن ویدیو استفاده می‌کند.

Python

from google import genai
import time

client = genai.Client()

myfile = client.files.upload(file="path/to/sample.mp4")

while not myfile.state or myfile.state.name != "ACTIVE":
    print("Processing video...")
    time.sleep(5)
    myfile = client.files.get(name=myfile.name)

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "video", "uri": myfile.uri, "mime_type": myfile.mime_type},
        {"type": "text", "text": "Summarize this video. Then create a quiz with an answer key based on the information in this video."}
    ]
)

print(interaction.output_text)

JavaScript

import { GoogleGenAI } 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" },
  });

  let getFile = await ai.files.get({ name: myfile.name });
  while (getFile.state === 'PROCESSING') {
      getFile = await ai.files.get({ name: myfile.name });
      console.log(`current file status: ${getFile.state}`);
      console.log('File is still processing, retrying in 5 seconds');

      await new Promise((resolve) => {
          setTimeout(resolve, 5000);
      });
  }
  if (getFile.state === 'FAILED') {
      throw new Error('File processing failed.');
  }

  const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input: [
      { type: "video", uri: myfile.uri, mime_type: myfile.mimeType },
      { type: "text", text: "Summarize this video. Then create a quiz with an answer key based on the information in this video." }
    ],
  });
  console.log(interaction.output_text);
}

await main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.File;
import com.google.genai.types.FileState;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

File myfile =
    client.files.upload(
        "path/to/sample.mp4", UploadFileConfig.builder().mimeType("video/mp4").build());

while (!myfile.state().isPresent()
    || myfile.state().get().knownEnum() != FileState.Known.ACTIVE) {
  System.out.println("Processing video...");
  Thread.sleep(5000);
  myfile = client.files.get(myfile.name().get(), null);
}

Content videoContent =
    VideoContent.builder()
        .uri(myfile.uri().get())
        .mimeType(VideoContentMimeType.of(myfile.mimeType().get()))
        .build();
Content textContent =
    TextContent.builder()
        .text(
            "Summarize this video. Then create a quiz with an answer key based on the information in this video.")
        .build();

List<Content> contents = Arrays.asList(videoContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

رفتن

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    myfile, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp4", &genai.UploadFileConfig{
        MIMEType: "video/mp4",
    })
    if err != nil {
        log.Fatal(err)
    }

    for myfile.State != genai.FileStateActive {
        fmt.Println("Processing video...")
        time.Sleep(5 * time.Second)
        myfile, err = client.Files.Get(ctx, myfile.Name, nil)
        if err != nil {
            log.Fatal(err)
        }
    }

    contents := []interactions.Content{
        interactions.NewContent(interactions.VideoContent{
            URI:      genai.Ptr(myfile.URI),
            MimeType: interactions.VideoContentMimeType(myfile.MIMEType).ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: "Summarize this video. Then create a quiz with an answer key based on the information in this video.",
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

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)
file_name=$(jq -r ".file.name" file_info.json)
echo file_uri=$file_uri

echo "File uploaded successfully. File URI: ${file_uri}"

# Polling loop
echo "Waiting for file to be processed..."
while true; do
  curl -s "https://generativelanguage.googleapis.com/v1beta/${file_name}" \
    -H "x-goog-api-key: $GEMINI_API_KEY" > file_status.json
  state=$(jq -r ".state" file_status.json)
  echo "Current state: $state"
  if [ "$state" == "ACTIVE" ]; then
    break
  elif [ "$state" == "FAILED" ]; then
    echo "File processing failed."
    exit 1
  fi
  sleep 5
done

echo "Generating content from video..."
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "video", "uri": "'${file_uri}'", "mime_type": "'${MIME_TYPE}'"},
        {"type": "text", "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 ".steps[].content[0].text" response.json

برای بهینه‌سازی کارایی و عملکرد توکن، استفاده از پردازش ویدیو Agentic را درنظر بگیرید.

همیشه وقتی اندازه کل درخواست (شامل فایل، پیام‌واره نوشتاری، دستورالعمل‌های سیستم، و غیره) بزرگ‌تر از ۲۰ مگابایت است، مدت ویدیو قابل‌توجه است، یا اگر قصد دارید از ویدیو یکسانی در پیام‌واره‌های متعددی استفاده کنید، از «میانای برنامه‌سازی کاربردی فایل‌ها» استفاده کنید. File API قالب‌های فایل ویدیویی را مستقیماً می‌پذیرد.

برای کسب اطلاعات بیشتر درباره کار با فایل‌های رسانه‌ای، Files API را ببینید.

انتقال داده‌های ویدیو به‌صورت درون‌خطی

به‌جای بارگذاری فایل ویدیو بااستفاده از «میانای برنامه‌سازی کاربردی فایل»، می‌توانید ویدیوهای کوچک‌تر را مستقیماً در درخواست ارسال کنید. این روش برای ویدیوهای کوتاه‌تر با اندازه کل درخواست کمتر از ۲۰ مگابایت مناسب است.

در اینجا نمونه‌ای از ارائه داده‌های ویدیو درون‌خطی آورده شده است:

Python

from google import genai
import base64

video_file_name = "/path/to/your/video.mp4"
video_bytes = open(video_file_name, 'rb').read()

client = genai.Client()
interaction = client.interactions.create(
    model='gemini-3.8-flash',
    input=[
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
            "type": "video",
            "data": base64.b64encode(video_bytes).decode('utf-8'),
            "mime_type": "video/mp4"
        }
    ]
)
print(interaction.output_text)

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 interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    { type: "text", text: "Please summarize the video in 3 sentences." },
    {
      type: "video",
      data: base64VideoFile,
      mime_type: "video/mp4",
    }
  ],
});
console.log(interaction.output_text);

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

String videoFileName = "/path/to/your/video.mp4";
byte[] videoBytes = Files.readAllBytes(Paths.get(videoFileName));
String base64Video = Base64.getEncoder().encodeToString(videoBytes);

Client client = new Client();

Content textContent =
    TextContent.builder().text("Please summarize the video in 3 sentences.").build();
Content videoContent =
    VideoContent.builder()
        .data(base64Video)
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    videoFileName := "/path/to/your/video.mp4"
    videoBytes, err := os.ReadFile(videoFileName)
    if err != nil {
        log.Fatal(err)
    }
    base64Video := base64.StdEncoding.EncodeToString(videoBytes)

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: "Please summarize the video in 3 sentences.",
        }),
        interactions.NewContent(interactions.VideoContent{
            Data:     genai.Ptr(base64Video),
            MimeType: interactions.VideoContentMimeTypeVideoMp4.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

REST

VIDEO_PATH=/path/to/your/video.mp4

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
          "type": "video",
          "data": "'$(base64 $B64FLAGS $VIDEO_PATH)'",
          "mime_type": "video/mp4"
        }
      ]
    }' 2> /dev/null

نشانی‌های وب YouTube را ارسال کنید

می‌توانید نشانی‌های وب YouTube را مستقیماً به‌عنوان بخشی از درخواست خود به Gemini API ارسال کنید:

Python

from google import genai

client = genai.Client()
interaction = client.interactions.create(
    model='gemini-3.8-flash',
    input=[
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
            "type": "video",
            "uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
        }
    ]
)
print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    { type: "text", text: "Please summarize the video in 3 sentences." },
    {
      type: "video",
      uri: "https://www.youtube.com/watch?v=9hE5-98ZeCg",
    }
  ],
});
console.log(interaction.output_text);

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

Content textContent =
    TextContent.builder().text("Please summarize the video in 3 sentences.").build();
Content videoContent =
    VideoContent.builder()
        .uri("https://www.youtube.com/watch?v=9hE5-98ZeCg")
        .build();

List<Content> contents = Arrays.asList(textContent, videoContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3.8-flash"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

رفتن

package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: "Please summarize the video in 3 sentences.",
        }),
        interactions.NewContent(interactions.VideoContent{
            URI: genai.Ptr("https://www.youtube.com/watch?v=9hE5-98ZeCg"),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3.8-flash"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3.8-flash",
      "input": [
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {
          "type": "video",
          "uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"
        }
      ]
    }' 2> /dev/null

محدودیت‌ها:

  • در سطح رایگان، نمی‌توانید بیش‌از ۸ ساعت ویدیو YouTube در روز بارگذاری کنید.
  • برای سطح پولی، هیچ محدودیتی براساس طول ویدیو وجود ندارد.
  • برای مدل‌های قبل‌از Gemini 2.5، فقط می‌توانید ۱ ویدیو در هر درخواست بارگذاری کنید. برای Gemini 2.5 و مدل‌های جدیدتر، می‌توانید حداکثر ۱۰ ویدیو در هر درخواست بارگذاری کنید.
  • فقط می‌توانید ویدیوهای عمومی بارگذاری کنید (نه ویدیوهای خصوصی یا فهرست‌نشده).

درک عامل‌گرایانه ویدیو

به‌طور پیش‌فرض، ورودی‌های ویدیو از پردازش ایستا (استخراج فریم‌ها با نرخ ۱ فریم در ثانیه) در همه مدل‌ها، ازجمله Gemini 4، استفاده می‌کنند. مدل‌های Gemini 4 Argon،‏ 3.8 Flash،‏ 3.6 Flash، و 3.5 Flash Lite نیز از درک ویدیو عامل‌محور پشتیبانی می‌کنند، حالت موافقت‌نامه‌ای که در آن مدل به‌صورت پویا جدول زمانی ویدیو را کاوش می‌کند، ترانویسی‌ها را به‌صورت انتخابی بازرسی می‌کند، و نرخ‌های فریم و وضوح را به‌صورت تطبیقی و در لحظه براساس پیام‌واره تنظیم می‌کند.

حالت شرح مدل‌های پشتیبانی‌شده
ثابت (پیش‌فرض) قاب‌ها را با نرخ ثابت (۱ قاب در ثانیه) استخراج می‌کند و آن‌ها را در یک گذر در بافت قرار می‌دهد. پیش‌فرض برای همه مدل‌های Gemini، ازجمله Gemini 4. همه مدل‌های Gemini
Agentic مدل به‌طور پویا در خط زمان ویدیو پیمایش می‌کند و فقط محتوایی را که براساس پیام‌واره نیاز دارد بار می‌کند. تا ۸۸٪ کارایی بیشتر در استفاده از توکن و حدود ۷٪ کیفیت بالاتر در محتوای طولانی. ‫Gemini 4 Argon،‏ 3.8 Flash،‏ 3.6 Flash،‏ 3.5 Flash Lite

انتخاب حالت پردازش

حالت پردازشی را که با طول ویدیو و نوع پُرسمان شما مطابقت دارد انتخاب کنید:

  • ایستا (پیش‌فرض): بهترین گزینه برای کلیپ‌های کوتاه (زیر ۵ دقیقه)، خلاصه‌های کلی از کل ویدیو که در آن کل ضبط مرتبط است، پُرسمان‌های حساس به تأخیر، یا دقت در سطح فریم در کل کلیپ. در ویدیوهای کوتاه یا پیام‌واره‌های گسترده‌ای که نیاز به بازرسی بیشتر ویدیو دارند، پردازش ایستا از نشانه‌های فکری اضافی (total_thought_tokens) و رفت‌وبرگشت‌های فراخوانی ابزار (total_tool_use_tokens) که ناشی از پیمایش خط زمان است جلوگیری می‌کند.
  • عامل‌محور: بهترین برای ویدیوهای طولانی (بیش‌از ۵ تا ۱۰ دقیقه)، بازیابی سوزن در انبار کاه، یا پُرسمان‌هایی که لحظات یا موضوعات خاصی را هدف‌یابی می‌کنند. این مدل ابتدا ترانویسی‌ها را بررسی می‌کند و فقط بخش‌های دیداری مربوطه را درصورت درخواست بار می‌کند، که این امر مصرف کد واحد ورودی ویدیو را تا ۸۸٪ کاهش می‌دهد بدون اینکه پنجره بافت را پر کند.

توجه: برای ویدیوهای طولانی یا پیام‌واره‌های پیچیده که پردازش عامل‌محور زمان بیشتری می‌برد، از جاری‌سازی (stream=True) یا اجرای پس‌زمینه (background=True) استفاده کنید. این کار اتصال را فعال نگه می‌دارد، مراحل استدلال میانی را نشان می‌دهد، و از اتمام زمان اتصال یا اصالت‌سنجی جلوگیری می‌کند.

تنظیم حالت پردازش

برای استفاده از درک ویدیو عاملی، "processing": "agentic" را روی بخش ویدیو در آرایه input تنظیم کنید.

پردازش ویدیو با عامل هوش مصنوعی ممکن است برای ویدیوهای طولانی بیشتر طول بکشد زیرا مدل برای پیمایش خط زمان چندین بار بازرسی انجام می‌دهد. برای جلوگیری از ازدست رفتن پیشرفت درصورت قطع اتصال شبکه، این نمونه از background=True برای اجرای ناهمگام تکلیف در سرور استفاده می‌کند. همچنین می‌توانید درخواست‌ها را به‌صورت هم‌زمان و بدون اجرای پس‌زمینه با حذف پارامتر background اجرا کنید که برای ویدیوهای کوتاه‌تر به‌خوبی کار می‌کند.

برای جزئیات مربوط به نظرسنجی، بازیابی نتایج، و مدیریت کردن تکالیف پس‌زمینه، راهنمای اجرا در پس‌زمینه را ببینید.

Python

import time
from google import genai

client = genai.Client()

# Upload a long video
video_file = client.files.upload(file="path/to/lecture.mp4")

while video_file.state.name == "PROCESSING":
    time.sleep(2)
    video_file = client.files.get(name=video_file.name)

# Use agentic processing with background execution
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": "agentic"
        },
        {"type": "text", "text": "What are the three main arguments presented?"}
    ],
    background=True,
)

while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(interaction.id)

print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

// Upload a long video
let videoFile = await ai.files.upload({
  file: "path/to/lecture.mp4",
  config: { mimeType: "video/mp4" }
});

while (videoFile.state === "PROCESSING") {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  videoFile = await ai.files.get({ name: videoFile.name });
}

// Use agentic processing with background execution
let interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: "agentic"
    },
    { type: "text", text: "What are the three main arguments presented?" }
  ],
  background: true,
});

while (interaction.status === "in_progress") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  interaction = await ai.interactions.get(interaction.id);
}

console.log(interaction.output_text);

REST

# 1. Start the interaction in the background
interaction=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": "agentic"
      },
      {"type": "text", "text": "What are the three main arguments presented?"}
    ],
    "background": true
  }')

id=$(echo "$interaction" | jq -r '.id')

# 2. Poll until the interaction finishes
while [ "$(echo "$interaction" | jq -r '.status')" = "in_progress" ]; do
  sleep 5
  interaction=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$id" \
    -H "x-goog-api-key: $GEMINI_API_KEY")
done

echo "$interaction" | jq '.'

توجه: برای تأیید اینکه از پردازش عامل‌گرا استفاده شده است، interaction.steps را بررسی کنید. وجود processing_call و processing_result نشان می‌دهد که مدل به‌صورت پویا در ویدیو پیمایش کرده است.

مراحل پاسخ

پردازش عامل دو نوع مرحله جدید به آرایه steps اضافه می‌کند:

  • ‫processing_call: مدل بخش ویدیویی یا ترانویسی صوتی را که با id شناسایی شده است درخواست کرد.
  • ‫processing_result: نتیجه آن بار، پیوندشده توسط call_id.

این‌ها به‌صورت درهم‌تنیده با مراحل thought (وقتی خلاصه‌ها فعال باشند) ظاهر می‌شوند و قبل‌از مرحله نهایی model_output قرار می‌گیرند. از این اعلان‌ها می‌توان برای نشان دادن رد پیشرفت در واسط کاربر استفاده کرد، اما نیازی به پاسخ ندارند.

نمونه زیر بار پاسخ را با مراحل پردازش درهم‌بافته نشان می‌دهد:

{
  "steps": [
    {
      "type": "thought",
      "signature": "sig_thought_1",
      "summary": [
        {
          "type": "text",
          "text": "Inspecting transcript for key discussion topics..."
        }
      ]
    },
    {
      "type": "processing_call",
      "id": "call_01",
      "signature": "sig_call_01"
    },
    {
      "type": "processing_result",
      "call_id": "call_01",
      "signature": "sig_result_01"
    },
    {
      "type": "thought",
      "signature": "sig_thought_2",
      "summary": [
        {
          "type": "text",
          "text": "Loading visual frames to verify slide content..."
        }
      ]
    },
    {
      "type": "processing_call",
      "id": "call_02",
      "signature": "sig_call_02"
    },
    {
      "type": "processing_result",
      "call_id": "call_02",
      "signature": "sig_result_02"
    },
    {
      "type": "thought",
      "signature": "sig_thought_3",
      "summary": [
        {
          "type": "text",
          "text": "Synthesizing answer from gathered evidence..."
        }
      ]
    },
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "The three main arguments presented in the lecture are..."
        }
      ]
    }
  ]
}

ترکیب حالت‌های پردازش در ویدیوها

تنظیم حالت‌های پردازش مختلف برای هر ویدیو در یک درخواست:

Python

import time
from google import genai

client = genai.Client()

lecture = client.files.upload(file="path/to/long-lecture.mp4")
experiment = client.files.upload(file="path/to/short-experiment.mp4")

# Use agentic processing with background execution
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": lecture.uri,
            "mime_type": lecture.mime_type,
            "processing": "agentic"  # Use agentic video understanding
        },
        {
            "type": "video",
            "uri": experiment.uri,
            "mime_type": experiment.mime_type,
            "processing": "static"  # Use static processing
        },
        {"type": "text", "text": "Compare the lecture content with the experiment results."}
    ],
    background=True,
)

while interaction.status == "in_progress":
    time.sleep(5)
    interaction = client.interactions.get(interaction.id)

print(interaction.output_text)

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const lecture = await ai.files.upload({
  file: "path/to/long-lecture.mp4",
  config: { mimeType: "video/mp4" }
});
const experiment = await ai.files.upload({
  file: "path/to/short-experiment.mp4",
  config: { mimeType: "video/mp4" }
});

// Use agentic processing with background execution
let interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: lecture.uri,
      mime_type: lecture.mimeType,
      processing: "agentic" // Use agentic video understanding
    },
    {
      type: "video",
      uri: experiment.uri,
      mime_type: experiment.mimeType,
      processing: "static" // Use static processing
    },
    { type: "text", text: "Compare the lecture content with the experiment results." }
  ],
  background: true,
});

while (interaction.status === "in_progress") {
  await new Promise((resolve) => setTimeout(resolve, 5000));
  interaction = await ai.interactions.get(interaction.id);
}

console.log(interaction.output_text);

REST

# 1. Start the interaction in the background
interaction=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${lecture_uri}'",
        "mime_type": "video/mp4",
        "processing": "agentic"
      },
      {
        "type": "video",
        "uri": "'${experiment_uri}'",
        "mime_type": "video/mp4",
        "processing": "static"
      },
      {"type": "text", "text": "Compare the lecture content with the experiment results."}
    ],
    "background": true
  }')

id=$(echo "$interaction" | jq -r '.id')

# 2. Poll until the interaction finishes
while [ "$(echo "$interaction" | jq -r '.status')" = "in_progress" ]; do
  sleep 5
  interaction=$(curl -s "https://generativelanguage.googleapis.com/v1beta/interactions/$id" \
    -H "x-goog-api-key: $GEMINI_API_KEY")
done

echo "$interaction" | jq '.'

مکالمه‌های ویدیویی چندنوبتی

بافت ویدیو درطول نوبت‌ها در مکالمه حفظ می‌شود. هنگام استفاده از پردازش عاملی:

  • حالت Stateful (بااستفاده از previous_interaction_id): سرور بافت ویدیو را حفظ می‌کند. نیازی به رسیدگی بیشتر نیست.
  • حالت عدم حفظ سابقه (بااستفاده از step_list): در حالت عدم حفظ سابقه، پاسخ شامل مراحل processing_call و processing_result است که بافت ویدیو را رمزگذاری می‌کند. برای حفظ بافت ویدیو، باید همه مراحل پاسخ را در step_list درخواست بعدی‌تان بگنجانید. اگرچه حذف آن‌ها درحال‌حاضر خطای API برنمی‌گرداند، اما با این کار بافت ویدیو ازدست می‌رود و کیفیت پاسخ به سؤالات بعدی به‌طور قابل‌توجهی کاهش می‌یابد. توجه داشته باشید که مراحل برگردانده‌شده که در درخواست‌های بعدی ارسال می‌شوند، به تعداد داده‌واحد ورودی اضافه می‌شوند.

به مُهرهای زمان در محتوا مراجعه کنید

می‌توانید درباره نقاط زمانی خاصی در ویدیو بااستفاده از مُهرهای زمان به شکل MM:SS سؤال بپرسید.

Python

prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?"

JavaScript

const prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?";

جاوا

String prompt = "What are the examples given at 00:05 and 00:10 supposed to show us?";

رفتن

prompt := "What are the examples given at 00:05 and 00:10 supposed to show us?"

استراحت

PROMPT="What are the examples given at 00:05 and 00:10 supposed to show us?"

استخراج اطلاعات آماری دقیق از ویدیو

مدل‌های Gemini با پردازش اطلاعات از هر دو جریان صوتی و تصویری، قابلیت‌های قدرتمندی برای درک محتوای ویدیویی ارائه می‌دهند. این به شما امکان می‌دهد مجموعه غنی‌ای از جزئیات را استخراج کنید، ازجمله تولید شرح درباره آنچه در ویدیو اتفاق می‌افتد و پاسخ دادن به سؤالات درباره محتوای آن.

برای شرح‌های تصویری، مدل ویدیو را با نرخ ۱ فریم در ثانیه (FPS) نمونه‌برداری می‌کند. این نرخ نمونه‌برداری پیش‌فرض برای اکثر محتواها به‌خوبی کار می‌کند، اما توجه داشته باشید که ممکن است جزئیات ویدیوهایی با حرکت سریع یا تغییرات صحنه سریع را ازدست بدهد.

Python

prompt = "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments."

JavaScript

const prompt = "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments.";

جاوا

String prompt =
    "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments.";

رفتن

prompt := "Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments."

استراحت

PROMPT="Describe the key events in this video, providing both audio and visual details. Include timestamps for salient moments."

سفارشی‌سازی پردازش ویدیو

می‌توانید پردازش ویدیو را در Gemini API با تنظیم فواصل برش یا ارائه نمونه‌برداری نرخ فریم سفارشی، سفارشی‌سازی کنید. این گزینه‌های سفارشی‌سازی فقط هنگام پردازش ویدیو در حالت "static" پشتیبانی می‌شوند.

تنظیم فواصل برش

می‌توانید با مشخص کردن start_offset و end_offset در شیء پیکربندی processing، ویدیو را برش دهید.

Python

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": {
                "type": "static",
                "start_offset": 1200,
                "end_offset": 1500,
            },
        },
        {"type": "text", "text": "Summarize this section of the video."},
    ],
)
print(interaction.output_text)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: {
        type: "static",
        start_offset: 1200,
        end_offset: 1500,
      },
    },
    { type: "text", text: "Summarize this section of the video." },
  ],
});
console.log(interaction.output_text);

استراحت

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": {
          "type": "static",
          "start_offset": 1200,
          "end_offset": 1500
        }
      },
      {"type": "text", "text": "Summarize this section of the video."}
    ]
  }' 2> /dev/null

تنظیم نرخ فریم سفارشی

می‌توانید با ارسال آرگومان fps در شیء پیکربندی processing، نمونه‌برداری نرخ فریم سفارشی تنظیم کنید.

Python

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": video_file.uri,
            "mime_type": video_file.mime_type,
            "processing": {
                "type": "static",
                "fps": 0.5,  # Sample 1 frame every 2 seconds
            },
        },
        {"type": "text", "text": "Describe the scene changes in this video."},
    ],
)
print(interaction.output_text)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-3.8-flash",
  input: [
    {
      type: "video",
      uri: videoFile.uri,
      mime_type: videoFile.mimeType,
      processing: {
        type: "static",
        fps: 0.5, // Sample 1 frame every 2 seconds
      },
    },
    { type: "text", text: "Describe the scene changes in this video." },
  ],
});
console.log(interaction.output_text);

استراحت

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3.8-flash",
    "input": [
      {
        "type": "video",
        "uri": "'${file_uri}'",
        "mime_type": "video/mp4",
        "processing": {
          "type": "static",
          "fps": 0.5
        }
      },
      {"type": "text", "text": "Describe the scene changes in this video."}
    ]
  }' 2> /dev/null

قالب‌های ویدیویی پشتیبانی‌شده

‫Gemini از انواع رسانه : نوع MIME قالب ویدیو زیر پشتیبانی می‌کند:

  • video/mp4
  • video/mpeg
  • video/mov
  • video/avi
  • video/x-flv
  • video/mpg
  • video/webm
  • video/wmv
  • video/3gpp

جزئیات فنی درباره ویدیوها

  • مدل‌ها و بافت‌های پشتیبانی‌شده: همه مدل‌های Gemini می‌توانند داده‌های ویدیویی را پردازش کنند.
    • مدل‌های دارای پنجره بافت ۱ میلیون داده‌واحدی می‌توانند ویدیوهای حداکثر ۳ ساعته را به‌طور پیش‌فرض (با وضوح پایین رسانه) یا ویدیوهای حداکثر ۱ ساعته را با وضوح بالای رسانه پردازش کنند.
  • حالت‌های پردازش: Gemini 4 Argon،‏ 3.8 Flash،‏ 3.6 Flash،‏ 3.5 Flash Lite، و مدل‌های جدیدتر از دو حالت پردازش ویدیو پشتیبانی می‌کنند:
    • ایستا: فریم‌ها با سرعت ۱ فریم در ثانیه استخراج می‌شوند و در بافت قرار می‌گیرند (پیش‌فرض برای همه مدل‌ها). صدا با سرعت ۱ کیلوبیت در ثانیه (تک کانال) پردازش می‌شود. مُهرهای زمان هر ثانیه اضافه می‌شوند. بهترین گزینه برای کلیپ‌های کوتاه یا زمانی‌که هر فریم مهم است (مانند بازرسی فریم‌به‌فریم). توجه داشته باشید که توالی‌های کنش سریع ممکن است به‌دلیل نرخ نمونه‌برداری ۱ فریم در ثانیه جزئیات را ازدست بدهند.
    • عاملی: مدل به‌طور پویا در ویدیو پیمایش می‌کند و ترانویسی و/یا فریم‌ها و/یا صدا را به‌صورت درخواستی بار می‌کند. این مدل برای محتوای طولانی تا ۸۸٪ کمتر از توکن‌ها استفاده می‌کند، هرچند پیمایش ممکن است «زمان تا اولین توکن» (TTFT) و کل استفاده از توکن را در کلیپ‌های کوتاه (کمتر از ۵ دقیقه) یا پُرسمان‌های گسترده به‌دلیل استدلال داخلی و رفت‌وبرگشت‌های ابزار افزایش دهد. بهترین برای ویدیوهای طولانی و پُرسمان‌های هدف‌گیری‌شده برای بهینه‌سازی هزینه‌های توکن و کیفیت پاسخ. در Gemini 4 Argon،‏ 3.8 Flash،‏ 3.6 Flash، و 3.5 Flash Lite پشتیبانی می‌شود. برای جزئیات، به درک ویدیو بااستفاده از عامل مراجعه کنید.
  • محاسبه نشان (حالت ایستا): هر ثانیه از ویدیو به‌صورت زیر نشان‌گذاری می‌شود:
    • فریم‌های تکی (نمونه‌برداری‌شده در ۱ فریم در ثانیه):
      • اگر media_resolution روی پایین تنظیم شده باشد، فریم‌ها با نرخ ۶۶ توکن در هر فریم نشانه‌گذاری می‌شوند.
      • درغیراین‌صورت، فریم‌ها با نرخ ۲۵۸ کد در هر فریم کدبندی می‌شوند.
    • صوت: ۳۲ واحد اطلاعات در ثانیه.
    • فراداده نیز گنجانده شده است.
    • مجموع: تقریباً ۱۰۰ نشانه به‌ازای هر ثانیه ویدیو در وضوح رسانه پیش‌فرض (پایین)، یا تقریباً ۳۰۰ نشانه به‌ازای هر ثانیه ویدیو در وضوح رسانه بالا.
  • محاسبه کردن توکن (حالت عاملی): استفاده از توکن براساس پیچیدگی محتوا و استراتژی پیمایش مدل متفاوت است. نشان‌های استدلال پیمایش تولیدشده درطول کاوش ویدیو به‌عنوان نشان‌های تفکر (total_thought_tokens) درنظر گرفته می‌شوند، درحالی‌که فریم‌ها، صدا، و ترانویسی بارشده براساس تقاضا به‌عنوان نشان‌های استفاده از ابزار (total_tool_use_tokens) درنظر گرفته می‌شوند. پردازش عاملی معمولاً تا ۸۸٪ نشان‌های کل کمتری نسبت‌به پردازش ایستا برای محتوای طولانی استفاده می‌کند، زیرا مدل فقط ترانویسی و/یا فریم‌ها و/یا صدای موردنیاز برای پاسخ به پیام‌واره را بار می‌کند (به راهنمای نشان‌ها مراجعه کنید).
  • وضوح رسانه: Gemini 3 با پارامتر media_resolution کنترل دقیق‌تری بر پردازش دید چندوجهی ارائه می‌دهد. پارامتر media_resolution حداکثر تعداد توکن‌های اختصاص‌یافته به هر تصویر ورودی یا فریم ویدیو را تعیین می‌کند. وضوح بالاتر توانایی مدل را برای خواندن نوشتار ریز یا شناسایی جزئیات کوچک بهبود می‌بخشد، اما مصرف ژتون و تأخیر را افزایش می‌دهد. پارامترهای media_resolution و processing مستقل هستند: می‌توانید هر دو را در یک ورودی ویدیو تنظیم کنید.

برای جزئیات بیشتر درباره محاسبات کد، به راهنمای کدها مراجعه کنید.

  • قالب مُهر زمان: هنگام اشاره به لحظات خاصی در ویدیو در پیام‌واره‌تان، از قالب MM:SS استفاده کنید (مثلاً 01:15 برای ۱ دقیقه و ۱۵ ثانیه).
  • جای‌گذاری پیام‌واره: اگر نوشتار و یک ویدیو را ترکیب می‌کنید، پیام‌واره نوشتاری را بعداز بخش ویدیویی در آرایه input قرار دهید.
  • وقفه زمانی برای درخواست‌های طولانی: برای ویدیوهایی که به زمان پردازش طولانی یا استدلال چندمرحله‌ای پیچیده نیاز دارند، از جاری‌سازی (stream=True) یا اجرا در پس‌زمینه (background=True) استفاده کنید. درخواست‌های همگام غیرجاری‌سازی که در شرایط تقاضای بالا با تلاش‌های مجدد در پس‌نما مواجه می‌شوند، ممکن است از پنجره‌های اعتبار اتصال یا توکن اصالت‌سنجی فراتر بروند، که می‌تواند به‌صورت خطاهای غیرمنتظره 401 Unauthorized یا وقفه زمانی ظاهر شود. جاری‌سازی اتصال را فعال نگه می‌دارد و استدلال واسطه‌ای و پیشرفت فراخوانی ابزار را نشان می‌دهد.

قدم بعدی چیست

  • وضوح رسانه: وضوح فریم‌های ویدیو را کنترل کنید تا بین کیفیت و استفاده از نمانه تعادل برقرار کنید.
  • نشان‌ها: با نحوه نشان‌گذاری محتوای ویدیویی در هر دو حالت پردازش ایستا و عاملی آشنا شوید.
  • اجرای پس‌زمینه: برای جلوگیری از اتمام زمان اتصال، وظایف درک ویدیو طولانی‌مدت را به‌صورت ناهمزمان اجرا کنید.
  • دستورالعمل‌های سیستم: دستورالعمل‌های سیستم به شما امکان می‌دهد رفتار مدل را براساس نیازها و موارد استفاده خاص خود هدایت کنید.
  • Files API: درباره بارگذاری و مدیریت کردن فایل‌ها برای استفاده با Gemini بیشتر بدانید.
  • استراتژی‌های پیام‌واره فایل: Gemini API از پیام‌واره با داده‌های نوشتاری، تصویری، صوتی، و ویدیویی پشتیبانی می‌کند که به آن پیام‌واره چندوجهی نیز گفته می‌شود.
  • راهنمایی ایمنی: گاهی‌اوقات مدل‌های هوش مصنوعی زایا بروندادهای غیرمنتظره‌ای تولید می‌کنند، مثلاً بروندادهای نادرست، جانبدارانه، یا توهین‌آمیز. پس‌پردازش و ارزیابی انسانی برای محدود کردن خطر آسیب ناشی از چنین بروندادهایی ضروری است.