Update hooks, fix captions, and ignore uploads

This commit is contained in:
juancarlos.cavero 2026-01-23 14:53:57 +01:00
parent 26a4c31087
commit bf577494b7
18 changed files with 1268 additions and 91 deletions

6
.gitignore vendored
View file

@ -1,5 +1,8 @@
# Video files # Video files
*.mp4 *.mp4
*.webm
*.mov
*.mkv
# YOLO model # YOLO model
*.pt *.pt
@ -10,7 +13,8 @@ __pycache__/
*.pyc *.pyc
# Temporary files # Temporary files
temp_*.mp4 temp_*
uploads/
.DS_Store .DS_Store

152
app.py
View file

@ -14,7 +14,7 @@ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Hea
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel from pydantic import BaseModel
from s3_uploader import upload_job_artifacts from s3_uploader import upload_job_artifacts, list_all_clips
load_dotenv() load_dotenv()
@ -364,6 +364,7 @@ async def get_status(job_id: str):
from editor import VideoEditor from editor import VideoEditor
from subtitles import generate_srt, burn_subtitles from subtitles import generate_srt, burn_subtitles
from hooks import add_hook_to_video
class EditRequest(BaseModel): class EditRequest(BaseModel):
job_id: str job_id: str
@ -569,19 +570,118 @@ async def add_subtitles(req: SubtitleRequest):
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
await loop.run_in_executor(None, run_burn) 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: except Exception as e:
print(f"❌ Subtitle Error: {e}") print(f"❌ Subtitle Error: {e}")
raise HTTPException(status_code=500, detail=str(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): class SocialPostRequest(BaseModel):
job_id: str job_id: str
clip_index: int clip_index: int
@ -731,5 +831,37 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key"))
return {"profiles": profiles_list} return {"profiles": profiles_list}
except Exception as e: except Exception as e:
raise HTTPException(status_code=500, detail=str(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))

View file

@ -1,9 +1,10 @@
import React, { useState, useEffect } from 'react'; 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 KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput'; import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard'; import ResultCard from './components/ResultCard';
import ProcessingAnimation from './components/ProcessingAnimation'; import ProcessingAnimation from './components/ProcessingAnimation';
// import Gallery from './components/Gallery';
import { getApiUrl } from './config'; import { getApiUrl } from './config';
// Enhanced "Encryption" using XOR + Base64 with a Salt // Enhanced "Encryption" using XOR + Base64 with a Salt
@ -300,6 +301,14 @@ function App() {
<span className="font-medium hidden lg:block">Dashboard</span> <span className="font-medium hidden lg:block">Dashboard</span>
</button> </button>
{/* <button
onClick={() => setActiveTab('gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'gallery' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
<LayoutGrid size={20} />
<span className="font-medium hidden lg:block">Gallery</span>
</button> */}
<button <button
onClick={() => setActiveTab('settings')} onClick={() => setActiveTab('settings')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'settings' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`} className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'settings' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
@ -433,6 +442,11 @@ function App() {
</div> </div>
)} )}
{/* View: Gallery */}
{/* {activeTab === 'gallery' && (
<Gallery />
)} */}
{/* View: Dashboard (Idle) */} {/* View: Dashboard (Idle) */}
{activeTab === 'dashboard' && status === 'idle' && ( {activeTab === 'dashboard' && status === 'idle' && (
<div className="h-full flex flex-col items-center justify-center p-6 animate-[fadeIn_0.3s_ease-out]"> <div className="h-full flex flex-col items-center justify-center p-6 animate-[fadeIn_0.3s_ease-out]">
@ -524,30 +538,30 @@ function App() {
</span> </span>
)} )}
{results?.cost_analysis && ( {results?.cost_analysis && (
<span className="text-xs bg-green-500/10 border border-green-500/20 text-green-400 px-2 py-0.5 rounded-full ml-2" title={`Input: ${results.cost_analysis.input_tokens} | Output: ${results.cost_analysis.output_tokens}`}> <span className="text-xs bg-green-500/10 border border-green-500/20 text-green-400 px-2 py-0.5 rounded-full ml-2" title={`Input: ${results.cost_analysis.input_tokens} | Output: ${results.cost_analysis.output_tokens}`}>
${results.cost_analysis.total_cost.toFixed(5)} ${results.cost_analysis.total_cost.toFixed(5)}
</span> </span>
)} )}
</h2> </h2>
<div className="flex-1 overflow-y-auto custom-scrollbar p-1"> <div className="flex-1 overflow-y-auto custom-scrollbar p-1">
{results && results.clips && results.clips.length > 0 ? ( {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'}`}> <div className={`grid gap-4 pb-10 ${status === 'complete' ? 'grid-cols-1 xl:grid-cols-2' : 'grid-cols-1'}`}>
{results.clips.map((clip, i) => ( {results.clips.map((clip, i) => (
<ResultCard <ResultCard
key={i} key={i}
clip={clip} clip={clip}
index={i} index={i}
jobId={jobId} jobId={jobId}
uploadPostKey={uploadPostKey} uploadPostKey={uploadPostKey}
uploadUserId={uploadUserId} uploadUserId={uploadUserId}
geminiApiKey={apiKey} geminiApiKey={apiKey}
onPlay={(time) => handleClipPlay(time)} onPlay={(time) => handleClipPlay(time)}
onPause={handleClipPause} onPause={handleClipPause}
/> />
))} ))}
</div> </div>
) : ( ) : (
status === 'processing' ? ( status === 'processing' ? (
<div className="h-full flex flex-col items-center justify-center text-zinc-500 space-y-4 opacity-50"> <div className="h-full flex flex-col items-center justify-center text-zinc-500 space-y-4 opacity-50">
<div className="w-12 h-12 rounded-full border-2 border-zinc-800 border-t-primary animate-spin" /> <div className="w-12 h-12 rounded-full border-2 border-zinc-800 border-t-primary animate-spin" />

View file

@ -0,0 +1,147 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { LayoutGrid, AlertCircle, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config';
import GalleryCard from './GalleryCard';
const CLIPS_PER_PAGE = 20;
export default function Gallery() {
const [clips, setClips] = useState([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState(null);
const [hasMore, setHasMore] = useState(true);
const [offset, setOffset] = useState(0);
const loaderRef = useRef(null);
const fetchClips = useCallback(async (currentOffset = 0, append = false) => {
try {
if (currentOffset === 0) setLoading(true);
else setLoadingMore(true);
const res = await fetch(
getApiUrl(`/api/gallery/clips?limit=${CLIPS_PER_PAGE}&offset=${currentOffset}`)
);
if (!res.ok) throw new Error('Failed to fetch clips');
const data = await res.json();
const newClips = data.clips || [];
if (append) {
setClips(prev => [...prev, ...newClips]);
} else {
setClips(newClips);
}
setHasMore(data.has_more ?? newClips.length === CLIPS_PER_PAGE);
setOffset(currentOffset + newClips.length);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, []);
// Initial load
useEffect(() => {
fetchClips(0, false);
}, [fetchClips]);
// Infinite scroll observer
useEffect(() => {
if (!hasMore || loadingMore || loading) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loadingMore) {
fetchClips(offset, true);
}
},
{ rootMargin: '200px', threshold: 0.1 }
);
if (loaderRef.current) {
observer.observe(loaderRef.current);
}
return () => {
if (loaderRef.current) {
observer.unobserve(loaderRef.current);
}
};
}, [hasMore, loadingMore, loading, offset, fetchClips]);
if (loading) {
return (
<div className="h-full flex flex-col items-center justify-center text-zinc-500 animate-[fadeIn_0.5s_ease-out]">
<Loader2 size={32} className="animate-spin mb-4 text-primary" />
<p>Loading your viral history...</p>
</div>
);
}
if (error) {
return (
<div className="h-full flex flex-col items-center justify-center text-red-400 p-6">
<AlertCircle size={32} className="mb-4" />
<p>Error loading gallery: {error}</p>
<button
onClick={() => {
setError(null);
setOffset(0);
fetchClips(0, false);
}}
className="mt-4 px-4 py-2 bg-white/5 hover:bg-white/10 rounded-lg text-sm text-white transition-colors"
>
Retry
</button>
</div>
);
}
return (
<div className="h-full overflow-y-auto p-6 md:p-8 animate-[fadeIn_0.3s_ease-out]">
<div className="flex items-center justify-between mb-8">
<h1 className="text-2xl font-bold flex items-center gap-3">
<LayoutGrid className="text-primary" /> Clip Gallery
</h1>
<span className="text-xs bg-white/10 text-white px-3 py-1 rounded-full border border-white/5">
{clips.length} {clips.length === 1 ? 'Clip' : 'Clips'}{hasMore ? '+' : ''}
</span>
</div>
{clips.length === 0 ? (
<div className="text-center py-20 text-zinc-500">
<p className="text-lg mb-2">No clips found yet.</p>
<p className="text-sm">Process some videos to populate your gallery!</p>
</div>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6 pb-10">
{clips.map((clip, i) => (
<GalleryCard key={`${clip.job_id}-${clip.index}`} clip={clip} />
))}
</div>
{/* Infinite scroll loader trigger */}
{hasMore && (
<div
ref={loaderRef}
className="flex justify-center py-8"
>
{loadingMore && (
<div className="flex items-center gap-2 text-zinc-500">
<Loader2 size={20} className="animate-spin" />
<span className="text-sm">Loading more clips...</span>
</div>
)}
</div>
)}
</>
)}
</div>
);
}

View file

@ -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 (
<div
ref={cardRef}
className="bg-surface border border-white/5 rounded-xl overflow-hidden flex flex-col hover:border-white/10 transition-all group animate-[fadeIn_0.5s_ease-out]"
>
{/* Video Player - Lazy loaded */}
<div className="aspect-[9/16] bg-black relative group/video">
{isVisible ? (
<video
ref={videoRef}
src={clip.url}
controls
className="w-full h-full object-cover"
playsInline
preload="metadata"
onLoadedData={() => setHasLoaded(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-zinc-900">
<div className="w-12 h-12 rounded-full bg-white/10 flex items-center justify-center">
<Play size={24} className="text-white/50 ml-1" />
</div>
</div>
)}
<div className="absolute top-2 left-2">
<span className="bg-black/60 backdrop-blur-md text-white text-[10px] font-bold px-2 py-1 rounded-md border border-white/10 tracking-wide">
{new Date(clip.created_at).toLocaleDateString()}
</span>
</div>
</div>
{/* Content & Details */}
<div className="flex-1 p-4 flex flex-col bg-[#121214] min-w-0">
<div className="mb-3">
<h3 className="text-sm font-bold text-white leading-tight line-clamp-2 mb-2 break-words" title={clip.title}>
{clip.title}
</h3>
<div className="flex flex-wrap gap-2 text-[10px] text-zinc-500 font-mono">
<span className="bg-white/5 px-1.5 py-0.5 rounded border border-white/5">{clip.duration.toFixed(1)}s</span>
<span className="bg-white/5 px-1.5 py-0.5 rounded border border-white/5 truncate max-w-[150px]" title={clip.job_id}>ID: {clip.job_id.substring(0, 8)}</span>
</div>
</div>
<div className="space-y-2 flex-1 overflow-y-auto custom-scrollbar max-h-[150px] pr-1 mb-3">
{/* YouTube Title */}
<div className="bg-black/20 rounded-lg p-2 border border-white/5 relative group/item">
<div className="flex items-center gap-1.5 text-[10px] font-bold text-red-400 mb-1 uppercase tracking-wider">
<Youtube size={10} className="shrink-0" /> YouTube Title
</div>
<p className="text-xs text-zinc-300 select-all line-clamp-2 hover:line-clamp-none transition-all">{clip.title}</p>
<button
onClick={() => handleCopy(clip.title, 'yt')}
className="absolute top-2 right-2 p-1 text-zinc-500 hover:text-white transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Title"
>
{copied === 'yt' ? <Check size={12} className="text-green-400" /> : <Copy size={12} />}
</button>
</div>
{/* TikTok / IG Caption */}
<div className="bg-black/20 rounded-lg p-2 border border-white/5 relative group/item">
<div className="flex items-center gap-1.5 text-[10px] font-bold text-zinc-400 mb-1 uppercase tracking-wider">
<Video size={10} className="text-cyan-400 shrink-0" />
<span className="text-zinc-600">/</span>
<Instagram size={10} className="text-pink-400 shrink-0" /> Caption
</div>
<p className="text-xs text-zinc-300 select-all line-clamp-3 hover:line-clamp-none transition-all cursor-pointer">
{clip.tiktok_desc || clip.insta_desc}
</p>
<button
onClick={() => handleCopy(clip.tiktok_desc || clip.insta_desc, 'caption')}
className="absolute top-2 right-2 p-1 text-zinc-500 hover:text-white transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Caption"
>
{copied === 'caption' ? <Check size={12} className="text-green-400" /> : <Copy size={12} />}
</button>
</div>
</div>
{/* Footer Action */}
<button
onClick={handleDownload}
className="w-full 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"
>
<Download size={14} className="shrink-0" /> Download Clip
</button>
</div>
</div>
);
}

View file

@ -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 (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]">
<div className="bg-[#121214] border border-white/10 p-6 rounded-2xl w-full max-w-4xl shadow-2xl relative flex flex-col md:flex-row gap-6 max-h-[90vh]">
<button
onClick={onClose}
className="absolute top-4 right-4 text-zinc-500 hover:text-white z-10"
>
<X size={20} />
</button>
{/* Left: Preview */}
<div className="flex-1 flex flex-col items-center justify-center bg-black rounded-lg border border-white/5 overflow-hidden relative aspect-[9/16] max-h-[600px]">
<video src={videoUrl} className="w-full h-full object-contain opacity-50" muted playsInline />
{/* Hook Overlay Preview */}
<div className={`absolute w-full px-8 text-center transition-all duration-300 pointer-events-none flex flex-col h-full ${getPositionClass()}`}>
<div
className="text-black font-bold px-3 py-2 rounded-xl shadow-2xl text-center whitespace-pre-wrap transition-all duration-200"
style={{
...getSizeStyle(),
backgroundColor: 'rgba(255, 255, 255, 0.82)', // Match backend 210/255 alpha
fontFamily: 'Noto Serif, serif',
boxShadow: '0 4px 15px rgba(0,0,0,0.5)',
paddingTop: '10px', // Reduced to scale (backend is 20px on 1080p ~ 2%)
paddingBottom: '10px',
paddingLeft: '12px',
paddingRight: '12px'
}}
>
{text || "Enter your text..."}
</div>
</div>
</div>
{/* Right: Controls */}
<div className="w-full md:w-80 flex flex-col">
<h3 className="text-xl font-bold text-white mb-6 flex items-center gap-2">
<Sparkles className="text-yellow-400" /> Viral Hook
</h3>
<div className="space-y-6 flex-1 overflow-y-auto custom-scrollbar pr-2">
{/* Text Input */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 block">Text</label>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={4}
className="w-full bg-black/40 border border-white/10 rounded-xl p-3 text-white placeholder-zinc-600 focus:outline-none focus:border-yellow-500/50 resize-none font-serif"
placeholder="Enter text that will stop the scroll..."
/>
</div>
{/* Position Control */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 flex items-center gap-2">
<MoveVertical size={12} /> Position
</label>
<div className="grid grid-cols-3 gap-2">
{['top', 'center', 'bottom'].map((pos) => (
<button
key={pos}
onClick={() => setPosition(pos)}
className={`py-2 px-1 rounded-lg text-xs font-bold capitalize transition-all border ${position === pos
? 'bg-white text-black border-white'
: 'bg-white/5 text-zinc-400 border-white/5 hover:bg-white/10'
}`}
>
{pos}
</button>
))}
</div>
</div>
{/* Size Control */}
<div>
<label className="text-xs font-bold text-zinc-400 uppercase tracking-wider mb-3 flex items-center gap-2">
<Maximize size={12} /> Size
</label>
<div className="grid grid-cols-3 gap-2">
{['S', 'M', 'L'].map((sz) => (
<button
key={sz}
onClick={() => setSize(sz)}
className={`py-2 px-1 rounded-lg text-xs font-bold transition-all border ${size === sz
? 'bg-white text-black border-white'
: 'bg-white/5 text-zinc-400 border-white/5 hover:bg-white/10'
}`}
>
{sz === 'S' ? 'Small' : sz === 'M' ? 'Medium' : 'Large'}
</button>
))}
</div>
</div>
<div className="p-3 bg-white/5 rounded-lg border border-white/5 text-[11px] text-zinc-400">
<strong>Tip:</strong> Keep it short and punchy. Using "POV:" or specific questions works best for retention.
</div>
</div>
<button
onClick={() => onGenerate({ text, position, size })}
disabled={isProcessing || !text.trim()}
className="w-full py-4 mt-4 bg-gradient-to-r from-yellow-500 to-amber-600 hover:from-yellow-400 hover:to-amber-500 text-black font-bold rounded-xl shadow-lg shadow-amber-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shrink-0"
>
{isProcessing ? <Loader2 size={20} className="animate-spin" /> : <Sparkles size={20} />}
{isProcessing ? 'Generating...' : 'Add Hook'}
</button>
</div>
</div>
</div>
);
}

View file

@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock } from 'lucide-react'; import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock } from 'lucide-react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import SubtitleModal from './SubtitleModal'; import SubtitleModal from './SubtitleModal';
import HookModal from './HookModal';
export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, onPlay, onPause }) { export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUserId, geminiApiKey, onPlay, onPause }) {
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
@ -24,6 +25,8 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [isSubtitling, setIsSubtitling] = useState(false); const [isSubtitling, setIsSubtitling] = useState(false);
const [isHooking, setIsHooking] = useState(false);
const [showHookModal, setShowHookModal] = useState(false);
const [editError, setEditError] = useState(null); const [editError, setEditError] = useState(null);
// Initialize/Reset form when modal opens // Initialize/Reset form when modal opens
@ -41,14 +44,14 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
setIsEditing(true); setIsEditing(true);
setEditError(null); setEditError(null);
try { try {
// Use passed prop or fallback // Use passed prop or fallback
const apiKey = geminiApiKey || localStorage.getItem('gemini_key'); const apiKey = geminiApiKey || localStorage.getItem('gemini_key');
if (!apiKey) { if (!apiKey) {
throw new Error("Gemini API Key is missing. Please set it in Settings."); throw new Error("Gemini API Key is missing. Please set it in Settings.");
} }
const res = await fetch(getApiUrl('/api/edit'), { const res = await fetch(getApiUrl('/api/edit'), {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -59,26 +62,26 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
clip_index: index, clip_index: index,
input_filename: currentVideoUrl.split('/').pop() input_filename: currentVideoUrl.split('/').pop()
}) })
}); });
if (!res.ok) { if (!res.ok) {
const errText = await res.text(); const errText = await res.text();
try { try {
const jsonErr = JSON.parse(errText); const jsonErr = JSON.parse(errText);
throw new Error(jsonErr.detail || errText); throw new Error(jsonErr.detail || errText);
} catch (e) { } catch (e) {
throw new Error(errText); throw new Error(errText);
} }
} }
const data = await res.json(); const data = await res.json();
if (data.new_video_url) { if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url)); setCurrentVideoUrl(getApiUrl(data.new_video_url));
// Reload video // Reload video
if (videoRef.current) { if (videoRef.current) {
videoRef.current.load(); videoRef.current.load();
} }
} }
} catch (e) { } catch (e) {
setEditError(e.message); setEditError(e.message);
@ -126,6 +129,50 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
} }
}; };
const handleHook = async (hookData) => {
setIsHooking(true);
setEditError(null);
try {
// Support both string (legacy) and object
const payload = typeof hookData === 'string'
? { text: hookData, position: 'top', size: 'M' }
: hookData;
const res = await fetch(getApiUrl('/api/hook'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
job_id: jobId,
clip_index: index,
text: payload.text,
position: payload.position,
size: payload.size,
input_filename: currentVideoUrl.split('/').pop()
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText);
}
const data = await res.json();
if (data.new_video_url) {
setCurrentVideoUrl(getApiUrl(data.new_video_url));
if (videoRef.current) {
videoRef.current.load();
}
setShowHookModal(false);
}
} catch (e) {
setEditError(e.message);
setTimeout(() => setEditError(null), 5000);
} finally {
setIsHooking(false);
}
};
const handlePost = async () => { const handlePost = async () => {
if (!uploadPostKey || !uploadUserId) { if (!uploadPostKey || !uploadUserId) {
setPostResult({ success: false, msg: "Missing API Key or User ID." }); setPostResult({ success: false, msg: "Missing API Key or User ID." });
@ -234,7 +281,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
{/* Right: Content & Details */} {/* Right: Content & Details */}
<div className="flex-1 p-4 md:p-5 flex flex-col bg-[#121214] overflow-hidden min-w-0"> <div className="flex-1 p-4 md:p-5 flex flex-col bg-[#121214] overflow-hidden min-w-0">
<div className="mb-4"> <div className="mb-4">
<h3 className="text-base font-bold text-white leading-tight line-clamp-2 mb-2 break-words" title={clip.video_title_for_youtube_short}> <h3 className="text-base font-bold text-white leading-tight line-clamp-2 mb-2 break-words" title={clip.video_title_for_youtube_short}>
{clip.video_title_for_youtube_short || "Viral Clip Generated"} {clip.video_title_for_youtube_short || "Viral Clip Generated"}
</h3> </h3>
<div className="flex flex-wrap gap-2 text-[10px] text-zinc-500 font-mono"> <div className="flex flex-wrap gap-2 text-[10px] text-zinc-500 font-mono">
@ -246,18 +293,18 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
{/* Scrollable Descriptions Area */} {/* Scrollable Descriptions Area */}
<div className="flex-1 overflow-y-auto custom-scrollbar space-y-3 pr-2 mb-4"> <div className="flex-1 overflow-y-auto custom-scrollbar space-y-3 pr-2 mb-4">
{/* YouTube */} {/* YouTube */}
<div className="bg-black/20 rounded-lg p-3 border border-white/5"> <div className="bg-black/20 rounded-lg p-3 border border-white/5">
<div className="flex items-center gap-2 text-[10px] font-bold text-red-400 mb-1.5 uppercase tracking-wider"> <div className="flex items-center gap-2 text-[10px] font-bold text-red-400 mb-1.5 uppercase tracking-wider">
<Youtube size={12} className="shrink-0" /> <span className="truncate">YouTube Title</span> <Youtube size={12} className="shrink-0" /> <span className="truncate">YouTube Title</span>
</div> </div>
<p className="text-xs text-zinc-300 select-all break-words"> <p className="text-xs text-zinc-300 select-all break-words">
{clip.video_title_for_youtube_short || "Viral Short Video"} {clip.video_title_for_youtube_short || "Viral Short Video"}
</p> </p>
</div> </div>
{/* TikTok / IG */} {/* TikTok / IG */}
<div className="bg-black/20 rounded-lg p-3 border border-white/5"> <div className="bg-black/20 rounded-lg p-3 border border-white/5">
<div className="flex items-center gap-2 text-[10px] font-bold text-zinc-400 mb-1.5 uppercase tracking-wider"> <div className="flex items-center gap-2 text-[10px] font-bold text-zinc-400 mb-1.5 uppercase tracking-wider">
<Video size={12} className="text-cyan-400 shrink-0" /> <Video size={12} className="text-cyan-400 shrink-0" />
<span className="text-zinc-500">/</span> <span className="text-zinc-500">/</span>
@ -267,7 +314,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
<p className="text-xs text-zinc-300 line-clamp-3 hover:line-clamp-none transition-all cursor-pointer select-all break-words"> <p className="text-xs text-zinc-300 line-clamp-3 hover:line-clamp-none transition-all cursor-pointer select-all break-words">
{clip.video_description_for_tiktok || clip.video_description_for_instagram} {clip.video_description_for_tiktok || clip.video_description_for_instagram}
</p> </p>
</div> </div>
</div> </div>
{/* Error Message */} {/* Error Message */}
@ -298,6 +345,15 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
{isSubtitling ? 'Adding...' : 'Subtitles'} {isSubtitling ? 'Adding...' : 'Subtitles'}
</button> </button>
<button
onClick={() => setShowHookModal(true)}
disabled={isHooking}
className="col-span-1 py-2 bg-gradient-to-r from-amber-400 to-yellow-500 hover:from-amber-300 hover:to-yellow-400 text-black rounded-lg text-xs font-bold shadow-lg shadow-yellow-500/20 transition-all active:scale-[0.98] flex items-center justify-center gap-2 mb-1 truncate px-1"
>
{isHooking ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}
{isHooking ? 'Adding...' : 'Viral Hook'}
</button>
<button <button
onClick={() => setShowModal(true)} 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" 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"
@ -449,6 +505,15 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
isProcessing={isSubtitling} isProcessing={isSubtitling}
videoUrl={currentVideoUrl} videoUrl={currentVideoUrl}
/> />
<HookModal
isOpen={showHookModal}
onClose={() => setShowHookModal(false)}
onGenerate={handleHook}
isProcessing={isHooking}
videoUrl={currentVideoUrl}
initialText={clip.viral_hook_text}
/>
</div> </div>
); );
} }

