File size: 6,233 Bytes
44cb2cf | 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 | import google.generativeai as genai
import os
class VideoCodeGenerator:
def __init__(self, api_key):
"""Initialize Gemini 2.5 Flash for code generation"""
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel('gemini-2.5-flash')
def generate_segment_code(self, segment_info, user_images, audio_path,
segment_number, previous_code=None):
"""Generate MoviePy code for a video segment"""
print(f"π€ Generating code for segment {segment_number}...")
context = ""
if previous_code:
context = f"""PREVIOUS SEGMENT CODE FOR REFERENCE:
```python
{previous_code[:1000]} # Truncated
```
Build upon this style and ensure smooth continuation.
"""
prompt = f"""{context}Generate Python MoviePy code for video segment {segment_number}.
SEGMENT SPECIFICATIONS:
- Start time: {segment_info['start_time']:.2f}s
- End time: {segment_info['end_time']:.2f}s
- Duration: {segment_info['duration']:.2f}s
- Transition IN: {segment_info['transition_in']}
- Transition OUT: {segment_info['transition_out']}
- Camera movement: {segment_info['camera_movement']}
- Zoom level: {segment_info['zoom_level']}
- Effects: {segment_info['effects']}
- Image position: {segment_info['image_position']}
AVAILABLE RESOURCES:
- Images: {len(user_images)} photos available
- Audio file path: {audio_path}
- Target resolution: 1080x1920 (9:16 portrait)
- Target FPS: 30
CODE REQUIREMENTS:
1. Import necessary MoviePy modules: from moviepy.editor import *
2. Create a function: create_segment_{segment_number}(images, audio_path)
3. Function must return a CompositeVideoClip object
4. Apply the specified transitions, camera movements, and effects
5. Use images from the 'images' list (cycle through them)
6. Sync timing with the audio (extract audio segment {segment_info['start_time']:.2f}s to {segment_info['end_time']:.2f}s)
7. All clips must be exactly {segment_info['duration']:.2f} seconds
8. Handle image orientation and aspect ratio (crop/resize to 9:16)
TRANSITION IMPLEMENTATIONS:
- fade: Use crossfadein/crossfadeout
- slide_left/right: Use set_position with animated x values
- zoom_in/out: Use resize with size changing over time
- wipe: Use mask animations
- cut: Direct clip placement
CAMERA MOVEMENTS:
- zoom_in: Start at scale 1.0, end at {segment_info['zoom_level']}
- zoom_out: Start at {segment_info['zoom_level']}, end at 1.0
- pan_left/right: Animate x position
- static: No movement
EFFECTS:
- vignette: Apply dark edges
- blur: Use gaussian blur filter
- color_grade: Adjust colors/brightness
- glitch: Random frame distortions
- flash: White overlay fade
EXAMPLE STRUCTURE:
```python
from moviepy.editor import *
import numpy as np
def create_segment_{segment_number}(images, audio_path):
# Load audio segment
audio = AudioFileClip(audio_path).subclip({segment_info['start_time']:.2f}, {segment_info['end_time']:.2f})
# Select image (cycle through list)
img_path = images[{segment_number} % len(images)]
# Create image clip with proper sizing
img_clip = ImageClip(img_path).set_duration({segment_info['duration']:.2f})
# Apply camera movement (zoom, pan, etc.)
# ... your implementation ...
# Apply transition IN
# ... your implementation ...
# Apply effects
# ... your implementation ...
# Composite final clip
final_clip = CompositeVideoClip([img_clip], size=(1080, 1920))
final_clip = final_clip.set_audio(audio)
return final_clip
```
Generate ONLY the complete, executable Python code. No explanations, no markdown except the code block.
The code must be production-ready and handle errors gracefully."""
response = self.model.generate_content(prompt)
code = self.extract_code_block(response.text)
print(f"β
Code generated ({len(code)} characters)")
return code
def regenerate_segment(self, segment_info, user_feedback, previous_code, segment_number):
"""Regenerate code based on user feedback"""
print(f"π Regenerating segment {segment_number} with feedback...")
prompt = f"""The user reviewed the generated video segment and provided feedback.
PREVIOUS CODE:
```python
{previous_code}
```
USER FEEDBACK: "{user_feedback}"
SEGMENT SPECS:
- Start: {segment_info['start_time']:.2f}s
- End: {segment_info['end_time']:.2f}s
- Duration: {segment_info['duration']:.2f}s
- Transition IN: {segment_info['transition_in']}
- Transition OUT: {segment_info['transition_out']}
- Camera: {segment_info['camera_movement']}
- Effects: {segment_info['effects']}
TASK:
1. Analyze the user's feedback carefully
2. Identify what needs to be changed in the code
3. Keep the same function signature: create_segment_{segment_number}(images, audio_path)
4. Modify the implementation to address the feedback
5. Maintain compatibility with the MoviePy framework
Common feedback types:
- "Too fast/slow" β Adjust animation timing
- "Wrong transition" β Change transition type
- "Image positioning" β Adjust crop/position
- "Effects too strong/weak" β Adjust effect intensity
- "Not smooth" β Add easing functions
Generate the IMPROVED code that addresses the feedback.
Return ONLY executable Python code, no explanations."""
response = self.model.generate_content(prompt)
code = self.extract_code_block(response.text)
print(f"β
Code regenerated")
return code
def extract_code_block(self, response_text):
"""Extract Python code from markdown code blocks"""
response_text = response_text.strip()
# Remove markdown code blocks
if "```python" in response_text:
code = response_text.split("```python")[1].split("```")[0]
elif "```" in response_text:
parts = response_text.split("```")
# Find the code block (usually the largest one)
code = max(parts[1::2], key=len) if len(parts) > 1 else response_text
else:
code = response_text
|