Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / label-reel.py

Raw 2.7 KB on 87dd19288bbd69b69b6ac6e250fb5d18bfebb877
1#!/usr/bin/env python3
2"""Label a native reel with one subtitle renderer; retain its existing soundtrack."""
3import json
4import subprocess
5import sys
6import uuid
7from pathlib import Path
8
9video = Path(sys.argv[1])
10meta = json.loads(video.with_suffix('.json').read_text())
11# Display-only renames do not change pixels or permanent IDs. Use the current registry.
12registry = json.loads(subprocess.check_output([sys.executable, str(Path(__file__).with_name('native-visualizer-catalog.py'))], text=True))
13meta['names'] = [effect['name'] for effect in registry['effects']]
14video.with_suffix('.json').write_text(json.dumps(meta, indent=2) + '\n')
15probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
16 '-show_entries', 'stream=width,height', '-of', 'json', str(video)], text=True))['streams'][0]
17width, height = probe['width'], probe['height']
18
19def timestamp(seconds):
20 ticks = round(seconds * 100)
21 return f'{ticks // 360000}:{ticks // 6000 % 60:02d}:{ticks // 100 % 60:02d}.{ticks % 100:02d}'
22
23script = video.with_suffix('.ass')
24margin = max(24, height // 30)
25header = f'''[Script Info]
26ScriptType: v4.00+
27PlayResX: {width}
28PlayResY: {height}
29WrapStyle: 2
30
31[V4+ Styles]
32Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
33Style: Default,Helvetica,{height // 27},&H00FFFFFF,&H00FFFFFF,&H88000000,&H88000000,0,0,0,0,100,100,0,0,3,12,0,1,{margin},{margin},{margin},1
34
35[Events]
36Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
37'''
38rows = []
39for segment in meta['segments']:
40 scene = int(segment['scene'])
41 name = meta['names'][scene].replace('\\', '').replace('{', '').replace('}', '').replace('\n', ' ')
42 text = f'{scene} {name}'
43 rows.append(f"Dialogue: 0,{timestamp(segment['start'])},{timestamp(segment['end'])},Default,,0,0,0,,{text}")
44script.write_text(header + '\n'.join(rows) + '\n')
45labeled = video.with_name(video.stem + '-labeled.mp4')
46render_target = video.with_name(video.stem + '-labels-' + uuid.uuid4().hex + '.mp4')
47# One libass filter avoids evaluating hundreds of drawtext filters on every 4K frame.
48subprocess.run(['ffmpeg', '-y', '-loglevel', 'warning', '-i', str(video),
49 '-vf', f"ass=filename='{script}'", '-c:v', 'h264_videotoolbox', '-b:v', '24M' if max(width, height) >= 3840 else '8M',
50 '-pix_fmt', 'yuv420p', '-c:a', 'copy', '-movflags', '+faststart', str(render_target)], check=True)
51render_target.replace(labeled)
52labeled.with_suffix('.json').write_text(json.dumps(meta, indent=2) + '\n')
53print(f'Labeled {labeled}')