-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Feat: quickstart video-analysis sample feature #1083
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sedanah-m
wants to merge
9
commits into
master
Choose a base branch
from
feat/video-anaylsis-final
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
944049f
feat: quickstart video-analysis sample feature
sedanah-m beb7527
fix: clean up UI
sedanah-m f6b1103
Update ai/ai-samples/src/features/video-anaylsis/service.ts
sedanah-m d7b9921
fix: typo
sedanah-m bb862c2
Merge branch 'feat/video-anaylsis-final' of github.com:firebase/quick…
sedanah-m d5ed1cb
fix: minor readibility revision
sedanah-m afd3ab2
fix:
sedanah-m c0ef5e5
fix typo
sedanah-m 95cf650
fix typo
sedanah-m File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { useState, useRef } from 'react'; | ||
| import { analyzeVideo, streamVideoAnalysis } from './service'; | ||
|
|
||
| export default function VideoAnalysisView() { | ||
| const [prompt, setPrompt] = useState('Describe what is happening in this video in detail.'); | ||
| const [useStreaming, setUseStreaming] = useState(true); | ||
| const [response, setResponse] = useState(''); | ||
| const [loading, setLoading] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| const fileInputRef = useRef<HTMLInputElement>(null); | ||
|
|
||
| const handleAnalyze = async () => { | ||
| const fileArray = Array.from(fileInputRef.current?.files ?? []); | ||
|
|
||
| if (fileArray.length === 0) { | ||
| setError('Please select a video file.'); | ||
| return; | ||
| } | ||
|
|
||
| const cleanedPrompt = prompt.trim(); | ||
| if (!cleanedPrompt) { | ||
| setError('Please enter a prompt.'); | ||
| return; | ||
| } | ||
|
|
||
| setLoading(true); | ||
| setError(null); | ||
| setResponse(''); | ||
|
|
||
| try { | ||
| if (useStreaming) { | ||
| await streamVideoAnalysis(cleanedPrompt, fileArray[0], (chunk) => { | ||
| setResponse((prev) => prev + chunk); | ||
| }); | ||
| } else { | ||
| const resultText = await analyzeVideo(cleanedPrompt, fileArray[0]); | ||
| setResponse(resultText); | ||
| } | ||
| } catch (err: unknown) { | ||
| const message = | ||
| err instanceof Error | ||
| ? err.message | ||
| : 'An unexpected error occurred during video analysis.'; | ||
| setError(message); | ||
| } finally { | ||
| setLoading(false); | ||
| } | ||
| }; | ||
|
|
||
| return ( | ||
| <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}> | ||
| <h2>Video Analysis</h2> | ||
| <p style={{ color: '#666', marginBottom: '20px' }}> | ||
| Upload a video file alongside a text prompt to analyze its content. | ||
| </p> | ||
|
|
||
| <div style={{ marginBottom: '15px' }}> | ||
| <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}> | ||
| Upload Video: | ||
| </label> | ||
| <input | ||
| type="file" | ||
| ref={fileInputRef} | ||
| accept="video/*" | ||
| style={{ width: '100%', padding: '8px' }} | ||
| /> | ||
| </div> | ||
|
|
||
| <div style={{ marginBottom: '15px' }}> | ||
| <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}> | ||
| Prompt: | ||
| </label> | ||
| <textarea | ||
| value={prompt} | ||
| onChange={(e) => setPrompt(e.target.value)} | ||
| rows={4} | ||
| style={{ width: '100%', padding: '8px', fontFamily: 'inherit' }} | ||
| /> | ||
| </div> | ||
|
|
||
| <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px' }}> | ||
| <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}> | ||
| <input | ||
| type="checkbox" | ||
| checked={useStreaming} | ||
| onChange={(e) => setUseStreaming(e.target.checked)} | ||
| disabled={loading} | ||
| /> | ||
| Stream response | ||
| </label> | ||
|
|
||
| <button | ||
| onClick={handleAnalyze} | ||
| disabled={loading} | ||
| style={{ | ||
| padding: '10px 20px', | ||
| cursor: loading ? 'not-allowed' : 'pointer', | ||
| backgroundColor: loading ? '#ccc' : '#007BFF', | ||
| color: '#fff', | ||
| border: 'none', | ||
| borderRadius: '4px', | ||
| }} | ||
| > | ||
| {loading ? 'Analyzing Video...' : 'Analyze Video'} | ||
| </button> | ||
| </div> | ||
|
|
||
| {error && ( | ||
| <div style={{ color: '#D8000C', backgroundColor: '#FFD2D2', padding: '10px', marginTop: '15px', borderRadius: '4px' }}> | ||
| <strong>Error:</strong> {error} | ||
| </div> | ||
| )} | ||
|
|
||
| {response && ( | ||
| <div style={{ marginTop: '20px', borderTop: '1px solid #eee', paddingTop: '15px' }}> | ||
| <h3>Response:</h3> | ||
| <p style={{ whiteSpace: 'pre-wrap', lineHeight: '1.5' }}>{response}</p> | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { getAiModel } from '../../services/firebaseAIService'; | ||
| import { Part } from 'firebase/ai'; | ||
|
|
||
| /** | ||
| * Converts a standard browser File object (Video) into a Firebase AI SDK Part. | ||
| * Uses the native browser FileReader API to extract the Base64 string. | ||
| * @param file The DOM File object from an <input type="file"> | ||
| * @returns A Promise that resolves to an InlineData Part object | ||
| */ | ||
| export async function fileToGenerativePart(file: File): Promise<Part> { | ||
| return new Promise((resolve, reject) => { | ||
| const reader = new FileReader(); | ||
|
|
||
| reader.onload = () => { | ||
| const result = reader.result; | ||
|
|
||
| if (typeof result !== 'string') { | ||
| return reject(new Error('Failed to parse video file data as Base64.')); | ||
| } | ||
| const splitResult = result.split(','); | ||
| const base64Data = splitResult[1]; | ||
| if (!base64Data) { | ||
| return reject(new Error('Failed to extract Base64 data from file.')); | ||
| } | ||
| resolve({ | ||
| inlineData: { | ||
| data: base64Data, | ||
| mimeType: file.type || 'video/mp4', | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is the fallback video/mp4? If there's no file.type isn't something wrong? Or do mp4s sometimes not have a file type? |
||
| }, | ||
| }); | ||
| }; | ||
|
|
||
| reader.onerror = () => reject(reader.error || new Error('Error reading video file.')); | ||
| reader.readAsDataURL(file); | ||
| }); | ||
| } | ||
|
|
||
| // Note: The Gemini API restricts the total size of inline data payloads. | ||
| // To process larger files without hitting HTTP 413 errors (PayLoad Too Large), | ||
| // See the official Firebase AI documentation for current file size limits and workarounds: | ||
| // https://firebase.google.com/docs/ai-logic/solutions/cloud-storage | ||
|
|
||
| /** | ||
| * Sends a video analysis request (prompt + video file) to the Gemini model. | ||
| * @param prompt The string instruction sent to the model (e.g. "Describe what happens in this video"). | ||
| * @param videoFile The DOM File object containing the video. | ||
| * @returns The text string response generated by the model. | ||
| */ | ||
| export async function analyzeVideo(prompt: string, videoFile: File): Promise<string> { | ||
| try { | ||
| const videoPart = await fileToGenerativePart(videoFile); | ||
| const model = getAiModel('gemini-3.7-flash'); | ||
| const result = await model.generateContent([prompt, videoPart]); | ||
| return result.response.text(); | ||
| } catch (error: unknown) { | ||
| throw error instanceof Error | ||
| ? error | ||
| : new Error('An unknown error occurred during video analysis.'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Streams the video analysis response from the Gemini model in real-time chunks. | ||
| * @param prompt The string instruction sent to the model. | ||
| * @param videoFile The DOM File object containing the video. | ||
| * @param onChunk Callback fired whenever a new text chunk is received. | ||
| */ | ||
| export async function streamVideoAnalysis( | ||
| prompt: string, | ||
| videoFile: File, | ||
| onChunk: (chunk: string) => void | ||
| ): Promise<void> { | ||
| try { | ||
| const videoPart = await fileToGenerativePart(videoFile); | ||
| const model = getAiModel('gemini-3.7-flash'); | ||
| const result = await model.generateContentStream([prompt, videoPart]); | ||
|
|
||
| for await (const chunk of result.stream) { | ||
| const chunkText = chunk.text(); | ||
| if (chunkText) { | ||
| onChunk(chunkText); | ||
| } | ||
| } | ||
| } catch (error: unknown) { | ||
| throw error instanceof Error | ||
| ? error | ||
| : new Error('An unknown error occurred during video streaming.'); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think package.json needs to be updated to include this script?