feat(subtitles): let users remove the default captions

Clips now ship captioned, and the modal could only restyle — there was no way
back to a clean clip, so anyone who didn't want captions was stuck with them.

Adds POST /api/subtitle/remove, which points the clip at its un-captioned
original. No re-encode and no quota: the pipeline already keeps the clean file
next to the derived subtitled_<ts>_ one, so removing is choosing the other file.
It reuses the burn path's walk-back, so it undoes any number of restyles, and
running it twice is a no-op.

Verified end to end: auto-caption, restyle (burning from the clean file rather
than stacking a second layer), remove, and remove again.
This commit is contained in:
juancarlos.cavero 2026-07-25 17:48:08 +02:00
parent a2237d07d3
commit fd7a2b2cd9
3 changed files with 121 additions and 1 deletions

64
app.py
View file

@ -2097,6 +2097,70 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
"new_video_url": f"/videos/{req.job_id}/{output_filename}" "new_video_url": f"/videos/{req.job_id}/{output_filename}"
} }
class RemoveSubtitlesRequest(BaseModel):
job_id: str
clip_index: int
input_filename: Optional[str] = None
@app.post("/api/subtitle/remove")
async def remove_subtitles(req: RemoveSubtitlesRequest, request: Request):
"""Point a clip back at its un-captioned original.
Clips ship captioned by default now, so there has to be a way out — without
this, a user who doesn't want captions is stuck with them. No re-encode and
no quota: the pipeline always keeps the clean file next to the derived
``subtitled_<ts>_`` one, so removing is just choosing the other file.
"""
await require_managed_entitlement(request)
await _ensure_job_files(req.job_id, request)
if req.job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id]
await _assert_job_owner(request, job)
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")
filename = os.path.basename(
req.input_filename
or (clips[req.clip_index].get('video_url') or '').split('/')[-1]
or f"{os.path.basename(json_files[0]).replace('_metadata.json', '')}"
f"_clip_{req.clip_index + 1}.mp4")
# Same walk-back the burn path uses, so this undoes any number of restyles.
while True:
m = re.match(r'^subtitled_\d+_(.+)$', filename)
if not m or not os.path.exists(os.path.join(output_dir, m.group(1))):
break
filename = m.group(1)
if not os.path.exists(os.path.join(output_dir, filename)):
raise HTTPException(status_code=404,
detail="The original clip is no longer available.")
new_url = f"/videos/{req.job_id}/{filename}"
if req.clip_index < len(job.get('result', {}).get('clips', [])):
job['result']['clips'][req.clip_index]['video_url'] = new_url
try:
clips[req.clip_index]['video_url'] = new_url
data['shorts'] = clips
with open(json_files[0], 'w') as f:
json.dump(data, f, indent=4)
except Exception as e:
print(f"⚠️ Failed to update metadata.json: {e}")
_archive_clip_edit_bg(req.job_id, req.clip_index, filename)
return {"success": True, "new_video_url": new_url}
class HookRequest(BaseModel): class HookRequest(BaseModel):
job_id: str job_id: str
clip_index: int clip_index: int

View file

@ -277,6 +277,49 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
} }
}; };
// Clips are captioned by default, so "no captions" has to be reachable.
// Nothing is re-encoded: the server still holds the clean file next to the
// captioned one and just points this clip back at it.
const handleRemoveSubtitles = async () => {
setIsSubtitling(true);
setEditError(null);
try {
const res = await apiFetch('/api/subtitle/remove', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
job_id: jobId, clip_index: index, input_filename: serverVideoFile,
}),
});
if (!res.ok) throw new Error(await res.text());
const data = await res.json();
if (data.new_video_url) {
const serverUrl = getApiUrl(data.new_video_url);
setServerVideoFile(data.new_video_url.split('/').pop());
const remaining = { ...activeLayers, subtitles: null };
setActiveLayers(remaining);
if (remaining.hook || remaining.effects) {
setCurrentVideoUrl(await renderInBrowser({
videoUrl: serverUrl,
durationInSeconds: clipDuration,
subtitles: null,
hook: remaining.hook,
effects: remaining.effects,
}));
} else {
setCurrentVideoUrl(serverUrl);
}
if (videoRef.current) videoRef.current.load();
setShowSubtitleModal(false);
}
} catch (e) {
setEditError(e.message);
setTimeout(() => setEditError(null), 5000);
} finally {
setIsSubtitling(false);
}
};
const handleSubtitle = async (options) => { const handleSubtitle = async (options) => {
setIsSubtitling(true); setIsSubtitling(true);
setEditError(null); setEditError(null);
@ -890,6 +933,7 @@ export default function ResultCard({ clip, index, jobId, durableUrl, uploadPostK
await onBulkSubtitle(options); await onBulkSubtitle(options);
setShowSubtitleModal(false); setShowSubtitleModal(false);
} : undefined} } : undefined}
onRemove={handleRemoveSubtitles}
bulkCount={clipCount} bulkCount={clipCount}
bulkProgress={bulkProgress} bulkProgress={bulkProgress}
isProcessing={isSubtitling || (bulkProgress?.running ?? false)} isProcessing={isSubtitling || (bulkProgress?.running ?? false)}

View file

@ -65,7 +65,7 @@ const swatchClass = (selected) =>
? 'ring-2 ring-[color:var(--color-accent)] ring-offset-2 ring-offset-[color:var(--color-paper-2)]' ? '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)]'}`; : 'ring-1 ring-[color:var(--color-rule-2)] hover:ring-[color:var(--color-accent)]'}`;
export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, isProcessing, videoUrl, jobId, clipIndex, existingHook, bulkCount = 0, bulkProgress }) { export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, onRemove, isProcessing, videoUrl, jobId, clipIndex, existingHook, bulkCount = 0, bulkProgress }) {
const [position, setPosition] = useState('bottom'); const [position, setPosition] = useState('bottom');
const [fontSize] = useState(24); const [fontSize] = useState(24);
const [fontName, setFontName] = useState('Verdana'); const [fontName, setFontName] = useState('Verdana');
@ -478,6 +478,18 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
: `apply this style to all ${bulkCount} clips`} : `apply this style to all ${bulkCount} clips`}
</button> </button>
)} )}
{/* Clips ship captioned by default, so the way
out has to be here — otherwise a user who
doesn't want captions is stuck with them. */}
{onRemove && (
<button
onClick={onRemove}
disabled={isProcessing}
className="text-xs text-muted underline underline-offset-2 lowercase hover:text-ink2 disabled:opacity-50"
>
remove captions from this clip
</button>
)}
</> </>
); );
})()} })()}