View file

@ -101,3 +101,4 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
); );
} }

View file

@ -1,3 +1,4 @@
@import url('https://fonts.googleapis.com/css2?family=Noto+Serif:wght@700&display=swap');
@tailwind base; @tailwind base;
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
@ -41,13 +42,31 @@
/* Custom Animations */ /* Custom Animations */
@keyframes scan { @keyframes scan {
0% { top: 0%; opacity: 0; } 0% {
10% { opacity: 1; } top: 0%;
90% { opacity: 1; } opacity: 0;
100% { top: 100%; opacity: 0; } }
10% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
top: 100%;
opacity: 0;
}
} }
@keyframes scan-overlay { @keyframes scan-overlay {
0% { top: -20%; } 0% {
100% { top: 100%; } top: -20%;
}
100% {
top: 100%;
}
} }

View file

@ -13,7 +13,7 @@ services:
build: ./dashboard build: ./dashboard
container_name: openshorts-frontend container_name: openshorts-frontend
ports: ports:
- "5173:5173" - "5175:5173"
volumes: volumes:
- ./dashboard:/app - ./dashboard:/app
- /app/node_modules - /app/node_modules

BIN
fonts/NotoSerif-Bold.ttf Normal file

Binary file not shown.

241
hooks.py Normal file
View file

