added auto editor with AI

This commit is contained in:
juancarlos.cavero 2025-12-22 13:06:33 +01:00
parent 6913e74f84
commit 820239425c
4 changed files with 481 additions and 18 deletions

112
app.py
View file

@ -310,6 +310,118 @@ async def get_status(job_id: str):
"result": job.get('result')
}
from editor import VideoEditor
class EditRequest(BaseModel):
job_id: str
clip_index: int
api_key: Optional[str] = None
@app.post("/api/edit")
async def edit_clip(
req: EditRequest,
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
):
# Determine API Key
final_api_key = req.api_key or x_gemini_key or os.environ.get("GEMINI_API_KEY")
if not final_api_key:
raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header or Body)")
if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id]
if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available")
try:
clip = job['result']['clips'][req.clip_index]
# Resolve file path
filename = clip['video_url'].split('/')[-1]
input_path = os.path.join(OUTPUT_DIR, req.job_id, filename)
if not os.path.exists(input_path):
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
# Define output path for edited video
edited_filename = f"edited_{filename}"
output_path = os.path.join(OUTPUT_DIR, req.job_id, edited_filename)
# Run editing in a thread to avoid blocking main loop
# Since VideoEditor uses blocking calls (subprocess, API wait)
def run_edit():
editor = VideoEditor(api_key=final_api_key)
# SAFE FILE RENAMING STRATEGY (Avoid UnicodeEncodeError in Docker)
# Create a safe ASCII filename in the same directory
safe_filename = f"temp_input_{req.job_id}.mp4"
safe_input_path = os.path.join(OUTPUT_DIR, req.job_id, safe_filename)
# Copy original file to safe path
# (Copy is safer than rename if something crashes, we keep original)
shutil.copy(input_path, safe_input_path)
try:
# 1. Upload (using safe path)
vid_file = editor.upload_video(safe_input_path)
# 2. Get duration
import cv2
cap = cv2.VideoCapture(safe_input_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
duration = frame_count / fps if fps else 0
cap.release()
# 3. Get Plan (Filter String)
filter_data = editor.get_ffmpeg_filter(vid_file, duration, fps=fps, width=width, height=height)
# 4. Apply
# Use safe output name first
safe_output_path = os.path.join(OUTPUT_DIR, req.job_id, f"temp_output_{req.job_id}.mp4")
editor.apply_edits(safe_input_path, safe_output_path, filter_data)
# Move result to final destination (rename works even if dest name has unicode if filesystem supports it,
# but python might still struggle if locale is broken? No, os.rename usually handles it better than subprocess args)
# Actually, output_path is defined above: f"edited_{filename}"
# If filename has unicode, output_path has unicode.
# Let's hope shutil.move / os.rename works.
if os.path.exists(safe_output_path):
shutil.move(safe_output_path, output_path)
return filter_data
finally:
# Cleanup temp safe input
if os.path.exists(safe_input_path):
os.remove(safe_input_path)
# Run in thread pool
loop = asyncio.get_event_loop()
plan = await loop.run_in_executor(None, run_edit)
# Update clip URL in the job result?
# Or return new URL and let frontend handle it?
# Updating job result allows persistence if page refreshes.
new_video_url = f"/videos/{req.job_id}/{edited_filename}"
# Start a new "edited" clip entry or just update the current one?
# Let's update the current one's video_url but keep backup?
# Or return the new URL to the frontend to display.
return {
"success": True,
"new_video_url": new_video_url,
"edit_plan": plan
}
except Exception as e:
print(f"❌ Edit Error: {e}")
raise HTTPException(status_code=500, detail=str(e))
class SocialPostRequest(BaseModel):
job_id: str
clip_index: int

View file

@ -533,16 +533,17 @@ function App() {
{results && results.clips && results.clips.length > 0 ? (
<div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}>
{results.clips.map((clip, i) => (
<ResultCard
key={i}
clip={clip}
index={i}
jobId={jobId}
uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId}
onPlay={(time) => handleClipPlay(time)}
onPause={handleClipPause}
/>
<ResultCard
key={i}
clip={clip}
index={i}
jobId={jobId}
uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId}
geminiApiKey={apiKey}
onPlay={(time) => handleClipPlay(time)}
onPause={handleClipPause}
/>
))}
</div>
) : (

View file

@ -1,10 +1,11 @@
import React, { useState } from 'react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy } from 'lucide-react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2 } from 'lucide-react';
import { getApiUrl } from '../config';
export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, onPlay, onPause }) {
export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, onPlay, onPause }) {
const [showModal, setShowModal] = useState(false);
const videoRef = React.useRef(null);
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url));
const [platforms, setPlatforms] = useState({
tiktok: true,
@ -14,6 +15,61 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
const [posting, setPosting] = useState(false);
const [postResult, setPostResult] = useState(null);
const [isEditing, setIsEditing] = useState(false);
const [editError, setEditError] = useState(null);
const handleAutoEdit = async () => {
setIsEditing(true);
setEditError(null);
try {
// Use passed prop or fallback
const apiKey = geminiApiKey || localStorage.getItem('gemini_key');
if (!apiKey) {
throw new Error("Gemini API Key is missing. Please set it in Settings.");
}
const res = await fetch(getApiUrl('/api/edit'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Gemini-Key': apiKey
},
body: JSON.stringify({
job_id: jobId,
clip_index: index,
// We send it in header now, but backend might expect it in body too currently.
// We will update backend to be flexible.
})
});
if (!res.ok) {
const errText = await res.text();
try {
const jsonErr = JSON.parse(errText);
throw new Error(jsonErr.detail || errText);
} catch (e) {
throw new Error(errText);
}
}
const data = await res.json();
if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url));
// Reload video
if (videoRef.current) {
videoRef.current.load();
}
}
} catch (e) {
setEditError(e.message);
setTimeout(() => setEditError(null), 5000);
} finally {
setIsEditing(false);
}
};
const handlePost = async () => {
if (!uploadPostKey || !uploadUserId) {
setPostResult({ success: false, msg: "Missing API Key or User ID." });
@ -65,15 +121,13 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
}
};
const videoUrl = getApiUrl(clip.video_url);
return (
<div className="bg-surface border border-white/5 rounded-2xl overflow-hidden flex flex-col md:flex-row group hover:border-white/10 transition-all animate-[fadeIn_0.5s_ease-out] min-h-[300px] h-auto" style={{ animationDelay: `${index * 0.1}s` }}>
{/* Left: Video Preview (Responsive Width) */}
<div className="w-full md:w-[180px] lg:w-[200px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto">
<div className="w-full md:w-[180px] lg:w-[200px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video">
<video
ref={videoRef}
src={videoUrl}
src={currentVideoUrl}
controls
className="w-full h-full object-cover"
playsInline
@ -94,6 +148,15 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
Clip {index + 1}
</span>
</div>
{/* Auto Edit Overlay if Processing */}
{isEditing && (
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm flex flex-col items-center justify-center z-10 p-4 text-center">
<Loader2 size={32} className="text-primary animate-spin mb-3" />
<span className="text-xs font-bold text-white uppercase tracking-wider">AI Magic in Progress...</span>
<span className="text-[10px] text-zinc-400 mt-1">Applying viral edits & zooms</span>
</div>
)}
</div>
{/* Right: Content & Details */}
@ -135,8 +198,25 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
</div>
</div>
{/* Error Message */}
{editError && (
<div className="mb-3 p-2 bg-red-500/10 border border-red-500/20 text-red-400 text-[10px] rounded-lg flex items-center gap-2">
<AlertCircle size={12} className="shrink-0" />
{editError}
</div>
)}
{/* Actions Footer */}
<div className="grid grid-cols-2 gap-3 mt-auto pt-4 border-t border-white/5">
<button
onClick={handleAutoEdit}
disabled={isEditing}
className="col-span-2 py-2 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white rounded-lg text-xs font-bold shadow-lg shadow-purple-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1"
>
{isEditing ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
{isEditing ? 'Editing with AI...' : 'Auto Edit with AI'}
</button>
<button
onClick={() => setShowModal(true)}
className="col-span-1 py-2 bg-primary hover:bg-blue-600 text-white rounded-lg text-xs font-bold shadow-lg shadow-primary/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 truncate px-2"
@ -147,7 +227,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
onClick={async (e) => {
e.preventDefault();
try {
const response = await fetch(videoUrl);
const response = await fetch(currentVideoUrl);
if (!response.ok) throw new Error('Download failed');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
@ -161,7 +241,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
document.body.removeChild(a);
} catch (err) {
console.error('Download error:', err);
window.open(videoUrl, '_blank');
window.open(currentVideoUrl, '_blank');
}
}}
className="col-span-1 py-2 bg-white/5 hover:bg-white/10 text-zinc-300 hover:text-white rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-2 border border-white/5 truncate px-2"

270
editor.py Normal file
View file

@ -0,0 +1,270 @@
import os
import json
import re
import subprocess
import time
from google import genai
from google.genai import types
class VideoEditor:
def __init__(self, api_key):
self.client = genai.Client(api_key=api_key)
self.model_name = "gemini-3-flash-preview"
def upload_video(self, video_path):
"""Uploads video to Gemini File API."""
print(f"📤 Uploading {video_path} to Gemini...")
# Ensure we are passing a path that exists
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video file not found: {video_path}")
# Using 'file' keyword instead of 'path'
try:
file_upload = self.client.files.upload(file=video_path)
except Exception as e:
print(f"❌ Gemini Upload Error: {e}")
raise e
# Wait for processing
print("⏳ Waiting for video processing by Gemini...")
while True:
file_info = self.client.files.get(name=file_upload.name)
if file_info.state == "ACTIVE":
print("✅ Video processed and ready.")
return file_upload
elif file_info.state == "FAILED":
raise Exception("Video processing failed by Gemini.")
time.sleep(2)
def get_ffmpeg_filter(self, video_file_obj, duration, fps=30, width=None, height=None):
"""Asks Gemini for a raw FFmpeg filter string."""
if width is None or height is None:
# Keep prompt usable even if caller didn't pass dimensions.
width, height = 1080, 1920
prompt = f"""
You are an expert FFmpeg video editor. Your task is to generate a complex video filter string to make a short video viral.
Video Duration: {duration} seconds.
Video FPS: {fps}
Video Resolution (MUST KEEP EXACT): {width}x{height}
Goal: Apply dynamic zooms, cuts (simulated with punch-ins), and visual effects to increase retention.
Instructions:
1. Analyze the video content (if possible) or apply a generic high-retention pacing.
2. Create a single valid FFmpeg filter complex string (for the -vf flag).
3. Use filters like `zoompan`, `eq` (contrast), `hue` (saturation/bw), `unsharp`.
4. Pacing: Something interesting should happen every 3-5 seconds.
5. CRITICAL SYNTAX RULES:
- DO NOT use comparison operators like `<`, `>`, `<=`, `>=` anywhere. They frequently break FFmpeg expression parsing.
- USE FFmpeg expression FUNCTIONS instead:
- `between(x,a,b)`
- `lt(x,y)`, `lte(x,y)`, `gt(x,y)`, `gte(x,y)`
- `if(cond,then,else)`
- Always wrap expression values in single quotes: `z='...'`, `x='...'`, `y='...'`, `enable='...'`.
- FOR `zoompan`:
- Prefer `on` (output frame index) to avoid time-variable quirks.
- Convert seconds to frames using FPS={fps}: `frame = seconds * {fps}`.
- Use `between(on, startFrame, endFrame)` for segmenting and pacing.
- Example:
`zoompan=z='1.1*between(on,0,75)+1.3*between(on,76,150)+1.15*between(on,151,300)+1.2*gte(on,301)'`
- ALWAYS set zoompan output size to EXACT `{width}x{height}` using `s={width}x{height}`.
- ALWAYS set `fps={fps}` and `d=1`.
- DO NOT use `scale`, `crop`, `pad` unless you keep EXACT `{width}x{height}` (no aspect ratio changes).
- FOR `eq`, `hue`, `curves`, `unsharp` (Visual Effects):
- **DO NOT** use dynamic expressions for parameter values (e.g. `contrast='1+0.5*t'`).
- **USE TIMELINE EDITING** via the `enable` option.
- Create MULTIPLE filter instances for different time ranges.
- **SYNTAX FOR ENABLE:**
- **USE** `between(t,start,end)` for clarity and robustness.
- **USE** single quotes around the enable expression.
- **Example:** `eq=contrast=1.2:enable='between(t,0,3)'`
- **Example:** `hue=s=0:enable='between(t,10,12)'`
- This is much safer and robust than boolean multiplication.
Constraints:
- Output JSON with a single key: "filter_string".
- The value must be the RAW filter string ready to be passed to `-vf`.
- OUTPUT MUST KEEP EXACT RESOLUTION AND ASPECT RATIO: {width}x{height}.
- Do NOT output 1280x720 or 1080x1080 unless the input is exactly that.
- IMPORTANT: Do NOT include the `-vf` flag itself, just the filter content.
- IMPORTANT: Ensure syntax is correct for FFmpeg.
Output JSON:
{{
"filter_string": "..."
}}
"""
print("🤖 Asking Gemini for FFmpeg filter...")
response = self.client.models.generate_content(
model=self.model_name,
contents=[video_file_obj, prompt],
config=types.GenerateContentConfig(
response_mime_type="application/json"
)
)
print(f"🔍 DEBUG: Gemini Raw Response:\n{response.text}")
try:
# Clean response text (remove potential markdown blocks)
text = response.text
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
# Additional cleanup for potential trailing characters outside JSON
# Find the first '{' and last '}'
start_idx = text.find('{')
end_idx = text.rfind('}')
if start_idx != -1 and end_idx != -1:
text = text[start_idx:end_idx+1]
print(f"🔍 DEBUG: Cleaned JSON Text:\n{text}")
return json.loads(text)
except json.JSONDecodeError:
print(f"❌ Failed to parse JSON: {response.text}")
return None
@staticmethod
def _split_filter_chain(filter_string: str) -> list[str]:
"""Split a -vf filter chain on commas, respecting single-quoted substrings."""
parts: list[str] = []
start = 0
in_quote = False
for i, ch in enumerate(filter_string):
if ch == "'":
in_quote = not in_quote
elif ch == "," and not in_quote:
parts.append(filter_string[start:i])
start = i + 1
parts.append(filter_string[start:])
return parts
@classmethod
def _enforce_zoompan_output_size(cls, filter_string: str, width: int, height: int) -> str:
"""Force any zoompan filter to output the same geometry as the input clip."""
parts = cls._split_filter_chain(filter_string)
out_parts: list[str] = []
for part in parts:
if "zoompan=" in part:
# Force s=WxH inside zoompan options (digitsxdigits only).
if re.search(r":s=\d+x\d+", part):
part = re.sub(r":s=\d+x\d+", f":s={width}x{height}", part)
else:
part = f"{part}:s={width}x{height}"
out_parts.append(part)
return ",".join(out_parts)
@staticmethod
def _sanitize_filter_string(filter_string: str) -> str:
"""
Best-effort sanitizer for Gemini-generated FFmpeg expressions.
Converts comparison operators (t<3, on>=75, etc.) into FFmpeg expr functions (lt(), gte(), ...),
which are far more reliably parsed across FFmpeg builds.
"""
s = filter_string
# Order matters: handle >= / <= before > / <
patterns: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"(?<![A-Za-z0-9_])([A-Za-z_]\w*)\s*>=\s*(-?\d+(?:\.\d+)?)"), r"gte(\1,\2)"),
(re.compile(r"(?<![A-Za-z0-9_])([A-Za-z_]\w*)\s*<=\s*(-?\d+(?:\.\d+)?)"), r"lte(\1,\2)"),
(re.compile(r"(?<![A-Za-z0-9_])([A-Za-z_]\w*)\s*>\s*(-?\d+(?:\.\d+)?)"), r"gt(\1,\2)"),
(re.compile(r"(?<![A-Za-z0-9_])([A-Za-z_]\w*)\s*<\s*(-?\d+(?:\.\d+)?)"), r"lt(\1,\2)"),
]
for pat, repl in patterns:
s = pat.sub(repl, s)
return s
def apply_edits(self, input_path, output_path, filter_data):
"""Executes FFmpeg with the generated filter."""
if not filter_data or "filter_string" not in filter_data:
print("⚠️ No filter string found. Copying original.")
subprocess.run(['ffmpeg', '-y', '-i', input_path, '-c', 'copy', output_path])
return
filter_string = filter_data["filter_string"]
# Get input dimensions so we can enforce geometry (avoid broken aspect ratios).
try:
probe_cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', input_path]
res_out = subprocess.check_output(probe_cmd, env={**os.environ, "LANG": "C.UTF-8"}).decode().strip()
w, h = map(int, res_out.split('x'))
except Exception as e:
print(f"⚠️ Could not probe resolution: {e}")
w, h = None, None
# Sanitize common expression pitfalls (e.g., t<3 / on>=75) before executing FFmpeg.
sanitized = self._sanitize_filter_string(filter_string)
if sanitized != filter_string:
print("🧼 Sanitized AI Filter (converted comparisons to lt/lte/gt/gte functions)")
print(f"🧼 Before: {filter_string}")
print(f"🧼 After: {sanitized}")
filter_string = sanitized
# Enforce zoompan output size to preserve aspect ratio / resolution.
if w and h:
enforced = self._enforce_zoompan_output_size(filter_string, w, h)
if enforced != filter_string:
print(f"📐 Enforced zoompan output size to {w}x{h}")
filter_string = enforced
# Ensure square pixels (avoid weird display stretching in some players).
if "setsar=" not in filter_string:
filter_string = f"{filter_string},setsar=1"
print(f"🎬 Executing AI Filter: {filter_string}")
cmd = [
'ffmpeg', '-y',
'-i', input_path,
'-vf', filter_string,
'-c:v', 'libx264', '-preset', 'fast', '-crf', '22',
'-c:a', 'copy',
output_path
]
# Use explicit environment with UTF-8 to avoid ascii errors in subprocess
env = os.environ.copy()
# On some minimal docker images, we need to ensure we use a UTF-8 locale
# Try C.UTF-8 first, fallback to en_US.UTF-8 if available, but C.UTF-8 is usually safer for minimal
env["LANG"] = "C.UTF-8"
env["LC_ALL"] = "C.UTF-8"
try:
# We must encode arguments if filesystem is ascii but we have unicode chars
# But subprocess in Python 3 handles unicode args by encoding them with os.fsencode().
# If sys.getfilesystemencoding() is ascii, this fails.
# We can't change fs encoding at runtime easily.
# Workaround: pass bytes directly? subprocess allows bytes in args.
# Convert command elements to bytes assuming utf-8 if they are strings
cmd_bytes = []
for arg in cmd:
if isinstance(arg, str):
cmd_bytes.append(arg.encode('utf-8'))
else:
cmd_bytes.append(arg)
subprocess.run(cmd_bytes, check=True, env=env)
except subprocess.CalledProcessError as e:
print(f"❌ FFmpeg failed: {e}")
raise e
if __name__ == "__main__":
pass