-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvideo_cli.py
More file actions
758 lines (636 loc) · 27.6 KB
/
Copy pathvideo_cli.py
File metadata and controls
758 lines (636 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#!/usr/bin/env python3
"""
Video CLI — FFmpeg-powered video editing pipeline for Claude Code.
Color grading, montage, transitions, text overlays, social media export.
"""
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
PROJECT_DIR = Path(__file__).parent
PRESETS_DIR = PROJECT_DIR / "presets"
OUTPUT_DIR = PROJECT_DIR / "output"
LUTS_DIR = PROJECT_DIR / "assets" / "luts"
# ══════════════════════════════════════════════════
# COLOR GRADING PRESETS
# ══════════════════════════════════════════════════
GRADE_PRESETS = {
"cinematic-warm": {
"desc": "Film look chaud, contrastes doux, tons dorés",
"filter": (
"curves=preset=cross_process,"
"colortemperature=temperature=6800,"
"vibrance=intensity=0.3,"
"eq=contrast=1.1:saturation=1.15,"
"unsharp=5:5:0.8,"
"colorlevels=rimin=0.02:rimax=0.98"
),
},
"cinematic-cold": {
"desc": "Film look froid, tons bleutés, contrastes forts",
"filter": (
"colortemperature=temperature=4500,"
"colorbalance=bs=0.08:bm=0.05,"
"eq=contrast=1.15:saturation=0.9:brightness=-0.02,"
"curves=r='0/0 0.25/0.2 0.5/0.48 1/0.95':g='0/0 0.5/0.5 1/1':b='0/0.05 0.5/0.55 1/1',"
"unsharp=5:5:0.6,"
"colorlevels=rimin=0.03:rimax=0.97"
),
},
"cinematic-teal-orange": {
"desc": "Look teal & orange blockbuster (peau chaude, ombres froides)",
"filter": (
"colorbalance=rs=-0.1:gs=-0.05:bs=0.15:rh=0.15:gh=0.05:bh=-0.1,"
"vibrance=intensity=0.25,"
"eq=contrast=1.12:saturation=1.2,"
"unsharp=5:5:0.7,"
"colorlevels=rimin=0.02:rimax=0.98"
),
},
"vintage-film": {
"desc": "Pellicule vintage, grain, noirs relevés, tons chauds",
"filter": (
"curves=r='0/0.05 0.5/0.55 1/0.95':g='0/0.03 0.5/0.5 1/0.92':b='0/0.08 0.5/0.48 1/0.88',"
"colortemperature=temperature=6200,"
"eq=contrast=1.05:saturation=0.85:brightness=0.02,"
"noise=c0s=12:c0f=t+u,"
"unsharp=3:3:0.4"
),
},
"moody-dark": {
"desc": "Sombre, désaturé, contrastes écrasés, ambiance thriller",
"filter": (
"eq=brightness=-0.06:contrast=1.2:saturation=0.7,"
"colorlevels=rimin=0.05:rimax=0.92:gimin=0.05:gimax=0.92:bimin=0.05:bimax=0.92,"
"colorbalance=bs=0.05:bm=0.03,"
"unsharp=5:5:0.5"
),
},
"bright-clean": {
"desc": "Lumineux, net, couleurs vives — style YouTube/TikTok",
"filter": (
"eq=brightness=0.04:contrast=1.08:saturation=1.25,"
"vibrance=intensity=0.3,"
"unsharp=5:5:1.0,"
"colorlevels=rimin=0.01:rimax=0.99"
),
},
"sunset-golden": {
"desc": "Golden hour, tons orangés chauds",
"filter": (
"colortemperature=temperature=7500,"
"colorbalance=rh=0.1:gh=0.03:bh=-0.08:rs=0.05,"
"vibrance=intensity=0.2,"
"eq=contrast=1.08:saturation=1.15:brightness=0.02,"
"unsharp=5:5:0.6"
),
},
"bw-contrast": {
"desc": "Noir et blanc contrasté, dramatique",
"filter": (
"huesaturation=s=-1,"
"eq=contrast=1.3:brightness=-0.02,"
"curves=all='0/0 0.15/0.05 0.5/0.5 0.85/0.95 1/1',"
"unsharp=5:5:0.8"
),
},
"pastel-soft": {
"desc": "Tons pastels doux, noirs relevés, style editorial",
"filter": (
"colorlevels=rimin=0.08:gimin=0.08:bimin=0.08,"
"eq=saturation=0.75:contrast=0.95:brightness=0.03,"
"colortemperature=temperature=5800,"
"unsharp=3:3:0.3"
),
},
"none": {
"desc": "Aucun grading (pass-through)",
"filter": "null",
},
}
# ══════════════════════════════════════════════════
# SOCIAL MEDIA EXPORT FORMATS
# ══════════════════════════════════════════════════
SOCIAL_FORMATS = {
"tiktok": {"w": 1080, "h": 1920, "label": "TikTok / Reels / Story (9:16)"},
"instagram": {"w": 1080, "h": 1080, "label": "Instagram Post (1:1)"},
"insta-port": {"w": 1080, "h": 1350, "label": "Instagram Portrait (4:5)"},
"youtube": {"w": 1920, "h": 1080, "label": "YouTube (16:9)"},
"linkedin": {"w": 1920, "h": 1080, "label": "LinkedIn Video (16:9)"},
"twitter": {"w": 1280, "h": 720, "label": "Twitter/X Video (16:9)"},
"whatsapp": {"w": 1080, "h": 1920, "label": "WhatsApp Status (9:16)"},
}
# ══════════════════════════════════════════════════
# TRANSITION PRESETS (xfade)
# ══════════════════════════════════════════════════
TRANSITIONS = [
"fade", "fadeblack", "fadewhite", "dissolve",
"wipeleft", "wiperight", "wipeup", "wipedown",
"slideleft", "slideright", "slideup", "slidedown",
"smoothleft", "smoothright", "smoothup", "smoothdown",
"circlecrop", "circleclose", "circleopen",
"radial", "pixelize", "diagtl", "diagtr",
]
# ══════════════════════════════════════════════════
# CORE FUNCTIONS
# ══════════════════════════════════════════════════
def run_ffmpeg(cmd, desc=""):
"""Run an ffmpeg command and handle errors."""
if desc:
print(f" → {desc}")
full = ["ffmpeg", "-hide_banner", "-y"] + cmd
print(f" $ {' '.join(full)[:200]}...")
result = subprocess.run(full, capture_output=True, text=True)
if result.returncode != 0:
print(f" ERROR: {result.stderr[-500:]}")
return False
return True
def probe(filepath):
"""Get video info via ffprobe."""
cmd = [
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", str(filepath)
]
result = subprocess.run(cmd, capture_output=True, text=True)
return json.loads(result.stdout) if result.returncode == 0 else None
def get_duration(filepath):
"""Get duration in seconds."""
info = probe(filepath)
if info and "format" in info:
return float(info["format"].get("duration", 0))
return 0
# ══════════════════════════════════════════════════
# COMMANDS
# ══════════════════════════════════════════════════
def cmd_grade(args):
"""Apply color grading preset to a video."""
preset = GRADE_PRESETS.get(args.preset)
if not preset:
print(f"Unknown preset: {args.preset}")
print(f"Available: {', '.join(GRADE_PRESETS.keys())}")
return
inp = args.input
out = args.output or str(OUTPUT_DIR / f"{Path(inp).stem}-{args.preset}.mp4")
print(f"\n Color grading: {args.preset}")
print(f" {preset['desc']}\n")
cmd = ["-i", inp, "-vf", preset["filter"], "-c:a", "copy", out]
if run_ffmpeg(cmd, f"Applying {args.preset}"):
print(f"\n Output: {out}\n")
def cmd_concat(args):
"""Concatenate videos with optional transitions."""
files = args.files
out = args.output or str(OUTPUT_DIR / "concat-output.mp4")
transition = args.transition or "fadeblack"
duration = args.duration or 0.5
if len(files) < 2:
print("Need at least 2 files to concatenate.")
return
if args.transition:
# Use xfade transitions
print(f"\n Concatenating {len(files)} clips with '{transition}' transition ({duration}s)\n")
_concat_xfade(files, out, transition, duration)
else:
# Simple concat demuxer
print(f"\n Concatenating {len(files)} clips (direct)\n")
_concat_simple(files, out)
def _concat_simple(files, out):
"""Simple concatenation via concat demuxer."""
list_file = "/tmp/video_cli_concat.txt"
with open(list_file, "w") as f:
for fp in files:
f.write(f"file '{os.path.abspath(fp)}'\n")
cmd = ["-f", "concat", "-safe", "0", "-i", list_file, "-c", "copy", out]
if run_ffmpeg(cmd, "Concatenating"):
print(f"\n Output: {out}\n")
def _concat_xfade(files, out, transition, duration):
"""Concatenation with xfade transitions between clips."""
if len(files) == 2:
d0 = get_duration(files[0])
offset = d0 - duration
cmd = [
"-i", files[0], "-i", files[1],
"-filter_complex",
f"xfade=transition={transition}:duration={duration}:offset={offset}",
"-c:a", "copy", out,
]
if run_ffmpeg(cmd, f"Transition {transition}"):
print(f"\n Output: {out}\n")
else:
# Chain xfade for 3+ clips
inputs = []
for f in files:
inputs.extend(["-i", f])
# Build filter chain
durations = [get_duration(f) for f in files]
filter_parts = []
offset_acc = durations[0] - duration
# First pair
filter_parts.append(
f"[0:v][1:v]xfade=transition={transition}:duration={duration}:offset={offset_acc}[v01]"
)
for i in range(2, len(files)):
prev = f"v{str(i-2).zfill(2)}{str(i-1).zfill(2)}" if i == 2 else f"v{i-1}"
offset_acc += durations[i-1] - duration
curr = f"v{i}"
filter_parts.append(
f"[{prev}][{i}:v]xfade=transition={transition}:duration={duration}:offset={offset_acc}[{curr}]"
)
last_label = f"v{len(files)-1}"
filter_str = ";".join(filter_parts)
cmd = inputs + ["-filter_complex", filter_str, "-map", f"[{last_label}]", "-c:a", "copy", out]
if run_ffmpeg(cmd, f"Chaining {len(files)} clips with {transition}"):
print(f"\n Output: {out}\n")
def cmd_overlay_text(args):
"""Add text overlay to video."""
inp = args.input
out = args.output or str(OUTPUT_DIR / f"{Path(inp).stem}-text.mp4")
text = args.text.replace("'", "\\'")
font = args.font or "Inter"
size = args.size or 72
color = args.color or "white"
position = args.position or "center"
start = args.start or 0
end = args.end or 0
# Position mapping
pos_map = {
"center": "x=(w-text_w)/2:y=(h-text_h)/2",
"top": "x=(w-text_w)/2:y=h*0.08",
"bottom": "x=(w-text_w)/2:y=h*0.88",
"top-left": "x=w*0.05:y=h*0.05",
"top-right": "x=w*0.95-text_w:y=h*0.05",
"bottom-left": "x=w*0.05:y=h*0.92",
"bottom-right": "x=w*0.95-text_w:y=h*0.92",
}
pos = pos_map.get(position, pos_map["center"])
# Build drawtext filter
dt = f"drawtext=text='{text}':fontsize={size}:fontcolor={color}:{pos}"
dt += f":shadowcolor=black@0.5:shadowx=2:shadowy=2"
# Enable/disable timing
if end > 0:
dt += f":enable='between(t,{start},{end})'"
elif start > 0:
dt += f":enable='gte(t,{start})'"
# Fade in text
if args.fade:
dt += f":alpha='if(lt(t,{start}+0.5),(t-{start})/0.5,1)'"
print(f"\n Adding text: \"{args.text}\"")
print(f" Position: {position}, Size: {size}, Color: {color}\n")
cmd = ["-i", inp, "-vf", dt, "-c:a", "copy", out]
if run_ffmpeg(cmd, "Adding text overlay"):
print(f"\n Output: {out}\n")
def cmd_resize(args):
"""Resize/crop video for social media format."""
inp = args.input
fmt = SOCIAL_FORMATS.get(args.format)
if not fmt:
print(f"Unknown format: {args.format}")
print(f"Available: {', '.join(SOCIAL_FORMATS.keys())}")
return
out = args.output or str(OUTPUT_DIR / f"{Path(inp).stem}-{args.format}.mp4")
w, h = fmt["w"], fmt["h"]
print(f"\n Resizing for {fmt['label']} ({w}x{h})\n")
# Scale and crop to fit aspect ratio
vf = f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
cmd = ["-i", inp, "-vf", vf, "-c:a", "copy", out]
if run_ffmpeg(cmd, f"Resizing to {w}x{h}"):
print(f"\n Output: {out}\n")
def cmd_trim(args):
"""Trim a video segment."""
inp = args.input
out = args.output or str(OUTPUT_DIR / f"{Path(inp).stem}-trimmed.mp4")
cmd = ["-i", inp]
if args.start:
cmd.extend(["-ss", args.start])
if args.end:
cmd.extend(["-to", args.end])
elif args.duration:
cmd.extend(["-t", args.duration])
cmd.extend(["-c", "copy", out])
print(f"\n Trimming: {args.start or '0'} → {args.end or args.duration or 'end'}\n")
if run_ffmpeg(cmd, "Trimming"):
print(f"\n Output: {out}\n")
def cmd_stabilize(args):
"""2-pass video stabilization."""
inp = args.input
out = args.output or str(OUTPUT_DIR / f"{Path(inp).stem}-stabilized.mp4")
transforms = "/tmp/video_cli_transforms.trf"
print(f"\n Stabilizing video (2 passes)...\n")
# Pass 1: detect
if not run_ffmpeg(
["-i", inp, "-vf", f"vidstabdetect=result={transforms}:shakiness=8", "-f", "null", "-"],
"Pass 1: detecting motion"
):
return
# Pass 2: transform
smoothing = args.smoothing or 10
if run_ffmpeg(
["-i", inp, "-vf", f"vidstabtransform=input={transforms}:smoothing={smoothing}:zoom=1", "-c:a", "copy", out],
"Pass 2: stabilizing"
):
print(f"\n Output: {out}\n")
def cmd_montage(args):
"""Full montage pipeline: intro + clips + outro with grading and text."""
intro = args.intro
clips = args.clips
outro = args.outro
grade = args.grade or "cinematic-warm"
transition = args.transition or "fadeblack"
title = args.title
subtitle = args.subtitle
out = args.output or str(OUTPUT_DIR / "montage-final.mp4")
fmt = args.format or "tiktok"
print(f"\n ═══ MONTAGE PIPELINE ═══")
print(f" Intro: {intro or 'none'}")
print(f" Clips: {len(clips)} files")
print(f" Outro: {outro or 'none'}")
print(f" Grade: {grade}")
print(f" Transition: {transition}")
print(f" Format: {fmt}")
print(f" Title: {title or 'none'}")
print()
all_parts = []
temp_files = []
# Step 1: Grade each clip
preset = GRADE_PRESETS.get(grade, GRADE_PRESETS["none"])
for i, clip in enumerate(clips):
graded = f"/tmp/video_cli_graded_{i}.mp4"
temp_files.append(graded)
cmd = ["-i", clip, "-vf", preset["filter"], "-c:a", "copy", graded]
if not run_ffmpeg(cmd, f"Grading clip {i+1}/{len(clips)}"):
print(f"Failed to grade {clip}")
return
# Step 2: Build parts list
if intro:
all_parts.append(intro)
all_parts.extend(temp_files)
if outro:
all_parts.append(outro)
# Step 3: Concatenate with transitions
concat_out = f"/tmp/video_cli_concat_montage.mp4"
temp_files.append(concat_out)
if len(all_parts) == 1:
concat_out = all_parts[0]
elif transition != "none":
_concat_xfade(all_parts, concat_out, transition, 0.5)
else:
_concat_simple(all_parts, concat_out)
# Step 4: Resize for social format
social = SOCIAL_FORMATS.get(fmt)
resized_out = f"/tmp/video_cli_resized.mp4"
temp_files.append(resized_out)
if social:
w, h = social["w"], social["h"]
vf = f"scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h}"
run_ffmpeg(["-i", concat_out, "-vf", vf, "-c:a", "copy", resized_out],
f"Resizing to {fmt} ({w}x{h})")
else:
resized_out = concat_out
# Step 5: Add title text
if title:
titled_out = f"/tmp/video_cli_titled.mp4"
temp_files.append(titled_out)
dt = (
f"drawtext=text='{title}':fontsize=80:fontcolor=white:"
f"x=(w-text_w)/2:y=(h-text_h)/2-50:"
f"shadowcolor=black@0.6:shadowx=3:shadowy=3:"
f"enable='between(t,0.5,4)'"
)
if subtitle:
dt += (
f",drawtext=text='{subtitle}':fontsize=36:fontcolor=white@0.8:"
f"x=(w-text_w)/2:y=(h-text_h)/2+50:"
f"shadowcolor=black@0.5:shadowx=2:shadowy=2:"
f"enable='between(t,1,4)'"
)
run_ffmpeg(["-i", resized_out, "-vf", dt, "-c:a", "copy", titled_out],
"Adding title")
resized_out = titled_out
# Step 6: Final output
if resized_out != out:
run_ffmpeg(["-i", resized_out, "-c", "copy", out], "Finalizing")
# Cleanup
for tf in temp_files:
if os.path.exists(tf):
os.remove(tf)
print(f"\n ═══ MONTAGE COMPLETE ═══")
print(f" Output: {out}\n")
def cmd_info(args):
"""Show video file information."""
info = probe(args.input)
if not info:
print(f"Cannot read: {args.input}")
return
fmt = info.get("format", {})
streams = info.get("streams", [])
print(f"\n ═══ VIDEO INFO ═══")
print(f" File: {args.input}")
print(f" Duration: {float(fmt.get('duration', 0)):.1f}s")
print(f" Size: {int(fmt.get('size', 0)) / 1024 / 1024:.1f} MB")
print(f" Bitrate: {int(fmt.get('bit_rate', 0)) / 1000:.0f} kbps")
for s in streams:
if s["codec_type"] == "video":
print(f" Video: {s.get('width')}x{s.get('height')} {s.get('codec_name')} @ {s.get('r_frame_rate')} fps")
elif s["codec_type"] == "audio":
print(f" Audio: {s.get('codec_name')} {s.get('sample_rate')}Hz {s.get('channels')}ch")
print()
def _cmd_highlights(args):
"""Delegate to highlights module."""
from highlights import cmd_highlights
cmd_highlights(args)
def cmd_presets(args):
"""List available presets."""
print("\n ═══ COLOR GRADING PRESETS ═══\n")
for name, p in GRADE_PRESETS.items():
print(f" {name:<25} {p['desc']}")
print("\n ═══ SOCIAL MEDIA FORMATS ═══\n")
for name, f in SOCIAL_FORMATS.items():
print(f" {name:<15} {f['label']} ({f['w']}x{f['h']})")
print("\n ═══ TRANSITIONS ═══\n")
for i in range(0, len(TRANSITIONS), 6):
print(f" {', '.join(TRANSITIONS[i:i+6])}")
print()
# ══════════════════════════════════════════════════
# CLI
# ══════════════════════════════════════════════════
def main():
parser = argparse.ArgumentParser(
description="Video CLI — FFmpeg-powered video editing for Claude Code",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
sub = parser.add_subparsers(dest="command")
# grade
p = sub.add_parser("grade", help="Apply color grading preset")
p.add_argument("-i", "--input", required=True)
p.add_argument("-p", "--preset", required=True)
p.add_argument("-o", "--output")
# concat
p = sub.add_parser("concat", help="Concatenate videos with transitions")
p.add_argument("files", nargs="+")
p.add_argument("-t", "--transition", help=f"Transition type ({', '.join(TRANSITIONS[:5])}...)")
p.add_argument("-d", "--duration", type=float, default=0.5, help="Transition duration (sec)")
p.add_argument("-o", "--output")
# text
p = sub.add_parser("text", help="Add text overlay")
p.add_argument("-i", "--input", required=True)
p.add_argument("--text", required=True)
p.add_argument("--font", default="Inter")
p.add_argument("--size", type=int, default=72)
p.add_argument("--color", default="white")
p.add_argument("--position", default="center", choices=["center","top","bottom","top-left","top-right","bottom-left","bottom-right"])
p.add_argument("--start", type=float, default=0)
p.add_argument("--end", type=float, default=0)
p.add_argument("--fade", action="store_true")
p.add_argument("-o", "--output")
# resize
p = sub.add_parser("resize", help="Resize for social media")
p.add_argument("-i", "--input", required=True)
p.add_argument("-f", "--format", required=True, choices=list(SOCIAL_FORMATS.keys()))
p.add_argument("-o", "--output")
# trim
p = sub.add_parser("trim", help="Trim video segment")
p.add_argument("-i", "--input", required=True)
p.add_argument("-s", "--start")
p.add_argument("-e", "--end")
p.add_argument("-d", "--duration")
p.add_argument("-o", "--output")
# stabilize
p = sub.add_parser("stabilize", help="2-pass video stabilization")
p.add_argument("-i", "--input", required=True)
p.add_argument("--smoothing", type=int, default=10)
p.add_argument("-o", "--output")
# montage
p = sub.add_parser("montage", help="Full montage pipeline")
p.add_argument("--intro", help="Intro video file")
p.add_argument("--clips", nargs="+", required=True, help="Main content clips")
p.add_argument("--outro", help="Outro video file")
p.add_argument("-g", "--grade", default="cinematic-warm", help="Color grading preset")
p.add_argument("-t", "--transition", default="fadeblack")
p.add_argument("-f", "--format", default="tiktok")
p.add_argument("--title", help="Title text overlay")
p.add_argument("--subtitle", help="Subtitle text overlay")
p.add_argument("-o", "--output")
# info
p = sub.add_parser("info", help="Show video info")
p.add_argument("input")
# highlights
p = sub.add_parser("highlights", help="Extract best scenes (smart highlight reel)")
p.add_argument("-i", "--input", required=True)
p.add_argument("-d", "--domain", default="general",
choices=["immobilier", "business", "food", "sport", "general"])
p.add_argument("--top", type=int, default=5, help="Number of top scenes")
p.add_argument("--mode", default="highlights", choices=["highlights", "highlights+full"])
p.add_argument("--no-ai", action="store_true", help="Signal-only (no transcript/LLM)")
p.add_argument("--threshold", type=float, default=27.0)
p.add_argument("-o", "--output")
# music
p = sub.add_parser("music", help="Generate background music via ElevenLabs AI")
p.add_argument("-s", "--style", choices=["jazz", "classical", "ambient", "upbeat", "cinematic", "lofi"],
help="Music style preset")
p.add_argument("-p", "--prompt", help="Custom music description")
p.add_argument("-d", "--duration", type=int, default=30, help="Duration in seconds (max 30 per chunk)")
p.add_argument("-o", "--output")
# presets
sub.add_parser("presets", help="List all presets, formats, transitions")
args = parser.parse_args()
commands = {
"grade": cmd_grade,
"concat": cmd_concat,
"text": cmd_overlay_text,
"resize": cmd_resize,
"trim": cmd_trim,
"stabilize": cmd_stabilize,
"montage": cmd_montage,
"info": cmd_info,
"highlights": _cmd_highlights,
"music": cmd_music,
"presets": cmd_presets,
}
if args.command in commands:
commands[args.command](args)
else:
parser.print_help()
if __name__ == "__main__":
main()
# ══════════════════════════════════════════════════
# AI MUSIC GENERATION (ElevenLabs)
# ══════════════════════════════════════════════════
def cmd_music(args):
"""Generate background music via ElevenLabs AI."""
api_key = os.environ.get("ELEVENLABS_API_KEY")
if not api_key:
print("Set ELEVENLABS_API_KEY env var. Get one at https://elevenlabs.io")
sys.exit(1)
prompt = args.prompt or "smooth jazz lounge, soft piano and bass, elegant luxury atmosphere, no vocals"
duration = args.duration or 30
out = args.output or str(OUTPUT_DIR / f"music-{args.style or 'custom'}.mp3")
STYLE_PROMPTS = {
"jazz": "smooth jazz lounge, soft piano chords and gentle upright bass, elegant luxury atmosphere, warm and inviting, no drums, calm",
"classical": "soft classical strings, gentle violin and cello, elegant and refined atmosphere, warm, no percussion",
"ambient": "ambient electronic pad, soft warm textures, floating atmosphere, minimal and elegant, no beats",
"upbeat": "upbeat positive acoustic guitar and light percussion, energetic and modern, corporate feel, no vocals",
"cinematic": "cinematic orchestral, soft strings and piano, emotional and inspiring, film score style, no vocals",
"lofi": "lo-fi hip hop beats, soft piano keys, vinyl crackle, relaxed chill study atmosphere, no vocals",
}
if args.style and args.style in STYLE_PROMPTS:
prompt = STYLE_PROMPTS[args.style]
print(f"\n Generating music via ElevenLabs...")
print(f" Style: {args.style or 'custom'}")
print(f" Prompt: {prompt[:80]}...")
print(f" Duration: {duration}s")
# ElevenLabs max 30s per call — generate parts if needed
parts = []
remaining = duration
part_num = 0
while remaining > 0:
chunk = min(30, remaining)
part_num += 1
part_path = f"/tmp/music_part_{part_num}.mp3"
p = prompt if part_num == 1 else f"{prompt}, continuation"
result = subprocess.run([
"curl", "-s", "https://api.elevenlabs.io/v1/sound-generation",
"-X", "POST",
"-H", f"xi-api-key: {api_key}",
"-H", "Content-Type: application/json",
"-d", json.dumps({"text": p, "duration_seconds": chunk}),
"--output", part_path,
], capture_output=True, text=True)
# Verify it's audio
check = subprocess.run(["file", part_path], capture_output=True, text=True)
if "Audio" not in check.stdout and "MPEG" not in check.stdout:
print(f" ERROR: Generation failed for part {part_num}")
with open(part_path) as f:
print(f" {f.read()[:200]}")
return
parts.append(part_path)
remaining -= chunk
print(f" Part {part_num}: {chunk}s ✓")
# Concat parts with crossfade
if len(parts) == 1:
subprocess.run(["cp", parts[0], out])
else:
inputs = []
for p in parts:
inputs.extend(["-i", p])
# Simple concat with crossfade
filter_parts = []
for i in range(len(parts)):
if i == 0:
filter_parts.append(f"[{i}:a]afade=t=out:st={min(30, duration) - 2}:d=2[a{i}]")
elif i == len(parts) - 1:
filter_parts.append(f"[{i}:a]afade=t=in:st=0:d=2[a{i}]")
else:
filter_parts.append(f"[{i}:a]afade=t=in:st=0:d=1,afade=t=out:st={min(30, duration) - 1}:d=1[a{i}]")
concat_labels = "".join(f"[a{i}]" for i in range(len(parts)))
filter_parts.append(f"{concat_labels}concat=n={len(parts)}:v=0:a=1")
subprocess.run(
["ffmpeg", "-hide_banner", "-y"] + inputs +
["-filter_complex", ";".join(filter_parts), "-c:a", "aac", "-b:a", "192k", out],
capture_output=True
)
# Cleanup
for p in parts:
if os.path.exists(p):
os.remove(p)
print(f"\n ✅ Music generated: {out}\n")