Gemini 모델에 인라인 (base64 인코딩) 또는 URL을 통해 제공하는 동영상 파일을 분석하도록 요청할 수 있습니다. Firebase AI Logic을 사용하면 앱에서 직접 이 요청을 할 수 있습니다.
이 기능을 사용하면 다음과 같은 작업을 할 수 있습니다.
- 동영상에 캡션을 추가하고 동영상에 관한 질문에 답변합니다.
- 타임스탬프를 사용하여 동영상의 특정 세그먼트를 분석합니다.
- 오디오 트랙과 시각적 프레임을 모두 처리하여 동영상 콘텐츠의 스크립트를 작성합니다.
- 오디오 트랙과 시각적 프레임을 모두 포함하여 동영상의 정보를 설명, 분할, 추출합니다.
|
동영상 작업에 관한 추가 옵션은 다른 가이드를 참고하세요. 구조화된 출력 생성 멀티턴 채팅 |
시작하기 전에
|
Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠 및 코드를 확인합니다. |
프롬프트를 테스트하고 반복하려면 다음을 사용하는 것이 좋습니다. Google AI Studio.
동영상 파일에서 텍스트 생성 (base64 인코딩)
|
이 샘플을 사용해 보기 전에 이 가이드의
시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다. |
텍스트와 동영상으로 프롬프트를 표시하여 Gemini 모델에
텍스트를 생성하도록 요청할 수 있습니다. 각
입력 파일의 mimeType과 파일 자체를 제공합니다. 이 페이지의 뒷부분에서 입력 파일의
요구사항 및 권장사항
을 확인하세요.
Swift
generateContent()
를 호출하여 텍스트 및 동영상 파일의 멀티모달 입력에서 텍스트를 생성할 수 있습니다.
import FirebaseAILogic
// 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-3-flash-preview")
// 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()
를 호출하여 텍스트 및 동영상 파일의 멀티모달 입력에서 텍스트를 생성할 수 있습니다.
// 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-3-flash-preview")
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 = model.generateContent(prompt)
Log.d(TAG, response.text ?: "")
}
}
Java
generateContent()
를 호출하여 텍스트 및 동영상 파일의 멀티모달 입력에서 텍스트를 생성할 수 있습니다.
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-3-flash-preview");
// 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-3-flash-preview" });
// 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()`
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-3-flash-preview');
// 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-3-flash-preview");
// 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 오류가 발생합니다.
다음과 같은 항목에 관한 자세한 내용은 '지원되는 입력 파일 및 요구사항' 페이지를 참고하세요.
- 요청에서 파일을 제공하는 다양한 옵션 (인라인 또는 파일의 URL 또는 URI 사용)
- 동영상 파일의 요구사항 및 권장사항
지원되는 동영상 MIME 유형
Gemini 멀티모달 모델은 다음과 같은 동영상 MIME 유형을 지원합니다.
- 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
요청당 한도
요청당 최대 파일 수: 동영상 파일 10개
또 뭘 할 수 있니?
- 모델에 긴 프롬프트를 보내기 전에 토큰 수를 집계하는 방법 을 알아보세요.
- Cloud Storage for Firebase 을(를) 설정하여 멀티모달 요청에 대용량 파일을 포함하고 프롬프트에서 파일을 제공하는 더 관리되는 솔루션을 사용할 수 있습니다. 파일에는 이미지, PDF, 동영상, 오디오가 포함될 수 있습니다.
-
- 프로덕션 준비를 고려하기 시작합니다 (프로덕션 체크리스트 참고).
- 승인되지 않은 클라이언트의 악용으로부터 Gemini API를 보호할 수 있도록 Firebase App Check 가능한 한 빨리 Firebase 앱 체크를 설정합니다.
- 통합 Firebase Remote Config 하여 새 앱 버전을 출시하지 않고도 앱의 값 (예: 모델 이름)을 업데이트합니다.
다른 기능 사용해 보기
- 멀티턴 대화 (채팅)를 빌드합니다.
- 텍스트 전용 프롬프트에서 텍스트를 생성합니다.
- 구조화된 출력 (예: JSON)을 생성합니다. 텍스트 및 멀티모달 프롬프트 모두에서.
- 이미지를 생성하고 수정합니다 텍스트 및 멀티모달 프롬프트 모두에서.
- 도구 (예: 함수 호출 및 Google 검색을 통한 그라운딩) 를 사용하여 Gemini 모델을 앱의 다른 부분과 외부 시스템 및 정보에 연결합니다.
콘텐츠 생성 제어 방법 알아보기
- 프롬프트 설계를 이해합니다. 여기에는 권장사항, 전략, 예시 프롬프트가 포함됩니다.
- 온도 및 최대 출력 토큰과 같은 모델 매개변수를 구성합니다.
- 안전 설정을 사용하여 유해하다고 간주될 수 있는 대답을 얻을 가능성을 조정합니다.
지원되는 모델 자세히 알아보기
다양한 사용 사례에 사용할 수 있는 모델 과 할당량 및 가격을 알아봅니다.의견 보내기 Firebase AI Logic 사용 경험에 관한