feat: bulk subtitles + download-all-as-ZIP (PR #50 block 2)

- app.py: GET /api/jobs/{job_id}/download-all bundles every clip's current
  file into one ZIP (stored, not deflated — already compressed), streamed
  via FileResponse and cleaned up after send; owner-guarded in cloud mode.
- App.jsx: 'subtitle all' opens the SubtitleModal in bulk mode and applies
  the chosen style to every clip sequentially (progress in the button),
  then refreshes results so each card shows its subtitled file. 'download
  all' fetches the ZIP and triggers a browser download.
- SubtitleModal: bulkCount prop -> 'apply to N clips' label.
This commit is contained in:
juancarlos.cavero 2026-07-17 20:42:14 +02:00
parent d94e126e0f
commit 82dcd0af89
3 changed files with 173 additions and 12 deletions

48
app.py
View file

@ -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

View file

@ -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)}
</span>
)}
{results?.clips?.length > 1 && status === 'complete' && (
<button
onClick={() => setShowScheduleWeek(true)}
className="btn-primary px-4 py-2 text-xs ml-auto"
>
<Calendar size={14} />
schedule week
</button>
{results?.clips?.length > 0 && status === 'complete' && (
<div className="flex items-center gap-2 ml-auto">
{results.clips.length > 1 && (
<button
onClick={() => setShowBulkSubtitles(true)}
disabled={bulkSub.running}
className="btn-ghost px-3 py-2 text-xs"
title="Apply one subtitle style to all clips"
>
{bulkSub.running
? <><Loader2 size={14} className="animate-spin" />subtitling {bulkSub.current}/{bulkSub.total}</>
: <><Type size={14} />subtitle all</>}
</button>
)}
<button
onClick={handleDownloadAll}
disabled={downloadingAll}
className="btn-ghost px-3 py-2 text-xs"
title="Download all clips as a ZIP"
>
{downloadingAll
? <><Loader2 size={14} className="animate-spin" />zipping…</>
: <><Download size={14} />download all</>}
</button>
{results.clips.length > 1 && (
<button
onClick={() => setShowScheduleWeek(true)}
className="btn-primary px-4 py-2 text-xs"
>
<Calendar size={14} />
schedule week
</button>
)}
</div>
)}
</h2>
@ -1291,6 +1392,20 @@ function App() {
isManaged={isManaged}
/>
{/* Bulk subtitles: preview on the first clip, apply the chosen style to all */}
{showBulkSubtitles && results?.clips?.length > 0 && (
<SubtitleModal
isOpen={showBulkSubtitles}
onClose={() => setShowBulkSubtitles(false)}
onGenerate={handleBulkSubtitles}
isProcessing={bulkSub.running}
videoUrl={getApiUrl(results.clips[0].video_url)}
jobId={jobId}
clipIndex={0}
bulkCount={results.clips.length}
/>
)}
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
{showTopUp && (
<TopUpModal

View file

@ -75,7 +75,7 @@ const swatchClass = (selected) =>
? 'ring-2 ring-[color:var(--color-accent)] ring-offset-2 ring-offset-[color:var(--color-paper-2)]'
: 'ring-1 ring-[color:var(--color-rule-2)] hover:ring-[color:var(--color-accent)]'}`;
export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, jobId, clipIndex, existingHook }) {
export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessing, videoUrl, jobId, clipIndex, existingHook, bulkCount = 0 }) {
const [position, setPosition] = useState('bottom');
const [fontSize] = useState(24);
const [fontName, setFontName] = useState('Verdana');
@ -495,7 +495,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
className="btn-primary flex-1"
>
{isProcessing && <Loader2 size={16} className="animate-spin text-brassink" />}
{isProcessing ? 'generating...' : 'apply subtitles'}
{isProcessing ? 'generating...' : (bulkCount > 1 ? `apply to ${bulkCount} clips` : 'apply subtitles')}
</button>
</div>
</div>