From 820239425cb8edb3a6dd6b57c35402944e1000cb Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Mon, 22 Dec 2025 13:06:33 +0100 Subject: [PATCH] added auto editor with AI --- app.py | 112 ++++++++++ dashboard/src/App.jsx | 21 +- dashboard/src/components/ResultCard.jsx | 96 ++++++++- editor.py | 270 ++++++++++++++++++++++++ 4 files changed, 481 insertions(+), 18 deletions(-) create mode 100644 editor.py diff --git a/app.py b/app.py index 9213f5d..bb8aadd 100644 --- a/app.py +++ b/app.py @@ -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 diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index e1eec9c..938876d 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -533,16 +533,17 @@ function App() { {results && results.clips && results.clips.length > 0 ? (
{results.clips.map((clip, i) => ( - handleClipPlay(time)} - onPause={handleClipPause} - /> + handleClipPlay(time)} + onPause={handleClipPause} + /> ))}
) : ( diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index cd19fdb..042c403 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -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 (
{/* Left: Video Preview (Responsive Width) */} -
+
+ + {/* Auto Edit Overlay if Processing */} + {isEditing && ( +
+ + AI Magic in Progress... + Applying viral edits & zooms +
+ )}
{/* Right: Content & Details */} @@ -135,8 +198,25 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
+ {/* Error Message */} + {editError && ( +
+ + {editError} +
+ )} + {/* Actions Footer */}
+ +