PRB1 commited on
Commit
44cb2cf
·
verified ·
1 Parent(s): b9a7fb4

Upload 10 files

Browse files
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
Dockerfile CHANGED
@@ -1,20 +1,31 @@
1
- FROM python:3.13.5-slim
2
-
3
- WORKDIR /app
4
-
5
- RUN apt-get update && apt-get install -y \
6
- build-essential \
7
- curl \
8
- git \
9
- && rm -rf /var/lib/apt/lists/*
10
-
11
- COPY requirements.txt ./
12
- COPY src/ ./src/
13
-
14
- RUN pip3 install -r requirements.txt
15
-
16
- EXPOSE 8501
17
-
18
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
-
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ ffmpeg \
7
+ libsm6 \
8
+ libxext6 \
9
+ libxrender-dev \
10
+ libgomp1 \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ COPY requirements.txt .
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
+
16
+ COPY . .
17
+
18
+ RUN mkdir -p /tmp && chmod 777 /tmp
19
+ RUN mkdir -p /.streamlit && chmod 777 /.streamlit
20
+
21
+ EXPOSE 7860
22
+
23
+ ENV HOME=/tmp
24
+ ENV STREAMLIT_SERVER_PORT=7860
25
+ ENV STREAMLIT_SERVER_ADDRESS=0.0.0.0
26
+ ENV STREAMLIT_SERVER_HEADLESS=true
27
+ ENV STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION=false
28
+ ENV STREAMLIT_SERVER_ENABLE_CORS=true
29
+ ENV STREAMLIT_SERVER_MAX_UPLOAD_SIZE=500
30
+
31
+ CMD ["python", "-m", "streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false", "--server.enableCORS=true"]
README.md CHANGED
@@ -1,20 +1,142 @@
1
- ---
2
- title: Velocity
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: I2Reel
12
- license: mit
13
- ---
14
-
15
- # Welcome to Streamlit!
16
-
17
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
18
-
19
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: AI Video Editor V2
3
+ emoji: 🤖
4
+ colorFrom: purple
5
+ colorTo: blue
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ ---
10
+
11
+ # 🤖 AI Video Editor V2
12
+
13
+ Transform any reference reel into your personalized video using AI-powered code generation.
14
+
15
+ ## 🎬 How It Works
16
+
17
+ 1. **Upload** your reference video and photos
18
+ 2. **AI Analysis** - Gemini analyzes video structure, transitions, and timing
19
+ 3. **Generate** - Review each 3-second segment with human-in-the-loop
20
+ 4. **Download** - Get your final professional video
21
+
22
+ ## 🔑 Getting Started
23
+
24
+ ### 1. Get Your Free Gemini API Key
25
+
26
+ Visit: [https://aistudio.google.com/apikey](https://aistudio.google.com/apikey)
27
+
28
+ **Free Tier Limits:**
29
+ - ✅ 10 requests/minute
30
+ - ✅ 250 requests/day
31
+ - ✅ 250K tokens/minute
32
+ - ✅ Completely FREE - No credit card required
33
+
34
+ ### 2. Use the App
35
+
36
+ 1. Enter your API key in the sidebar
37
+ 2. Upload a reference video (10-60 seconds)
38
+ 3. Upload 5-20 photos
39
+ 4. Let AI analyze and generate segments
40
+ 5. Approve or regenerate each segment
41
+ 6. Download your final video
42
+
43
+ ## ✨ Features
44
+
45
+ - 🎥 **Video Analysis**: AI understands transitions, effects, timing
46
+ - 🤖 **Code Generation**: Gemini writes MoviePy code for each segment
47
+ - 👤 **Human-in-the-Loop**: Review and approve each 3-second segment
48
+ - 🔄 **Iterative Refinement**: Provide feedback to regenerate
49
+ - 📹 **Professional Output**: 1080x1920 (9:16) portrait videos
50
+
51
+ ## 🛠️ Tech Stack
52
+
53
+ - **Frontend**: Streamlit
54
+ - **AI Model**: Google Gemini 2.5 Flash
55
+ - **Video Processing**: MoviePy
56
+ - **Image Processing**: Pillow, OpenCV
57
+
58
+ ## 📊 API Usage
59
+
60
+ With 250 requests/day on free tier:
61
+ - Video analysis: ~5-10 requests
62
+ - Segment generation: ~20-30 segments
63
+ - Regenerations: ~10-15 retries
64
+ - **Total: ~50-70 requests per video**
65
+ - **Can create 3-4 complete videos per day**
66
+
67
+ ## 💡 Tips
68
+
69
+ - Use high-quality photos (1080x1920 ideal)
70
+ - Keep reference videos under 60 seconds
71
+ - Provide specific feedback for better regenerations
72
+ - Approve segments progressively to save API calls
73
+
74
+ ## 🔒 Privacy
75
+
76
+ - Your API key is never stored
77
+ - All processing happens in your session
78
+ - Files are temporary and auto-deleted
79
+
80
+ ## 📝 License
81
+
82
+ MIT License - Free to use and modify!
83
+
84
+ ## 🤝 Support
85
+
86
+ Having issues? Check that:
87
+ - Your API key is valid
88
+ - Reference video is under 100MB
89
+ - Photos are in JPG/PNG format
90
+ - You're within the free tier limits
91
+
92
+ ## 📦 File Structure
93
+
94
+ ```
95
+ velocity-video-editor-v2/
96
+ ├── app.py # Main Streamlit application
97
+ ├── ai_video_analyzer.py # Video analysis with Gemini
98
+ ├── code_generator.py # AI code generation
99
+ ├── video_executor.py # Safe code execution
100
+ ├── requirements.txt # Python dependencies
101
+ ├── Dockerfile # Container configuration
102
+ ├── README.md # This file
103
+ └── .streamlit/
104
+ └── config.toml # Streamlit configuration
105
+ ```
106
+
107
+ ## 🚀 Local Development
108
+
109
+ ```bash
110
+ # Install dependencies
111
+ pip install -r requirements.txt
112
+
113
+ # Run the app
114
+ streamlit run app.py
115
+
116
+ # Open browser at http://localhost:8501
117
+ ```
118
+
119
+ ## 🐳 Docker Deployment
120
+
121
+ ```bash
122
+ # Build Docker image
123
+ docker build -t ai-video-editor .
124
+
125
+ # Run container
126
+ docker run -p 7860:7860 ai-video-editor
127
+ ```
128
+
129
+ ## 🌐 Hugging Face Spaces Deployment
130
+
131
+ 1. Create new Space with Docker SDK
132
+ 2. Upload all files
133
+ 3. HF automatically builds and deploys
134
+ 4. Share with users!
135
+
136
+ ---
137
+
138
+ Made with ❤️ using Gemini 2.5 Flash
139
+
140
+ **Creator**: PPV Productions
141
+ **Version**: 2.0
142
+ **Last Updated**: February 2026
__pycache__/ai_video_analyzer.cpython-313.pyc ADDED
Binary file (9.3 kB). View file
 
ai_video_analyzer.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import cv2
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import time
7
+
8
+ class VideoAnalyzer:
9
+ def __init__(self, api_key):
10
+ """Initialize Gemini 2.5 Flash for video analysis"""
11
+ genai.configure(api_key=api_key)
12
+ self.model = genai.GenerativeModel('gemini-2.5-flash')
13
+
14
+ def analyze_reference_video(self, video_path):
15
+ """Analyze reference video and extract structure, transitions, timing"""
16
+
17
+ print(f"📹 Analyzing video: {video_path}")
18
+
19
+ # Get video metadata
20
+ metadata = self.get_video_metadata(video_path)
21
+
22
+ # Upload video to Gemini
23
+ print("☁️ Uploading video to Gemini...")
24
+ video_file = genai.upload_file(video_path)
25
+
26
+ # Wait for processing
27
+ while video_file.state.name == "PROCESSING":
28
+ print("⏳ Processing video...")
29
+ time.sleep(2)
30
+ video_file = genai.get_file(video_file.name)
31
+
32
+ if video_file.state.name == "FAILED":
33
+ raise ValueError("❌ Video processing failed")
34
+
35
+ print("✅ Video uploaded successfully")
36
+
37
+ # Analyze video
38
+ prompt = self.create_analysis_prompt(metadata)
39
+
40
+ print("🤖 Generating analysis...")
41
+ response = self.model.generate_content([video_file, prompt])
42
+
43
+ # Parse response
44
+ analysis = self.parse_analysis(response.text, metadata)
45
+
46
+ # Delete uploaded file
47
+ genai.delete_file(video_file.name)
48
+ print("🧹 Cleanup complete")
49
+
50
+ return analysis
51
+
52
+ def get_video_metadata(self, video_path):
53
+ """Extract basic video metadata"""
54
+ cap = cv2.VideoCapture(video_path)
55
+
56
+ metadata = {
57
+ 'fps': cap.get(cv2.CAP_PROP_FPS),
58
+ 'total_frames': int(cap.get(cv2.CAP_PROP_FRAME_COUNT)),
59
+ 'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
60
+ 'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
61
+ }
62
+
63
+ metadata['duration'] = metadata['total_frames'] / metadata['fps']
64
+
65
+ cap.release()
66
+ return metadata
67
+
68
+ def create_analysis_prompt(self, metadata):
69
+ """Create detailed analysis prompt for Gemini"""
70
+
71
+ duration = metadata['duration']
72
+ num_segments = max(3, min(int(duration / 3), 20)) # 3-second segments
73
+
74
+ prompt = f"""Analyze this video in extreme detail and provide a comprehensive breakdown for recreation.
75
+
76
+ VIDEO INFO:
77
+ - Duration: {duration:.2f} seconds
78
+ - FPS: {metadata['fps']}
79
+ - Resolution: {metadata['width']}x{metadata['height']}
80
+
81
+ ANALYSIS REQUIREMENTS:
82
+
83
+ 1. **Divide the video into {num_segments} segments** (approximately 3 seconds each)
84
+
85
+ 2. For EACH segment, identify:
86
+ - Exact start and end timestamps
87
+ - Transition type entering the segment (fade, slide, zoom, cut, wipe, etc.)
88
+ - Transition type exiting the segment
89
+ - Camera movements (static, zoom in, zoom out, pan left, pan right, rotation, etc.)
90
+ - Zoom level or scale (1.0 = normal, 1.2 = slight zoom, 1.5 = heavy zoom)
91
+ - Visual effects applied (blur, color grade, glitch, flash, overlay, etc.)
92
+ - Image/subject positioning (center, rule of thirds, top, bottom)
93
+ - Motion speed (normal, slow-mo, fast forward)
94
+
95
+ 3. **Beat sync points**: Identify timestamps where visual changes sync with audio beats or significant audio events
96
+
97
+ 4. **Overall style**: Describe the video's aesthetic (cinematic, energetic, calm, vintage, modern, etc.)
98
+
99
+ OUTPUT FORMAT (valid JSON only):
100
+ {{
101
+ "duration": {duration},
102
+ "fps": {metadata['fps']},
103
+ "style": "description of overall style",
104
+ "segments": [
105
+ {{
106
+ "start_time": 0.0,
107
+ "end_time": 3.0,
108
+ "duration": 3.0,
109
+ "transition_in": "fade",
110
+ "transition_out": "slide_left",
111
+ "camera_movement": "zoom_in",
112
+ "zoom_level": "1.2",
113
+ "effects": ["color_grade_warm", "vignette"],
114
+ "image_position": "center",
115
+ "motion_speed": "normal"
116
+ }},
117
+ ...
118
+ ],
119
+ "beat_sync": [1.2, 2.5, 5.0, 7.8, ...]
120
+ }}
121
+
122
+ Be specific and detailed. This analysis will be used to recreate the video programmatically.
123
+ Return ONLY valid JSON, no additional text."""
124
+
125
+ return prompt
126
+
127
+ def parse_analysis(self, response_text, metadata):
128
+ """Parse and validate Gemini's analysis response"""
129
+
130
+ # Extract JSON from response
131
+ response_text = response_text.strip()
132
+
133
+ # Remove markdown code blocks if present
134
+ if response_text.startswith("```json"):
135
+ response_text = response_text.split("```json").split("```")[1]
136
+ elif response_text.startswith("```"):
137
+ response_text = response_text.split("```")[1].split("```")[0]
138
+
139
+ try:
140
+ analysis = json.loads(response_text)
141
+ except json.JSONDecodeError as e:
142
+ print(f"⚠️ JSON parsing error: {e}")
143
+ print("Response:", response_text[:500])
144
+ # Fallback: create basic analysis
145
+ analysis = self.create_fallback_analysis(metadata)
146
+
147
+ # Validate and fill defaults
148
+ analysis = self.validate_analysis(analysis, metadata)
149
+
150
+ return analysis
151
+
152
+ def validate_analysis(self, analysis, metadata):
153
+ """Validate and fill missing fields in analysis"""
154
+
155
+ # Ensure required fields
156
+ if 'duration' not in analysis:
157
+ analysis['duration'] = metadata['duration']
158
+
159
+ if 'fps' not in analysis:
160
+ analysis['fps'] = metadata['fps']
161
+
162
+ if 'style' not in analysis:
163
+ analysis['style'] = "modern"
164
+
165
+ if 'segments' not in analysis or not analysis['segments']:
166
+ analysis['segments'] = self.create_default_segments(metadata['duration'])
167
+
168
+ # Validate each segment
169
+ for segment in analysis['segments']:
170
+ self.validate_segment(segment)
171
+
172
+ if 'beat_sync' not in analysis:
173
+ analysis['beat_sync'] = []
174
+
175
+ return analysis
176
+
177
+ def validate_segment(self, segment):
178
+ """Ensure segment has all required fields"""
179
+ defaults = {
180
+ 'transition_in': 'fade',
181
+ 'transition_out': 'fade',
182
+ 'camera_movement': 'static',
183
+ 'zoom_level': '1.0',
184
+ 'effects': [],
185
+ 'image_position': 'center',
186
+ 'motion_speed': 'normal'
187
+ }
188
+
189
+ for key, default_value in defaults.items():
190
+ if key not in segment:
191
+ segment[key] = default_value
192
+
193
+ def create_default_segments(self, duration):
194
+ """Create default segments if analysis fails"""
195
+ num_segments = max(3, int(duration / 3))
196
+ segment_duration = duration / num_segments
197
+
198
+ segments = []
199
+ for i in range(num_segments):
200
+ segments.append({
201
+ 'start_time': i * segment_duration,
202
+ 'end_time': (i + 1) * segment_duration,
203
+ 'duration': segment_duration,
204
+ 'transition_in': 'fade' if i == 0 else 'cut',
205
+ 'transition_out': 'fade' if i == num_segments - 1 else 'cut',
206
+ 'camera_movement': 'zoom_in' if i % 2 == 0 else 'zoom_out',
207
+ 'zoom_level': '1.2',
208
+ 'effects': [],
209
+ 'image_position': 'center',
210
+ 'motion_speed': 'normal'
211
+ })
212
+
213
+ return segments
214
+
215
+ def create_fallback_analysis(self, metadata):
216
+ """Create fallback analysis if AI fails"""
217
+ return {
218
+ 'duration': metadata['duration'],
219
+ 'fps': metadata['fps'],
220
+ 'style': 'modern',
221
+ 'segments': self.create_default_segments(metadata['duration']),
222
+ 'beat_sync': []
223
+ }
app.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import tempfile
4
+ from pathlib import Path
5
+ import time
6
+ import gc
7
+ from PIL import Image, ImageOps
8
+ import io
9
+ import json
10
+ from moviepy.editor import VideoFileClip, concatenate_videoclips
11
+
12
+ from ai_video_analyzer import VideoAnalyzer
13
+ from code_generator import VideoCodeGenerator
14
+ from video_executor import VideoExecutor
15
+
16
+ # Page config
17
+ st.set_page_config(
18
+ page_title="AI Video Editor V2",
19
+ page_icon="🤖",
20
+ layout="wide"
21
+ )
22
+
23
+ # Custom CSS
24
+ st.markdown("""
25
+ <style>
26
+ .main-header {
27
+ font-size: 3rem;
28
+ font-weight: 700;
29
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
30
+ -webkit-background-clip: text;
31
+ -webkit-text-fill-color: transparent;
32
+ text-align: center;
33
+ margin-bottom: 1rem;
34
+ }
35
+ .sub-header {
36
+ text-align: center;
37
+ color: #666;
38
+ font-size: 1.2rem;
39
+ margin-bottom: 2rem;
40
+ }
41
+ .stButton>button {
42
+ width: 100%;
43
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
44
+ color: white;
45
+ border: none;
46
+ padding: 0.75rem 1.5rem;
47
+ font-size: 1rem;
48
+ font-weight: 600;
49
+ border-radius: 8px;
50
+ transition: all 0.3s;
51
+ }
52
+ .stButton>button:hover {
53
+ transform: translateY(-2px);
54
+ box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
55
+ }
56
+ .segment-card {
57
+ background: #f8f9fa;
58
+ border-radius: 10px;
59
+ padding: 1.5rem;
60
+ margin: 1rem 0;
61
+ border: 2px solid #e9ecef;
62
+ }
63
+ .video-container {
64
+ border-radius: 15px;
65
+ overflow: hidden;
66
+ box-shadow: 0 10px 30px rgba(0,0,0,0.2);
67
+ }
68
+ .api-key-box {
69
+ background: #fff3cd;
70
+ border: 2px solid #ffc107;
71
+ border-radius: 8px;
72
+ padding: 1rem;
73
+ margin: 1rem 0;
74
+ }
75
+ </style>
76
+ """, unsafe_allow_html=True)
77
+
78
+ TARGET_SIZE = (1080, 1920) # 9:16 aspect ratio
79
+
80
+ def init_session_state():
81
+ """Initialize session state variables"""
82
+ defaults = {
83
+ 'video_ready': False,
84
+ 'output_path': None,
85
+ 'analysis': None,
86
+ 'segments': [],
87
+ 'current_segment': 0,
88
+ 'approved_clips': [],
89
+ 'user_images_paths': [],
90
+ 'reference_video_path': None,
91
+ 'audio_path': None,
92
+ 'current_code': None,
93
+ 'preview_path': None,
94
+ 'api_key_valid': False
95
+ }
96
+
97
+ for key, value in defaults.items():
98
+ if key not in st.session_state:
99
+ st.session_state[key] = value
100
+
101
+ def process_image_to_portrait(image_file):
102
+ """Fix phone orientation and force resize to 9:16 (1080x1920)"""
103
+ try:
104
+ image_bytes = image_file.getvalue()
105
+ img = Image.open(io.BytesIO(image_bytes))
106
+
107
+ if img.mode != 'RGB':
108
+ img = img.convert('RGB')
109
+
110
+ # Fix orientation using EXIF
111
+ img = ImageOps.exif_transpose(img)
112
+
113
+ # Force 9:16 aspect ratio
114
+ target_width, target_height = TARGET_SIZE
115
+ target_ratio = target_width / target_height
116
+ current_width, current_height = img.size
117
+ current_ratio = current_width / current_height
118
+
119
+ if current_ratio > target_ratio:
120
+ # Crop width
121
+ new_width = int(target_ratio * current_height)
122
+ left = (current_width - new_width) // 2
123
+ img = img.crop((left, 0, left + new_width, current_height))
124
+ else:
125
+ # Crop height
126
+ new_height = int(current_width / target_ratio)
127
+ top = (current_height - new_height) // 2
128
+ img = img.crop((0, top, current_width, top + new_height))
129
+
130
+ # Resize to exact dimensions
131
+ img = img.resize(TARGET_SIZE, Image.Resampling.LANCZOS)
132
+
133
+ return img
134
+ except Exception as e:
135
+ st.warning(f"⚠️ Error processing image: {str(e)}")
136
+ return None
137
+
138
+ def save_uploaded_images(uploaded_images):
139
+ """Save and process uploaded images"""
140
+ temp_dir = tempfile.mkdtemp()
141
+ image_paths = []
142
+
143
+ for idx, img_file in enumerate(uploaded_images):
144
+ processed_img = process_image_to_portrait(img_file)
145
+ if processed_img:
146
+ try:
147
+ path = os.path.join(temp_dir, f"img_{idx:03d}.jpg")
148
+ processed_img.save(path, 'JPEG', quality=95, optimize=True)
149
+ image_paths.append(path)
150
+ processed_img.close()
151
+ except Exception as e:
152
+ st.warning(f"⚠️ Could not save image {idx+1}: {str(e)}")
153
+
154
+ if idx % 5 == 0:
155
+ gc.collect()
156
+
157
+ return image_paths
158
+
159
+ def extract_audio_from_video(video_path):
160
+ """Extract audio from video file"""
161
+ try:
162
+ video = VideoFileClip(video_path)
163
+ audio_path = os.path.join(tempfile.gettempdir(), "reference_audio.mp3")
164
+
165
+ if video.audio is not None:
166
+ video.audio.write_audiofile(audio_path, logger=None)
167
+ video.close()
168
+ return audio_path
169
+ else:
170
+ video.close()
171
+ st.warning("⚠️ Reference video has no audio")
172
+ return None
173
+ except Exception as e:
174
+ st.error(f"Error extracting audio: {e}")
175
+ return None
176
+
177
+ def main():
178
+ init_session_state()
179
+
180
+ # Header
181
+ st.markdown('<div class="main-header">🤖 AI Video Editor V2</div>', unsafe_allow_html=True)
182
+ st.markdown('<div class="sub-header">Transform any reel with AI-powered video generation</div>', unsafe_allow_html=True)
183
+
184
+ # API Key input in sidebar - REQUIRED FOR USER INPUT
185
+ with st.sidebar:
186
+ st.markdown("### 🔑 API Configuration")
187
+
188
+ st.markdown("""
189
+ <div class="api-key-box">
190
+ <strong>⚠️ API Key Required</strong><br>
191
+ Get your <strong>FREE</strong> Gemini API key from:<br>
192
+ <a href="https://aistudio.google.com/apikey" target="_blank">
193
+ https://aistudio.google.com/apikey
194
+ </a>
195
+ </div>
196
+ """, unsafe_allow_html=True)
197
+
198
+ api_key = st.text_input(
199
+ "Enter Your Gemini API Key",
200
+ type="password",
201
+ help="Your API key is never stored. It's only used for this session.",
202
+ placeholder="Enter your API key here..."
203
+ )
204
+
205
+ if not api_key:
206
+ st.error("⚠️ Please enter your API key to use the app")
207
+ st.info("""
208
+ **Free Tier Limits:**
209
+ - ✅ 10 requests/minute
210
+ - ✅ 250 requests/day
211
+ - ✅ 250K tokens/minute
212
+ - ✅ Completely FREE
213
+ """)
214
+ else:
215
+ st.success("✅ API Key configured")
216
+ st.session_state.api_key_valid = True
217
+
218
+ st.markdown("---")
219
+ st.markdown("### 📊 Progress")
220
+ if st.session_state.segments:
221
+ progress = st.session_state.current_segment / len(st.session_state.segments)
222
+ st.progress(progress)
223
+ st.metric("Segments Approved", f"{len(st.session_state.approved_clips)}/{len(st.session_state.segments)}")
224
+
225
+ st.markdown("---")
226
+ st.markdown("### 💡 How It Works")
227
+ st.markdown("""
228
+ 1. Upload reference video & photos
229
+ 2. AI analyzes video structure
230
+ 3. Review each 3-second segment
231
+ 4. Approve or regenerate
232
+ 5. Download final video
233
+ """)
234
+
235
+ # Main content - only show if API key is provided
236
+ if not api_key:
237
+ st.warning("👈 Please enter your Gemini API key in the sidebar to get started")
238
+
239
+ # Show demo/instructions
240
+ st.markdown("## 🎬 How This Works")
241
+ col1, col2, col3 = st.columns(3)
242
+
243
+ with col1:
244
+ st.markdown("### 1️⃣ Upload")
245
+ st.info("Upload a reference reel and your photos")
246
+
247
+ with col2:
248
+ st.markdown("### 2️⃣ AI Analysis")
249
+ st.info("AI analyzes transitions, timing, and effects")
250
+
251
+ with col3:
252
+ st.markdown("### 3️⃣ Generate")
253
+ st.info("Review and approve each segment")
254
+
255
+ st.markdown("---")
256
+ st.markdown("### 🆓 Free Tier Benefits")
257
+ st.success("""
258
+ With Gemini 2.5 Flash free tier, you can:
259
+ - Create 3-4 complete videos per day
260
+ - Analyze videos up to 60 seconds
261
+ - Generate 20-30 segments per video
262
+ - **100% FREE - No credit card required**
263
+ """)
264
+
265
+ return
266
+
267
+ # Main tabs
268
+ tab1, tab2, tab3, tab4 = st.tabs(["📤 Upload", "🔍 Analysis", "🎬 Generation", "⬇️ Download"])
269
+
270
+ with tab1:
271
+ upload_section(api_key)
272
+
273
+ with tab2:
274
+ analysis_section()
275
+
276
+ with tab3:
277
+ generation_section(api_key)
278
+
279
+ with tab4:
280
+ download_section()
281
+
282
+ def upload_section(api_key):
283
+ """Upload reference video and user images"""
284
+ st.markdown("## 📤 Upload Your Content")
285
+
286
+ col1, col2 = st.columns(2)
287
+
288
+ with col1:
289
+ st.markdown("### 🎥 Reference Video")
290
+ st.markdown("Upload the reel/video you want to recreate")
291
+ reference_video = st.file_uploader(
292
+ "Upload reference video",
293
+ type=['mp4', 'mov', 'avi', 'mkv'],
294
+ help="This video will be analyzed for transitions, timing, and effects"
295
+ )
296
+
297
+ if reference_video:
298
+ st.video(reference_video)
299
+
300
+ with col2:
301
+ st.markdown("### 📸 Your Photos")
302
+ st.markdown("Upload photos to use in your video")
303
+ user_images = st.file_uploader(
304
+ "Upload your photos",
305
+ type=['jpg', 'jpeg', 'png'],
306
+ accept_multiple_files=True,
307
+ help="Upload 5-20 photos for best results"
308
+ )
309
+
310
+ if user_images:
311
+ st.info(f"✅ {len(user_images)} photos uploaded")
312
+ # Show thumbnail grid
313
+ cols = st.columns(5)
314
+ for idx, img in enumerate(user_images[:10]):
315
+ with cols[idx % 5]:
316
+ st.image(img, use_container_width=True)
317
+ if len(user_images) > 10:
318
+ st.caption(f"...and {len(user_images) - 10} more")
319
+
320
+ st.markdown("---")
321
+
322
+ if reference_video and user_images:
323
+ if st.button("🚀 Analyze Video & Start Generation", width=200):
324
+ with st.spinner("🔍 Analyzing reference video..."):
325
+ try:
326
+ # Save reference video
327
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_video:
328
+ tmp_video.write(reference_video.read())
329
+ video_path = tmp_video.name
330
+
331
+ st.session_state.reference_video_path = video_path
332
+
333
+ # Extract audio
334
+ audio_path = extract_audio_from_video(video_path)
335
+ st.session_state.audio_path = audio_path
336
+
337
+ # Process and save user images
338
+ with st.spinner("📸 Processing your photos..."):
339
+ image_paths = save_uploaded_images(user_images)
340
+ st.session_state.user_images_paths = image_paths
341
+
342
+ # Analyze video
343
+ with st.spinner("🤖 AI is analyzing the video structure..."):
344
+ analyzer = VideoAnalyzer(api_key)
345
+ analysis = analyzer.analyze_reference_video(video_path)
346
+ st.session_state.analysis = analysis
347
+ st.session_state.segments = analysis['segments']
348
+
349
+ st.success("✅ Analysis complete! Go to 'Analysis' tab to review")
350
+ st.balloons()
351
+
352
+ except Exception as e:
353
+ st.error(f"❌ Error during analysis: {str(e)}")
354
+ st.exception(e)
355
+ else:
356
+ if not reference_video:
357
+ st.info("👆 Upload a reference video to begin")
358
+ elif not user_images:
359
+ st.info("👆 Upload your photos to continue")
360
+
361
+ def analysis_section():
362
+ """Display video analysis results"""
363
+ if not st.session_state.analysis:
364
+ st.info("👈 Upload and analyze a video first in the Upload tab")
365
+ return
366
+
367
+ st.markdown("## 🔍 Video Analysis Results")
368
+
369
+ analysis = st.session_state.analysis
370
+
371
+ # Summary metrics
372
+ col1, col2, col3, col4 = st.columns(4)
373
+ with col1:
374
+ st.metric("Duration", f"{analysis['duration']:.1f}s")
375
+ with col2:
376
+ st.metric("Segments", len(analysis['segments']))
377
+ with col3:
378
+ st.metric("FPS", analysis.get('fps', 30))
379
+ with col4:
380
+ st.metric("Style", analysis.get('style', 'Modern'))
381
+
382
+ st.markdown("---")
383
+
384
+ # Detailed segment breakdown
385
+ st.markdown("### 📋 Segment Breakdown")
386
+
387
+ for idx, segment in enumerate(analysis['segments']):
388
+ with st.expander(f"Segment {idx + 1}: {segment['start_time']:.1f}s - {segment['end_time']:.1f}s"):
389
+ col1, col2 = st.columns(2)
390
+
391
+ with col1:
392
+ st.markdown(f"**Duration:** {segment['duration']:.2f}s")
393
+ st.markdown(f"**Transition In:** {segment['transition_in']}")
394
+ st.markdown(f"**Transition Out:** {segment['transition_out']}")
395
+
396
+ with col2:
397
+ st.markdown(f"**Camera Movement:** {segment['camera_movement']}")
398
+ st.markdown(f"**Zoom Level:** {segment['zoom_level']}")
399
+ st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
400
+
401
+ st.markdown("---")
402
+
403
+ # Start generation button
404
+ if st.button("✨ Start Video Generation", use_container_width=True):
405
+ st.session_state.current_segment = 0
406
+ st.session_state.approved_clips = []
407
+ st.info("👉 Go to 'Generation' tab to create your video!")
408
+ st.rerun()
409
+
410
+ def generation_section(api_key):
411
+ """Iterative segment generation with human-in-the-loop"""
412
+ if not st.session_state.segments:
413
+ st.info("👈 Analyze a video first in the Analysis tab")
414
+ return
415
+
416
+ current_idx = st.session_state.current_segment
417
+ total_segments = len(st.session_state.segments)
418
+
419
+ if current_idx >= total_segments:
420
+ st.success("🎉 All segments completed! Go to Download tab to render final video")
421
+ return
422
+
423
+ st.markdown(f"## 🎬 Segment {current_idx + 1} / {total_segments}")
424
+
425
+ segment = st.session_state.segments[current_idx]
426
+
427
+ # Segment info card
428
+ st.markdown('<div class="segment-card">', unsafe_allow_html=True)
429
+ col1, col2, col3 = st.columns(3)
430
+ with col1:
431
+ st.metric("Time", f"{segment['start_time']:.1f}s - {segment['end_time']:.1f}s")
432
+ with col2:
433
+ st.metric("Duration", f"{segment['duration']:.2f}s")
434
+ with col3:
435
+ st.metric("Transition", segment['transition_in'])
436
+
437
+ st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
438
+ st.markdown(f"**Camera:** {segment['camera_movement']}")
439
+ st.markdown('</div>', unsafe_allow_html=True)
440
+
441
+ st.markdown("---")
442
+
443
+ # Generate button
444
+ col1, col2 = st.columns([3, 1])
445
+ with col1:
446
+ if st.button("🎬 Generate This Segment", use_container_width=True):
447
+ generate_segment(api_key, segment, current_idx)
448
+
449
+ with col2:
450
+ if st.button("⏭️ Skip", use_container_width=True):
451
+ st.session_state.current_segment += 1
452
+ st.rerun()
453
+
454
+ # Show preview if generated
455
+ if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
456
+ st.markdown("### 🎥 Preview")
457
+ st.markdown('<div class="video-container">', unsafe_allow_html=True)
458
+ st.video(st.session_state.preview_path)
459
+ st.markdown('</div>', unsafe_allow_html=True)
460
+
461
+ # Show generated code
462
+ if st.session_state.current_code:
463
+ with st.expander("📝 View Generated Code"):
464
+ st.code(st.session_state.current_code, language='python')
465
+
466
+ st.markdown("---")
467
+
468
+ # Approval actions
469
+ st.markdown("### ✅ Review & Approve")
470
+
471
+ col1, col2, col3 = st.columns(3)
472
+
473
+ with col1:
474
+ if st.button("✅ Approve & Continue", use_container_width=True, type="primary"):
475
+ st.session_state.approved_clips.append(st.session_state.preview_path)
476
+ st.session_state.current_segment += 1
477
+ st.session_state.preview_path = None
478
+ st.session_state.current_code = None
479
+ st.success("Segment approved!")
480
+ time.sleep(0.5)
481
+ st.rerun()
482
+
483
+ with col2:
484
+ feedback = st.text_input("What needs improvement?", key=f"feedback_{current_idx}")
485
+ if st.button("🔄 Regenerate", use_container_width=True) and feedback:
486
+ regenerate_segment(api_key, segment, current_idx, feedback)
487
+
488
+ with col3:
489
+ if st.button("❌ Discard & Skip", use_container_width=True):
490
+ if os.path.exists(st.session_state.preview_path):
491
+ os.remove(st.session_state.preview_path)
492
+ st.session_state.current_segment += 1
493
+ st.session_state.preview_path = None
494
+ st.session_state.current_code = None
495
+ st.rerun()
496
+
497
+ def generate_segment(api_key, segment, segment_idx):
498
+ """Generate code and video for a segment"""
499
+ try:
500
+ with st.spinner("🤖 Generating code..."):
501
+ generator = VideoCodeGenerator(api_key)
502
+
503
+ # Get previous code for context
504
+ previous_code = st.session_state.current_code if segment_idx > 0 else None
505
+
506
+ # Generate code
507
+ code = generator.generate_segment_code(
508
+ segment,
509
+ st.session_state.user_images_paths,
510
+ st.session_state.audio_path or st.session_state.reference_video_path,
511
+ segment_idx,
512
+ previous_code
513
+ )
514
+
515
+ st.session_state.current_code = code
516
+
517
+ with st.spinner("🎬 Rendering video..."):
518
+ # Execute code
519
+ executor = VideoExecutor()
520
+ video_path = executor.execute_code(
521
+ code,
522
+ st.session_state.user_images_paths,
523
+ st.session_state.audio_path or st.session_state.reference_video_path,
524
+ segment_idx
525
+ )
526
+
527
+ st.session_state.preview_path = video_path
528
+ st.success("✅ Segment generated!")
529
+ st.rerun()
530
+
531
+ except Exception as e:
532
+ st.error(f"❌ Error generating segment: {str(e)}")
533
+ with st.expander("🐛 Error Details"):
534
+ st.exception(e)
535
+
536
+ def regenerate_segment(api_key, segment, segment_idx, feedback):
537
+ """Regenerate segment based on user feedback"""
538
+ try:
539
+ with st.spinner(f"🔄 Regenerating with feedback: '{feedback}'..."):
540
+ generator = VideoCodeGenerator(api_key)
541
+
542
+ # Regenerate with feedback
543
+ new_code = generator.regenerate_segment(
544
+ segment,
545
+ feedback,
546
+ st.session_state.current_code,
547
+ segment_idx
548
+ )
549
+
550
+ st.session_state.current_code = new_code
551
+
552
+ with st.spinner("🎬 Rendering updated video..."):
553
+ executor = VideoExecutor()
554
+ video_path = executor.execute_code(
555
+ new_code,
556
+ st.session_state.user_images_paths,
557
+ st.session_state.audio_path or st.session_state.reference_video_path,
558
+ segment_idx
559
+ )
560
+
561
+ # Remove old preview
562
+ if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
563
+ os.remove(st.session_state.preview_path)
564
+
565
+ st.session_state.preview_path = video_path
566
+ st.success("✅ Segment regenerated!")
567
+ st.rerun()
568
+
569
+ except Exception as e:
570
+ st.error(f"❌ Error regenerating segment: {str(e)}")
571
+ st.exception(e)
572
+
573
+ def download_section():
574
+ """Render and download final video"""
575
+ if not st.session_state.approved_clips:
576
+ st.info("👈 Generate and approve segments first in the Generation tab")
577
+ return
578
+
579
+ st.markdown("## ⬇️ Final Video")
580
+
581
+ total_segments = len(st.session_state.segments)
582
+ approved_count = len(st.session_state.approved_clips)
583
+
584
+ col1, col2 = st.columns(2)
585
+ with col1:
586
+ st.metric("Total Segments", total_segments)
587
+ with col2:
588
+ st.metric("Approved Segments", approved_count)
589
+
590
+ if approved_count < total_segments:
591
+ st.warning(f"⚠️ You have only approved {approved_count}/{total_segments} segments. Continue to Generation tab to complete all segments.")
592
+
593
+ st.markdown("---")
594
+
595
+ if st.button("🎥 Render Final Video", use_container_width=True, type="primary"):
596
+ render_final_video()
597
+
598
+ # Show final video if already rendered
599
+ if st.session_state.output_path and os.path.exists(st.session_state.output_path):
600
+ st.markdown("### 🎉 Your Final Video")
601
+ st.markdown('<div class="video-container">', unsafe_allow_html=True)
602
+ st.video(st.session_state.output_path)
603
+ st.markdown('</div>', unsafe_allow_html=True)
604
+
605
+ # Download button
606
+ with open(st.session_state.output_path, 'rb') as f:
607
+ video_bytes = f.read()
608
+ st.download_button(
609
+ label="📥 Download Video",
610
+ data=video_bytes,
611
+ file_name="ai_generated_video.mp4",
612
+ mime="video/mp4",
613
+ use_container_width=True
614
+ )
615
+
616
+ def render_final_video():
617
+ """Combine all approved segments into final video"""
618
+ try:
619
+ with st.spinner("🎬 Combining segments..."):
620
+ clips = []
621
+ for path in st.session_state.approved_clips:
622
+ if os.path.exists(path):
623
+ clip = VideoFileClip(path)
624
+ clips.append(clip)
625
+
626
+ if not clips:
627
+ st.error("❌ No valid clips to combine")
628
+ return
629
+
630
+ # Concatenate clips
631
+ final_clip = concatenate_videoclips(clips, method="compose")
632
+
633
+ # Output path
634
+ output_path = os.path.join(tempfile.gettempdir(), "final_ai_video.mp4")
635
+
636
+ # Write final video
637
+ final_clip.write_videofile(
638
+ output_path,
639
+ fps=30,
640
+ codec="libx264",
641
+ audio_codec="aac",
642
+ threads=4,
643
+ logger=None
644
+ )
645
+
646
+ # Cleanup
647
+ for clip in clips:
648
+ clip.close()
649
+ final_clip.close()
650
+
651
+ st.session_state.output_path = output_path
652
+ st.session_state.video_ready = True
653
+
654
+ st.success("✅ Final video rendered successfully!")
655
+ st.balloons()
656
+ st.rerun()
657
+
658
+ except Exception as e:
659
+ st.error(f"❌ Error rendering final video: {str(e)}")
660
+ st.exception(e)
661
+
662
+ if __name__ == "__main__":
663
+ main()
code_generator.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import os
3
+
4
+ class VideoCodeGenerator:
5
+ def __init__(self, api_key):
6
+ """Initialize Gemini 2.5 Flash for code generation"""
7
+ genai.configure(api_key=api_key)
8
+ self.model = genai.GenerativeModel('gemini-2.5-flash')
9
+
10
+ def generate_segment_code(self, segment_info, user_images, audio_path,
11
+ segment_number, previous_code=None):
12
+ """Generate MoviePy code for a video segment"""
13
+
14
+ print(f"🤖 Generating code for segment {segment_number}...")
15
+
16
+ context = ""
17
+ if previous_code:
18
+ context = f"""PREVIOUS SEGMENT CODE FOR REFERENCE:
19
+ ```python
20
+ {previous_code[:1000]} # Truncated
21
+ ```
22
+
23
+ Build upon this style and ensure smooth continuation.
24
+
25
+ """
26
+
27
+ prompt = f"""{context}Generate Python MoviePy code for video segment {segment_number}.
28
+
29
+ SEGMENT SPECIFICATIONS:
30
+ - Start time: {segment_info['start_time']:.2f}s
31
+ - End time: {segment_info['end_time']:.2f}s
32
+ - Duration: {segment_info['duration']:.2f}s
33
+ - Transition IN: {segment_info['transition_in']}
34
+ - Transition OUT: {segment_info['transition_out']}
35
+ - Camera movement: {segment_info['camera_movement']}
36
+ - Zoom level: {segment_info['zoom_level']}
37
+ - Effects: {segment_info['effects']}
38
+ - Image position: {segment_info['image_position']}
39
+
40
+ AVAILABLE RESOURCES:
41
+ - Images: {len(user_images)} photos available
42
+ - Audio file path: {audio_path}
43
+ - Target resolution: 1080x1920 (9:16 portrait)
44
+ - Target FPS: 30
45
+
46
+ CODE REQUIREMENTS:
47
+ 1. Import necessary MoviePy modules: from moviepy.editor import *
48
+ 2. Create a function: create_segment_{segment_number}(images, audio_path)
49
+ 3. Function must return a CompositeVideoClip object
50
+ 4. Apply the specified transitions, camera movements, and effects
51
+ 5. Use images from the 'images' list (cycle through them)
52
+ 6. Sync timing with the audio (extract audio segment {segment_info['start_time']:.2f}s to {segment_info['end_time']:.2f}s)
53
+ 7. All clips must be exactly {segment_info['duration']:.2f} seconds
54
+ 8. Handle image orientation and aspect ratio (crop/resize to 9:16)
55
+
56
+ TRANSITION IMPLEMENTATIONS:
57
+ - fade: Use crossfadein/crossfadeout
58
+ - slide_left/right: Use set_position with animated x values
59
+ - zoom_in/out: Use resize with size changing over time
60
+ - wipe: Use mask animations
61
+ - cut: Direct clip placement
62
+
63
+ CAMERA MOVEMENTS:
64
+ - zoom_in: Start at scale 1.0, end at {segment_info['zoom_level']}
65
+ - zoom_out: Start at {segment_info['zoom_level']}, end at 1.0
66
+ - pan_left/right: Animate x position
67
+ - static: No movement
68
+
69
+ EFFECTS:
70
+ - vignette: Apply dark edges
71
+ - blur: Use gaussian blur filter
72
+ - color_grade: Adjust colors/brightness
73
+ - glitch: Random frame distortions
74
+ - flash: White overlay fade
75
+
76
+ EXAMPLE STRUCTURE:
77
+ ```python
78
+ from moviepy.editor import *
79
+ import numpy as np
80
+
81
+ def create_segment_{segment_number}(images, audio_path):
82
+ # Load audio segment
83
+ audio = AudioFileClip(audio_path).subclip({segment_info['start_time']:.2f}, {segment_info['end_time']:.2f})
84
+
85
+ # Select image (cycle through list)
86
+ img_path = images[{segment_number} % len(images)]
87
+
88
+ # Create image clip with proper sizing
89
+ img_clip = ImageClip(img_path).set_duration({segment_info['duration']:.2f})
90
+
91
+ # Apply camera movement (zoom, pan, etc.)
92
+ # ... your implementation ...
93
+
94
+ # Apply transition IN
95
+ # ... your implementation ...
96
+
97
+ # Apply effects
98
+ # ... your implementation ...
99
+
100
+ # Composite final clip
101
+ final_clip = CompositeVideoClip([img_clip], size=(1080, 1920))
102
+ final_clip = final_clip.set_audio(audio)
103
+
104
+ return final_clip
105
+ ```
106
+
107
+ Generate ONLY the complete, executable Python code. No explanations, no markdown except the code block.
108
+ The code must be production-ready and handle errors gracefully."""
109
+
110
+ response = self.model.generate_content(prompt)
111
+ code = self.extract_code_block(response.text)
112
+
113
+ print(f"✅ Code generated ({len(code)} characters)")
114
+
115
+ return code
116
+
117
+ def regenerate_segment(self, segment_info, user_feedback, previous_code, segment_number):
118
+ """Regenerate code based on user feedback"""
119
+
120
+ print(f"🔄 Regenerating segment {segment_number} with feedback...")
121
+
122
+ prompt = f"""The user reviewed the generated video segment and provided feedback.
123
+
124
+ PREVIOUS CODE:
125
+ ```python
126
+ {previous_code}
127
+ ```
128
+
129
+ USER FEEDBACK: "{user_feedback}"
130
+
131
+ SEGMENT SPECS:
132
+ - Start: {segment_info['start_time']:.2f}s
133
+ - End: {segment_info['end_time']:.2f}s
134
+ - Duration: {segment_info['duration']:.2f}s
135
+ - Transition IN: {segment_info['transition_in']}
136
+ - Transition OUT: {segment_info['transition_out']}
137
+ - Camera: {segment_info['camera_movement']}
138
+ - Effects: {segment_info['effects']}
139
+
140
+ TASK:
141
+ 1. Analyze the user's feedback carefully
142
+ 2. Identify what needs to be changed in the code
143
+ 3. Keep the same function signature: create_segment_{segment_number}(images, audio_path)
144
+ 4. Modify the implementation to address the feedback
145
+ 5. Maintain compatibility with the MoviePy framework
146
+
147
+ Common feedback types:
148
+ - "Too fast/slow" → Adjust animation timing
149
+ - "Wrong transition" → Change transition type
150
+ - "Image positioning" → Adjust crop/position
151
+ - "Effects too strong/weak" → Adjust effect intensity
152
+ - "Not smooth" → Add easing functions
153
+
154
+ Generate the IMPROVED code that addresses the feedback.
155
+ Return ONLY executable Python code, no explanations."""
156
+
157
+ response = self.model.generate_content(prompt)
158
+ code = self.extract_code_block(response.text)
159
+
160
+ print(f"✅ Code regenerated")
161
+
162
+ return code
163
+
164
+ def extract_code_block(self, response_text):
165
+ """Extract Python code from markdown code blocks"""
166
+ response_text = response_text.strip()
167
+
168
+ # Remove markdown code blocks
169
+ if "```python" in response_text:
170
+ code = response_text.split("```python")[1].split("```")[0]
171
+ elif "```" in response_text:
172
+ parts = response_text.split("```")
173
+ # Find the code block (usually the largest one)
174
+ code = max(parts[1::2], key=len) if len(parts) > 1 else response_text
175
+ else:
176
+ code = response_text
177
+
178
+
requirements.txt CHANGED
@@ -1,3 +1,12 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.38.0
2
+ google-generativeai==0.8.3
3
+ moviepy==1.0.3
4
+ opencv-python-headless==4.9.0.80
5
+ numpy==1.24.3
6
+ pillow==10.2.0
7
+ imageio==2.34.0
8
+ imageio-ffmpeg==0.4.9
9
+ requests==2.31.0
10
+ decorator==4.4.2
11
+ proglog==0.1.10
12
+ tqdm==4.66.1
streamlit/config.toml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ maxUploadSize = 500
3
+ enableXsrfProtection = false
4
+ enableCORS = true
5
+ headless = true
6
+
7
+ [browser]
8
+ gatherUsageStats = false
9
+
video_executor.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import tempfile
4
+ from pathlib import Path
5
+ import traceback
6
+
7
+ class VideoExecutor:
8
+ def __init__(self):
9
+ """Initialize video code executor"""
10
+ self.temp_dir = tempfile.gettempdir()
11
+
12
+ def execute_code(self, code, images, audio_path, segment_number):
13
+ """Execute generated code safely and return video path"""
14
+
15
+ print(f"⚙️ Executing segment {segment_number} code...")
16
+
17
+ # Create execution environment
18
+ exec_globals = {
19
+ '__builtins__': __builtins__,
20
+ 'images': images,
21
+ 'audio_path': audio_path,
22
+ }
23
+
24
+ # Import necessary modules into execution environment
25
+ exec("""
26
+ from moviepy.editor import *
27
+ import numpy as np
28
+ import cv2
29
+ from PIL import Image
30
+ import random
31
+ """, exec_globals)
32
+
33
+ try:
34
+ # Execute the generated code
35
+ exec(code, exec_globals)
36
+
37
+ # Find the segment creation function
38
+ func_name = f'create_segment_{segment_number}'
39
+
40
+ if func_name not in exec_globals:
41
+ raise ValueError(f"❌ Function '{func_name}' not found in generated code")
42
+
43
+ # Call the function
44
+ segment_func = exec_globals[func_name]
45
+ clip = segment_func(images, audio_path)
46
+
47
+ if clip is None:
48
+ raise ValueError("❌ Function returned None instead of a clip")
49
+
50
+ # Render to temp file
51
+ output_path = os.path.join(self.temp_dir, f"segment_{segment_number}_{os.urandom(4).hex()}.mp4")
52
+
53
+ print(f"🎬 Rendering segment to: {output_path}")
54
+
55
+ clip.write_videofile(
56
+ output_path,
57
+ fps=30,
58
+ codec="libx264",
59
+ audio_codec="aac",
60
+ preset='medium',
61
+ threads=4,
62
+ logger=None
63
+ )
64
+
65
+ # Cleanup
66
+ clip.close()
67
+
68
+ print(f"✅ Segment {segment_number} rendered successfully")
69
+
70
+ return output_path
71
+
72
+ except Exception as e:
73
+ print(f"❌ Error executing code: {str(e)}")
74
+ print("Traceback:")
75
+ traceback.print_exc()
76
+ raise e
77
+
78
+ def validate_code(self, code):
79
+ """Basic validation of generated code"""
80
+
81
+ # Check for dangerous operations
82
+ dangerous_patterns = [
83
+ 'os.system',
84
+ 'subprocess',
85
+ 'eval(',
86
+ '__import__',
87
+ 'open(',
88
+ 'file(',
89
+ ]
90
+
91
+ for pattern in dangerous_patterns:
92
+ if pattern in code:
93
+ raise ValueError(f"⚠️ Potentially dangerous operation detected: {pattern}")
94
+
95
+ # Check for required imports
96
+ required_patterns = [
97
+ 'from moviepy',
98
+ 'def create_segment_',
99
+ 'return '
100
+ ]
101
+
102
+ for pattern in required_patterns:
103
+ if pattern not in code:
104
+ raise ValueError(f"⚠️ Required pattern missing: {pattern}")