-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1932 lines (1629 loc) · 72.7 KB
/
Copy pathserver.py
File metadata and controls
1932 lines (1629 loc) · 72.7 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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
conv-edit v2: AI-assisted video clip annotation workbench
Auto scene detection → smart auto-annotation → one-click pipeline
"""
import json
import subprocess
import tempfile
import hashlib
import base64
import re
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Optional
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
# Import our own modules
import sys
sys.path.insert(0, str(Path(__file__).parent))
from planner import CutPlanner, load_clips_from_json, load_music_timeline
from planner.validator import validate, auto_fix
from audio.analyzer import AudioAnalyzer
from overlay import OverlayDef, build_clip_vf, overlays_from_dict, overlays_to_dict
# ─── Logging ──────────────────────────────────────
import logging
LOG_DIR = Path.home() / ".conv-edit"
LOG_DIR.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%m-%d %H:%M:%S",
handlers=[
logging.FileHandler(LOG_DIR / "server.log", encoding="utf-8"),
logging.StreamHandler(),
],
)
log = logging.getLogger("conv-edit")
log.info("=== conv-edit server starting ===")
app = FastAPI(title="conv-edit")
SESSIONS: dict[str, dict] = {}
BGM_SESSIONS: dict[str, dict] = {}
OUTPUT_DIR = Path(__file__).parent / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)
STATIC_DIR = Path(__file__).parent / "static"
STATIC_DIR.mkdir(exist_ok=True)
RENDER_DIR = Path(__file__).parent / "renders"
RENDER_DIR.mkdir(exist_ok=True)
# ─── Data model ────────────────────────────────────────
@dataclass
class Scene:
index: int
start_sec: float
end_sec: float
duration_sec: float
thumbnail_b64: str = ""
selected: bool = True
trim_start: float = 0.0
trim_end: float = 0.0
# Auto-detected (user can override)
intensity: float = 0.5
intensity_auto: bool = True # True = auto, False = user-set
audio_mode: str = "融入BGM"
audio_mode_auto: bool = True
tags: list[str] = None
description: str = ""
protect_end: bool = False
def __post_init__(self):
if self.tags is None:
self.tags = []
if self.trim_end == 0.0:
self.trim_end = self.duration_sec
@property
def effective_start(self) -> float:
return self.start_sec + self.trim_start
@property
def effective_end(self) -> float:
return self.start_sec + self.trim_end
@property
def effective_duration(self) -> float:
return max(0.1, self.effective_end - self.effective_start)
# ═══════════════════════════════════════════════════════
# Auto-detection engines
# ═══════════════════════════════════════════════════════
def auto_detect_attributes(video_path: str, scenes: list[Scene]) -> None:
"""Run all auto-detection on scenes. Mutates scenes in-place."""
for s in scenes:
mid = s.start_sec + s.duration_sec / 2
# 1. Intensity from audio RMS
rms_db = _measure_rms(video_path, s.start_sec, s.duration_sec)
s.intensity = _rms_to_intensity(rms_db)
s.intensity_auto = True
# 2. Audio mode from silence analysis
s.audio_mode = _detect_audio_mode(video_path, s.start_sec, s.duration_sec)
s.audio_mode_auto = True
# 3. Auto-tags
s.tags = _suggest_tags(s)
# 4. Auto protect_end for short high-intensity clips
if s.duration_sec < 3.0 and s.intensity > 0.75:
s.protect_end = True
def _measure_rms(video_path: str, start: float, duration: float) -> float:
"""Measure RMS audio level in dB. Returns e.g. -15.0."""
try:
r = subprocess.run(
["ffmpeg", "-ss", str(start), "-t", str(min(duration, 10)),
"-i", video_path,
"-af", "volumedetect", "-vn", "-sn",
"-f", "null", "/dev/null"],
capture_output=True, text=True, timeout=20
)
m = re.search(r"mean_volume:\s*([-\d.]+)\s*dB", r.stderr)
if m:
return float(m.group(1))
except Exception:
pass
return -70.0 # effectively silent
def _rms_to_intensity(rms_db: float) -> float:
"""Map RMS dB to 0-1 intensity. -10dB=0.9, -25dB=0.5, -40dB=0.1."""
return round(max(0.0, min(1.0, (rms_db + 50) / 40)), 2)
def _detect_audio_mode(video_path: str, start: float, duration: float) -> str:
"""Classify audio mode based on silence detection."""
try:
r = subprocess.run(
["ffmpeg", "-ss", str(start), "-t", str(min(duration, 10)),
"-i", video_path,
"-af", "silencedetect=n=-30dB:d=0.5",
"-vn", "-sn",
"-f", "null", "/dev/null"],
capture_output=True, text=True, timeout=20
)
# Count silence segments
silences = re.findall(r"silence_start:\s*([\d.]+)", r.stderr)
silence_ends = re.findall(r"silence_end:\s*([\d.]+)", r.stderr)
total_silence = 0.0
for i in range(min(len(silences), len(silence_ends))):
total_silence += float(silence_ends[i]) - float(silences[i])
if duration <= 0:
return "融入BGM"
silence_ratio = total_silence / duration
# Near total silence → 纯BGM (source audio is just ambiance)
if silence_ratio > 0.8:
return "纯BGM"
# Lots of short non-silence bursts → likely speech
non_silence_count = len(silences) - 1
if non_silence_count >= 3 and silence_ratio < 0.5:
return "突出人声"
return "融入BGM"
except Exception:
return "融入BGM"
def _suggest_tags(s: Scene) -> list[str]:
"""Suggest tags based on clip characteristics."""
tags = []
if s.duration_sec < 2.0 and s.intensity > 0.7:
tags.append("快节奏")
if s.duration_sec > 6.0 and s.intensity < 0.4:
tags.append("过渡")
if s.intensity > 0.8:
tags.append("高能")
elif s.intensity < 0.3:
tags.append("平静")
return tags
# ═══════════════════════════════════════════════════════
# FFmpeg helpers
# ═══════════════════════════════════════════════════════
def _merge_high_energy_fragments(video_path: str, scene_times: list[float], duration: float) -> list[float]:
"""方案一:如果两个切点间隔 < 2.5s 且该区间音频响度极高(激战),
强制删除中间切点,把碎片合并为完整的战斗段落。"""
if len(scene_times) <= 2:
return scene_times
# 提取音频 RMS 强度(采样间隔 ~1s)
try:
cmd = [
"ffmpeg", "-i", video_path,
"-af", "aresample=1000,asetnsamples=1000,astats=metadata=1:reset=1",
"-vn", "-sn", "-f", "null", "-"
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
rms_db = []
for line in result.stderr.split('\n'):
m = re.search(r'RMS level dB: ([-\\d.]+)', line)
if m:
rms_db.append(float(m.group(1)))
except Exception:
return scene_times # 失败则跳过保护
if len(rms_db) < 10:
return scene_times
# dB → 0-1 强度
intensities = [max(0.0, min(1.0, (v + 50) / 40)) for v in rms_db]
sample_dur = duration / len(intensities)
def _intensity_at(t: float) -> float:
idx = min(int(t / sample_dur), len(intensities) - 1)
return intensities[idx]
MIN_GAP = 2.5 # 小于此间隔的碎片候选合并
HIGH_ENERGY = 0.6 # 强度阈值,超过视为激战
merged = [scene_times[0]]
skipped = 0
for i in range(1, len(scene_times) - 1):
gap = scene_times[i] - scene_times[i - 1]
mid = (scene_times[i - 1] + scene_times[i]) / 2
energy = _intensity_at(mid)
if gap < MIN_GAP and energy > HIGH_ENERGY:
# 激战中的碎切点 → 跳过,合并到前后
skipped += 1
continue
merged.append(scene_times[i])
merged.append(scene_times[-1])
if skipped:
print(f"[高能保护] 合并了 {skipped} 个碎切点,保留高光片段完整")
return merged
def _detect_bpm(bgm_path: str) -> float:
"""从 BGM 文件检测 BPM,使用 ffmpeg astats 瞬态分析。"""
try:
cmd = ["ffmpeg", "-i", bgm_path,
"-af", "astats=metadata=1:reset=1",
"-f", "null", "-"]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
rms_vals = []
for line in result.stderr.split('\n'):
m = re.search(r'RMS level dB: ([-\\d.]+)', line)
if m:
rms_vals.append(float(m.group(1)))
if len(rms_vals) < 10:
return 0
# 瞬态峰值密度 → 估算 BPM
peaks = sum(1 for v in rms_vals if v > -15)
bpm = (peaks / len(rms_vals)) * 60 * 2
return max(60, min(180, bpm))
except Exception:
return 0
def detect_scenes_ffmpeg(video_path: str, threshold: float = 0.3) -> list[Scene]:
"""Use ffmpeg's scene detection filter to find cut points.
Retries with lower thresholds before falling back to intensity-based splitting."""
def _run_scdet(thresh: float) -> list[float]:
cmd = [
"ffmpeg", "-i", video_path,
"-vf", f"select='gt(scene\\\\,{thresh})',showinfo",
"-vsync", "vfr",
"-f", "null", "-"
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
timestamps = [0.0]
for line in result.stderr.split('\n'):
m = re.search(r'pts_time:([\d.]+)', line)
if m:
t = float(m.group(1))
if t > timestamps[-1] + 0.5:
timestamps.append(t)
return timestamps
duration = get_video_duration(video_path)
# ─── 方案二:高阈值策略(游戏内容不需要细切) ───
# 阈值越高越不敏感,只识别真正的场景切换(如地图切换),忽略枪火/跑动
for thresh in [threshold, 0.4, 0.35]:
timestamps = _run_scdet(thresh)
if timestamps[-1] < duration - 0.5:
timestamps.append(duration)
if len(timestamps) >= 3:
break
# ─── 方案一:高能片段保护合并(防止击杀镜头被切碎) ───
timestamps = _merge_high_energy_fragments(video_path, timestamps, duration)
# If scdet found nothing useful (0 or 1 cuts), skip to intensity-based
if len(timestamps) <= 2:
return _intensity_split(video_path, duration)
MIN_SCENE = 1.5
MAX_SCENE = 8.0
scenes = []
for i in range(len(timestamps) - 1):
start = timestamps[i]
end = timestamps[i + 1]
dur = end - start
# Merge very short scenes into neighbors
if dur < MIN_SCENE:
if scenes:
scenes[-1].end_sec = end
scenes[-1].duration_sec = scenes[-1].end_sec - scenes[-1].start_sec
continue
# Split overly long scenes
if dur > MAX_SCENE:
sub_n = int(dur / MAX_SCENE) + 1
sub_dur = dur / sub_n
for j in range(sub_n):
sub_start = start + j * sub_dur
sub_end = min(start + (j + 1) * sub_dur, end)
if sub_end - sub_start >= MIN_SCENE:
scenes.append(Scene(
index=len(scenes),
start_sec=sub_start,
end_sec=sub_end,
duration_sec=sub_end - sub_start
))
else:
scenes.append(Scene(
index=len(scenes),
start_sec=start,
end_sec=end,
duration_sec=dur
))
# Fallback: intensity-based splitting using audio energy
if len(scenes) < 3:
scenes = _intensity_split(video_path, duration)
return scenes
def _intensity_split(video_path: str, duration: float) -> list[Scene]:
"""Split video by audio intensity peaks instead of fixed time chunks."""
try:
cmd = [
"ffmpeg", "-i", video_path,
"-af", "aresample=1000,asetnsamples=1000,astats=metadata=1:reset=1",
"-vn", "-sn",
"-f", "null", "-"
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
rms_values = []
for line in result.stderr.split('\n'):
m = re.search(r'RMS level dB: ([-\d.]+)', line)
if m:
rms_values.append(float(m.group(1)))
except Exception:
rms_values = []
if len(rms_values) < 10:
# Ultimate fallback: moderate chunking (not 5s, vary by 3-7s)
return _adaptive_chunk(duration)
# Convert dB to 0-1 intensity, find peaks
intensities = [max(0.0, min(1.0, (v + 50) / 40)) for v in rms_values]
sample_dur = duration / len(intensities)
# Find local minima as split points
splits = [0.0]
window = max(3, len(intensities) // 20) # ~5% of video as window
for i in range(window, len(intensities) - window):
# Local minimum in a window, lower threshold for more splits
neighborhood = intensities[i-window:i+window+1]
if intensities[i] == min(neighborhood) and intensities[i] < 0.5:
t = (i + 0.5) * sample_dur
if t - splits[-1] >= 1.5: # Minimum 1.5s between splits
splits.append(t)
splits.append(duration)
scenes = []
MIN_SCENE = 1.5
for i in range(len(splits) - 1):
start = splits[i]
end = splits[i + 1]
dur = end - start
if dur >= MIN_SCENE or len(scenes) == 0:
scenes.append(Scene(
index=len(scenes),
start_sec=start,
end_sec=end,
duration_sec=dur
))
else:
scenes[-1].end_sec = end
scenes[-1].duration_sec = scenes[-1].end_sec - scenes[-1].start_sec
return scenes
def _adaptive_chunk(duration: float) -> list[Scene]:
"""Adaptive chunking: shorter chunks for short videos, longer for long ones."""
if duration <= 30:
chunk = 3.0
elif duration <= 120:
chunk = 5.0
else:
chunk = 8.0
scenes = []
t = 0.0
idx = 0
while t < duration:
end = min(t + chunk, duration)
# Vary chunk size slightly to avoid uniform splits
if idx > 0 and end < duration:
import random
end = min(end + random.uniform(-1.5, 1.5), duration)
if end - t >= 1.5:
scenes.append(Scene(index=idx, start_sec=t, end_sec=end, duration_sec=end - t))
t = end
idx += 1
else:
t = end
return scenes
def get_video_duration(video_path: str) -> float:
cmd = [
"ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of", "default=noprint_wrappers=1:nokey=1",
video_path
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
try:
return float(result.stdout.strip())
except (ValueError, TypeError):
return 0.0
def generate_thumbnail(video_path: str, time_sec: float, width: int = 320) -> str:
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as f:
thumb_path = f.name
cmd = [
"ffmpeg", "-y", "-ss", str(time_sec), "-i", video_path,
"-vframes", "1", "-vf", f"scale={width}:-1",
"-q:v", "5", thumb_path
]
subprocess.run(cmd, capture_output=True, timeout=15)
with open(thumb_path, 'rb') as f:
data = base64.b64encode(f.read()).decode()
Path(thumb_path).unlink(missing_ok=True)
return f"data:image/jpeg;base64,{data}"
# ═══════════════════════════════════════════════════════
# API Routes
# ═══════════════════════════════════════════════════════
@app.post("/api/analyze")
async def analyze_video(file: UploadFile = File(...), threshold: float = Form(0.3)):
"""Upload video, detect scenes, auto-annotate, return results."""
ext = Path(file.filename).suffix or ".mp4"
session_id = hashlib.md5(file.filename.encode()).hexdigest()[:12]
video_path = OUTPUT_DIR / f"{session_id}{ext}"
content = await file.read()
video_path.write_bytes(content)
try:
scenes = detect_scenes_ffmpeg(str(video_path), threshold)
if len(scenes) > 200:
scenes = scenes[:200]
except Exception as e:
video_path.unlink(missing_ok=True)
raise HTTPException(500, f"Scene detection failed: {e}")
# ── Auto-detection ──────────────────────────
auto_detect_attributes(str(video_path), scenes)
# ── Thumbnails ──────────────────────────────
for s in scenes:
mid = s.start_sec + s.duration_sec / 2
try:
s.thumbnail_b64 = generate_thumbnail(str(video_path), mid)
except Exception:
s.thumbnail_b64 = ""
SESSIONS[session_id] = {
"video_path": str(video_path),
"scenes": [asdict(s) for s in scenes],
"filename": file.filename
}
return {
"session_id": session_id,
"filename": file.filename,
"duration": get_video_duration(str(video_path)),
"scene_count": len(scenes),
"scenes": [asdict(s) for s in scenes]
}
@app.post("/api/analyze-bgm")
async def analyze_bgm(file: UploadFile = File(...)):
"""Upload BGM, auto-analyze, return waveform + beats for visualization."""
bgm_id = hashlib.md5(file.filename.encode()).hexdigest()[:12]
bgm_path = OUTPUT_DIR / f"bgm_{bgm_id}{Path(file.filename).suffix or '.mp3'}"
content = await file.read()
bgm_path.write_bytes(content)
try:
analyzer = AudioAnalyzer()
timeline = analyzer.analyze(str(bgm_path))
result = timeline.to_dict()
result["bgm_id"] = bgm_id
result["bgm_path"] = str(bgm_path)
result["filename"] = file.filename
# Downsample energy curve for frontend waveform (max 200 points)
curve = result.get("energy_curve", [])
if len(curve) > 200:
step = len(curve) // 200
result["energy_curve"] = [curve[i] for i in range(0, len(curve), step)]
BGM_SESSIONS[bgm_id] = result
return result
except Exception as e:
bgm_path.unlink(missing_ok=True)
raise HTTPException(500, f"BGM analysis failed: {e}")
@app.post("/api/plan")
async def plan_timeline(data: dict):
"""Generate render timeline from clips + BGM selection."""
session_id = data.get("session_id")
bgm_id = data.get("bgm_id")
strategy = data.get("strategy", "fit")
seed = data.get("seed", 42)
offset = data.get("offset", 0.0)
auto_offset = data.get("auto_offset", True)
scale_mode = data.get("scale_mode", "letterbox")
preset_name = data.get("preset_name", "")
arc = data.get("arc", None)
if not arc and preset_name and preset_name in EDITING_PRESETS:
arc = EDITING_PRESETS[preset_name].get("arc", None)
if session_id not in SESSIONS:
raise HTTPException(404, "Video session not found")
if bgm_id not in BGM_SESSIONS:
raise HTTPException(404, "BGM session not found")
session = SESSIONS[session_id]
bgm = BGM_SESSIONS[bgm_id]
# Build clips from session scenes
video_path = session["video_path"]
clips = []
for s in session["scenes"]:
if not s.get("selected", True):
continue
from planner import ClipInfo
start = s["start_sec"] + s.get("trim_start", 0)
end = s["start_sec"] + s.get("trim_end", s["duration_sec"])
clips.append(ClipInfo(
clip_id=f"{session_id}_{s['index']:03d}",
source_path=video_path,
start_sec=start,
end_sec=end,
duration_sec=max(0.1, end - start),
tags=s.get("tags", []),
intensity=s.get("intensity", 0.5),
audio_mode=s.get("audio_mode", "融入BGM"),
description=s.get("description", ""),
protect_end=s.get("protect_end", False),
))
if not clips:
raise HTTPException(400, "No clips selected")
# Build music timeline from BGM analysis
music_timeline = {
"bpm": bgm.get("bpm", 120),
"duration_sec": bgm.get("duration_sec", 60),
"beats_sec": bgm.get("beats_sec", []),
"downbeats_sec": bgm.get("downbeats_sec", []),
"segments": bgm.get("segments", []),
"suggested_intro_offset": bgm.get("suggested_intro_offset", 0.0),
}
# Run planner
planner = CutPlanner(seed=seed)
timeline = planner.plan(
clips, music_timeline, bgm["bgm_path"],
duration_strategy=strategy,
bgm_start_offset=offset,
auto_offset=auto_offset,
scale_mode=scale_mode,
arc=arc,
)
plan_dict = timeline.to_dict()
# Run validator inline
issues = validate(plan_dict)
errors = [i for i in issues if i.severity == "ERROR"]
warnings = [i for i in issues if i.severity == "WARN"]
# If gaps are too large and strategy was 'fit', retry with 'loop'
gap_errors = [i for i in errors if "Gap" in i.message and "too large" in i.message]
if gap_errors and strategy == "fit":
try:
timeline2 = planner.plan(
clips, music_timeline, bgm["bgm_path"],
duration_strategy="loop",
bgm_start_offset=offset,
auto_offset=auto_offset,
scale_mode=scale_mode,
)
plan_dict = timeline2.to_dict()
issues = validate(plan_dict)
errors = [i for i in issues if i.severity == "ERROR"]
warnings = [i for i in issues if i.severity == "WARN"]
except Exception:
pass
# Auto-fix if there are warnings but no errors
if warnings and not errors:
try:
plan_dict = auto_fix(plan_dict)
issues = validate(plan_dict)
errors = [i for i in issues if i.severity == "ERROR"]
warnings = [i for i in issues if i.severity == "WARN"]
except Exception:
pass
# Build intensity heatmap for frontend
heatmap = []
for seg in plan_dict.get("segments", []):
heatmap.append({
"start": seg["timeline_start"],
"end": seg["timeline_end"],
"intensity": seg.get("intensity", 0.5),
"audio_mode": seg.get("audio_mode", "融入BGM"),
"clip_id": seg["clip_id"],
})
return {
"plan": plan_dict,
"heatmap": heatmap,
"errors": [{"msg": i.message, "seg": i.segment_index, "fix": i.fix} for i in errors],
"warnings": [{"msg": i.message, "seg": i.segment_index, "fix": i.fix} for i in warnings],
"ready": len(errors) == 0,
}
@app.post("/api/render")
async def render_video(data: dict):
"""Render final video from a plan."""
plan = data.get("plan")
if not plan:
raise HTTPException(400, "No plan provided")
render_id = hashlib.md5(json.dumps(plan).encode()).hexdigest()[:12]
output_path = RENDER_DIR / f"render_{render_id}.mp4"
# Save plan for reference
plan_path = RENDER_DIR / f"render_{render_id}.json"
plan_path.write_text(json.dumps(plan, indent=2), encoding='utf-8')
segs = plan.get("segments", [])
if not segs:
raise HTTPException(400, "No segments in plan")
# ─── Parse overlays ───
raw_overlays = plan.get("overlays", [])
overlays: list[OverlayDef] = overlays_from_dict(raw_overlays) if raw_overlays else []
log.info(f"render -> {len(overlays)} overlay(s) loaded")
bgm = plan.get("bgm_path", "")
offset = plan.get("bgm_start_offset_sec", 0.0)
fps = plan.get("output_fps", 30)
width, height = 1920, 1080
if plan.get("output_resolution"):
w, h = plan["output_resolution"].split("x")
width, height = int(w), int(h)
scale_mode = plan.get("scale_mode", "letterbox")
# Build filter complex for concatenation
filter_parts = []
audio_parts = []
# Deduplicate source files → map each to a unique input index
unique_sources = []
source_to_idx = {}
for s in segs:
sp = s["source_path"]
if sp not in source_to_idx:
source_to_idx[sp] = len(unique_sources)
unique_sources.append(sp)
# Two-phase approach for reliable rendering:
# Phase 1: cut individual clips (fast, -c copy where possible)
# Phase 2: concat via demuxer + mix BGM
# ─── Beat-sync: snap clip start times to BGM beats ───
if plan.get("beat_sync", True) and bgm:
bpm = _detect_bpm(bgm)
if bpm > 0:
beat_interval = 60.0 / bpm
offset = plan.get("bgm_start_offset_sec", 0.0)
# Snap each segment's timeline_start to nearest beat
cursor = offset
for s in segs:
# Snap start to beat, but keep source_duration intact
snapped_start = round(cursor / beat_interval) * beat_interval
dur = s.get("timeline_end", 0) - s.get("timeline_start", 0)
s["timeline_start"] = snapped_start
s["timeline_end"] = snapped_start + dur
cursor = snapped_start + dur
# Update total duration
last_end = max(s["timeline_end"] for s in segs) if segs else 0
plan["total_duration_sec"] = last_end
print(f"[节拍同步] BPM={bpm:.0f} 节拍间隔={beat_interval:.2f}s 总长={last_end:.1f}s")
# Build scale filter once
if scale_mode == "letterbox":
scale_filter = f"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black"
elif scale_mode == "crop":
scale_filter = f"scale={width}:{height}:force_original_aspect_ratio=increase,crop={width}:{height}"
else:
scale_filter = f"scale={width}:{height}"
import tempfile, shutil
tmp_dir = Path(tempfile.mkdtemp(dir=RENDER_DIR, prefix="tmp_"))
clip_files = []
clip_list = tmp_dir / "concat_list.txt"
lines = []
try:
for i, s in enumerate(segs):
src = s["source_path"]
src_start = s["source_start"]
src_dur = s["source_duration"]
speed = s.get("playback_speed", 1.0)
src_vol = s.get("source_audio_volume", 1.0)
clip_out = tmp_dir / f"clip_{i:03d}.mp4"
# Cut clip with video scaling + audio (preserves sync)
# Vocal reduction: notch out 200-500Hz and 800-1500Hz (voice range),
# keep bass (footsteps) and highs (gunshots/explosions) intact
vocal_reduce = plan.get("vocal_reduction", True)
base_vf = f"{scale_filter},fps={fps},format=yuv420p"
if vocal_reduce:
af = f"bandreject=f=300:w=300:width_type=h,bandreject=f=1200:w=600:width_type=h,volume={src_vol}"
else:
af = f"volume={src_vol}"
if abs(speed - 1.0) > 0.001:
base_vf = f"setpts={speed}*PTS,{scale_filter},fps={fps},format=yuv420p"
if vocal_reduce:
af = f"bandreject=f=300:w=300:width_type=h,bandreject=f=1200:w=600:width_type=h,atempo={1/speed},volume={src_vol}"
else:
af = f"atempo={1/speed},volume={src_vol}"
# ─── Apply overlays ───
clip_global_start = s.get("timeline_start", 0.0)
vf = build_clip_vf(base_vf, overlays, clip_global_start, src_dur)
subprocess.run(["ffmpeg", "-y", "-vsync", "cfr",
"-i", src, "-ss", str(src_start), "-t", str(src_dur),
"-vf", vf, "-af", af,
"-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2",
str(clip_out)], capture_output=True, timeout=120)
clip_files.append(str(clip_out))
lines.append(f"file '{clip_out}'\n")
# Phase 2: concat all clips, then mix with BGM
clip_list.write_text("".join(lines))
# ─── 音频避让:枪响/爆炸时BGM自动压低(sidechain compression) ───
if plan.get("audio_ducking", True):
# [1:a]=BGM(主信号) [0:a]=源音频(侧链触发)
# 当源音频 > -20dB 时,BGM被压低到 30%,释放时间 150ms
audio_filter = f"[1:a][0:a]sidechaincompress=threshold=0.08:ratio=6:attack=5:release=150:level_sc=0.3[aout]"
else:
bgm_vol = 10 ** (plan.get('bgm_volume_db', -12.0) / 20)
audio_filter = f"[0:a][1:a]amix=inputs=2:duration=first:weights=1 {bgm_vol}[aout]"
cmd = ["ffmpeg", "-y",
"-fflags", "+genpts",
"-f", "concat", "-safe", "0", "-i", str(clip_list),
"-i", bgm,
"-filter_complex", audio_filter,
"-map", "0:v",
"-map", "[aout]",
"-c:v", "copy",
"-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2",
"-t", str(plan.get("total_duration_sec", 60)),
str(output_path)
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode != 0:
raise HTTPException(500, f"Render failed: {result.stderr[-500:]}")
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
return {
"render_id": render_id,
"output": str(output_path),
"download_url": f"/api/download/{render_id}",
}
@app.get("/api/download/{render_id}")
async def download_render(render_id: str):
"""Download rendered video."""
path = RENDER_DIR / f"render_{render_id}.mp4"
if not path.exists():
raise HTTPException(404, "Render not found")
return FileResponse(path, media_type="video/mp4", filename=f"output_{render_id}.mp4")
@app.post("/api/export/{session_id}")
async def export_clips(session_id: str, data: dict):
"""Export selected/trimmed scenes as unified clip format JSON."""
if session_id not in SESSIONS:
raise HTTPException(404, "Session not found")
session = SESSIONS[session_id]
video_path = session["video_path"]
clips = []
for s in data.get("scenes", session["scenes"]):
if not s.get("selected", True):
continue
start = s.get("start_sec", 0) + s.get("trim_start", 0)
end = s.get("start_sec", 0) + s.get("trim_end", s.get("duration_sec", 0))
clip = {
"clip_id": f"{session_id}_{s.get('index', 0):03d}",
"source_path": video_path,
"start_sec": start,
"end_sec": end,
"duration_sec": max(0.1, end - start),
"tags": s.get("tags", []),
"intensity": s.get("intensity", 0.5),
"audio_mode": s.get("audio_mode", "融入BGM"),
"description": s.get("description", ""),
"protect_end": s.get("protect_end", False),
}
clips.append(clip)
# Save clips to file
clips_path = OUTPUT_DIR / f"clips_{session_id}.json"
output = {"source_video": video_path, "clip_count": len(clips), "clips": clips}
clips_path.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding='utf-8')
return output
@app.get("/api/preview/{session_id}/{scene_index}")
async def preview_scene(session_id: str, scene_index: int):
if session_id not in SESSIONS:
raise HTTPException(404, "Session not found")
scenes = SESSIONS[session_id]["scenes"]
if scene_index >= len(scenes):
raise HTTPException(404, "Scene not found")
s = scenes[scene_index]
video_path = SESSIONS[session_id]["video_path"]
preview_path = OUTPUT_DIR / f"preview_{session_id}_{scene_index}.mp4"
start = s["start_sec"]
duration = min(s["duration_sec"], 10.0)
cmd = [
"ffmpeg", "-y", "-ss", str(start), "-i", video_path,
"-t", str(duration), "-vf", "scale=854:-2",
"-c:v", "libx264", "-preset", "ultrafast", "-crf", "28",
"-c:a", "aac", "-b:a", "64k",
str(preview_path)
]
subprocess.run(cmd, capture_output=True, timeout=30)
return FileResponse(preview_path, media_type="video/mp4")
@app.get("/", response_class=HTMLResponse)
async def index():
html_path = STATIC_DIR / "index.html"
if html_path.exists():
return html_path.read_text(encoding='utf-8')
return "<h1>Static files not found</h1>"
@app.get("/health")
async def health():
return {
"status": "ok",
"sessions": len(SESSIONS),
"bgm_sessions": len(BGM_SESSIONS),
}
# ═══════════════════════════════════════════════════════
# LLM / VLM integration
# ═══════════════════════════════════════════════════════
import httpx
LLM_CONFIG_PATH = Path.home() / ".conv-edit" / "llm_config.json"
LLM_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
DEFAULT_LLM_CONFIG = {
"api_base": "http://localhost:11434/v1",
"api_key": "",
"llm_model": "qwen3.6:27b",
"vision_model": "minicpm-v:8b",
"enabled": False,
"max_tokens": 2048,
}
def _load_llm_config() -> dict:
if LLM_CONFIG_PATH.exists():
try:
cfg = json.loads(LLM_CONFIG_PATH.read_text(encoding='utf-8'))
log.debug(f"config loaded -> enabled={cfg.get('enabled')} llm={cfg.get('llm_model')} vision={cfg.get('vision_model')} base={cfg.get('api_base')}")
return cfg
except Exception as e:
log.warning(f"config load failed: {e}, using defaults")
log.debug("config -> using defaults (not found or corrupt)")
return dict(DEFAULT_LLM_CONFIG)
def _save_llm_config(config: dict) -> None:
LLM_CONFIG_PATH.write_text(json.dumps(config, indent=2, ensure_ascii=False), encoding='utf-8')
async def _llm_chat(config: dict, messages: list[dict], model: str = None) -> str:
"""Send a chat request to OpenAI-compatible API."""
m = model or config.get("llm_model", DEFAULT_LLM_CONFIG["llm_model"])
api_url = f"{config['api_base'].rstrip('/')}/chat/completions"
msg_count = len(messages)
img_count = 0
if messages and isinstance(messages[-1].get("content"), list):
img_count = sum(1 for c in messages[-1]["content"] if c.get("type") == "image_url")
log.info(f"LLM request -> model={m} url={api_url} msgs={msg_count} images={img_count} timeout=30s")
try:
async with httpx.AsyncClient(timeout=30) as client:
headers = {"Content-Type": "application/json"}
if config.get("api_key"):
headers["Authorization"] = f"Bearer {config['api_key']}"
resp = await client.post(
api_url,
headers=headers,
json={
"model": m,
"messages": messages,
"max_tokens": config.get("max_tokens", 2048),
"temperature": 0.3,
},
)
if resp.status_code != 200:
log.error(f"LLM API error -> status={resp.status_code} body={resp.text[:300]}")
raise HTTPException(502, f"LLM API error: {resp.text[:300]}")
data = resp.json()