feat(clips): four quality fixes found by auditing real user output

Captions must always be the LAST layer. Editing or hooking a clip that already
had them burned in produced `edited_subtitled_<...>`, and the next subtitle pass
stacked a second caption layer on top of the first — visibly doubled and
unreadable in a real user clip found in prod today. /api/edit and /api/hook now
derive from the clean file and put captions back afterwards, so a restyle always
has an un-captioned base to burn onto. The latent bug predates auto-captions but
shipping them by default made it the normal path. The walk-back is now one
helper instead of being open-coded in the subtitle endpoint.

Loudness was uncontrolled. A clip inherited whatever its source was mastered at,
measured across real delivered clips from -13.8 LUFS on a loud upload down to
-28 on a quiet talk, while TikTok/Reels/Shorts all normalise playback to around
-14 — so the quiet ones just sound thin in the feed. loudnorm at the clip cut,
where the audio is already being encoded, so it costs nothing. Verified to pull
both extremes to target: -29.7 -> -13.7 and -10.1 -> -13.5. AUDIO_NORMALIZE=0.

The GENERAL layout wasted the frame. Fitting a 16:9 source to full width left
it 608px tall in a 1920 frame: 32% content, 68% blurred filler. Now scaled by
height to 42%, trimming the overflow. Deliberately conservative — GENERAL is
chosen for groups and landscapes, exactly where cropping the sides cuts someone
out, so 0.55 was tried and rejected for throwing away 42% of the width. 0.42
keeps ~76%. GENERAL_CONTENT_HEIGHT_RATIO=0.32 restores the old behaviour.

The TRACK/GENERAL classifier only counted faces, so a screencast that happened
to contain one face was cropped to it — real prod clips came out with headlines
cut mid-word and unreadable. A cheap Canny pass over the side thirds (the part a
9:16 crop discards), with face boxes blanked first, now routes text-dense scenes
to GENERAL instead. GRAPHIC_DENSITY_THRESHOLD=1.0 disables it.
This commit is contained in:
juancarlos.cavero 2026-07-26 20:35:35 +02:00
parent bdd9e5d53d
commit ea78445953
5 changed files with 226 additions and 16 deletions

86
app.py
View file

