diff --git a/app.py b/app.py index bf1ce11..18ba070 100644 --- a/app.py +++ b/app.py @@ -7,6 +7,7 @@ import json import shutil import glob import time +import zipfile import math import itertools import asyncio @@ -16,7 +17,8 @@ from contextlib import asynccontextmanager from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Request, Header, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles -from fastapi.responses import HTMLResponse +from fastapi.responses import HTMLResponse, FileResponse +from starlette.background import BackgroundTask from pydantic import BaseModel from s3_uploader import upload_job_artifacts, list_all_clips, upload_actor_to_s3, list_actor_gallery, upload_video_to_gallery, list_video_gallery @@ -808,6 +810,50 @@ async def get_status(job_id: str, request: Request): "result": job.get('result') } + +@app.get("/api/jobs/{job_id}/download-all") +async def download_all_clips(job_id: str, request: Request): + """Bundle the current version of every clip of a job into one ZIP.""" + if job_id in jobs: + await _assert_job_owner(request, jobs[job_id]) + + output_dir = os.path.join(OUTPUT_DIR, job_id) + json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) + if not json_files: + raise HTTPException(status_code=404, detail="Job not found") + + with open(json_files[0], 'r', encoding='utf-8') as f: + data = json.load(f) + + files = [] + for i, clip in enumerate(data.get('shorts', [])): + filename = os.path.basename(clip.get('video_url', '').split('/')[-1]) + path = os.path.join(output_dir, filename) + if filename and os.path.exists(path): + files.append((i, path)) + + if not files: + raise HTTPException(status_code=404, detail="No clip files found for this job") + + zip_path = os.path.join(output_dir, f"clips_{int(time.time())}.zip") + + def build_zip(): + # Videos are already compressed; store instead of deflate for speed. + with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED) as zf: + for i, path in files: + zf.write(path, arcname=f"clip_{i + 1:02d}_{os.path.basename(path)}") + + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, build_zip) + + return FileResponse( + zip_path, + media_type="application/zip", + filename=f"openshorts_clips_{job_id[:8]}.zip", + background=BackgroundTask(os.remove, zip_path), + ) + + from editor import VideoEditor from subtitles import generate_srt, generate_ass, burn_subtitles, generate_srt_from_video from hooks import add_hook_to_video diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index f64e6b1..9c2e4c6 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -1,8 +1,9 @@ import React, { useState, useEffect } from 'react'; -import { Upload, Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail, Loader2 } from 'lucide-react'; +import { Upload, Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail, Loader2, Download, Type } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; +import SubtitleModal from './components/SubtitleModal'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; import ThumbnailStudio from './components/ThumbnailStudio'; @@ -18,6 +19,7 @@ import AdvancedBanner from './components/AdvancedBanner'; import HistoryTab from './components/HistoryTab'; import ProfileMenu from './components/ProfileMenu'; import Modal from './components/ui/Modal'; +import { getApiUrl } from './config'; import { useAuth } from './contexts/AuthContext'; import { apiFetch, apiJson, QuotaError } from './lib/api'; @@ -181,6 +183,10 @@ function App() { const [jobId, setJobId] = useState(null); const [status, setStatus] = useState('idle'); // idle, processing, complete, error const [results, setResults] = useState(null); + // Bulk subtitles: apply one style to every clip of the job + const [showBulkSubtitles, setShowBulkSubtitles] = useState(false); + const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 }); + const [downloadingAll, setDownloadingAll] = useState(false); const [logs, setLogs] = useState([]); const [logsVisible, setLogsVisible] = useState(true); const [processingMedia, setProcessingMedia] = useState(null); @@ -208,6 +214,75 @@ function App() { setIsSyncedPlaying(false); }; + // Apply one subtitle style to every clip of the job, sequentially. + const handleBulkSubtitles = async (options) => { + const clips = results?.clips || []; + const total = clips.length; + if (!total) return; + setBulkSub({ running: true, current: 0, total, errors: 0 }); + let errors = 0; + for (let i = 0; i < total; i++) { + setBulkSub({ running: true, current: i + 1, total, errors }); + try { + const res = await apiFetch('/api/subtitle', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + job_id: jobId, + clip_index: i, + position: options.position, + font_size: options.fontSize, + font_name: options.fontName, + font_color: options.fontColor, + border_color: options.borderColor, + border_width: options.borderWidth, + bg_color: options.bgColor, + bg_opacity: options.bgOpacity, + style: options.style || 'classic', + highlight_color: options.highlightColor || '#FFD700', + effect: options.effect || 'none', + base_opacity: options.baseOpacity ?? 1.0, + uppercase: options.uppercase || false, + // Chain from the clip's current server file (its video_url basename). + input_filename: (clips[i].video_url || '').split('/').pop(), + }), + }); + if (!res.ok) errors++; + } catch { + errors++; + } + } + setBulkSub({ running: false, current: total, total, errors }); + setShowBulkSubtitles(false); + // Refresh results so each ResultCard picks up its new subtitled video_url. + try { + const data = await pollJob(jobId); + if (data.result) setResults(data.result); + } catch { /* keep current results */ } + }; + + const handleDownloadAll = async () => { + if (!jobId) return; + setDownloadingAll(true); + try { + const res = await apiFetch(`/api/jobs/${jobId}/download-all`); + if (!res.ok) throw new Error(await res.text()); + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `openshorts_clips_${(jobId || '').slice(0, 8)}.zip`; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + } catch (e) { + alert(`Download failed: ${e.message}`); + } finally { + setDownloadingAll(false); + } + }; + // Session Recovery: Restore on mount useEffect(() => { try { @@ -1135,14 +1210,40 @@ function App() { GEMINI · ${results.cost_analysis.total_cost.toFixed(5)} )} - {results?.clips?.length > 1 && status === 'complete' && ( - + {results?.clips?.length > 0 && status === 'complete' && ( +