From bf577494b750153b8209b0c3548c6422f8d5af48 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Fri, 23 Jan 2026 14:53:57 +0100 Subject: [PATCH] Update hooks, fix captions, and ignore uploads --- .gitignore | 6 +- app.py | 152 ++++++++++++- dashboard/src/App.jsx | 66 +++--- dashboard/src/components/Gallery.jsx | 147 +++++++++++++ dashboard/src/components/GalleryCard.jsx | 156 +++++++++++++ dashboard/src/components/HookModal.jsx | 140 ++++++++++++ dashboard/src/components/ResultCard.jsx | 155 +++++++++---- dashboard/src/components/SubtitleModal.jsx | 1 + dashboard/src/index.css | 33 ++- docker-compose.yml | 2 +- fonts/NotoSerif-Bold.ttf | Bin 0 -> 638164 bytes hooks.py | 241 +++++++++++++++++++++ main.py | 3 +- requirements.txt | 1 + s3_uploader.py | 151 +++++++++++++ verify_aesthetic.py | 37 ++++ verify_custom_hook.py | 32 +++ verify_hooks.py | 36 +++ 18 files changed, 1268 insertions(+), 91 deletions(-) create mode 100644 dashboard/src/components/Gallery.jsx create mode 100644 dashboard/src/components/GalleryCard.jsx create mode 100644 dashboard/src/components/HookModal.jsx create mode 100644 fonts/NotoSerif-Bold.ttf create mode 100644 hooks.py create mode 100644 verify_aesthetic.py create mode 100644 verify_custom_hook.py create mode 100644 verify_hooks.py diff --git a/.gitignore b/.gitignore index e56ffaf..98b4320 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ # Video files *.mp4 +*.webm +*.mov +*.mkv # YOLO model *.pt @@ -10,7 +13,8 @@ __pycache__/ *.pyc # Temporary files -temp_*.mp4 +temp_* +uploads/ .DS_Store diff --git a/app.py b/app.py index 5a47f11..31fc60f 100644 --- a/app.py +++ b/app.py @@ -14,7 +14,7 @@ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Hea from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pydantic import BaseModel -from s3_uploader import upload_job_artifacts +from s3_uploader import upload_job_artifacts, list_all_clips load_dotenv() @@ -364,6 +364,7 @@ async def get_status(job_id: str): from editor import VideoEditor from subtitles import generate_srt, burn_subtitles +from hooks import add_hook_to_video class EditRequest(BaseModel): job_id: str @@ -569,18 +570,117 @@ async def add_subtitles(req: SubtitleRequest): loop = asyncio.get_event_loop() await loop.run_in_executor(None, run_burn) - # 3. Update Result? - # We return the new URL. - new_video_url = f"/videos/{req.job_id}/{output_filename}" - - return { - "success": True, - "new_video_url": new_video_url - } - except Exception as e: print(f"❌ Subtitle Error: {e}") raise HTTPException(status_code=500, detail=str(e)) + + # 3. Update Result and Metadata + # Update InMemory Jobs + if req.clip_index < len(job['result']['clips']): + job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + + # Update Metadata on Disk (Persistence) + try: + if req.clip_index < len(clips): + clips[req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + # Update the main data structure + data['shorts'] = clips + + # Write back + with open(json_files[0], 'w') as f: + json.dump(data, f, indent=4) + print(f"✅ Metadata updated with subtitled video for clip {req.clip_index}") + except Exception as e: + print(f"⚠️ Failed to update metadata.json: {e}") + # Non-critical, but good for persistence + + return { + "success": True, + "new_video_url": f"/videos/{req.job_id}/{output_filename}" + } + +class HookRequest(BaseModel): + job_id: str + clip_index: int + text: str + input_filename: Optional[str] = None + position: Optional[str] = "top" # top, center, bottom + size: Optional[str] = "M" # S, M, L + +@app.post("/api/hook") +async def add_hook(req: HookRequest): + if req.job_id not in jobs: + raise HTTPException(status_code=404, detail="Job not found") + + job = jobs[req.job_id] + output_dir = os.path.join(OUTPUT_DIR, req.job_id) + json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) + + if not json_files: + raise HTTPException(status_code=404, detail="Metadata not found") + + with open(json_files[0], 'r') as f: + data = json.load(f) + + clips = data.get('shorts', []) + if req.clip_index >= len(clips): + raise HTTPException(status_code=404, detail="Clip not found") + + clip_data = clips[req.clip_index] + + # Video Path + if req.input_filename: + filename = os.path.basename(req.input_filename) + else: + filename = clip_data.get('video_url', '').split('/')[-1] + if not filename: + base_name = os.path.basename(json_files[0]).replace('_metadata.json', '') + filename = f"{base_name}_clip_{req.clip_index+1}.mp4" + + input_path = os.path.join(output_dir, filename) + if not os.path.exists(input_path): + raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}") + + # Output video + output_filename = f"hook_{filename}" + output_path = os.path.join(output_dir, output_filename) + + # Map Size to Scale + size_map = {"S": 0.8, "M": 1.0, "L": 1.3} + font_scale = size_map.get(req.size, 1.0) + + try: + # Run in thread pool + def run_hook(): + add_hook_to_video(input_path, req.text, output_path, position=req.position, font_scale=font_scale) + + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, run_hook) + + except Exception as e: + print(f"❌ Hook Error: {e}") + raise HTTPException(status_code=500, detail=str(e)) + + # Update Persistence (Same logic as subtitles) + # Update InMemory Jobs + if req.clip_index < len(job['result']['clips']): + job['result']['clips'][req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + + # Update Metadata on Disk + try: + if req.clip_index < len(clips): + clips[req.clip_index]['video_url'] = f"/videos/{req.job_id}/{output_filename}" + data['shorts'] = clips + with open(json_files[0], 'w') as f: + json.dump(data, f, indent=4) + print(f"✅ Metadata updated with hook video for clip {req.clip_index}") + except Exception as e: + print(f"⚠️ Failed to update metadata.json: {e}") + + return { + "success": True, + "new_video_url": f"/videos/{req.job_id}/{output_filename}" + } class SocialPostRequest(BaseModel): job_id: str @@ -731,5 +831,37 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")) return {"profiles": profiles_list} + except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + +# @app.get("/api/gallery/clips") +# async def get_gallery_clips(limit: int = 20, offset: int = 0, refresh: bool = False): +# """ +# Fetch clips from S3 for the gallery with pagination. +# +# Args: +# limit: Number of clips to return (default 20, max 100) +# offset: Starting position for pagination +# refresh: Force refresh cache +# """ +# try: +# # Clamp limit to reasonable values +# limit = min(max(1, limit), 100) +# +# # Get clips (uses cache internally) +# all_clips = list_all_clips(limit=limit + offset, force_refresh=refresh) +# +# # Apply offset for pagination +# clips = all_clips[offset:offset + limit] +# +# return { +# "clips": clips, +# "total": len(all_clips), +# "limit": limit, +# "offset": offset, +# "has_more": len(all_clips) > offset + limit +# } +# except Exception as e: +# print(f"❌ Gallery Error: {e}") +# raise HTTPException(status_code=500, detail=str(e)) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 8f1b918..d437797 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -1,9 +1,10 @@ import React, { useState, useEffect } from 'react'; -import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield } from 'lucide-react'; +import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; +// import Gallery from './components/Gallery'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -143,7 +144,7 @@ function App() { const [logsVisible, setLogsVisible] = useState(true); const [processingMedia, setProcessingMedia] = useState(null); const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings - + // Sync state for original video playback const [syncedTime, setSyncedTime] = useState(0); const [isSyncedPlaying, setIsSyncedPlaying] = useState(false); @@ -300,6 +301,14 @@ function App() { Dashboard + {/* */} + + + ); + } + + return ( +
+
+

