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

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

בעזרת היכולת הזו, אתם יכולים:

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

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


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

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

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

אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה. במדריך הזה מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות ה-Backend עבור ספק 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.5-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 הזה הן פונקציות השהיה וצריך להפעיל אותן מהיקף של 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.5-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.5-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.5-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.5-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.5-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?