@ -0,0 +1,241 @@
import os
import textwrap
import subprocess
import urllib.request
from PIL import Image, ImageDraw, ImageFont, ImageFilter
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
FONT_DIR = "fonts"
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
def download_font_if_needed():
"""Downloads a serif font for the hook text if not present."""
if not os.path.exists(FONT_DIR):
os.makedirs(FONT_DIR)
if not os.path.exists(FONT_PATH):
print(f"⬇️ Downloading font from {FONT_URL}...")
try:
# Add user agent to avoid 403s slightly
req = urllib.request.Request(
FONT_URL,
headers={'User-Agent': 'Mozilla/5.0'}
)
with urllib.request.urlopen(req) as response, open(FONT_PATH, 'wb') as out_file:
out_file.write(response.read())
print("✅ Font downloaded.")
except Exception as e:
print(f"❌ Failed to download font: {e}")
def create_hook_image(text, target_width, output_image_path="hook_overlay.png", font_scale=1.0):
"""
Generates a white box with black serif text using pixel-based wrapping.
target_width: The max width the box should occupy (e.g. 85% of video)
"""
download_font_if_needed()
# Configuration
padding_x = 30 # Balanced padding
padding_y = 25
line_spacing = 20 # Increased spacing
cornerradius = 20
shadow_offset = (5, 5)
shadow_blur = 10
# Font Size Calculation (approx 5% of width - tuned to match Noto Serif Bold metrics in browser)
base_font_size = int(target_width * 0.05)
font_size = int(base_font_size * font_scale)
try:
font = ImageFont.truetype(FONT_PATH, font_size)
except Exception as e:
print(f"⚠️ Warning: Could not load font {FONT_PATH}, using default. Error: {e}")
font = ImageFont.load_default()
# Wrap text logic (Pixel-based)
dummy_img = Image.new('RGBA', (1, 1))
draw = ImageDraw.Draw(dummy_img)
max_text_width = target_width - (2 * padding_x)
# Handle manual newlines first
paragraphs = text.split('\n')
lines = []
for p in paragraphs:
if not p.strip():
lines.append("")
continue
words = p.split()
current_line = []
for word in words:
# Test if adding word fits
test_line = ' '.join(current_line + [word])
bbox = draw.textbbox((0, 0), test_line, font=font)
w = bbox[2] - bbox[0]
if w <= max_text_width:
current_line.append(word)
else:
# Line full, push current_line and start new
if current_line:
lines.append(' '.join(current_line))
current_line = [word]
else:
# Single word too long? Force it.
lines.append(word)
current_line = []
if current_line:
lines.append(' '.join(current_line))
# Recalculate true width/height
max_line_width = 0
text_heights = []
for line in lines:
if not line:
text_heights.append(font_size) # Use font size for empty line height
continue
bbox = draw.textbbox((0, 0), line, font=font)
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
max_line_width = max(max_line_width, w)
text_heights.append(h)
# Box dimensions
# We want the box to fit the text exactly + padding
# Ensure min width for aesthetic reasons if text is short (at least 30% of target)
box_width = max(max_line_width + (2 * padding_x), int(target_width * 0.3))
# Total Text Height: sum(heights) + spacing * (n-1)
if not text_heights:
total_text_height = font_size
else:
total_text_height = sum(text_heights) + (len(text_heights) - 1) * line_spacing
box_height = total_text_height + (2 * padding_y)
# Create Final Image with Rounded Corners and Shadow
# 1. Canvas for Shadow (larger than box)
canvas_w = box_width + 40
canvas_h = box_height + 40
img = Image.new('RGBA', (canvas_w, canvas_h), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# 2. Draw Shadow
shadow_box = [
(20 + shadow_offset[0], 20 + shadow_offset[1]),
(20 + box_width + shadow_offset[0], 20 + box_height + shadow_offset[1])
]
draw.rounded_rectangle(shadow_box, radius=cornerradius, fill=(0, 0, 0, 100))
# 3. Blur Shadow
img = img.filter(ImageFilter.GaussianBlur(5))
# 4. Draw White Box (sharper, on top of blurred shadow)
draw_final = ImageDraw.Draw(img)
main_box = [
(20, 20),
(20 + box_width, 20 + box_height)
]
# Semi-transparent white (240/255 alpha ~ 94% opacity)
draw_final.rounded_rectangle(main_box, radius=cornerradius, fill=(255, 255, 255, 240))
# 5. Draw Text
current_y = 20 + padding_y - 2 # Minor visual adjustment
for i, line in enumerate(lines):
if not line:
current_y += font_size + line_spacing
continue
bbox = draw_final.textbbox((0, 0), line, font=font)
line_w = bbox[2] - bbox[0]
line_h = text_heights[i] if i < len(text_heights) else bbox[3] - bbox[1]
# Center X
x = 20 + (box_width - line_w) // 2
# Draw Black Text
draw_final.text((x, current_y), line, font=font, fill="black")
current_y += line_h + line_spacing
img.save(output_image_path)
return output_image_path, canvas_w, canvas_h
def add_hook_to_video(video_path, text, output_path, position="top", font_scale=1.0):
"""
Overlays text hook onto video.
position: 'top', 'center', 'bottom'
font_scale: float multiplier (1.0 = default)
"""
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video {video_path} not found")
# 1. Probe video width to scale text properly
try:
cmd = ['ffprobe', '-v', 'error', '-show_entries', 'stream=width,height', '-of', 'csv=s=x:p=0', video_path]
res = subprocess.check_output(cmd).decode().strip()
# Takes first stream if multiple
dims = res.split('\n')[0].split('x')
video_width = int(dims[0])
video_height = int(dims[1])
except Exception as e:
print(f"⚠️ FFprobe failed: {e}. Assuming 1080x1920")
video_width = 1080
video_height = 1920
# 2. Generate Image
# Box check: Don't let it be wider than 90% of screen
target_box_width = int(video_width * 0.9)
hook_filename = f"temp_hook_{os.path.basename(video_path)}.png"
# Ensure unique or temp location if needed, but relative is fine for this app structure
try:
img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale)
# 3. Calculate Overlay Position
overlay_x = (video_width - box_w) // 2
if position == "center":
overlay_y = (video_height - box_h) // 2
elif position == "bottom":
# Bottom 20% mark (approx)
overlay_y = int(video_height * 0.70)
else:
# Top 20% mark
overlay_y = int(video_height * 0.20)
# 4. FFmpeg Command
print(f"🎬 Overlaying hook: '{text}' at {overlay_x},{overlay_y}")
ffmpeg_cmd = [
'ffmpeg', '-y',
'-i', video_path,
'-i', img_path,
'-filter_complex', f"[0:v][1:v]overlay={overlay_x}:{overlay_y}",
'-c:a', 'copy',
'-c:v', 'libx264', '-preset', 'fast', '-crf', '22',
output_path
]
subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"✅ Hook added to {output_path}")
return True
except subprocess.CalledProcessError as e:
print(f"❌ FFmpeg Error: {e.stderr.decode() if e.stderr else 'Unknown'}")
raise e
except Exception as e:
print(f"❌ Hook Gen Error: {e}")
raise e
finally:
# Cleanup temp image
if os.path.exists(hook_filename):
os.remove(hook_filename)