@ -378,6 +378,50 @@ def _canonical_clip_file(output_dir, base_name, index):
return os.path.basename(max(derived, key=os.path.getmtime))
def _strip_burned_captions(output_dir, filename):
"""Walk ``subtitled_<ts>_`` prefixes back to the file without burned captions.
Returns the name unchanged when there is nothing to strip (or when the
underlying file is gone, e.g. a library restore that only kept the current
version).
"""
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))):
return filename
filename = m.group(1)
def _reapply_captions(job_id, clip_index, video_path):
"""Re-burn the default captions onto a freshly derived file.
Captions must always be the LAST layer. Editing or hooking a clip that
already had them burned in produced `edited_subtitled_<...>`, and the next
subtitle pass then stacked a second caption layer on top of the first —
visibly doubled and unreadable in real user clips (26-jul-2026). So the
derivation runs on the clean file and captions go back on afterwards.
Returns the captioned path, or None if there was nothing to caption.
"""
try:
meta_files = glob.glob(os.path.join(OUTPUT_DIR, job_id, "*_metadata.json"))
if not meta_files:
return None
with open(meta_files[0], 'r') as f:
data = json.load(f)
transcript = data.get('transcript')
clips = data.get('shorts', [])
if not transcript or clip_index >= len(clips):
return None
clip = clips[clip_index]
import main as _main
return _main.auto_caption_clip(video_path, transcript,
clip['start'], clip['end'])
except Exception as e:
print(f"⚠️ Could not re-apply captions to {video_path}: {e}")
return None
def _recover_jobs_from_disk():
"""Rebuild completed jobs from OUTPUT_DIR after a restart (issue #46 / #18).
@ -1600,6 +1644,15 @@ async def edit_clip(
if not os.path.exists(input_path):
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
# Edit the clip WITHOUT its burned captions, then put them back on top —
# otherwise the captions are baked into the edit and the next subtitle
# pass stacks a second layer over them (see _reapply_captions).
clean_name = _strip_burned_captions(os.path.join(OUTPUT_DIR, req.job_id), filename)
had_captions = clean_name != filename
if had_captions:
filename = clean_name
input_path = os.path.join(OUTPUT_DIR, req.job_id, clean_name)
# Define output path for edited video
edited_filename = f"edited_{filename}"
output_path = os.path.join(OUTPUT_DIR, req.job_id, edited_filename)
@ -1673,6 +1726,14 @@ async def edit_clip(
loop = asyncio.get_event_loop()
plan = await loop.run_in_executor(None, run_edit)
# Captions back on top, so the clip the user sees keeps them and the
# clean edited file stays available for a later restyle.
if had_captions:
recap = await loop.run_in_executor(
None, _reapply_captions, req.job_id, req.clip_index, output_path)
if recap:
edited_filename = os.path.basename(recap)
new_video_url = f"/videos/{req.job_id}/{edited_filename}"
# Persist the new current file like /api/subtitle does: in-memory job
@ -1977,13 +2038,8 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
base_name = os.path.basename(json_files[0]).replace('_metadata.json', '')
filename = f"{base_name}_clip_{req.clip_index+1}.mp4"
# Re-subtitling must replace previous subtitles instead of burning over
# them: walk subtitled_<ts>_ prefixes back to the pre-subtitle file.
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)
# Re-subtitling must replace previous subtitles instead of burning over them.
filename = _strip_burned_captions(output_dir, filename)
input_path = os.path.join(output_dir, filename)
if not os.path.exists(input_path):
@ -2208,6 +2264,15 @@ async def add_hook(req: HookRequest, request: Request):
if not os.path.exists(input_path):
raise HTTPException(status_code=404, detail=f"Video file not found: {input_path}")
# Same invariant as /api/edit: overlay onto the clip WITHOUT its burned
# captions, then put them back on top, so a later restyle never stacks a
# second caption layer (see _reapply_captions).
clean_name = _strip_burned_captions(output_dir, filename)
had_captions = clean_name != filename
if had_captions:
filename = clean_name
input_path = os.path.join(output_dir, clean_name)
# Output video
output_filename = f"hook_{filename}"
output_path = os.path.join(output_dir, output_filename)
@ -2238,6 +2303,13 @@ async def add_hook(req: HookRequest, request: Request):
if reservation_id:
await _metering.commit_reservation(reservation_id)
# Captions back on top (see /api/edit for the same invariant).
if had_captions:
recap = await asyncio.get_event_loop().run_in_executor(
None, _reapply_captions, req.job_id, req.clip_index, output_path)
if recap:
output_filename = os.path.basename(recap)
# Update Persistence (Same logic as subtitles)
# Update InMemory Jobs
if req.clip_index < len(job['result']['clips']):

View file

@ -54,6 +54,29 @@ _NVENC_ARGS = {
METADATA_SCRUB = ["-map_metadata", "-1", "-map_chapters", "-1",
"-map_metadata:s:v", "-1", "-map_metadata:s:a", "-1"]
# Loudness normalisation for the delivered clip.
#
# Without this the clip inherits whatever the source was mastered at, so a
# user's clips land anywhere: measured across real delivered clips on
# 26-jul-2026, from -13.8 LUFS on a loud upload down to -28 LUFS on a quiet
# talk. TikTok, Reels and Shorts all normalise playback to roughly -14 LUFS,
# which means the quiet ones just sound thin next to everything else in the
# feed — the loud ones aren't rewarded, the quiet ones are punished.
#
# I=-14 matches the platforms' target, TP=-1.5 leaves headroom so their own
# re-encode can't clip, LRA=11 is the usual allowance for speech. Applied at
# the clip cut, where the audio is being encoded to AAC anyway, so it costs
# nothing extra. AUDIO_NORMALIZE=0 turns it off.
LOUDNORM_FILTER = "loudnorm=I=-14:TP=-1.5:LRA=11"
def audio_encode_args():
"""AAC encode args for a delivered clip, with loudness normalisation."""
args = ["-c:a", "aac"]
if os.environ.get("AUDIO_NORMALIZE", "1").strip() != "0":
args = ["-af", LOUDNORM_FILTER] + args
return args
_probe_lock = threading.Lock()
_nvenc_ok = None # None = not probed yet
_announced = False

57
main.py
View file

@ -22,7 +22,8 @@ from google.genai import types as genai_types
import gemini_worker
from clip_selection import build_transcript_windows, snap_clip_to_words
from ffmpeg_utils import video_encode_args, QUALITY, QUALITY_FAST, METADATA_SCRUB
from ffmpeg_utils import (video_encode_args, audio_encode_args, QUALITY,
QUALITY_FAST, METADATA_SCRUB)
from dotenv import load_dotenv
import json
@ -477,6 +478,45 @@ def create_general_frame(frame, output_width, output_height):
return final_frame
# Share of the frame's SIDE regions that has to look like text/graphics before a
# single-face scene is treated as a screencast rather than a talking head.
# Tuned against real prod clips; GRAPHIC_DENSITY_THRESHOLD=1.0 disables the rule.
GRAPHIC_DENSITY_THRESHOLD = float(
os.environ.get("GRAPHIC_DENSITY_THRESHOLD", "0.085"))
def _graphic_density(frame, face_candidates):
"""Rough share of the frame's left/right thirds carrying text or graphics.
Text and UI have a signature a face doesn't: dense, high-contrast, mostly
axis-aligned edges. A Canny pass over the side thirds — the parts a 9:16
crop would throw away — separates "talking head on a plain background"
(near zero) from "talking head next to a chart" (high) well enough to
route the scene, and costs a fraction of a millisecond per sampled frame.
Face boxes are blanked first so a detailed face or busy clothing can't be
mistaken for a graphic.
"""
try:
h, w = frame.shape[:2]
if w < 60 or h < 60:
return 0.0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
for cand in face_candidates or []:
fx, fy, fw, fh = [int(v) for v in cand.get('box', (0, 0, 0, 0))]
# Generous margin: hair, shoulders and headsets are not graphics.
x0, y0 = max(0, fx - fw // 2), max(0, fy - fh // 2)
x1, y1 = min(w, fx + fw + fw // 2), min(h, fy + fh + fh // 2)
if x1 > x0 and y1 > y0:
gray[y0:y1, x0:x1] = 0
third = w // 3
sides = np.hstack((gray[:, :third], gray[:, -third:]))
edges = cv2.Canny(sides, 100, 200)
return float(np.count_nonzero(edges)) / edges.size
except Exception:
return 0.0 # never let the heuristic break scene analysis
def analyze_scenes_strategy(video_path, scenes):
"""
Analyzes each scene to determine if it should be TRACK (Single person) or GENERAL (Group/Wide).
@ -500,6 +540,7 @@ def analyze_scenes_strategy(video_path, scenes):
))
face_counts = []
graphic_scores = []
for f_idx in frames_to_check:
cap.set(cv2.CAP_PROP_POS_FRAMES, f_idx)
ret, frame = cap.read()
@ -513,6 +554,7 @@ def analyze_scenes_strategy(video_path, scenes):
# Detect faces
candidates = detect_face_candidates(frame)
face_counts.append(len(candidates))
graphic_scores.append(_graphic_density(frame, candidates))
# Decision Logic
if not face_counts:
@ -525,8 +567,19 @@ def analyze_scenes_strategy(video_path, scenes):
# 1 face -> TRACK
# > 1.2 faces -> GENERAL (Group)
avg_graphic = (sum(graphic_scores) / len(graphic_scores)
if graphic_scores else 0.0)
# A lone face normally means TRACK — crop to the speaker. But a scene
# that is ALSO dense with text or graphics outside the face (a
# screencast, a chart, a headline, a comparison table) loses its whole
# point when cropped to 9:16: seen in real prod clips where headlines
# came out cut mid-word and unreadable. Those go to GENERAL, which
# keeps the full width.
if avg_faces > 1.2 or avg_faces < 0.5:
strategies.append('GENERAL')
elif avg_graphic > GRAPHIC_DENSITY_THRESHOLD:
strategies.append('GENERAL')
else:
strategies.append('TRACK')
@ -1485,7 +1538,7 @@ if __name__ == '__main__':
'-to', str(end),
'-i', input_video,
*video_encode_args(QUALITY_FAST),
'-c:a', 'aac',
*audio_encode_args(),
clip_temp_path
]
subprocess.run(cut_command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)