+ Clip Gallery +

+ + {clips.length} {clips.length === 1 ? 'Clip' : 'Clips'}{hasMore ? '+' : ''} + +
+ + {clips.length === 0 ? ( +
+

No clips found yet.

+

Process some videos to populate your gallery!

+
+ ) : ( + <> +
+ {clips.map((clip, i) => ( + + ))} +
+ + {/* Infinite scroll loader trigger */} + {hasMore && ( +
+ {loadingMore && ( +
+ + Loading more clips... +
+ )} +
+ )} + + )} +
+ ); +} + diff --git a/dashboard/src/components/GalleryCard.jsx b/dashboard/src/components/GalleryCard.jsx new file mode 100644 index 0000000..eafdd19 --- /dev/null +++ b/dashboard/src/components/GalleryCard.jsx @@ -0,0 +1,156 @@ +import React, { useRef, useState, useEffect } from 'react'; +import { Download, Youtube, Instagram, Video, Copy, Check, Play } from 'lucide-react'; + +export default function GalleryCard({ clip }) { + const [copied, setCopied] = useState(null); + const [isVisible, setIsVisible] = useState(false); + const [hasLoaded, setHasLoaded] = useState(false); + const cardRef = useRef(null); + const videoRef = useRef(null); + + // Lazy loading with IntersectionObserver + useEffect(() => { + const observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + setIsVisible(true); + // Once loaded, we don't need to observe anymore + observer.unobserve(entry.target); + } + }); + }, + { + rootMargin: '200px', // Start loading 200px before entering viewport + threshold: 0.1 + } + ); + + if (cardRef.current) { + observer.observe(cardRef.current); + } + + return () => { + if (cardRef.current) { + observer.unobserve(cardRef.current); + } + }; + }, []); + + const handleCopy = (text, field) => { + navigator.clipboard.writeText(text); + setCopied(field); + setTimeout(() => setCopied(null), 2000); + }; + + const handleDownload = async (e) => { + e.preventDefault(); + try { + const response = await fetch(clip.url); + if (!response.ok) throw new Error('Download failed'); + const blob = await response.blob(); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.style.display = 'none'; + a.href = url; + a.download = `clip_${clip.job_id}_${clip.index + 1}.mp4`; + document.body.appendChild(a); + a.click(); + window.URL.revokeObjectURL(url); + document.body.removeChild(a); + } catch (err) { + console.error('Download error:', err); + window.open(clip.url, '_blank'); + } + }; + + return ( +
+ {/* Video Player - Lazy loaded */} +
+ {isVisible ? ( +
+ + {/* Content & Details */} +
+
+

+ {clip.title} +

+
+ {clip.duration.toFixed(1)}s + ID: {clip.job_id.substring(0, 8)} +
+
+ +
+ {/* YouTube Title */} +
+
+ YouTube Title +
+

{clip.title}

+ +
+ + {/* TikTok / IG Caption */} +
+
+
+

+ {clip.tiktok_desc || clip.insta_desc} +

+ +
+
+ + {/* Footer Action */} + +
+
+ ); +} diff --git a/dashboard/src/components/HookModal.jsx b/dashboard/src/components/HookModal.jsx new file mode 100644 index 0000000..93a896f --- /dev/null +++ b/dashboard/src/components/HookModal.jsx @@ -0,0 +1,140 @@ +import React, { useState } from 'react'; +import { X, Sparkles, Loader2, Maximize, MoveVertical } from 'lucide-react'; + +export default function HookModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, initialText }) { + const [text, setText] = useState(initialText || 'POV: You are using the viral hook feature'); + const [position, setPosition] = useState('top'); // top, center, bottom + const [size, setSize] = useState('M'); // S, M, L + + if (!isOpen) return null; + + // Preview Logic + const getPositionClass = () => { + switch (position) { + case 'center': return 'items-center justify-center'; + case 'bottom': return 'items-center justify-end pb-[20%]'; + case 'top': default: return 'items-center justify-start pt-[20%]'; + } + }; + + const getSizeStyle = () => { + switch (size) { + case 'S': return { fontSize: '14px', maxWidth: '80%' }; + case 'L': return { fontSize: '24px', maxWidth: '95%' }; + case 'M': default: return { fontSize: '18px', maxWidth: '90%' }; + } + }; + + return ( +
+
+ + + {/* Left: Preview */} +
+
+ + {/* Right: Controls */} +
+

+ Viral Hook +

+ +
+ {/* Text Input */} +
+ +