View file

@ -60,7 +60,8 @@ OUTPUT — RETURN ONLY VALID JSON (no markdown, no comments). Order clips by pre
"end": <number in seconds, e.g., 37.900>, "end": <number in seconds, e.g., 37.900>,
"video_description_for_tiktok": "<description for TikTok oriented to get views>", "video_description_for_tiktok": "<description for TikTok oriented to get views>",
"video_description_for_instagram": "<description for Instagram oriented to get views>", "video_description_for_instagram": "<description for Instagram oriented to get views>",
"video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>" "video_title_for_youtube_short": "<title for YouTube Short oriented to get views 100 chars max>",
"viral_hook_text": "<SHORT punchy text overlay (max 10 words). MUST BE IN THE SAME LANGUAGE AS THE VIDEO TRANSCRIPT. Examples: 'POV: You realized...', 'Did you know?', 'Stop doing this!'>"
}} }}
] ]
}} }}

View file

@ -14,3 +14,4 @@ fastapi
uvicorn uvicorn
python-multipart python-multipart
httpx httpx
Pillow

View file

@ -38,6 +38,156 @@ def upload_file_to_s3(file_path, bucket_name, s3_key):
except Exception: except Exception:
return False return False
from botocore.config import Config
import json
import time as time_module
# Simple in-memory cache for gallery clips
_clips_cache = {
"data": None,
"timestamp": 0
}
CACHE_TTL_SECONDS = 300 # 5 minutes
def get_s3_client():
"""Returns an authenticated S3 client."""
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
region = os.environ.get('AWS_REGION', 'us-east-1')
if not access_key or not secret_key:
return None
return boto3.client(
's3',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=region,
config=Config(signature_version='s3v4')
)
def generate_presigned_url(bucket_name, object_key, expiration=3600):
"""Generate a presigned URL to share an S3 object."""
s3_client = get_s3_client()
if not s3_client:
return None
try:
response = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name,
'Key': object_key},
ExpiresIn=expiration)
return response
except ClientError as e:
logger.error(e)
return None
def list_all_clips(bucket_name=None, limit=50, force_refresh=False):
"""
List recent clips from the S3 bucket by finding metadata files.
Returns a list of dicts containing clip info and signed URLs.
Args:
bucket_name: S3 bucket name (defaults to AWS_S3_BUCKET env var)
limit: Maximum number of clips to return (default 50 for speed)
force_refresh: If True, bypass cache
"""
global _clips_cache
# Check cache first
now = time_module.time()
if not force_refresh and _clips_cache["data"] is not None:
if now - _clips_cache["timestamp"] < CACHE_TTL_SECONDS:
cached = _clips_cache["data"]
return cached[:limit] if limit else cached
if not bucket_name:
bucket_name = os.environ.get('AWS_S3_BUCKET', 'openshorts.app-clips')
s3_client = get_s3_client()
if not s3_client:
return []
all_clips = []
try:
# List all objects in bucket
# Note: For very large buckets, pagination is needed.
# Assuming reasonable size for now, but adding continuation token support is best practice.
paginator = s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=bucket_name)
metadata_files = []
for page in pages:
if 'Contents' in page:
for obj in page['Contents']:
if obj['Key'].endswith('_metadata.json'):
metadata_files.append(obj)
# Sort metadata by LastModified (newest first)
metadata_files.sort(key=lambda x: x['LastModified'], reverse=True)
for meta_obj in metadata_files:
key = meta_obj['Key']
# key format: {job_id}/..._metadata.json
# Read metadata content
try:
obj_resp = s3_client.get_object(Bucket=bucket_name, Key=key)
content = obj_resp['Body'].read().decode('utf-8')
data = json.loads(content)
parts = key.split('/')
job_id = parts[0] if len(parts) > 1 else "unknown"
# Filename base for clips in same folder
# Meta key: "job_id/filename_metadata.json"
# Base name in metadata usually matches filename without ext
meta_filename = os.path.basename(key)
base_name = meta_filename.replace('_metadata.json', '')
clips_data = data.get('shorts', [])
for i, clip in enumerate(clips_data):
clip_filename = f"{base_name}_clip_{i+1}.mp4"
clip_key = f"{job_id}/{clip_filename}"
# Generate signed URL
signed_url = generate_presigned_url(bucket_name, clip_key, expiration=7200) # 2 hours
if signed_url:
all_clips.append({
"job_id": job_id,
"index": i,
"url": signed_url,
"title": clip.get('video_title_for_youtube_short', 'Untitled Clip'),
"tiktok_desc": clip.get('video_description_for_tiktok', ''),
"insta_desc": clip.get('video_description_for_instagram', ''),
"created_at": meta_obj['LastModified'].isoformat(),
"duration": clip.get('end', 0) - clip.get('start', 0)
})
# Early exit if we have enough clips
if limit and len(all_clips) >= limit:
break
# Early exit if we have enough clips
if limit and len(all_clips) >= limit:
break
except Exception as e:
logger.error(f"Error processing metadata {key}: {e}")
continue
except Exception as e:
logger.error(f"Error listing bucket: {e}")
return []
# Update cache with full results (keep for pagination later)
_clips_cache["data"] = all_clips
_clips_cache["timestamp"] = now
return all_clips[:limit] if limit else all_clips
def upload_job_artifacts(directory, job_id): def upload_job_artifacts(directory, job_id):
""" """
Upload all generated clips and metadata for a job to S3. Upload all generated clips and metadata for a job to S3.
@ -54,3 +204,4 @@ def upload_job_artifacts(directory, job_id):
s3_key = f"{job_id}/{filename}" s3_key = f"{job_id}/{filename}"
upload_file_to_s3(file_path, bucket_name, s3_key) upload_file_to_s3(file_path, bucket_name, s3_key)

