import streamlit as st
import os
import tempfile
from pathlib import Path
import time
import gc
from PIL import Image, ImageOps
import io
import json
from moviepy.editor import VideoFileClip, concatenate_videoclips
from ai_video_analyzer import VideoAnalyzer
from code_generator import VideoCodeGenerator
from video_executor import VideoExecutor
# Page config
st.set_page_config(
page_title="AI Video Editor V2",
page_icon="🤖",
layout="wide"
)
# Custom CSS
st.markdown("""
""", unsafe_allow_html=True)
TARGET_SIZE = (1080, 1920) # 9:16 aspect ratio
def init_session_state():
"""Initialize session state variables"""
defaults = {
'video_ready': False,
'output_path': None,
'analysis': None,
'segments': [],
'current_segment': 0,
'approved_clips': [],
'user_images_paths': [],
'reference_video_path': None,
'audio_path': None,
'current_code': None,
'preview_path': None,
'api_key_valid': False
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
def process_image_to_portrait(image_file):
"""Fix phone orientation and force resize to 9:16 (1080x1920)"""
try:
image_bytes = image_file.getvalue()
img = Image.open(io.BytesIO(image_bytes))
if img.mode != 'RGB':
img = img.convert('RGB')
# Fix orientation using EXIF
img = ImageOps.exif_transpose(img)
# Force 9:16 aspect ratio
target_width, target_height = TARGET_SIZE
target_ratio = target_width / target_height
current_width, current_height = img.size
current_ratio = current_width / current_height
if current_ratio > target_ratio:
# Crop width
new_width = int(target_ratio * current_height)
left = (current_width - new_width) // 2
img = img.crop((left, 0, left + new_width, current_height))
else:
# Crop height
new_height = int(current_width / target_ratio)
top = (current_height - new_height) // 2
img = img.crop((0, top, current_width, top + new_height))
# Resize to exact dimensions
img = img.resize(TARGET_SIZE, Image.Resampling.LANCZOS)
return img
except Exception as e:
st.warning(f"⚠️ Error processing image: {str(e)}")
return None
def save_uploaded_images(uploaded_images):
"""Save and process uploaded images"""
temp_dir = tempfile.mkdtemp()
image_paths = []
for idx, img_file in enumerate(uploaded_images):
processed_img = process_image_to_portrait(img_file)
if processed_img:
try:
path = os.path.join(temp_dir, f"img_{idx:03d}.jpg")
processed_img.save(path, 'JPEG', quality=95, optimize=True)
image_paths.append(path)
processed_img.close()
except Exception as e:
st.warning(f"⚠️ Could not save image {idx+1}: {str(e)}")
if idx % 5 == 0:
gc.collect()
return image_paths
def extract_audio_from_video(video_path):
"""Extract audio from video file"""
try:
video = VideoFileClip(video_path)
audio_path = os.path.join(tempfile.gettempdir(), "reference_audio.mp3")
if video.audio is not None:
video.audio.write_audiofile(audio_path, logger=None)
video.close()
return audio_path
else:
video.close()
st.warning("⚠️ Reference video has no audio")
return None
except Exception as e:
st.error(f"Error extracting audio: {e}")
return None
def main():
init_session_state()
# Header
st.markdown('
🤖 AI Video Editor V2
', unsafe_allow_html=True)
st.markdown('', unsafe_allow_html=True)
# API Key input in sidebar - REQUIRED FOR USER INPUT
with st.sidebar:
st.markdown("### 🔑 API Configuration")
st.markdown("""
""", unsafe_allow_html=True)
api_key = st.text_input(
"Enter Your Gemini API Key",
type="password",
help="Your API key is never stored. It's only used for this session.",
placeholder="Enter your API key here..."
)
if not api_key:
st.error("⚠️ Please enter your API key to use the app")
st.info("""
**Free Tier Limits:**
- ✅ 10 requests/minute
- ✅ 250 requests/day
- ✅ 250K tokens/minute
- ✅ Completely FREE
""")
else:
st.success("✅ API Key configured")
st.session_state.api_key_valid = True
st.markdown("---")
st.markdown("### 📊 Progress")
if st.session_state.segments:
progress = st.session_state.current_segment / len(st.session_state.segments)
st.progress(progress)
st.metric("Segments Approved", f"{len(st.session_state.approved_clips)}/{len(st.session_state.segments)}")
st.markdown("---")
st.markdown("### 💡 How It Works")
st.markdown("""
1. Upload reference video & photos
2. AI analyzes video structure
3. Review each 3-second segment
4. Approve or regenerate
5. Download final video
""")
# Main content - only show if API key is provided
if not api_key:
st.warning("👈 Please enter your Gemini API key in the sidebar to get started")
# Show demo/instructions
st.markdown("## 🎬 How This Works")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("### 1️⃣ Upload")
st.info("Upload a reference reel and your photos")
with col2:
st.markdown("### 2️⃣ AI Analysis")
st.info("AI analyzes transitions, timing, and effects")
with col3:
st.markdown("### 3️⃣ Generate")
st.info("Review and approve each segment")
st.markdown("---")
st.markdown("### 🆓 Free Tier Benefits")
st.success("""
With Gemini 2.5 Flash free tier, you can:
- Create 3-4 complete videos per day
- Analyze videos up to 60 seconds
- Generate 20-30 segments per video
- **100% FREE - No credit card required**
""")
return
# Main tabs
tab1, tab2, tab3, tab4 = st.tabs(["📤 Upload", "🔍 Analysis", "🎬 Generation", "⬇️ Download"])
with tab1:
upload_section(api_key)
with tab2:
analysis_section()
with tab3:
generation_section(api_key)
with tab4:
download_section()
def upload_section(api_key):
"""Upload reference video and user images"""
st.markdown("## 📤 Upload Your Content")
col1, col2 = st.columns(2)
with col1:
st.markdown("### 🎥 Reference Video")
st.markdown("Upload the reel/video you want to recreate")
reference_video = st.file_uploader(
"Upload reference video",
type=['mp4', 'mov', 'avi', 'mkv'],
help="This video will be analyzed for transitions, timing, and effects"
)
if reference_video:
st.video(reference_video)
with col2:
st.markdown("### 📸 Your Photos")
st.markdown("Upload photos to use in your video")
user_images = st.file_uploader(
"Upload your photos",
type=['jpg', 'jpeg', 'png'],
accept_multiple_files=True,
help="Upload 5-20 photos for best results"
)
if user_images:
st.info(f"✅ {len(user_images)} photos uploaded")
# Show thumbnail grid
cols = st.columns(5)
for idx, img in enumerate(user_images[:10]):
with cols[idx % 5]:
st.image(img, use_container_width=True)
if len(user_images) > 10:
st.caption(f"...and {len(user_images) - 10} more")
st.markdown("---")
if reference_video and user_images:
if st.button("🚀 Analyze Video & Start Generation", width=200):
with st.spinner("🔍 Analyzing reference video..."):
try:
# Save reference video
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as tmp_video:
tmp_video.write(reference_video.read())
video_path = tmp_video.name
st.session_state.reference_video_path = video_path
# Extract audio
audio_path = extract_audio_from_video(video_path)
st.session_state.audio_path = audio_path
# Process and save user images
with st.spinner("📸 Processing your photos..."):
image_paths = save_uploaded_images(user_images)
st.session_state.user_images_paths = image_paths
# Analyze video
with st.spinner("🤖 AI is analyzing the video structure..."):
analyzer = VideoAnalyzer(api_key)
analysis = analyzer.analyze_reference_video(video_path)
st.session_state.analysis = analysis
st.session_state.segments = analysis['segments']
st.success("✅ Analysis complete! Go to 'Analysis' tab to review")
st.balloons()
except Exception as e:
st.error(f"❌ Error during analysis: {str(e)}")
st.exception(e)
else:
if not reference_video:
st.info("👆 Upload a reference video to begin")
elif not user_images:
st.info("👆 Upload your photos to continue")
def analysis_section():
"""Display video analysis results"""
if not st.session_state.analysis:
st.info("👈 Upload and analyze a video first in the Upload tab")
return
st.markdown("## 🔍 Video Analysis Results")
analysis = st.session_state.analysis
# Summary metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Duration", f"{analysis['duration']:.1f}s")
with col2:
st.metric("Segments", len(analysis['segments']))
with col3:
st.metric("FPS", analysis.get('fps', 30))
with col4:
st.metric("Style", analysis.get('style', 'Modern'))
st.markdown("---")
# Detailed segment breakdown
st.markdown("### 📋 Segment Breakdown")
for idx, segment in enumerate(analysis['segments']):
with st.expander(f"Segment {idx + 1}: {segment['start_time']:.1f}s - {segment['end_time']:.1f}s"):
col1, col2 = st.columns(2)
with col1:
st.markdown(f"**Duration:** {segment['duration']:.2f}s")
st.markdown(f"**Transition In:** {segment['transition_in']}")
st.markdown(f"**Transition Out:** {segment['transition_out']}")
with col2:
st.markdown(f"**Camera Movement:** {segment['camera_movement']}")
st.markdown(f"**Zoom Level:** {segment['zoom_level']}")
st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
st.markdown("---")
# Start generation button
if st.button("✨ Start Video Generation", use_container_width=True):
st.session_state.current_segment = 0
st.session_state.approved_clips = []
st.info("👉 Go to 'Generation' tab to create your video!")
st.rerun()
def generation_section(api_key):
"""Iterative segment generation with human-in-the-loop"""
if not st.session_state.segments:
st.info("👈 Analyze a video first in the Analysis tab")
return
current_idx = st.session_state.current_segment
total_segments = len(st.session_state.segments)
if current_idx >= total_segments:
st.success("🎉 All segments completed! Go to Download tab to render final video")
return
st.markdown(f"## 🎬 Segment {current_idx + 1} / {total_segments}")
segment = st.session_state.segments[current_idx]
# Segment info card
st.markdown('', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Time", f"{segment['start_time']:.1f}s - {segment['end_time']:.1f}s")
with col2:
st.metric("Duration", f"{segment['duration']:.2f}s")
with col3:
st.metric("Transition", segment['transition_in'])
st.markdown(f"**Effects:** {', '.join(segment['effects']) if segment['effects'] else 'None'}")
st.markdown(f"**Camera:** {segment['camera_movement']}")
st.markdown('
', unsafe_allow_html=True)
st.markdown("---")
# Generate button
col1, col2 = st.columns([3, 1])
with col1:
if st.button("🎬 Generate This Segment", use_container_width=True):
generate_segment(api_key, segment, current_idx)
with col2:
if st.button("⏭️ Skip", use_container_width=True):
st.session_state.current_segment += 1
st.rerun()
# Show preview if generated
if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
st.markdown("### 🎥 Preview")
st.markdown('', unsafe_allow_html=True)
st.video(st.session_state.preview_path)
st.markdown('
', unsafe_allow_html=True)
# Show generated code
if st.session_state.current_code:
with st.expander("📝 View Generated Code"):
st.code(st.session_state.current_code, language='python')
st.markdown("---")
# Approval actions
st.markdown("### ✅ Review & Approve")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("✅ Approve & Continue", use_container_width=True, type="primary"):
st.session_state.approved_clips.append(st.session_state.preview_path)
st.session_state.current_segment += 1
st.session_state.preview_path = None
st.session_state.current_code = None
st.success("Segment approved!")
time.sleep(0.5)
st.rerun()
with col2:
feedback = st.text_input("What needs improvement?", key=f"feedback_{current_idx}")
if st.button("🔄 Regenerate", use_container_width=True) and feedback:
regenerate_segment(api_key, segment, current_idx, feedback)
with col3:
if st.button("❌ Discard & Skip", use_container_width=True):
if os.path.exists(st.session_state.preview_path):
os.remove(st.session_state.preview_path)
st.session_state.current_segment += 1
st.session_state.preview_path = None
st.session_state.current_code = None
st.rerun()
def generate_segment(api_key, segment, segment_idx):
"""Generate code and video for a segment"""
try:
with st.spinner("🤖 Generating code..."):
generator = VideoCodeGenerator(api_key)
# Get previous code for context
previous_code = st.session_state.current_code if segment_idx > 0 else None
# Generate code
code = generator.generate_segment_code(
segment,
st.session_state.user_images_paths,
st.session_state.audio_path or st.session_state.reference_video_path,
segment_idx,
previous_code
)
st.session_state.current_code = code
with st.spinner("🎬 Rendering video..."):
# Execute code
executor = VideoExecutor()
video_path = executor.execute_code(
code,
st.session_state.user_images_paths,
st.session_state.audio_path or st.session_state.reference_video_path,
segment_idx
)
st.session_state.preview_path = video_path
st.success("✅ Segment generated!")
st.rerun()
except Exception as e:
st.error(f"❌ Error generating segment: {str(e)}")
with st.expander("🐛 Error Details"):
st.exception(e)
def regenerate_segment(api_key, segment, segment_idx, feedback):
"""Regenerate segment based on user feedback"""
try:
with st.spinner(f"🔄 Regenerating with feedback: '{feedback}'..."):
generator = VideoCodeGenerator(api_key)
# Regenerate with feedback
new_code = generator.regenerate_segment(
segment,
feedback,
st.session_state.current_code,
segment_idx
)
st.session_state.current_code = new_code
with st.spinner("🎬 Rendering updated video..."):
executor = VideoExecutor()
video_path = executor.execute_code(
new_code,
st.session_state.user_images_paths,
st.session_state.audio_path or st.session_state.reference_video_path,
segment_idx
)
# Remove old preview
if st.session_state.preview_path and os.path.exists(st.session_state.preview_path):
os.remove(st.session_state.preview_path)
st.session_state.preview_path = video_path
st.success("✅ Segment regenerated!")
st.rerun()
except Exception as e:
st.error(f"❌ Error regenerating segment: {str(e)}")
st.exception(e)
def download_section():
"""Render and download final video"""
if not st.session_state.approved_clips:
st.info("👈 Generate and approve segments first in the Generation tab")
return
st.markdown("## ⬇️ Final Video")
total_segments = len(st.session_state.segments)
approved_count = len(st.session_state.approved_clips)
col1, col2 = st.columns(2)
with col1:
st.metric("Total Segments", total_segments)
with col2:
st.metric("Approved Segments", approved_count)
if approved_count < total_segments:
st.warning(f"⚠️ You have only approved {approved_count}/{total_segments} segments. Continue to Generation tab to complete all segments.")
st.markdown("---")
if st.button("🎥 Render Final Video", use_container_width=True, type="primary"):
render_final_video()
# Show final video if already rendered
if st.session_state.output_path and os.path.exists(st.session_state.output_path):
st.markdown("### 🎉 Your Final Video")
st.markdown('', unsafe_allow_html=True)
st.video(st.session_state.output_path)
st.markdown('
', unsafe_allow_html=True)
# Download button
with open(st.session_state.output_path, 'rb') as f:
video_bytes = f.read()
st.download_button(
label="📥 Download Video",
data=video_bytes,
file_name="ai_generated_video.mp4",
mime="video/mp4",
use_container_width=True
)
def render_final_video():
"""Combine all approved segments into final video"""
try:
with st.spinner("🎬 Combining segments..."):
clips = []
for path in st.session_state.approved_clips:
if os.path.exists(path):
clip = VideoFileClip(path)
clips.append(clip)
if not clips:
st.error("❌ No valid clips to combine")
return
# Concatenate clips
final_clip = concatenate_videoclips(clips, method="compose")
# Output path
output_path = os.path.join(tempfile.gettempdir(), "final_ai_video.mp4")
# Write final video
final_clip.write_videofile(
output_path,
fps=30,
codec="libx264",
audio_codec="aac",
threads=4,
logger=None
)
# Cleanup
for clip in clips:
clip.close()
final_clip.close()
st.session_state.output_path = output_path
st.session_state.video_ready = True
st.success("✅ Final video rendered successfully!")
st.balloons()
st.rerun()
except Exception as e:
st.error(f"❌ Error rendering final video: {str(e)}")
st.exception(e)
if __name__ == "__main__":
main()