Download code_generator.py from PRB1/Velocity: direct link, hf CLI and curl.
- Browser
- Download file 6.23 kB
-
https://huggingface.co/spaces/PRB1/Velocity/resolve/main/code_generator.py
- Command line
-
hf download hf://spaces/PRB1/Velocity/code_generator.py
-
curl -L -o code_generator.py https://huggingface.co/spaces/PRB1/Velocity/resolve/main/code_generator.py
6.23 kB
| 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 | |