View file

@ -91,15 +91,39 @@ def concat_list_content(segment_paths):
return "".join(f"file '{p}'\n" for p in segment_paths)
# How much of the frame height the real content should fill in GENERAL layout.
#
# Fitting a 16:9 source to the full output width leaves it 608px tall in a
# 1920px frame — the content is 32% of the screen and 68% is blurred filler.
# That reads as a thumbnail floating in soup, and it is what a GENERAL scene
# looked like in real delivered clips (audited 26-jul-2026).
#
# Scaling the content up and letting the sides overflow trades width for
# presence, and the trade has to stay conservative: GENERAL is chosen for group
# shots and landscapes, exactly the material where cropping the sides cuts
# someone out of frame. At 0.42 a 16:9 source keeps ~76% of its width while
# going from 32% to 42% of the frame height. 0.55 was tried and rejected — it
# reaches 55% height but throws away 42% of the width.
#
# GENERAL_CONTENT_HEIGHT_RATIO=0.32 restores the old full-width behaviour.
GENERAL_CONTENT_HEIGHT_RATIO = float(
os.environ.get("GENERAL_CONTENT_HEIGHT_RATIO", "0.42"))
def general_filtergraph(out_w, out_h):
"""Blurred-background 'general shot' layout, mirroring v1's
create_general_frame: bg fills height (center-cropped, blurred), fg fits
width, centered vertically."""
"""Blurred-background 'general shot' layout: bg fills the frame (centre-
cropped, blurred), fg is scaled to a readable share of the height and
centred, overflowing the sides rather than floating small in the middle."""
fg_h = int(out_h * GENERAL_CONTENT_HEIGHT_RATIO)
fg_h += fg_h % 2
return (
f"[0:v]split=2[bga][fga];"
f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h},"
f"scale={out_w}:{out_h},gblur=sigma=12[bg];"
f"[fga]scale={out_w}:-2[fg];"
# Scale by HEIGHT, then trim any overflow to the output width. crop
# centres by default, and min() makes it a no-op when the scaled source
# is already narrower than the frame (portrait/square sources).
f"[fga]scale=-2:{fg_h},crop=w=min(iw\\,{out_w}):h=ih[fg];"
f"[bg][fg]overlay=x=(W-w)/2:y=(H-h)/2,setsar=1[v]"
)

