File size: 6,451 Bytes
928442a
 
 
 
 
 
75f5536
 
 
 
 
 
 
031ec2d
 
 
 
75f5536
 
 
 
 
 
397509e
75f5536
 
3533176
75f5536
 
 
 
3533176
75f5536
3533176
 
75f5536
397509e
75f5536
 
 
 
397509e
75f5536
 
ff90e76
75f5536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319aac2
75f5536
 
 
 
 
 
 
 
 
 
 
 
 
319aac2
75f5536
 
 
319aac2
75f5536
 
 
 
 
ff90e76
75f5536
 
 
3533176
75f5536
3533176
75f5536
 
 
 
3533176
75f5536
3533176
75f5536
 
 
 
 
 
 
3533176
75f5536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0564daa
75f5536
 
319aac2
75f5536
 
 
 
319aac2
 
75f5536
 
 
319aac2
75f5536
 
 
 
 
 
 
 
 
3533176
75f5536
 
0564daa
75f5536
 
 
 
319aac2
75f5536
 
 
 
 
3533176
75f5536
 
 
 
3533176
75f5536
 
 
 
 
 
3533176
75f5536
 
 
 
ff90e76
75f5536
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import streamlit as st
import google.generativeai as genai
import os
import tempfile
import time

# Configure page
st.set_page_config(
    page_title="Video AI Analysis", 
    page_icon="πŸŽ₯", 
    layout="wide"
)

# Initialize session state
if 'show_recorder' not in st.session_state:
    st.session_state.show_recorder = False

# Title
st.title("πŸŽ₯ Video Recording & AI Analysis")
st.markdown("Upload or record a video to get instant AI-powered insights")
st.divider()

# Get API key
def get_api_key():
    # Try environment variable first (for Hugging Face Spaces)
    api_key = os.environ.get("GOOGLE_API_KEY", "")
    
    # If not found, allow manual input
    if not api_key:
        api_key = st.sidebar.text_input(
            "Enter Gemini API key:", 
            type="password",
            help="Set this in HF Spaces secrets for production"
        )
    
    return api_key

# Initialize Gemini
@st.cache_resource
def init_gemini(api_key):
    if api_key:
        genai.configure(api_key=api_key)
        return genai.GenerativeModel("gemini-2.0-flash-exp")
    return None

# Process video
def process_video(model, video_bytes, filename):
    # Save to temp file
    with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp:
        tmp.write(video_bytes)
        tmp_path = tmp.name
    
    try:
        # Upload to Gemini
        with st.spinner("πŸ“€ Uploading video..."):
            video_file = genai.upload_file(path=tmp_path, display_name=filename)
        
        # Wait for processing
        with st.spinner("⏳ Processing... (30-60 seconds)"):
            attempts = 0
            while video_file.state.name == "PROCESSING" and attempts < 30:
                time.sleep(2)
                video_file = genai.get_file(video_file.name)
                attempts += 1
            
            if video_file.state.name == "FAILED":
                raise Exception("Video processing failed")
            elif video_file.state.name == "PROCESSING":
                raise Exception("Processing timeout - try a shorter video")
        
        # Generate summary
        with st.spinner("πŸ€– Generating AI summary..."):
            prompt = """Analyze this video and provide a summary including:
            1. Main content and activities
            2. Key moments or information  
            3. Visual elements (people, objects, scenes)
            4. Audio/speech content if present
            5. Overall purpose or message
            
            Format as a clear, structured summary."""
            
            response = model.generate_content([video_file, prompt])
            return response.text
            
    finally:
        # Clean up
        if os.path.exists(tmp_path):
            os.unlink(tmp_path)

# Sidebar
with st.sidebar:
    st.markdown("### πŸ”‘ Configuration")
    
    api_key = get_api_key()
    
    if api_key:
        st.success("βœ… API Key set")
    else:
        st.warning("⚠️ API Key required")
    
    st.divider()
    
    st.markdown("### πŸ“– Instructions")
    st.markdown("""
    1. Set API key (HF secrets)
    2. Upload/record video
    3. Click Analyze
    4. View summary
    """)
    
    st.divider()
    
    st.markdown("### πŸ”— Links")
    st.markdown("[Get API Key](https://makersuite.google.com/app/apikey)")
    st.markdown("[Documentation](https://ai.google.dev)")
    
    if st.button("πŸ”„ Reset"):
        st.cache_data.clear()
        st.cache_resource.clear()
        st.rerun()

# Main content
if not api_key:
    st.error("Please enter your Gemini API key in the sidebar")
    st.info("""
    **For Hugging Face Spaces:**
    1. Go to Settings β†’ Repository secrets
    2. Add 'GOOGLE_API_KEY' secret
    3. Paste your Gemini API key
    """)
else:
    # Initialize model
    model = init_gemini(api_key)
    
    if model:
        # Create tabs
        tab1, tab2 = st.tabs(["πŸ“€ Upload Video", "πŸ“Ή Record Video"])
        
        with tab1:
            uploaded = st.file_uploader(
                "Choose video file (max 50MB recommended)",
                type=['mp4', 'mov', 'avi', 'webm']
            )
            
            if uploaded:
                st.video(uploaded)
                
                if st.button("πŸ” Analyze Upload", type="primary", key="analyze_upload"):
                    try:
                        video_bytes = uploaded.getvalue()
                        summary = process_video(model, video_bytes, uploaded.name)
                        
                        st.success("βœ… Analysis complete!")
                        st.divider()
                        st.subheader("πŸ“ Video Summary")
                        st.write(summary)
                        
                        # Download button
                        st.download_button(
                            "πŸ“₯ Download Summary",
                            summary,
                            "video_summary.txt",
                            "text/plain"
                        )
                    except Exception as e:
                        st.error(f"Error: {str(e)}")
        
        with tab2:
            st.info("πŸ“± Works best on mobile devices")
            
            recorded = st.camera_input("Click to record")
            
            if recorded:
                st.video(recorded)
                
                if st.button("πŸ” Analyze Recording", type="primary", key="analyze_record"):
                    try:
                        recorded.seek(0)
                        video_bytes = recorded.read()
                        summary = process_video(model, video_bytes, "recording.mp4")
                        
                        st.success("βœ… Analysis complete!")
                        st.divider()
                        st.subheader("πŸ“ Video Summary")
                        st.write(summary)
                        
                        # Download button
                        st.download_button(
                            "πŸ“₯ Download Summary",
                            summary,
                            "recording_summary.txt",
                            "text/plain"
                        )
                    except Exception as e:
                        st.error(f"Error: {str(e)}")
    else:
        st.error("Failed to initialize Gemini model")

# Footer
st.divider()
st.caption("Powered by Google Gemini 2.0 | Built with Streamlit")