37
verify_aesthetic.py Normal file
View file

@ -0,0 +1,37 @@
import os
import shutil
# Check if PIL is installed, if not we can't run this locally but it will run in docker
try:
from hooks import create_hook_image
except ImportError:
print("⚠️ PIL not found locally. Please run this inside the Docker container.")
# Mocking for local check if needed or just exit
exit(1)
def verify():
print("🧪 Verifying Hook Aesthetics...")
test_text = "POV: You are testing\nthe new aesthetic feature\nwith explicit lines."
output_path = "aesthetic_hook.png"
target_width = 800
try:
path, w, h = create_hook_image(test_text, target_width, output_image_path=output_path)
print(f"✅ Image generated at {path}")
print(f" Dimensions including shadow: {w}x{h}")
# Verify it's larger than the text box would be (due to shadow/padding)
# Just rudimentary checks
if not os.path.exists(path):
print("❌ File does not exist")
return False
print("✨ Verification Successful! (Inspect aesthetic_hook.png visually)")
return True
except Exception as e:
print(f"❌ Verification Failed: {e}")
return False
if __name__ == "__main__":
verify()

32
verify_custom_hook.py Normal file
View file

@ -0,0 +1,32 @@
import os
try:
from hooks import create_hook_image
except ImportError:
print("⚠️ PIL not found locally. Run inside Docker.")
exit(1)
def verify():
print("🧪 Verifying Hook Customization...")
test_text = "Custom Position\n& Size Test"
# Test 1: Small + Top
print(" Testing Small + Top...")
p1, w1, h1 = create_hook_image(test_text, 800, "hook_small.png", font_scale=0.8)
print(f" ✅ Small: {w1}x{h1}")
# Test 2: Large + Center
print(" Testing Large...")
p2, w2, h2 = create_hook_image(test_text, 800, "hook_large.png", font_scale=1.3)
print(f" ✅ Large: {w2}x{h2}")
if w2 > w1 and h2 > h1:
print(" ✅ Scaling logic works (Large > Small)")
else:
print(" ❌ Scaling logic failed")
# Cleanup
if os.path.exists(p1): os.remove(p1)
if os.path.exists(p2): os.remove(p2)
if __name__ == "__main__":
verify()

36
verify_hooks.py Normal file
View file

@ -0,0 +1,36 @@
import os
import shutil
from hooks import create_hook_image
def verify():
print("🧪 Verifying Hook Image Generation...")
test_text = "POV: You are testing the viral hook feature\nand it works perfectly."
output_path = "test_hook.png"
target_width = 800
try:
path, w, h = create_hook_image(test_text, target_width, output_image_path=output_path)
print(f"✅ Image generated at {path}")
print(f" Dimensions: {w}x{h}")
if not os.path.exists(path):
print("❌ File does not exist")
return False
if os.path.getsize(path) == 0:
print("❌ File is empty")
return False
print("✨ Verification Successful!")
return True
except Exception as e:
print(f"❌ Verification Failed: {e}")
return False
finally:
if os.path.exists(output_path):
os.remove(output_path)
if __name__ == "__main__":
verify()