View file

@ -83,7 +83,45 @@ class TestDeliverySize:
def test_general_filtergraph_targets_output_geometry():
graph = general_filtergraph(608, 1080)
graph = general_filtergraph(1080, 1920)
assert "gblur" in graph
assert "scale=608:-2" in graph
assert "overlay=x=(W-w)/2:y=(H-h)/2" in graph
class TestGeneralLayout:
"""GENERAL used to leave the content at 32% of the frame, floating in blur."""
def test_content_is_scaled_by_height_not_width(self):
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
graph = general_filtergraph(1080, 1920)
expected = int(1920 * GENERAL_CONTENT_HEIGHT_RATIO)
expected += expected % 2
assert f"scale=-2:{expected}" in graph
def test_content_height_is_even(self):
# Odd dimensions are rejected by the encoder. Read the FOREGROUND
# scale — the background line also contains a scale=-2: term.
for out_h in (1920, 1080, 1078, 976):
graph = general_filtergraph(1080, out_h)
fg = graph.split("[fga]scale=-2:")[1]
h = int(fg.split(",")[0])
assert h % 2 == 0, (out_h, h)
def test_overflow_is_trimmed_never_padded(self):
# min() keeps it a no-op for sources narrower than the frame.
graph = general_filtergraph(1080, 1920)
assert "crop=w=min(iw\\,1080):h=ih" in graph
def test_content_fills_more_than_the_old_full_width_fit(self):
# A 16:9 source fitted to full width was 9/16 of it — 0.5625 * 1080
# = 608px, i.e. 32% of a 1920 frame. The new layout must beat that.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
old_ratio = (1080 * 9 / 16) / 1920
assert GENERAL_CONTENT_HEIGHT_RATIO > old_ratio
def test_keeps_most_of_the_source_width(self):
# GENERAL is for groups and landscapes: cropping the sides too hard
# cuts people out of frame, which is the whole thing it exists to avoid.
from reframe_v2 import GENERAL_CONTENT_HEIGHT_RATIO
scaled_w = 1920 * GENERAL_CONTENT_HEIGHT_RATIO * (16 / 9)
assert 1080 / scaled_w > 0.70, "keeps less than 70% of the source width"