ניתוח קובצי וידאו באמצעות Gemini API

אפשר לבקש מדגם Gemini לנתח קובצי וידאו שאתם מספקים, בין שבתוך הטקסט (בקידוד base64) ובין שבאמצעות כתובת URL. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.

בעזרת היכולת הזו תוכלו לבצע פעולות כמו:

  • הוספת כתוביות ותשובות לשאלות על סרטונים
  • ניתוח פלחים ספציפיים בסרטון באמצעות חותמות זמן
  • תמלול תוכן וידאו על ידי עיבוד של טראק האודיו ושל הפריימים החזותיים
  • תיאור, פילוח וחילוץ מידע מסרטונים, כולל הטראק של האודיו והפריימים החזותיים

מעבר לדוגמאות הקוד מעבר לקוד של תגובות בסטרימינג


במדריכים נוספים מפורטות אפשרויות נוספות לעבודה עם סרטונים
יצירת פלט מובנה צ'אט בכמה סבבים

לפני שמתחילים

לוחצים על ספק Gemini API כדי להציג בדף הזה תוכן וקוד ספציפיים לספק.

אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את שירות הקצה העורפי של ספק Gemini API שבחרתם ויוצרים מכונה של GenerativeModel.

כדי לבדוק את ההנחיות ולבצע בהן שינויים, ואפילו לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.

יצירת טקסט מקובצי וידאו (בקידוד base64)

לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה.

אפשר לבקש ממודל Gemini ליצור טקסט על ידי הצגת הנחיות עם טקסט וסרטון – ולספק את הערך של mimeType לכל קובץ קלט ואת הקובץ עצמו. בהמשך הדף מפורטות הדרישות וההמלצות לקובצי קלט.

הערה: בדוגמה הזו מוצגת הוספת הקובץ בקוד, אבל ערכות ה-SDK תומכות גם בהוספת כתובת URL של YouTube.

Swift

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")


// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")

// Provide a text prompt to include with the video
let prompt = "What is in the video?"

// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")

Kotlin

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")


val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To generate text output, call generateContent with the prompt
    val response = generativeModel.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}

Java

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.

ב-Java, השיטות ב-SDK הזה מחזירות ListenableFuture.

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To generate text output, call generateContent with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                String resultText = result.getText();
                System.out.println(resultText);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        }, executor);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

Web

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the video
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const videoPart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call generateContent with the text and video
  const result = await model.generateContent([prompt, videoPart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

אפשר להפעיל את הפונקציה generateContent() כדי ליצור טקסט מקלט מולטימודלי של קובצי טקסט וקובצי וידאו.


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");

// Prepare video for input
final video = await File('video0.mp4').readAsBytes();

// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);

// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
  Content.multi([prompt, ...videoPart])
]);
print(response.text);

Unity

אפשר להפעיל את הפונקציה GenerateContentAsync() כדי ליצור טקסט מקלט רב-מודלי של קובצי טקסט וקובצי וידאו.


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
          UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));

// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");

// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

איך בוחרים מודל שמתאים לתרחיש לדוגמה ולסוג האפליקציה שלכם

שידור התשובה

לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה.

כדי לקבל אינטראקציות מהירות יותר, אפשר לא להמתין לתוצאה המלאה של יצירת המודל, אלא להשתמש בסטרימינג כדי לטפל בתוצאות חלקיות. כדי להעביר את התשובה בסטרימינג, קוראים ל-generateContentStream.



דרישות והמלצות לגבי קובצי וידאו להזנה

חשוב לזכור שקובץ שסופק כנתונים בתוך שורה מקודד ל-base64 במהלך ההעברה, וכתוצאה מכך גדל גודל הבקשה. אם בקשה גדולה מדי, תקבלו את השגיאה HTTP 413.

במאמר 'קבצי קלט נתמכים ודרישות ל-Vertex AI Gemini API' מפורט מידע על הנושאים הבאים:

סוגי MIME נתמכים של סרטונים

Gemini מודלים רב-מודאליים תומכים בסוגי ה-MIME הבאים של וידאו:

סוג ה-MIME של סרטונים Gemini 2.0 Flash Gemini 2.0 Flash‑Lite
FLV –‏ video/x-flv
MOV –‏ video/quicktime
MPEG - video/mpeg
MPEGPS – video/mpegps
MPG - video/mpg
MP4 – video/mp4
WEBM – video/webm
WMV – video/wmv
3GPP – video/3gpp

מגבלות לכל בקשה

זהו המספר המקסימלי של קובצי וידאו שמותר לבקש בבקשה להנחיה:

  • Gemini 2.0 Flash ו-Gemini 2.0 Flash‑Lite: 10 קובצי וידאו



מה עוד אפשר לעשות?

לנסות יכולות אחרות

איך שולטים ביצירת תוכן

אפשר גם להתנסות בהנחיות ובהגדרות של מודלים, ואפילו ליצור קטע קוד באמצעות Google AI Studio.

מידע נוסף על המודלים הנתמכים

כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.


שליחת משוב על חוויית השימוש ב-Firebase AI Logic