@dsh-gis/dsh-video-studio-skill 0.4.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +93 -18
  2. package/docs/styles/demo-results.json +76 -0
  3. package/docs/styles/sheet-8-styles.png +0 -0
  4. package/docs/styles/sheet-ai.png +0 -0
  5. package/docs/styles/sheet-craft.png +0 -0
  6. package/docs/styles/sheet-night.png +0 -0
  7. package/index.js +20 -7
  8. package/package.json +13 -3
  9. package/schemas/film.schema.json +599 -0
  10. package/skills/video-studio/SKILL.md +252 -28
  11. package/skills/video-studio/assets/film.json +78 -24
  12. package/skills/video-studio/assets/scenes.py +1005 -42
  13. package/skills/video-studio/assets/web/engine.js +18 -1
  14. package/skills/video-studio/assets/web/film.js +29 -4
  15. package/skills/video-studio/assets/web/index.html +5 -0
  16. package/skills/video-studio/references/audio-variation.md +158 -0
  17. package/skills/video-studio/references/audio.md +96 -6
  18. package/skills/video-studio/references/change-impact.md +54 -0
  19. package/skills/video-studio/references/quality-gates.md +1 -1
  20. package/skills/video-studio/references/style-packs.md +178 -0
  21. package/skills/video-studio/references/web-engine.md +1 -1
  22. package/skills/video-studio/requirements.txt +13 -1
  23. package/skills/video-studio/scripts/filmcheck.py +725 -0
  24. package/skills/video-studio/scripts/filmkit.py +953 -76
  25. package/skills/video-studio/scripts/gates.py +509 -0
  26. package/skills/video-studio/scripts/qa_frames.py +109 -19
  27. package/skills/video-studio/scripts/render.py +942 -45
  28. package/skills/video-studio/scripts/scorekit.py +1887 -27
  29. package/skills/video-studio/scripts/selfcheck.py +648 -2
  30. package/skills/video-studio/scripts/sfxkit.py +132 -30
  31. package/skills/video-studio/scripts/stagewatch.py +405 -0
  32. package/skills/video-studio/scripts/stylekit.py +1012 -0
  33. package/skills/video-studio/scripts/voicekit.py +880 -0
  34. package/skills/video-studio/scripts/webengine.py +68 -14
  35. package/tools/audio_similarity.py +279 -0
  36. package/tools/ci_check.py +450 -0
  37. package/tools/estimate.py +657 -0
  38. package/tools/selftest_noscipy.py +70 -0
@@ -1,5 +1,5 @@
1
1
  # -*- coding: utf-8 -*-
2
- """scorekit.py — 程序化配乐(v0.3.0)。
2
+ """scorekit.py — 程序化配乐(v0.7.0)。
3
3
 
4
4
  用代码写一张能贯穿整部片子的配乐:调性/和弦表、段落能量、节拍网格、律动层、
5
5
  段落过门、自动电平与"吸气",全部由 numpy + sfxkit 现场合成,不用任何采样。
@@ -21,6 +21,30 @@
21
21
  class Score: section / plan_from_anchors / suck / render / report
22
22
  render(duration, bpm=120, key="Dm", anchors=None, sections=None, seed=7) -> (samples, report)
23
23
  save(path, x, sr=SR) / load(path, sr=SR) / selftest()
24
+
25
+ v0.5 新增(配乐风格层):
26
+ MUSIC_STYLES / MUSIC_STYLE_IDS 9 个配乐风格(8 个与 stylekit 同名 + legacy)
27
+ render_styled(duration, *, style, bpm=None, key=None, mood=None, anchors=None,
28
+ sections=None, seed=7, fingerprint=None, sucks=None,
29
+ music_plan=None, pace=None) -> (samples, report)
30
+ music_plan = stylekit.resolve_script_style(script)["music"](非 None 时盖过 bpm/key/mood/seed)
31
+ pace = stylekit 的 pacing dict(只用 min_dur+hold 合并过碎段落,不改片长)
32
+ render(..., style=None, mood="steady", fingerprint=None)
33
+ style 为 None / "legacy" 时走 v0.4 原路径(逐样本一致);否则走风格化合成。
34
+ KEYS_MAJOR / KEYS_ALL 6 个大调 + 全部 10 个调
35
+ spectral_centroid(x, sr=SR) 频谱质心(量"亮度",验证风格差异用)
36
+
37
+ v0.7 新增(内容指纹变奏,references/audio-variation.md §3.3):
38
+ fingerprint 不再只派生音色 seed —— 同一风格换内容指纹时,结构层也稳定地变:
39
+ * 进行档:按指纹从 style["progressions"] 的 calm/body/drive 里另选一档
40
+ (整片一个偏移、climax 仍复用 drive,片内各段的进行关系保持连贯);
41
+ * 和弦:每两小节一次稳定替换(i<->i7 / VI<->VI7 / III<->III7 / VII<->VII7;
42
+ 大调侧 I<->Imaj7 / IV<->IVmaj7),不覆盖乐句末属和弦与片尾主和弦;
43
+ * 动机:每个 (拍, 级数, 时值) 做 ±1 级数偏移(只改级数不改节奏;问句/答句/
44
+ 片尾三种动机独立派生,跨主音的上下行用八度偏移修正);
45
+ * 鼓型:kick 最多加一记 ghost 落点(0.5 拍网格、不与现有落点重复),clap ±0.5 拍。
46
+ report["variation"] = {"chord_swaps", "motif_shifts", "drum_ghosts"} 记实际发生数。
47
+ style=None 的 legacy 路径不经过这些代码,仍然逐字节兼容(selfcheck 20 条)。
24
48
  """
25
49
  from __future__ import annotations
26
50
 
@@ -38,7 +62,7 @@ import numpy as np
38
62
 
39
63
  import sfxkit as S # 唯一音频依赖:numpy + sfxkit
40
64
 
41
- __version__ = "0.3.0"
65
+ __version__ = "0.7.0"
42
66
 
43
67
  SR = 48000 # 采样率(与 filmkit / sfxkit 一致)
44
68
  BEATS_PER_BAR = 4 # 4/4
@@ -102,8 +126,30 @@ _DEGREE_TABLE = (
102
126
  ("VII", 10, (0, 4, 7, 12), ""),
103
127
  ("I", 0, (0, 4, 7, 12), ""), # 结尾大三和弦(皮卡迪三度)
104
128
  ("sus2", 0, (0, 2, 7, 12), "sus2"), # 悬留色彩,过门/段首可用
129
+ # ---- v0.5:大调级数与七和弦色彩。只允许在表尾追加;前 10 项顺序不许动(_build_key 依赖) ----
130
+ ("ii", 2, (0, 3, 7, 12), "m"),
131
+ ("iii", 4, (0, 3, 7, 12), "m"),
132
+ ("IV", 5, (0, 4, 7, 12), ""),
133
+ ("vi", 9, (0, 3, 7, 12), "m"),
134
+ ("vii", 11, (0, 3, 6, 12), "dim"),
135
+ ("sus4", 0, (0, 5, 7, 12), "sus4"),
136
+ ("Imaj7", 0, (0, 4, 7, 11), "maj7"),
137
+ ("ii7", 2, (0, 3, 7, 10), "m7"),
138
+ ("iii7", 4, (0, 3, 7, 10), "m7"),
139
+ ("IVmaj7", 5, (0, 4, 7, 11), "maj7"),
140
+ ("V7", 7, (0, 4, 7, 10), "7"),
141
+ ("vi7", 9, (0, 3, 7, 10), "m7"),
142
+ ("i7", 0, (0, 3, 7, 10), "m7"),
143
+ # ---- v0.7:和弦替换用的七和弦色彩。同根音、同三音,只把五度后的音换成小七度;
144
+ # 只允许在表尾追加(前 10 项顺序被 _build_key / 老报告依赖),供 _CHORD_SWAPS 使用。 ----
145
+ ("VI7", 8, (0, 4, 7, 10), "7"),
146
+ ("III7", 3, (0, 4, 7, 10), "7"),
147
+ ("VII7", 10, (0, 4, 7, 10), "7"),
105
148
  )
106
149
 
150
+ # 级数名 -> 定义行(旋律生成/mood 色彩/自测校验用;只读映射,不参与 _build_key)
151
+ _DEGREE_BY_NAME = {row[0]: row for row in _DEGREE_TABLE}
152
+
107
153
 
108
154
  # ============================================================================
109
155
  # 小工具(全部确定性、无副作用)
@@ -177,7 +223,8 @@ def _build_key(root_name: str, root_pc: int, accidentals: str, cn_name: str) ->
177
223
  for degree, base, intervals, quality in _DEGREE_TABLE:
178
224
  notes = [_semi_note(root_pc, 3, base + iv, names) for iv in intervals]
179
225
  bass_pc = (root_pc + base) % 12
180
- suffix = {"m": "m", "dim": "dim", "sus2": "sus2", "": ""}[quality]
226
+ suffix = {"m": "m", "dim": "dim", "sus2": "sus2", "sus4": "sus4",
227
+ "maj7": "maj7", "m7": "m7", "7": "7", "": ""}[quality]
181
228
  chords[degree] = {
182
229
  "degree": degree,
183
230
  "name": f"{names[bass_pc]}{suffix}",
@@ -204,6 +251,32 @@ KEYS = {
204
251
  "Em": _build_key("E", 4, "sharp", "E 小调"),
205
252
  }
206
253
 
254
+ # 大调三档和声进行(v0.5)。小调那边 PROGRESSIONS 保持原样:legacy 路径只读 PROGRESSIONS。
255
+ PROGRESSIONS_MAJOR = {
256
+ "calm": ("I", "vi", "IV", "V"),
257
+ "body": ("I", "V", "vi", "IV"),
258
+ "drive": ("I", "IV", "V", "I"),
259
+ }
260
+
261
+ # v0.5:6 个大调(与 stylekit.MAJOR_KEYS 同名同义)。用同一个 _build_key 构建,
262
+ # 语义与小调键完全一致(级数表 -> 和弦名/低音/音名);只是 progression 换成大调级数。
263
+ # 写法按惯例挑:C/F/Bb 用降号、G/D/A 用升号。
264
+ KEYS_MAJOR = {
265
+ "C": _build_key("C", 0, "flat", "C 大调"),
266
+ "G": _build_key("G", 7, "sharp", "G 大调"),
267
+ "D": _build_key("D", 2, "sharp", "D 大调"),
268
+ "F": _build_key("F", 5, "flat", "F 大调"),
269
+ "A": _build_key("A", 9, "sharp", "A 大调"),
270
+ "Bb": _build_key("Bb", 10, "flat", "Bb 大调"),
271
+ }
272
+ for _kname in KEYS_MAJOR:
273
+ KEYS_MAJOR[_kname]["progression"] = dict(PROGRESSIONS_MAJOR)
274
+ del _kname
275
+
276
+ # 全部可用调:4 个小调 + 6 个大调。KEYS 本身保持 v0.4 的 4 个小调不变(兼容性锚点)。
277
+ KEYS_ALL = dict(KEYS)
278
+ KEYS_ALL.update(KEYS_MAJOR)
279
+
207
280
 
208
281
  # ============================================================================
209
282
  # 电平测量(简化 K 加权;只用于段落间相对电平匹配与报告,不追求 BS.1770 精度)
@@ -220,6 +293,10 @@ def _decimate_mono(x: np.ndarray, k: int = 4) -> np.ndarray:
220
293
  def _moving_avg(v: np.ndarray, w: int) -> np.ndarray:
221
294
  """移动平均(边界复制),O(n),用来做"一阶高通/低通"的近似。"""
222
295
  w = max(2, int(w))
296
+ if len(v) == 0:
297
+ # 空输入:np.pad(mode="edge") 对空数组直接抛 "can't extend empty axis 0",
298
+ # 而空数组只在 duration*sr < 4(不足 4 个采样)时出现(duration=1e-6 实测崩这)。
299
+ return np.zeros(0, dtype=np.float64)
223
300
  pad = w // 2
224
301
  vp = np.pad(v, (pad, w - pad), mode="edge")
225
302
  c = np.cumsum(vp)
@@ -335,6 +412,7 @@ class _Bank:
335
412
  self._cache: dict = {}
336
413
  self._pad_cores: dict = {}
337
414
  self._pad_envs: dict = {}
415
+ self._str_cores: dict = {}
338
416
  self._pad_n = max(16, _ns(self.bar_s * 1.02 + 1.3, self.sr))
339
417
  self._pad_dur = self.bar_s * 1.02
340
418
  # 鼓组:预渲染几套变体,交替使用,避免机械重复
@@ -565,6 +643,211 @@ class _Bank:
565
643
  self._cache[key] = tex
566
644
  return tex
567
645
 
646
+
647
+ # ---------------- v0.5 风格化音色(只用已有原语组合;不碰老乐器的 RNG 序列) ----------------
648
+ #
649
+ # 三个约定,保证 legacy 逐样本不变:
650
+ # 1) 每个新音色都走 self._cached(...) / self._cache,种子用 self._seed("<新名字>", ...),
651
+ # 名字前缀与老乐器不重叠,老乐器一次都不读新缓存;
652
+ # 2) 不在 __init__ 里预渲染任何新素材(既有 rng 调用次序不变);
653
+ # 3) 新方法只在 render_styled 里被调用。
654
+ def strings(self, chord: dict, bright: float, attack: float, release: float = 0.7,
655
+ octave: int = 0) -> np.ndarray:
656
+ """弦乐铺底:5 声部超级锯齿(detune 0.06)过低通,比合成器 pad 更宽、更"有机"。"""
657
+ key = ("strings", chord["name"], int(round(bright * 10)),
658
+ int(round(attack * 100)), int(octave))
659
+ hit = self._cache.get(key)
660
+ if hit is not None:
661
+ return hit
662
+ core = self._strings_core(chord, bright, octave)
663
+ env = self._pad_env(attack, release)
664
+ tex = self._edge_fade(_f32(core * env[:, None]), 0.002, 0.02)
665
+ self._cache[key] = tex
666
+ return tex
667
+
668
+ def _strings_core(self, chord: dict, bright: float, octave: int) -> np.ndarray:
669
+ key = ("strcore", chord["name"], int(round(bright * 10)), int(octave))
670
+ hit = self._str_cores.get(key)
671
+ if hit is not None:
672
+ return hit
673
+ names = [_up(nt, octave) for nt in chord["notes"]] if octave else list(chord["notes"])
674
+ n = self._pad_n
675
+ out = np.zeros((n, 2), np.float32)
676
+ for c in range(2):
677
+ g = S.rng(self._seed("strings", chord["name"], int(round(bright * 10)), octave, c))
678
+ acc = np.zeros(n, np.float64)
679
+ for nt in names:
680
+ acc += S.supersaw(S.hz(nt), n, voices=5, detune=0.06, seed=g, sr=self.sr)
681
+ acc = S.lowpass(acc, 420.0 + 2600.0 * bright, 0.8, sr=self.sr)
682
+ acc = S.highpass(acc, 70.0, sr=self.sr)
683
+ out[:, c] = _f32(acc)
684
+ out *= np.float32(1.9 / max(1, len(names)))
685
+ self._str_cores[key] = out
686
+ return out
687
+
688
+ def cello(self, note: str, dur: float, bright: float) -> np.ndarray:
689
+ """大提琴式低音:锯齿 + 脉冲、带一点揉弦,慢起音。"""
690
+ key = ("cello", note, round(float(dur), 3), int(round(bright * 10)))
691
+ return self._cached(key, lambda: self._make_cello(note, dur, bright))
692
+
693
+ def _make_cello(self, note: str, dur: float, bright: float) -> np.ndarray:
694
+ f = S.hz(note)
695
+ n = _ns(dur + 0.06, self.sr)
696
+ t = _t(n, self.sr)
697
+ vib = 1.0 + 0.0045 * np.sin(2.0 * np.pi * 5.1 * t)
698
+ osc = (0.70 * S.saw(f * vib, n, sr=self.sr)
699
+ + 0.35 * S.pulse(f * vib * 1.001, n, 0.42, sr=self.sr))
700
+ x = S.lowpass(osc, 260.0 + 1500.0 * bright, 1.1, sr=self.sr)
701
+ env = np.minimum(1.0, t / 0.025) * np.clip((dur + 0.05 - t) / 0.06, 0.0, 1.0)
702
+ x = np.tanh(x * 1.6) * 0.5 * env
703
+ return self._edge_fade(_f32(x), 0.002, 0.01)
704
+
705
+ def sub_bass(self, note: str, dur: float) -> np.ndarray:
706
+ """808 式超低音:正弦轻微下滑 + tanh 饱和(lo-fi / 电子底的"地基")。"""
707
+ key = ("subbass", note, round(float(dur), 3))
708
+ return self._cached(key, lambda: self._make_sub_bass(note, dur))
709
+
710
+ def _make_sub_bass(self, note: str, dur: float) -> np.ndarray:
711
+ f = S.hz(note)
712
+ d = float(min(1.2, max(0.08, dur)))
713
+ n = _ns(d + 0.08, self.sr)
714
+ t = _t(n, self.sr)
715
+ fr = f + (f * 1.03 - f) * np.exp(-t / 0.04)
716
+ x = S.sine(fr, n, sr=self.sr) * np.exp(-t / max(0.08, d * 0.55))
717
+ x = np.tanh(x * 1.8) * 0.8 * np.minimum(1.0, t / 0.003)
718
+ return self._edge_fade(_f32(x), 0.001, 0.01)
719
+
720
+ def pulse_bass(self, note: str, dur: float, bright: float) -> np.ndarray:
721
+ """脉冲贝斯:方波为主 + 时变低通,比老 bass 更"电子"。"""
722
+ key = ("pulsebass", note, round(float(dur), 3), int(round(bright * 10)))
723
+ return self._cached(key, lambda: self._make_pulse_bass(note, dur, bright))
724
+
725
+ def _make_pulse_bass(self, note: str, dur: float, bright: float) -> np.ndarray:
726
+ f = S.hz(note)
727
+ n = _ns(dur + 0.07, self.sr)
728
+ t = _t(n, self.sr)
729
+ osc = (0.80 * S.pulse(f, n, 0.34, sr=self.sr)
730
+ + 0.35 * S.saw(f * 1.002, n, sr=self.sr))
731
+ cut = 190.0 + (420.0 + 1700.0 * bright) * np.exp(-t / 0.1)
732
+ x = S.tv_filter(osc, "lowpass", cut, 1.0, block=64, sr=self.sr)
733
+ env = np.minimum(1.0, t / 0.004) * np.clip((dur + 0.05 - t) / 0.05, 0.0, 1.0)
734
+ x = np.tanh(x * 1.7) * 0.55 * env
735
+ return self._edge_fade(_f32(x), 0.001, 0.005)
736
+
737
+ def pluck_note(self, note: str, dur: float, bright: float) -> np.ndarray:
738
+ """Karplus-Strong 拨弦(sfxkit.pluck)—— 民谣 / 手作的木头感。"""
739
+ key = ("plucknote", note, round(float(dur), 3), int(round(bright * 10)))
740
+ return self._cached(key, lambda: self._make_pluck(note, dur, bright))
741
+
742
+ def _make_pluck(self, note: str, dur: float, bright: float) -> np.ndarray:
743
+ f = S.hz(note)
744
+ d = float(min(0.9, max(0.12, dur)))
745
+ x = S.pluck(f, d, brightness=_clip01(0.35 + 0.55 * bright), decay=0.9962,
746
+ seed=self._seed("pluck", note, int(round(bright * 10))), sr=self.sr)
747
+ x = np.asarray(x, dtype=np.float64)
748
+ want = _ns(d, self.sr)
749
+ if len(x) < want:
750
+ x = np.pad(x, (0, want - len(x)))
751
+ return self._edge_fade(_f32(x * 0.9), 0.0005, 0.01)
752
+
753
+ def epiano(self, note: str, dur: float) -> np.ndarray:
754
+ """电钢:FM 钟的变体 + 低八度正弦托底(杂志 / lo-fi 的"暖")。"""
755
+ key = ("epiano", note, round(float(dur), 3))
756
+ return self._cached(key, lambda: self._make_epiano(note, dur))
757
+
758
+ def _make_epiano(self, note: str, dur: float) -> np.ndarray:
759
+ f = S.hz(note)
760
+ d = float(min(3.0, max(0.25, dur)))
761
+ n = _ns(d, self.sr)
762
+ t = _t(n, self.sr)
763
+ idx = 1.5 * np.exp(-t / 0.12)
764
+ x = S.fm(f, 2.0, idx, n, sr=self.sr) * np.exp(-t / (d * 0.45))
765
+ x += 0.42 * S.sine(f * 0.5, n, sr=self.sr) * np.exp(-t / (d * 0.7))
766
+ x += 0.12 * S.fm(f * 2.0, 1.0, 0.35, n, sr=self.sr) * np.exp(-t / 0.25)
767
+ x *= np.minimum(1.0, t / 0.003)
768
+ return self._edge_fade(_f32(x * 0.6), 0.001, 0.02)
769
+
770
+ def marimba(self, note: str, dur: float) -> np.ndarray:
771
+ """马林巴:正弦基音 + 很短的 FM 敲击泛音。"""
772
+ key = ("marimba", note, round(float(dur), 3))
773
+ return self._cached(key, lambda: self._make_marimba(note, dur))
774
+
775
+ def _make_marimba(self, note: str, dur: float) -> np.ndarray:
776
+ f = S.hz(note)
777
+ d = float(min(2.0, max(0.35, dur)))
778
+ n = _ns(d, self.sr)
779
+ t = _t(n, self.sr)
780
+ x = S.sine(f, n, sr=self.sr) * np.exp(-t / 0.30)
781
+ x += 0.45 * S.fm(f, 3.0, 1.1 * np.exp(-t / 0.02), n, sr=self.sr) * np.exp(-t / 0.06)
782
+ x += 0.20 * S.sine(4.0 * f, n, sr=self.sr) * np.exp(-t / 0.05)
783
+ x *= np.minimum(1.0, t / 0.0015)
784
+ return self._edge_fade(_f32(x * 0.7), 0.0008, 0.02)
785
+
786
+ def glock(self, note: str, dur: float = 1.0) -> np.ndarray:
787
+ """钟琴:高比率 FM + 非谐波正弦,短促闪亮(vivid 的"活力")。"""
788
+ key = ("glock", note, round(float(dur), 2))
789
+ return self._cached(key, lambda: self._make_glock(note, dur))
790
+
791
+ def _make_glock(self, note: str, dur: float) -> np.ndarray:
792
+ f = S.hz(note)
793
+ d = float(min(1.6, max(0.25, dur)))
794
+ n = _ns(d, self.sr)
795
+ t = _t(n, self.sr)
796
+ x = S.fm(f, 3.5, 1.8 * np.exp(-t / 0.09), n, sr=self.sr) * np.exp(-t / 0.28)
797
+ x += 0.30 * S.sine(2.76 * f, n, sr=self.sr) * np.exp(-t / 0.16)
798
+ x *= np.minimum(1.0, t / 0.001)
799
+ return self._edge_fade(_f32(x * 0.55), 0.0005, 0.02)
800
+
801
+ def strings_bell(self, note: str, dur: float) -> np.ndarray:
802
+ """弦乐 + 钟的混合主奏:有弓弦的持续感,又有钟的起音(cinema / magazine)。"""
803
+ key = ("strbell", note, round(float(dur), 2))
804
+ return self._cached(key, lambda: self._make_strbell(note, dur))
805
+
806
+ def _make_strbell(self, note: str, dur: float) -> np.ndarray:
807
+ f = S.hz(note)
808
+ d = float(min(3.4, max(0.8, dur)))
809
+ n = _ns(d, self.sr)
810
+ t = _t(n, self.sr)
811
+ g = S.rng(self._seed("strbell", note, round(d, 2)))
812
+ osc = S.supersaw(f, n, voices=3, detune=0.05, seed=g, sr=self.sr)
813
+ osc = S.lowpass(osc, 1500.0, 0.8, sr=self.sr) * np.exp(-t / (d * 0.55))
814
+ bell = S.fm(f, 3.5, 1.6 * np.exp(-t / 0.3), n, sr=self.sr) * np.exp(-t / (d * 0.4))
815
+ x = (0.55 * osc + 0.85 * bell) * np.minimum(1.0, t / 0.004)
816
+ return self._edge_fade(_f32(x * 0.6), 0.002, 0.03)
817
+
818
+ def brass(self, note: str, dur: float, bright: float) -> np.ndarray:
819
+ """铜管:锯齿 + 脉冲过带通,起音短促(epic 的"定格重音")。"""
820
+ key = ("brass", note, round(float(dur), 3), int(round(bright * 10)))
821
+ return self._cached(key, lambda: self._make_brass(note, dur, bright))
822
+
823
+ def _make_brass(self, note: str, dur: float, bright: float) -> np.ndarray:
824
+ f = S.hz(note)
825
+ n = _ns(dur + 0.06, self.sr)
826
+ t = _t(n, self.sr)
827
+ osc = (0.85 * S.saw(f, n, sr=self.sr)
828
+ + 0.40 * S.pulse(f * 1.001, n, 0.42, sr=self.sr))
829
+ x = S.tv_filter(osc, "lowpass", 900.0 + 2600.0 * bright, 1.2, block=64, sr=self.sr)
830
+ x = S.bandpass(x, 900.0 + 1200.0 * bright, 0.8, sr=self.sr)
831
+ env = np.minimum(1.0, t / 0.035) * np.clip((dur + 0.04 - t) / 0.06, 0.0, 1.0)
832
+ x = np.tanh(x * 1.5) * 0.5 * env
833
+ return self._edge_fade(_f32(x), 0.002, 0.01)
834
+
835
+ def stab(self, note: str, dur: float, bright: float) -> np.ndarray:
836
+ """和弦短切音:极短带通脉冲,琶音层用它做"打点"。"""
837
+ key = ("stab", note, round(float(dur), 3), int(round(bright * 10)))
838
+ return self._cached(key, lambda: self._make_stab(note, dur, bright))
839
+
840
+ def _make_stab(self, note: str, dur: float, bright: float) -> np.ndarray:
841
+ f = S.hz(note)
842
+ d = float(min(0.6, max(0.12, dur)))
843
+ n = _ns(d, self.sr)
844
+ t = _t(n, self.sr)
845
+ osc = (0.70 * S.pulse(f, n, 0.30, sr=self.sr)
846
+ + 0.50 * S.saw(f * 1.003, n, sr=self.sr))
847
+ x = S.bandpass(osc, 1000.0 + 2400.0 * bright, 1.1, sr=self.sr) * np.exp(-t / 0.06)
848
+ x *= np.minimum(1.0, t / 0.001)
849
+ return self._edge_fade(_f32(x * 0.8), 0.0005, 0.008)
850
+
568
851
  # ---------------- 效果素材 ----------------
569
852
  def sub_boom(self, dur: float = 2.2, f0: float = 55.0, f1: float = 30.0) -> np.ndarray:
570
853
  """低频轰鸣:音高下滑的正弦(重击的"地基")。"""
@@ -693,7 +976,7 @@ class Score:
693
976
  _require(isinstance(bpm, (int, float)) and math.isfinite(float(bpm))
694
977
  and float(bpm) > 0.0,
695
978
  f"bpm 必须是有限正数,收到 {bpm!r}")
696
- _require(key in KEYS, f"未知调性 {key!r};可选:{'/'.join(KEYS)}")
979
+ _require(key in KEYS_ALL, f"未知调性 {key!r};可选:{'/'.join(KEYS_ALL)}")
697
980
  self.duration = float(duration)
698
981
  self.bpm = float(bpm)
699
982
  self.key = key
@@ -710,7 +993,7 @@ class Score:
710
993
  # ---------------- 公开属性 ----------------
711
994
  @property
712
995
  def k(self) -> dict:
713
- return KEYS[self.key]
996
+ return KEYS_ALL[self.key]
714
997
 
715
998
  def __repr__(self) -> str: # 只用于调试输出
716
999
  return (f"Score(duration={self.duration:g}, bpm={self.bpm:g}, key={self.key!r}, "
@@ -1153,7 +1436,10 @@ class Score:
1153
1436
  peak = float(np.max(np.abs(master))) if n else 0.0
1154
1437
  if peak > 1e-9:
1155
1438
  master *= np.float32(_db_amp(TARGET_PEAK_DB) / peak)
1156
- peak_db = float(20.0 * math.log10(max(float(np.max(np.abs(master))), 1e-12)))
1439
+ # 亚采样时长(duration*sr < 1)时 master 是 (0,2):np.max 对空数组直接抛
1440
+ # "zero-size array to reduction operation maximum"(duration=1e-6 实测崩这)。
1441
+ peak_db = (float(20.0 * math.log10(max(float(np.max(np.abs(master))), 1e-12)))
1442
+ if n else -240.0)
1157
1443
  lufs = _approx_lufs(master, self.sr)
1158
1444
  meas = [{"name": s["name"], "start": round(s["start"], 3), "end": round(s["end"], 3),
1159
1445
  "energy": round(s["energy"], 3), "gain_db": round(lv["gain"], 2),
@@ -1162,7 +1448,7 @@ class Score:
1162
1448
  "rendered": True,
1163
1449
  "peak_dbfs": round(peak_db, 2),
1164
1450
  "lufs_approx": round(lufs, 1),
1165
- "dc_max": round(float(np.max(np.abs(master.mean(axis=0)))), 9),
1451
+ "dc_max": round(float(np.max(np.abs(master.mean(axis=0)))), 9) if n else 0.0,
1166
1452
  "render_s": round(time.perf_counter() - t_start, 3),
1167
1453
  "measured_sections": meas,
1168
1454
  }
@@ -1327,7 +1613,7 @@ class Score:
1327
1613
  plan = self._build_plan()
1328
1614
  rep = {
1329
1615
  "version": 1,
1330
- "generator": f"scorekit {__version__}",
1616
+ "generator": "scorekit",
1331
1617
  "bpm": self.bpm,
1332
1618
  "key": self.key,
1333
1619
  "key_name": self.k["name"],
@@ -1358,6 +1644,1392 @@ class Score:
1358
1644
  return rep
1359
1645
 
1360
1646
 
1647
+
1648
+ # ============================================================================
1649
+ # v0.5 配乐风格层(MUSIC_STYLES):一个 style id = 一种"配乐性格"
1650
+ # ============================================================================
1651
+ #
1652
+ # 为什么要这一层:v0.4 的配乐只有一套和声进行 / 一套动机 / 一张 energy 查表,
1653
+ # 所以「不管什么内容,听众听到的都是同一首曲子的不同时长」。v0.5 把"写什么"拆成
1654
+ # 风格包:和弦进行、动机、鼓型、音色、空间、动态各自成表,同一部片的配乐由 style 决定。
1655
+ #
1656
+ # 与 stylekit.STYLES 的关系:
1657
+ # * 本模块不 import stylekit(scorekit 要能单独拷走运行,且 stylekit 是本模块的上游);
1658
+ # style id 与调池手工对齐,selftest 在 stylekit 存在时会交叉核对(缺失则 skip);
1659
+ # * stylekit 管"策展层"(BPM 梯度 / 调池 / 情绪),这里管"合成层"(和弦 / 鼓型 / 音色 /
1660
+ # 空间 / 动态),两边用同一个 style id 对齐。
1661
+ #
1662
+ # 数据契约(每个风格一个纯数据 dict,无 RNG 副作用):
1663
+ # bpm_hint 仅供文档 / CLI 显示;真正 BPM 由 stylekit 决定后传给 render_styled
1664
+ # keys 调池(与 STYLES[sid]["music"]["keys"] 一致;不在池里的调也能渲,只是不"正宗")
1665
+ # progressions {"calm"/"body"/"drive": 级数元组},级数必须在 _DEGREE_TABLE 里
1666
+ # motif {"q"/"a"/"end": ((拍, 级数, 时值拍), ...)}:级数相对主音,供主奏轮换
1667
+ # layers 层 -> 最低能量(0~1);过线才出现,进出各花 1 小节渐入渐出
1668
+ # voices {"pad"/"bass"/"arp"/"lead": 音色名},可选值见 _STYLE_VOICES
1669
+ # lead_cycle 主奏音色轮换表(每 phrase_bars 轮换一个)
1670
+ # drums {"calm"/"body"/"drive"/"climax": {kick,hat,clap,bass,arp}}
1671
+ # space {"delay_beats","delay_db","taps"} 乒乓延迟(拍为单位)
1672
+ # phrase_bars 4 / 8
1673
+ # duck {"bass","pad"} 侧链深度
1674
+ # level_span_db 段落能量 -> 电平的跨度(dB);8.5 与 legacy 的 energy_target_db 同口径
1675
+ # swing 0.0 / 0.08~0.16:奇数列踩镲与琶音延后(拍),只改位置不改 RNG 调用次数
1676
+
1677
+ MUSIC_STYLES = {
1678
+ # 科技深蓝:电子、切分、拨弦琶音;小调,四四拍推进
1679
+ "tech-deep": {
1680
+ "label": "科技深蓝",
1681
+ "bpm_hint": (104, 112, 120),
1682
+ "keys": ("Dm", "Am", "Em", "Cm"),
1683
+ "progressions": {
1684
+ "calm": ("i", "VI", "iv", "v"),
1685
+ "body": ("i", "VI", "III", "VII"),
1686
+ "drive": ("i", "VII", "VI", "V"),
1687
+ },
1688
+ "motif": {
1689
+ "q": ((0.0, "v", 0.75), (1.0, "i", 0.75), (2.0, "III", 0.75), (3.0, "iv", 1.75),
1690
+ (5.0, "III", 0.75), (6.0, "v", 0.75), (7.0, "i", 1.5)),
1691
+ "a": ((0.0, "v", 0.75), (1.0, "i", 0.75), (2.0, "III", 0.75), (3.0, "v", 0.75),
1692
+ (4.0, "VII", 2.0)),
1693
+ "end": ((0.0, "v", 1.0), (1.5, "i", 1.0), (2.5, "III", 1.5), (4.0, "i", 3.0)),
1694
+ },
1695
+ "layers": {"pad": 0.0, "bass": 0.24, "kick": 0.36, "hat": 0.46,
1696
+ "arp": 0.54, "melody": 0.66, "shine": 0.86},
1697
+ "voices": {"pad": "pad_saw", "bass": "pulse", "arp": "pluck", "lead": "bell"},
1698
+ "lead_cycle": ("bell", "marimba"),
1699
+ "drums": {
1700
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1701
+ "body": {"kick": (0.0, 2.0), "hat": 1.0, "clap": (), "bass": "half", "arp": 0.5},
1702
+ "drive": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.5, "clap": (1.0, 3.0),
1703
+ "bass": "off8", "arp": 0.25},
1704
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1705
+ "bass": "16", "arp": 0.25},
1706
+ },
1707
+ "space": {"delay_beats": 0.75, "delay_db": -15.0, "taps": 3},
1708
+ "phrase_bars": 4,
1709
+ "duck": {"bass": 0.44, "pad": 0.30},
1710
+ "level_span_db": 8.5,
1711
+ "swing": 0.0,
1712
+ },
1713
+ # 杂志暖白:大调七和弦、电钢、大提琴贝斯;慢速、留白多
1714
+ "magazine": {
1715
+ "label": "杂志暖白",
1716
+ "bpm_hint": (88, 92, 96, 100),
1717
+ "keys": ("C", "G", "D", "F"),
1718
+ "progressions": {
1719
+ "calm": ("Imaj7", "vi7", "ii7", "V7"),
1720
+ "body": ("I", "vi", "IV", "V"),
1721
+ "drive": ("I", "IV", "V", "vi"),
1722
+ },
1723
+ "motif": {
1724
+ "q": ((0.0, "V", 0.9), (0.9, "VI", 0.9), (1.8, "V", 0.9), (2.7, "III", 0.9),
1725
+ (3.5, "I", 1.5), (5.0, "ii", 0.9), (5.9, "III", 0.9), (6.8, "V", 2.2)),
1726
+ "a": ((0.0, "V", 0.9), (0.9, "VI", 0.9), (1.8, "iii", 0.9), (2.7, "ii", 0.9),
1727
+ (3.5, "I", 1.5), (5.0, "III", 0.9), (6.0, "V", 2.4)),
1728
+ "end": ((0.0, "V", 1.2), (1.5, "VI", 0.9), (2.5, "V", 1.0), (3.5, "I", 3.0)),
1729
+ },
1730
+ "layers": {"pad": 0.0, "bass": 0.30, "kick": 0.42, "hat": 0.52,
1731
+ "arp": 0.50, "melody": 0.30, "shine": 0.90},
1732
+ "voices": {"pad": "strings", "bass": "cello", "arp": "epiano", "lead": "celesta"},
1733
+ "lead_cycle": ("celesta", "strings_bell"),
1734
+ "drums": {
1735
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1736
+ "body": {"kick": (0.0, 2.0), "hat": 1.0, "clap": (), "bass": "half", "arp": 0.5},
1737
+ "drive": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (1.0, 3.0),
1738
+ "bass": "off8", "arp": 0.5},
1739
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1740
+ "bass": "off8", "arp": 0.25},
1741
+ },
1742
+ "space": {"delay_beats": 1.0, "delay_db": -17.0, "taps": 2},
1743
+ "phrase_bars": 8,
1744
+ "duck": {"bass": 0.34, "pad": 0.24},
1745
+ "level_span_db": 7.0,
1746
+ "swing": 0.0,
1747
+ },
1748
+ # 手绘纸感:木吉他拨弦、马林巴、轻微摇摆;大调,温暖
1749
+ "paper": {
1750
+ "label": "手绘纸感",
1751
+ "bpm_hint": (84, 88, 92),
1752
+ "keys": ("G", "D", "C"),
1753
+ "progressions": {
1754
+ "calm": ("I", "IV", "vi", "V"),
1755
+ "body": ("I", "IV", "V", "vi"),
1756
+ "drive": ("I", "V", "IV", "I"),
1757
+ },
1758
+ "motif": {
1759
+ "q": ((0.0, "I", 1.0), (1.0, "III", 1.0), (2.0, "V", 1.0), (3.0, "VI", 1.5),
1760
+ (4.5, "V", 0.75), (5.25, "III", 0.75), (6.0, "I", 2.0)),
1761
+ "a": ((0.0, "III", 1.0), (1.0, "V", 1.0), (2.0, "VI", 1.0), (3.0, "V", 1.5),
1762
+ (4.5, "III", 0.75), (5.25, "V", 0.75), (6.0, "I", 2.0)),
1763
+ "end": ((0.0, "V", 1.0), (1.5, "VI", 1.0), (2.5, "V", 1.5), (4.0, "I", 3.5)),
1764
+ },
1765
+ "layers": {"pad": 0.0, "bass": 0.28, "kick": 0.50, "hat": 0.62,
1766
+ "arp": 0.45, "melody": 0.30, "shine": 0.88},
1767
+ "voices": {"pad": "strings", "bass": "cello", "arp": "pluck", "lead": "marimba"},
1768
+ "lead_cycle": ("marimba", "celesta"),
1769
+ "drums": {
1770
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1771
+ "body": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (), "bass": "half", "arp": 0.5},
1772
+ "drive": {"kick": (0.0, 2.0), "hat": 0.25, "clap": (1.0, 3.0),
1773
+ "bass": "off8", "arp": 0.25},
1774
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1775
+ "bass": "off8", "arp": 0.25},
1776
+ },
1777
+ "space": {"delay_beats": 0.5, "delay_db": -18.0, "taps": 2},
1778
+ "phrase_bars": 4,
1779
+ "duck": {"bass": 0.28, "pad": 0.22},
1780
+ "level_span_db": 7.5,
1781
+ "swing": 0.10,
1782
+ },
1783
+ # 活力撞色:大调 4/4、短切和弦、钟琴主奏;高能量、明亮
1784
+ "vivid": {
1785
+ "label": "活力撞色",
1786
+ "bpm_hint": (120, 126, 132),
1787
+ "keys": ("D", "G", "A"),
1788
+ "progressions": {
1789
+ "calm": ("I", "vi", "IV", "V"),
1790
+ "body": ("I", "V", "vi", "IV"),
1791
+ "drive": ("I", "IV", "V", "I"),
1792
+ },
1793
+ "motif": {
1794
+ "q": ((0.0, "V", 0.5), (0.5, "V", 0.25), (1.0, "VI", 0.5), (1.5, "V", 0.5),
1795
+ (2.0, "III", 0.5), (2.5, "I", 1.5), (4.0, "V", 0.5), (4.5, "VI", 0.5),
1796
+ (5.0, "V", 1.0), (6.0, "I", 2.0)),
1797
+ "a": ((0.0, "III", 0.5), (0.5, "III", 0.25), (1.0, "V", 0.5), (1.5, "III", 0.5),
1798
+ (2.0, "V", 0.5), (2.5, "VI", 1.5), (4.0, "V", 0.5), (5.0, "III", 1.0),
1799
+ (6.0, "I", 2.0)),
1800
+ "end": ((0.0, "V", 0.5), (1.0, "VI", 0.75), (2.0, "V", 1.5), (4.0, "I", 3.0)),
1801
+ },
1802
+ "layers": {"pad": 0.0, "bass": 0.20, "kick": 0.30, "hat": 0.40,
1803
+ "arp": 0.44, "melody": 0.48, "shine": 0.78},
1804
+ "voices": {"pad": "pad_saw", "bass": "pulse", "arp": "stab", "lead": "glock"},
1805
+ "lead_cycle": ("glock", "bell"),
1806
+ "drums": {
1807
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1808
+ "body": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (1.0, 3.0),
1809
+ "bass": "off8", "arp": 0.5},
1810
+ "drive": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1811
+ "bass": "16", "arp": 0.25},
1812
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1813
+ "bass": "16", "arp": 0.25},
1814
+ },
1815
+ "space": {"delay_beats": 0.5, "delay_db": -16.0, "taps": 3},
1816
+ "phrase_bars": 4,
1817
+ "duck": {"bass": 0.50, "pad": 0.32},
1818
+ "level_span_db": 9.0,
1819
+ "swing": 0.0,
1820
+ },
1821
+ # 极简黑白:只有必要的声音,长音、留白、钢片琴;慢速
1822
+ "mono": {
1823
+ "label": "极简黑白",
1824
+ "bpm_hint": (60, 64, 68),
1825
+ "keys": ("C", "F", "Am"),
1826
+ "progressions": {
1827
+ "calm": ("I", "IV", "I", "V"),
1828
+ "body": ("I", "IV", "V", "IV"),
1829
+ "drive": ("I", "IV", "V", "I"),
1830
+ },
1831
+ "motif": {
1832
+ "q": ((0.0, "I", 1.5), (1.5, "III", 1.5), (3.0, "V", 2.0),
1833
+ (6.0, "III", 1.0), (7.0, "V", 3.0)),
1834
+ "a": ((0.0, "V", 1.5), (1.5, "III", 1.5), (3.0, "I", 2.0),
1835
+ (6.0, "V", 1.0), (7.0, "I", 3.0)),
1836
+ "end": ((0.0, "V", 2.0), (2.0, "III", 1.5), (3.5, "I", 4.0)),
1837
+ },
1838
+ "layers": {"pad": 0.0, "bass": 0.34, "kick": 0.55, "hat": 0.70,
1839
+ "arp": 0.60, "melody": 0.25, "shine": 0.92},
1840
+ "voices": {"pad": "strings", "bass": "cello", "arp": "epiano", "lead": "celesta"},
1841
+ "lead_cycle": ("celesta", "bell"),
1842
+ "drums": {
1843
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1844
+ "body": {"kick": (0.0,), "hat": None, "clap": (), "bass": "whole", "arp": None},
1845
+ "drive": {"kick": (0.0, 2.0), "hat": 1.0, "clap": (), "bass": "half", "arp": 0.5},
1846
+ "climax": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (),
1847
+ "bass": "half", "arp": 0.5},
1848
+ },
1849
+ "space": {"delay_beats": 2.0, "delay_db": -20.0, "taps": 2},
1850
+ "phrase_bars": 8,
1851
+ "duck": {"bass": 0.30, "pad": 0.20},
1852
+ "level_span_db": 6.0,
1853
+ "swing": 0.0,
1854
+ },
1855
+ # 电影青橙:小调、弦乐铺底、大空间;安静到爆发跨度最大
1856
+ "cinema": {
1857
+ "label": "电影青橙",
1858
+ "bpm_hint": (76, 80, 84),
1859
+ "keys": ("Dm", "Am"),
1860
+ "progressions": {
1861
+ "calm": ("i", "VI", "III", "VII"),
1862
+ "body": ("i", "VII", "VI", "V"),
1863
+ "drive": ("i", "VI", "III", "VII"),
1864
+ },
1865
+ "motif": {
1866
+ "q": ((0.0, "i", 1.5), (1.5, "III", 1.0), (2.5, "iv", 2.0),
1867
+ (5.0, "III", 1.0), (6.0, "i", 3.0)),
1868
+ "a": ((0.0, "III", 1.5), (1.5, "VI", 1.0), (2.5, "VII", 2.0),
1869
+ (5.0, "v", 1.0), (6.0, "i", 3.0)),
1870
+ "end": ((0.0, "VI", 1.5), (1.5, "VII", 1.0), (2.5, "v", 1.5), (4.0, "i", 4.0)),
1871
+ },
1872
+ "layers": {"pad": 0.0, "bass": 0.26, "kick": 0.52, "hat": 0.68,
1873
+ "arp": 0.62, "melody": 0.30, "shine": 0.88},
1874
+ "voices": {"pad": "strings", "bass": "cello", "arp": "epiano",
1875
+ "lead": "strings_bell"},
1876
+ "lead_cycle": ("strings_bell", "celesta"),
1877
+ "drums": {
1878
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1879
+ "body": {"kick": (0.0,), "hat": None, "clap": (), "bass": "whole", "arp": None},
1880
+ "drive": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (), "bass": "half", "arp": 0.5},
1881
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1882
+ "bass": "off8", "arp": 0.25},
1883
+ },
1884
+ "space": {"delay_beats": 1.5, "delay_db": -14.0, "taps": 3},
1885
+ "phrase_bars": 8,
1886
+ "duck": {"bass": 0.40, "pad": 0.26},
1887
+ "level_span_db": 10.0,
1888
+ "swing": 0.0,
1889
+ },
1890
+ # 暖灰薄荷:lo-fi 摇摆、电钢、808 贝斯;轻鼓、留白
1891
+ "lo-fi": {
1892
+ "label": "暖灰薄荷",
1893
+ "bpm_hint": (72, 78, 84),
1894
+ "keys": ("C", "F", "G"),
1895
+ "progressions": {
1896
+ "calm": ("Imaj7", "vi7", "ii7", "V7"),
1897
+ "body": ("Imaj7", "IVmaj7", "iii7", "vi7"),
1898
+ "drive": ("ii7", "V7", "Imaj7", "IVmaj7"),
1899
+ },
1900
+ "motif": {
1901
+ "q": ((0.0, "III", 1.0), (1.0, "V", 1.0), (2.0, "VI", 1.0), (3.0, "V", 1.0),
1902
+ (4.0, "I", 1.0), (5.0, "ii", 1.0), (6.0, "III", 1.0), (7.0, "I", 2.0)),
1903
+ "a": ((0.0, "V", 1.0), (1.0, "VI", 1.0), (2.0, "V", 1.0), (3.0, "III", 1.0),
1904
+ (4.0, "ii", 1.0), (5.0, "III", 1.0), (6.0, "V", 1.0), (7.0, "I", 2.0)),
1905
+ "end": ((0.0, "V", 1.0), (1.0, "VI", 1.0), (2.0, "V", 1.0), (3.0, "I", 4.0)),
1906
+ },
1907
+ "layers": {"pad": 0.0, "bass": 0.24, "kick": 0.40, "hat": 0.48,
1908
+ "arp": 0.44, "melody": 0.32, "shine": 0.90},
1909
+ "voices": {"pad": "pad_saw", "bass": "sub", "arp": "epiano", "lead": "marimba"},
1910
+ "lead_cycle": ("marimba", "celesta"),
1911
+ "drums": {
1912
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1913
+ "body": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (), "bass": "half", "arp": 0.5},
1914
+ "drive": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (1.0, 3.0),
1915
+ "bass": "off8", "arp": 0.5},
1916
+ "climax": {"kick": (0.0, 2.0), "hat": 0.25, "clap": (1.0, 3.0),
1917
+ "bass": "off8", "arp": 0.25},
1918
+ },
1919
+ "space": {"delay_beats": 0.75, "delay_db": -16.0, "taps": 2},
1920
+ "phrase_bars": 4,
1921
+ "duck": {"bass": 0.38, "pad": 0.26},
1922
+ "level_span_db": 6.5,
1923
+ "swing": 0.12,
1924
+ },
1925
+ # 深黑鎏金:小调、铜管主奏、四四拍重击;动态跨度最大
1926
+ "epic": {
1927
+ "label": "深黑鎏金",
1928
+ "bpm_hint": (88, 92, 96),
1929
+ "keys": ("Cm", "Dm"),
1930
+ "progressions": {
1931
+ "calm": ("i", "VI", "iv", "V"),
1932
+ "body": ("i", "VI", "III", "VII"),
1933
+ "drive": ("i", "VII", "VI", "V"),
1934
+ },
1935
+ "motif": {
1936
+ "q": ((0.0, "i", 1.0), (1.0, "III", 1.0), (2.0, "v", 1.0), (3.0, "VI", 2.0),
1937
+ (5.0, "v", 1.0), (6.0, "i", 3.0)),
1938
+ "a": ((0.0, "v", 1.0), (1.0, "VI", 1.0), (2.0, "VII", 1.0), (3.0, "V", 2.0),
1939
+ (5.0, "VII", 1.0), (6.0, "i", 3.0)),
1940
+ "end": ((0.0, "VI", 1.5), (1.5, "VII", 1.0), (2.5, "v", 1.0), (3.5, "i", 4.0)),
1941
+ },
1942
+ "layers": {"pad": 0.0, "bass": 0.20, "kick": 0.32, "hat": 0.42,
1943
+ "arp": 0.50, "melody": 0.30, "shine": 0.80},
1944
+ "voices": {"pad": "strings", "bass": "cello", "arp": "stab", "lead": "brass"},
1945
+ "lead_cycle": ("brass", "strings_bell"),
1946
+ "drums": {
1947
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1948
+ "body": {"kick": (0.0, 2.0), "hat": 0.5, "clap": (), "bass": "half", "arp": 0.5},
1949
+ "drive": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1950
+ "bass": "16", "arp": 0.25},
1951
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1952
+ "bass": "16", "arp": 0.25},
1953
+ },
1954
+ "space": {"delay_beats": 0.75, "delay_db": -13.0, "taps": 3},
1955
+ "phrase_bars": 4,
1956
+ "duck": {"bass": 0.46, "pad": 0.34},
1957
+ "level_span_db": 11.0,
1958
+ "swing": 0.0,
1959
+ },
1960
+ # legacy:给 render_styled 用的"v0.4 近似包"(真实兼容路径不经过这里;
1961
+ # render(style=None) / render(style="legacy") 直接走老的 Score.render())
1962
+ "legacy": {
1963
+ "label": "v0.4 兼容",
1964
+ "bpm_hint": (120,),
1965
+ "keys": ("Dm", "Am", "Cm", "Em"),
1966
+ "progressions": {
1967
+ "calm": ("i", "VI", "iv", "v"),
1968
+ "body": ("i", "VI", "III", "VII"),
1969
+ "drive": ("i", "VII", "VI", "V"),
1970
+ },
1971
+ "motif": {
1972
+ "q": ((0.0, "i", 0.9), (1.0, "v", 0.9), (2.0, "I", 0.9), (3.0, "III", 1.8),
1973
+ (5.0, "i", 0.9), (6.0, "VII", 0.9), (7.0, "v", 1.6)),
1974
+ "a": ((0.0, "v", 0.9), (1.0, "i", 0.9), (2.0, "III", 0.9), (3.0, "iv", 0.9),
1975
+ (4.0, "v", 2.4)),
1976
+ "end": ((0.0, "v", 0.9), (1.0, "i", 0.9), (2.0, "III", 0.9), (3.0, "iv", 1.6),
1977
+ (5.0, "i", 3.0)),
1978
+ },
1979
+ "layers": {"pad": 0.0, "bass": 0.22, "kick": 0.34, "hat": 0.44,
1980
+ "arp": 0.55, "melody": 0.66, "shine": 0.82},
1981
+ "voices": {"pad": "pad_saw", "bass": "pulse", "arp": "fm", "lead": "bell"},
1982
+ "lead_cycle": ("bell", "celesta"),
1983
+ "drums": {
1984
+ "calm": {"kick": (), "hat": None, "clap": (), "bass": "whole", "arp": None},
1985
+ "body": {"kick": (0.0, 2.0), "hat": 1.0, "clap": (), "bass": "half", "arp": 0.5},
1986
+ "drive": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1987
+ "bass": "16", "arp": 0.25},
1988
+ "climax": {"kick": (0.0, 1.0, 2.0, 3.0), "hat": 0.25, "clap": (1.0, 3.0),
1989
+ "bass": "16", "arp": 0.25},
1990
+ },
1991
+ "space": {"delay_beats": 0.56, "delay_db": -15.0, "taps": 3},
1992
+ "phrase_bars": 4,
1993
+ "duck": {"bass": 0.42, "pad": 0.30},
1994
+ "level_span_db": 8.5,
1995
+ "swing": 0.0,
1996
+ },
1997
+ }
1998
+
1999
+ MUSIC_STYLE_IDS = tuple(MUSIC_STYLES)
2000
+ LEGACY_MUSIC_STYLE = "legacy"
2001
+
2002
+ # 情绪修饰:不改和弦功能,只改亮度 / 层数 / 鼓密度 / 主奏电平
2003
+ MOOD_IDS = ("steady", "calm", "reflective", "hopeful", "uplifting", "driving", "tense")
2004
+ _MOOD = {
2005
+ "steady": {"bright": 0.00, "layer": 0.00, "drum": 0.00, "lead_db": 0.0},
2006
+ "calm": {"bright": -0.18, "layer": 0.06, "drum": -0.06, "lead_db": -1.5},
2007
+ "reflective": {"bright": -0.12, "layer": 0.04, "drum": -0.04, "lead_db": -1.0},
2008
+ "hopeful": {"bright": 0.04, "layer": -0.02, "drum": 0.00, "lead_db": 0.5},
2009
+ "uplifting": {"bright": 0.14, "layer": -0.05, "drum": 0.05, "lead_db": 1.0},
2010
+ "driving": {"bright": 0.22, "layer": -0.07, "drum": 0.07, "lead_db": 1.2},
2011
+ "tense": {"bright": 0.02, "layer": 0.00, "drum": 0.03, "lead_db": 0.5},
2012
+ }
2013
+
2014
+ # 音色槽 -> 可选音色(实现见 _Bank 的 v0.5 方法;"fm" 复用老 FM 琶音)
2015
+ _STYLE_VOICES = {
2016
+ "pad": {"pad_saw": "pad", "strings": "strings"},
2017
+ "bass": {"pulse": "pulse", "cello": "cello", "sub": "sub"},
2018
+ "arp": {"pluck": "pluck", "epiano": "epiano", "stab": "stab", "fm": "fm"},
2019
+ "lead": {"bell": "bell", "celesta": "celesta", "marimba": "marimba",
2020
+ "glock": "glock", "strings_bell": "strings_bell", "brass": "brass",
2021
+ "epiano": "epiano"},
2022
+ }
2023
+
2024
+
2025
+ def _normalize_style_id(style):
2026
+ """None / "" / "legacy" -> None(走 v0.4 原路径);其余必须是 MUSIC_STYLES 的键。"""
2027
+ if style is None:
2028
+ return None
2029
+ sid = str(style).strip()
2030
+ if sid in ("", LEGACY_MUSIC_STYLE):
2031
+ return None
2032
+ _require(sid in MUSIC_STYLES, f"未知配乐风格 {style!r};可选:{'/'.join(MUSIC_STYLE_IDS)}")
2033
+ return sid
2034
+
2035
+
2036
+ def _styled_tier(energy: float) -> str:
2037
+ """风格化四档:calm / body / drive / climax(比 legacy 多一档,给 epic / vivid 用)。"""
2038
+ if energy < 0.40:
2039
+ return "calm"
2040
+ if energy < 0.70:
2041
+ return "body"
2042
+ if energy < 0.88:
2043
+ return "drive"
2044
+ return "climax"
2045
+
2046
+
2047
+ def _styled_layers(pack: dict, energy: float, mood: str) -> list:
2048
+ """按"层阈值 + mood 偏移"算本段出现的层;pad 恒在(配乐不能没有和声底)。"""
2049
+ m = _MOOD.get(mood, _MOOD["steady"])
2050
+ out = []
2051
+ for name in LAYER_ORDER:
2052
+ thr = float(pack["layers"][name])
2053
+ if name == "pad":
2054
+ out.append(name)
2055
+ continue
2056
+ if name == "bass":
2057
+ adj = 0.5 * m["layer"]
2058
+ elif name in ("kick", "hat"):
2059
+ adj = m["layer"] * 1.5 - m["drum"]
2060
+ else:
2061
+ adj = m["layer"]
2062
+ if energy >= max(0.0, thr + adj):
2063
+ out.append(name)
2064
+ return out
2065
+
2066
+
2067
+ # ---- v0.7 内容指纹变奏(references/audio-variation.md §3.3)----------------
2068
+ # v0.6 及以前指纹只进 seed(只改音色细节):同风格 / 同 bpm / 同调、只换内容指纹,
2069
+ # 两段配乐相关性 0.966 —— 因为和弦进行 / 动机 / 鼓型全写死。
2070
+ # v0.7 把指纹推到"结构层":和弦做每两小节一次的稳定替换、动机级数做 ±1 稳定偏移、
2071
+ # 鼓型加 ghost 落点。三处决策全部走 _hash_int(FNV-1a,跨进程稳定),所以
2072
+ # 同指纹逐采样一致、不同指纹稳定地不同;没有引入额外随机源(变奏全部由指纹决定)。
2073
+ _VARIATION_SALT = "v0.7"
2074
+
2075
+ # 和弦替换对:同根音、同三音,只在"三和弦 <-> 七和弦色彩"之间换(契约 §3.3 的替代级数集)
2076
+ _CHORD_SWAPS = {
2077
+ "minor": {"i": "i7", "i7": "i", "VI": "VI7", "VI7": "VI",
2078
+ "III": "III7", "III7": "III", "VII": "VII7", "VII7": "VII"},
2079
+ "major": {"I": "Imaj7", "Imaj7": "I", "IV": "IVmaj7", "IVmaj7": "IV"},
2080
+ }
2081
+
2082
+ # 动机级数邻接表:只走"调内级数"的上下各一级(只换级数,节奏 / 时值不动)。
2083
+ # 值是 ((下方级数, 八度偏移), (上方级数, 八度偏移));跨主音时八度偏移 ±1,
2084
+ # 否则 i 下行一级会变成高 10 个半音的 VII(旋律轮廓会翻掉)。
2085
+ _MOTIF_NEIGHBORS = {
2086
+ "minor": {
2087
+ "i": (("VII", -1), ("ii°", 0)), "ii°": (("i", 0), ("III", 0)),
2088
+ "III": (("ii°", 0), ("iv", 0)), "iv": (("III", 0), ("v", 0)),
2089
+ "v": (("iv", 0), ("VI", 0)), "V": (("iv", 0), ("VI", 0)),
2090
+ "VI": (("v", 0), ("VII", 0)), "VII": (("VI", 0), ("i", 1)),
2091
+ "I": (("VII", -1), ("ii°", 0)), "i7": (("VII", -1), ("ii°", 0)),
2092
+ },
2093
+ "major": {
2094
+ "I": (("vii", -1), ("ii", 0)), "vii": (("vi", 0), ("I", 1)),
2095
+ "ii": (("I", 0), ("iii", 0)), "iii": (("ii", 0), ("IV", 0)),
2096
+ "IV": (("iii", 0), ("V", 0)), "V": (("IV", 0), ("vi", 0)),
2097
+ "vi": (("V", 0), ("vii", 0)), "VI": (("V", 0), ("VII", 0)),
2098
+ "III": (("ii", 0), ("IV", 0)), "iv": (("iii", 0), ("V", 0)),
2099
+ "Imaj7": (("vii", -1), ("ii", 0)), "IVmaj7": (("iii", 0), ("V", 0)),
2100
+ },
2101
+ }
2102
+
2103
+ # 进行档位(按"安静 -> 推进"排);climax 复用 drive(v0.5 语义:高潮靠鼓与层数)
2104
+ _PROG_TIERS = ("calm", "body", "drive")
2105
+
2106
+
2107
+ def _styled_mode(pack: dict) -> str:
2108
+ """风格包是小调还是大调:看 progressions 的主和弦写法(i/i7 = 小调,I/Imaj7 = 大调)。
2109
+
2110
+ 调式只决定"替换对 / 级数邻接表"用哪一套;真正的调性仍由 key 决定,两者不改动。
2111
+ """
2112
+ degs = {str(d) for seq in pack["progressions"].values() for d in seq}
2113
+ return "minor" if (degs & {"i", "i7"}) else "major"
2114
+
2115
+
2116
+ def _styled_has_fp(fingerprint) -> str:
2117
+ """指纹归一化:None / "" -> ""(= 关掉全部结构变奏,与 v0.5 逐字节一致)。"""
2118
+ if fingerprint is None:
2119
+ return ""
2120
+ s = str(fingerprint)
2121
+ return s if s != "" else ""
2122
+
2123
+
2124
+ def _styled_progression(pack: dict, tier: str, mood: str, fingerprint=None) -> tuple:
2125
+ """取该 tier 的级数进行;climax 复用 drive(高潮靠鼓与层数,不靠换和弦)。
2126
+
2127
+ v0.7:给了指纹时,按指纹从该风格的 progressions 里另选一档(契约 §3.3)——
2128
+ 同一风格的两部片可以拿到不同的和弦功能顺序,但调式 / 音色 / 鼓型 / 段落结构不变。
2129
+ 偏移量对整部片只有一个(哈希里不带段落号),片内各段的进行关系因此仍然连贯;
2130
+ 无指纹 -> 与 v0.5 完全同一结果(只按能量档取)。
2131
+ """
2132
+ progs = pack["progressions"]
2133
+ key = tier if tier in progs else ("drive" if tier == "climax" else "body")
2134
+ fp = _styled_has_fp(fingerprint)
2135
+ tiers = [t for t in _PROG_TIERS if t in progs]
2136
+ if fp and tiers and tier != "climax": # climax 仍复用 drive(v0.5 语义:高潮靠鼓与层数)
2137
+ base = tiers.index(key) if key in tiers else min(1, len(tiers) - 1)
2138
+ off = _hash_int(_VARIATION_SALT, "tier", fp) % len(tiers)
2139
+ key = tiers[(base + off) % len(tiers)]
2140
+ return tuple(progs[key])
2141
+
2142
+
2143
+ def _styled_chord_rules(deg: str, j: int, nb: int, ph: int, tier: str,
2144
+ mood: str, is_last_sec: bool) -> str:
2145
+ """单小节的硬规则(与 v0.5 逐字同序):乐句末属和弦 -> mood 色彩 -> 片尾主和弦。
2146
+
2147
+ 单独拆出来是为了让"变奏前 / 变奏后"各跑一遍:替换是否真的落地、有没有被
2148
+ 硬规则吃掉(乐句末收 V、片尾落 I)都能算清楚,report 里的计数才是真数。
2149
+ """
2150
+ # 每两乐句收一次属和弦(制造张力,与 legacy 的写法同源)
2151
+ if j % ph == ph - 1 and (j // ph) % 2 == 1:
2152
+ deg = "V"
2153
+ # mood 色彩:hopeful 加 maj7 / sus2;tense 用 sus4 悬留
2154
+ if mood == "hopeful":
2155
+ if deg == "I":
2156
+ deg = "Imaj7"
2157
+ elif deg == "IV":
2158
+ deg = "IVmaj7"
2159
+ elif deg == "i":
2160
+ deg = "i7"
2161
+ elif j == 0 and tier == "calm":
2162
+ deg = "sus2"
2163
+ elif mood == "tense" and j % ph == ph - 2 and deg in ("i", "I"):
2164
+ deg = "sus4"
2165
+ # 片尾落主和弦(与 legacy 同口径:I = 皮卡迪三度 / 大调主)
2166
+ if is_last_sec and nb >= 2 and j >= nb - 2:
2167
+ deg = "I"
2168
+ return deg
2169
+
2170
+
2171
+ def _styled_chords(sec: dict, si: int, secs: list, prog: tuple, pack: dict, mood: str,
2172
+ fingerprint=None, mode: str = "minor") -> tuple:
2173
+ """一小节一个和弦:级数循环 + 乐句末收属和弦 + mood 色彩 + 片尾落 I。
2174
+
2175
+ v0.7:给了指纹时,**每两小节做一次稳定替换**(契约 §3.3):按指纹决定替换
2176
+ 块内第 1 小节还是第 2 小节,被选中的小节在 _CHORD_SWAPS 里换成同根音的七和弦
2177
+ 色彩(该小节级数不在替代集里就跳过)。替换先于硬规则执行,所以乐句末属和弦与
2178
+ 片尾主和弦永远不被改坏(契约的"只在不冲突时替换")。
2179
+ 返回 (和弦级数列表, 实际替换次数);无指纹时替换次数恒 0、列表与 v0.5 逐项一致。
2180
+ """
2181
+ nb = len(sec["bars"])
2182
+ ph = int(pack["phrase_bars"])
2183
+ tier = sec["tier"]
2184
+ is_last_sec = (si == len(secs) - 1)
2185
+ fp = _styled_has_fp(fingerprint)
2186
+ smap = _CHORD_SWAPS.get(mode, {})
2187
+ out = []
2188
+ swaps = 0
2189
+ for j in range(nb):
2190
+ base = prog[j % len(prog)]
2191
+ deg = _styled_chord_rules(base, j, nb, ph, tier, mood, is_last_sec)
2192
+ if fp and smap:
2193
+ # 每两小节一次稳定替换:按指纹决定替换块内第 1 还是第 2 小节
2194
+ # (该小节级数不在替代集里就跳过,不硬造不存在的替代级数)
2195
+ pick = _hash_int(_VARIATION_SALT, "chord", fp, si, j // 2) % 2
2196
+ if pick == (j % 2) and base in smap:
2197
+ alt = _styled_chord_rules(smap[base], j, nb, ph, tier, mood, is_last_sec)
2198
+ if alt != deg: # 被硬规则吃掉的替换不算一次替换
2199
+ deg = alt
2200
+ swaps += 1
2201
+ out.append(deg)
2202
+ return out, swaps
2203
+
2204
+
2205
+ def _styled_kick_ghost(cfg: dict, fp: str, si: int, j: int,
2206
+ fill_bar: bool, breath: bool):
2207
+ """按指纹给这一小节加一个 kick ghost 落点;返回落点(拍)或 None。
2208
+
2209
+ ghost 只落在 0.5 拍网格上、不与 cfg["kick"] 现有落点重合;fill / breath 小节
2210
+ 只允许落在 [0, 3) 拍内(那几个位置要留给鼓加花与呼吸,契约 §3.3)。
2211
+ 每小节最多一记,1/3 的小节不加 —— 否则"每小节都多一记"会变成另一种机械。
2212
+ """
2213
+ used = [float(x) for x in cfg.get("kick", ())]
2214
+ cand = []
2215
+ for k in range(int(round(BEATS_PER_BAR / 0.5))):
2216
+ pos = 0.5 * k
2217
+ if any(abs(pos - u) < 1e-9 for u in used):
2218
+ continue
2219
+ if (fill_bar or breath) and pos >= 3.0 - 1e-9:
2220
+ continue
2221
+ cand.append(pos)
2222
+ if not cand:
2223
+ return None
2224
+ h = _hash_int(_VARIATION_SALT, "ghost", fp, si, j)
2225
+ if h % 3 == 0:
2226
+ return None
2227
+ return cand[(h >> 3) % len(cand)]
2228
+
2229
+
2230
+ def _styled_clap_shift(fp: str, si: int, j: int, idx: int) -> float:
2231
+ """拍手位置的指纹位移:±0.5 拍(契约 §3.3);1/3 不动,保留原律动的稳定感。"""
2232
+ h = _hash_int(_VARIATION_SALT, "clap", fp, si, j, idx)
2233
+ m = h % 3
2234
+ return 0.0 if m == 2 else (0.5 if m == 0 else -0.5)
2235
+
2236
+
2237
+ def _styled_target_db(energy: float, span: float) -> float:
2238
+ """能量 -> 相对电平(dB)。span = 最安静段到最响段的电平跨度;
2239
+
2240
+ span=8.5 时与 legacy 的 energy_target_db() 完全同式:-8.5 * (1 - energy)。
2241
+ """
2242
+ return -float(span) * (1.0 - _clip01(energy))
2243
+
2244
+
2245
+ def _styled_swing_shift(swing: float, step: float, k: int) -> float:
2246
+ """摇摆:只延后"奇数细分"(不影响 RNG 调用次数,只改落点)。"""
2247
+ if swing <= 0.0 or step >= 1.0 or (k % 2) == 0:
2248
+ return 0.0
2249
+ return float(swing) * min(1.0, step / 0.5)
2250
+
2251
+
2252
+ def _degree_note(kval: dict, degree: str, octave: int = 4) -> str:
2253
+ """级数 -> 音名(相对主音,跨八度自动进位)。"""
2254
+ row = _DEGREE_BY_NAME[degree]
2255
+ return _semi_note(kval["root_pc"], int(octave), int(row[1]), kval["names"])
2256
+
2257
+
2258
+ def _check_voice(slot: str, voice: str) -> str:
2259
+ """校验风格音色名并返回内部实现名(未知音色直接报错,不静默回落)。"""
2260
+ table = _STYLE_VOICES[slot]
2261
+ _require(voice in table, f"风格音色 {slot}={voice!r} 未知;可选:{'/'.join(table)}")
2262
+ return table[voice]
2263
+
2264
+
2265
+ def _bass_texture(bank: "_Bank", voice: str, note: str, dur: float, bright: float) -> np.ndarray:
2266
+ if voice == "cello":
2267
+ return bank.cello(note, dur, bright)
2268
+ if voice == "sub":
2269
+ return bank.sub_bass(note, dur)
2270
+ return bank.pulse_bass(note, dur, bright)
2271
+
2272
+
2273
+ def _arp_texture(bank: "_Bank", voice: str, note: str, bright: float, dur: float = 0.3) -> np.ndarray:
2274
+ if voice == "pluck":
2275
+ return bank.pluck_note(note, dur, bright)
2276
+ if voice == "epiano":
2277
+ return bank.epiano(note, max(0.35, dur))
2278
+ if voice == "stab":
2279
+ return bank.stab(note, dur, bright)
2280
+ return bank.arp(note, bright, dur)
2281
+
2282
+
2283
+ def _lead_texture(bank: "_Bank", voice: str, note: str, dur: float, bright: float) -> np.ndarray:
2284
+ if voice == "celesta":
2285
+ return bank.celesta(note, max(2.8, dur))
2286
+ if voice == "marimba":
2287
+ return bank.marimba(note, max(0.6, dur))
2288
+ if voice == "glock":
2289
+ return bank.glock(note, max(0.5, dur))
2290
+ if voice == "strings_bell":
2291
+ return bank.strings_bell(note, max(1.2, dur))
2292
+ if voice == "brass":
2293
+ return bank.brass(note, max(0.5, dur), bright)
2294
+ if voice == "epiano":
2295
+ return bank.epiano(note, max(0.8, dur))
2296
+ return bank.bell(note, max(2.4, dur))
2297
+
2298
+
2299
+ def _styled_motif_shift(motif, kind: str, fingerprint, style: str, mode: str) -> tuple:
2300
+ """按指纹给动机的每个事件派生 ±1 级数偏移;返回 (事件列表, 偏移次数)。
2301
+
2302
+ 只改级数不改节奏:拍位与时值原样保留。偏移方向按 "指纹 + 风格 + 动机类型 + 事件序号"
2303
+ 哈希派生,所以问句(q) / 答句(a) / 片尾(end) **各自独立**(契约 §3.3 的"独立派生"):
2304
+ 同一部片里同种动机稳定,两部片不会同步变形(q 上移的片子 a 未必也上移)。
2305
+ 返回的事件是 (拍, 级数, 时值, 八度偏移):跨主音上行 / 下行时用八度偏移修正,
2306
+ 否则"小调 i 下行一级"会变成高 10 个半音的 VII,旋律轮廓会翻掉。
2307
+ """
2308
+ fp = _styled_has_fp(fingerprint)
2309
+ table = _MOTIF_NEIGHBORS.get(mode, {})
2310
+ if not fp or not table:
2311
+ return [(float(ev[0]), str(ev[1]), float(ev[2]), 0) for ev in motif], 0
2312
+ # 整句的偏移方向只由 "指纹 + 风格 + 动机类型" 决定(同种动机稳定),
2313
+ # 每个事件在±1 里取哪边由事件序号决定 —— q 与 a 的方向各自独立派生。
2314
+ up = _hash_int(_VARIATION_SALT, "motif-dir", fp, style, kind) % 2 == 1
2315
+ out = []
2316
+ shifted = 0
2317
+ for idx, ev in enumerate(motif):
2318
+ pos, deg, dur = float(ev[0]), str(ev[1]), float(ev[2])
2319
+ pair = table.get(deg)
2320
+ h = _hash_int(_VARIATION_SALT, "motif", fp, style, kind, idx)
2321
+ if pair is None: # 邻接表没收录的级数不动,绝不瞎编级数
2322
+ out.append((pos, deg, dur, 0))
2323
+ continue
2324
+ name, oct_delta = pair[1] if (up != bool(h % 2)) else pair[0]
2325
+ out.append((pos, name, dur, int(oct_delta)))
2326
+ shifted += 1
2327
+ return out, shifted
2328
+
2329
+
2330
+ def _emit_styled_motif(bus: "_Bus", bank: "_Bank", motif, kval: dict, voice: str,
2331
+ t0: float, beat: float, db: float, bright: float,
2332
+ fingerprint=None, style: str = "", kind: str = "",
2333
+ mode: str = "minor") -> int:
2334
+ """把风格动机铺到主奏总线:级数 -> 音名,乐器由 lead_cycle 指定。
2335
+
2336
+ v0.7:先按指纹做级数 ±1 偏移(_styled_motif_shift)再铺;返回被偏移的事件数,
2337
+ 供 report["variation"]["motif_shifts"] 审计。无指纹时偏移数恒 0、逐音与 v0.5 相同。
2338
+ """
2339
+ events, shifted = _styled_motif_shift(motif, kind, fingerprint, style, mode)
2340
+ for idx, ev in enumerate(events):
2341
+ pos_beats = float(ev[0])
2342
+ degree, dur_beats, oct_delta = str(ev[1]), float(ev[2]), int(ev[3])
2343
+ note = _degree_note(kval, degree, 4 + oct_delta)
2344
+ tex = _lead_texture(bank, voice, note, dur_beats * beat, bright)
2345
+ pan = 0.18 if idx % 2 == 0 else -0.18
2346
+ bus.add(tex, t0 + pos_beats * beat, db, pan)
2347
+ return shifted
2348
+
2349
+
2350
+ def _styled_gate_env(n: int, secs: list, present: list, bar: float, sr: int = SR) -> np.ndarray:
2351
+ """层进出门控:某层在相邻段缺席时,用 1 小节线性坡道渐入 / 渐出。"""
2352
+ env = np.ones(int(n), np.float32)
2353
+ L = max(2, _ns(bar, sr))
2354
+ nsec = len(secs)
2355
+ for si, sec in enumerate(secs):
2356
+ s = max(0, min(int(n), int(round(float(sec["start"]) * sr))))
2357
+ e = max(0, min(int(n), int(round(float(sec["end"]) * sr))))
2358
+ if e - s < 2:
2359
+ continue
2360
+ if not present[si]:
2361
+ env[s:e] = 0.0
2362
+ continue
2363
+ prev = present[si - 1] if si > 0 else present[si]
2364
+ nxt = present[si + 1] if si + 1 < nsec else present[si]
2365
+ if not prev:
2366
+ seg = env[s:min(e, s + L)]
2367
+ seg *= _f32(np.linspace(0.0, 1.0, len(seg)) ** 1.5)
2368
+ if not nxt:
2369
+ seg = env[max(s, e - L):e]
2370
+ seg *= _f32(np.linspace(1.0, 0.0, len(seg)) ** 1.5)
2371
+ return env
2372
+
2373
+
2374
+ def _styled_seed(seed: int, fingerprint, style: str, mood: str) -> int:
2375
+ """内容指纹 -> 音色细节 seed(只影响 v0.5 风格路径;legacy 不参与)。"""
2376
+ base = int(seed)
2377
+ if fingerprint is None or str(fingerprint) == "":
2378
+ return base
2379
+ h = _hash_int("v0.5", style, mood, str(fingerprint))
2380
+ return base * 1000 + (h % 1000)
2381
+
2382
+
2383
+ def _styled_params(style: str, bpm, key, mood, seed, music_plan) -> dict:
2384
+ """合并显式参数与 stylekit 的 music dict:plan 优先,显式参数只在 plan 缺项时兜底。
2385
+
2386
+ music_plan 可以是 resolve_script_style()["music"](推荐),也可以是整份 plan(含 music 子字典)。
2387
+ 缺省回退顺序:plan -> 显式参数 -> 风格包自带值(bpm_hint 中位 / 调池首个 / steady / 7)。
2388
+ """
2389
+ pack = MUSIC_STYLES[style]
2390
+ hint = pack["bpm_hint"]
2391
+ eff = {
2392
+ "bpm": None if bpm is None else float(bpm),
2393
+ "key": None if key is None else str(key),
2394
+ "mood": "steady" if mood is None else str(mood),
2395
+ "seed": 7 if seed is None else int(seed),
2396
+ }
2397
+ plan = music_plan
2398
+ if isinstance(plan, dict):
2399
+ if isinstance(plan.get("music"), dict):
2400
+ plan = plan["music"]
2401
+ if plan.get("bpm") not in (None, ""):
2402
+ eff["bpm"] = float(plan["bpm"])
2403
+ if plan.get("key") not in (None, ""):
2404
+ eff["key"] = str(plan["key"])
2405
+ if plan.get("mood") not in (None, ""):
2406
+ eff["mood"] = str(plan["mood"]).strip().lower() or "steady"
2407
+ # seed_effective 是 stylekit 已经掺过内容指纹的最终种子;没有就退回 seed
2408
+ for fld in ("seed_effective", "seed"):
2409
+ if plan.get(fld) is not None:
2410
+ try:
2411
+ eff["seed"] = abs(int(plan[fld]))
2412
+ break
2413
+ except (TypeError, ValueError):
2414
+ continue
2415
+ if eff["bpm"] is None:
2416
+ eff["bpm"] = float(hint[len(hint) // 2])
2417
+ if eff["key"] is None:
2418
+ eff["key"] = str(pack["keys"][0])
2419
+ eff["mood"] = str(eff["mood"] or "steady").strip().lower() or "steady"
2420
+ return eff
2421
+
2422
+
2423
+ def _apply_pace(blocks: list, pace) -> list:
2424
+ """按 pacing 的 min_dur + hold 把过碎的段落合并到下限(不改片长、不挪时间轴)。
2425
+
2426
+ stylekit 的 min_dur 是"一条字幕至少停留多久",hold 是"句末额外留白";
2427
+ 这里只用两者之和当"段落最短长度":太碎的锚点(例如 1 小节一个)会被并进前一段,
2428
+ 名字保留前一段,energy 取较高者(合并后的段要能代表最响的那一刻)。
2429
+ """
2430
+ if not pace or not isinstance(pace, dict) or not blocks:
2431
+ return blocks
2432
+ try:
2433
+ lo = float(pace.get("min_dur", 0.0)) + float(pace.get("hold", 0.0))
2434
+ except (TypeError, ValueError):
2435
+ return blocks
2436
+ if lo <= 0.0:
2437
+ return blocks
2438
+ out = [dict(blocks[0])]
2439
+ for b in blocks[1:]:
2440
+ prev = out[-1]
2441
+ if float(prev["end"]) - float(prev["start"]) < lo - 1e-9:
2442
+ prev["end"] = float(b["end"])
2443
+ prev["energy"] = max(float(prev["energy"]), float(b["energy"]))
2444
+ else:
2445
+ out.append(dict(b))
2446
+ while len(out) > 1 and (float(out[-1]["end"]) - float(out[-1]["start"])) < lo - 1e-9:
2447
+ last = out.pop()
2448
+ out[-1]["end"] = float(last["end"])
2449
+ out[-1]["energy"] = max(float(out[-1]["energy"]), float(last["energy"]))
2450
+ return out
2451
+
2452
+
2453
+ def render_styled(duration, *, style, bpm=None, key=None, mood=None, anchors=None,
2454
+ sections=None, seed=7, fingerprint=None, sucks=None,
2455
+ music_plan=None, pace=None) -> tuple:
2456
+ """按风格渲一条配乐(v0.5):返回 (samples, report)。
2457
+
2458
+ 与 render() 的区别只在"怎么写",对外保证相同:
2459
+ * 时长精确(ceil(duration*sr) 采样)、峰值 <= -1.5 dBFS、同 seed 逐样本一致;
2460
+ * 复用老 _Bank 的鼓组与 _Bus 总线,只新增音色方法,不重写任何老乐器;
2461
+ * 老路径(render(style=None) / "legacy")完全不受影响,逐样本与 v0.4 相同。
2462
+
2463
+ anchors / sections 语义与 render() 一致;mood 见 MOOD_IDS。
2464
+ fingerprint(v0.7):参与 seed 派生 + 结构层变奏(契约 §3.3)——和弦每两小节一次
2465
+ 七和弦色彩替换、按指纹选进行档、动机级数 ±1 稳定偏移、鼓型 ghost 落点 / clap 位移。
2466
+ None / "" 时三处变奏全部关闭,逐样本与 v0.5 相同;报告里的 variation 是这三项的计数。
2467
+
2468
+ music_plan:stylekit.resolve_script_style(script) 的 "music" 子字典(整份 plan 也接受)。
2469
+ 非 None 时 bpm / key / mood / seed 以它为准(优先级高于显式参数)——render.py 只需
2470
+ 传一个 dict,不必和两处默认值打架;显式参数退化成"plan 里没写时的缺省"。
2471
+ pace:stylekit 的 pacing dict(至少含 min_dur / hold)。只按"min_dur + hold"把过碎的段落
2472
+ 合并到下限,不改 anchors 时间轴、不改片长;没有 pacing 需求时传 None 即可。
2473
+
2474
+ 性能:styled 比 legacy 慢约 1.5~2.5x(多声部弦乐 + 新音色是主要成本);
2475
+ 本机实测 60 s 片 3~6 s、388 s 片约 20~40 s(legacy 60 s ≈ 2.4 s),属预期。
2476
+ """
2477
+ t_start = time.perf_counter()
2478
+ _require(style in MUSIC_STYLES, f"未知配乐风格 {style!r};可选:{'/'.join(MUSIC_STYLE_IDS)}")
2479
+ eff = _styled_params(style, bpm, key, mood, seed, music_plan)
2480
+ bpm, key, mood, seed = eff["bpm"], eff["key"], eff["mood"], eff["seed"]
2481
+ _require(mood in MOOD_IDS, f"未知情绪 {mood!r};可选:{'/'.join(MOOD_IDS)}")
2482
+ _require(isinstance(bpm, (int, float)) and math.isfinite(float(bpm)) and float(bpm) > 0.0,
2483
+ f"bpm 必须是有限正数,收到 {bpm!r}")
2484
+ _require(key in KEYS_ALL, f"未知调性 {key!r};可选:{'/'.join(KEYS_ALL)}")
2485
+ pack = MUSIC_STYLES[style]
2486
+ # v0.7:调式决定和弦替换对 / 级数邻接表用哪一套;fp_s 为空 = 全部结构变奏关闭
2487
+ mode = _styled_mode(pack)
2488
+ fp_s = _styled_has_fp(fingerprint)
2489
+ dur = float(duration)
2490
+ sr = SR
2491
+ sc = Score(duration, bpm=float(bpm), key=key, seed=int(seed))
2492
+ # _merge_sections 在没有 anchors/sections 时已经返回"全片",这里不要再补一段:
2493
+ # 补了会在非小节对齐的片长上多出一个 0.x 秒的重复段(legacy 路径保留该历史行为)。
2494
+ for s in _apply_pace(_merge_sections(anchors, sections, dur), pace):
2495
+ sc.section(s["name"], s["start"], s["end"], s["energy"])
2496
+ for t, db, d in (sucks or ()):
2497
+ sc.suck(t, db, d)
2498
+ plan = sc._build_plan()
2499
+ secs = plan["sections"]
2500
+ bar, beat = plan["bar_s"], plan["beat_s"]
2501
+ n = max(int(plan["n"]), int(math.ceil(dur * sr - 1e-9)))
2502
+ kval = sc.k
2503
+ seed_eff = _styled_seed(sc.seed, fingerprint, style, mood)
2504
+ bank = _Bank(seed_eff, beat, bar, sr)
2505
+
2506
+ m = _MOOD[mood]
2507
+ mood_bright = float(m["bright"])
2508
+ span = float(pack["level_span_db"])
2509
+ ph = int(pack["phrase_bars"])
2510
+ swing = float(pack["swing"])
2511
+ space = pack["space"]
2512
+
2513
+ # ---- 1) 段落规划:tier / 层 / 和弦 / 电平目标 ----
2514
+ # v0.7:指纹变奏计数(chord_swaps / motif_shifts / drum_ghosts)进 report["variation"]。
2515
+ # 无指纹时三处变奏全关、计数恒 0,和弦仍走 v0.5 那条"只按能量档取进行"的分支。
2516
+ chord_swaps = 0
2517
+ motif_shifts = 0
2518
+ drum_ghosts = 0
2519
+ for si, sec in enumerate(secs):
2520
+ e = sec["energy"]
2521
+ tier = _styled_tier(e)
2522
+ sec["tier"] = tier
2523
+ sec["layers"] = _styled_layers(pack, e, mood)
2524
+ prog = _styled_progression(pack, tier, mood, fingerprint)
2525
+ sec["chords"], n_swap = _styled_chords(sec, si, secs, prog, pack, mood,
2526
+ fingerprint, mode)
2527
+ chord_swaps += n_swap
2528
+ sec["target_db"] = round(_styled_target_db(e, span), 2)
2529
+ sec["target_lufs"] = round(BASE_LUFS + sec["target_db"], 1)
2530
+ sec["breath"] = {"calm": 2, "body": 1, "drive": 0, "climax": 0}[tier]
2531
+ present = {name: [name in s["layers"] for s in secs] for name in LAYER_ORDER}
2532
+ last_si = len(secs) - 1
2533
+
2534
+ master = np.zeros((n, 2), np.float32)
2535
+
2536
+ # ---- 2) 鼓:按 style["drums"][tier] 的 kick 落点 / hat 步长 / clap ----
2537
+ hits: list = []
2538
+ drums = _Bus(n, sr)
2539
+ drum_pres = [bool(s["layers"].count("kick") + s["layers"].count("hat")) for s in secs]
2540
+ for si, sec in enumerate(secs):
2541
+ e = sec["energy"]
2542
+ tier = sec["tier"]
2543
+ cfg = pack["drums"][tier]
2544
+ has_kick = "kick" in sec["layers"]
2545
+ has_hat = "hat" in sec["layers"]
2546
+ if not has_kick and not has_hat:
2547
+ continue
2548
+ nb = len(sec["bars"])
2549
+ bm = sec["breath"]
2550
+ kick_db = -12.0 + 7.5 * e + (1.0 if tier == "climax" else 0.0)
2551
+ hat_db = -20.0 + 8.0 * e - float(m["drum"]) * 4.0
2552
+ for j, bi in enumerate(sec["bars"]):
2553
+ t0 = bi * bar
2554
+ phrase_end = (j % ph == ph - 1) and nb >= ph
2555
+ fill_bar = (j == nb - 1) and (si < len(secs) - 1)
2556
+ breath = phrase_end and not fill_bar and bm > 0
2557
+ if has_kick:
2558
+ for kb in cfg.get("kick", ()):
2559
+ if (fill_bar and kb >= 3.0) or (breath and kb >= 3.0):
2560
+ continue
2561
+ accent = 1.5 if abs(kb) < 1e-9 else 0.0
2562
+ var = bank.kicks[(bi * 4 + int(round(kb))) % len(bank.kicks)]
2563
+ drums.add(var, t0 + kb * beat, kick_db + accent)
2564
+ hits.append((t0 + kb * beat, 0.28 + 0.22 * e))
2565
+ # v0.7:指纹再塞一记 ghost kick(0.5 拍网格、不与现有落点重复;见 _styled_kick_ghost)
2566
+ if fp_s:
2567
+ ghost_pos = _styled_kick_ghost(cfg, fp_s, si, j, fill_bar, breath)
2568
+ if ghost_pos is not None:
2569
+ gidx = (bi * 4 + int(round(ghost_pos * 2)) + 2) % len(bank.kicks)
2570
+ drums.add(bank.kicks[gidx], t0 + ghost_pos * beat, kick_db - 5.5)
2571
+ hits.append((t0 + ghost_pos * beat, 0.12 + 0.12 * e))
2572
+ drum_ghosts += 1
2573
+ if has_hat and cfg.get("hat"):
2574
+ step = float(cfg["hat"])
2575
+ total = int(round(BEATS_PER_BAR / step))
2576
+ for k in range(total):
2577
+ base_pos = k * step
2578
+ pos = base_pos + _styled_swing_shift(swing, step, k)
2579
+ if fill_bar and pos >= 3.0 - 1e-9:
2580
+ continue
2581
+ if breath and pos >= (3.0 if bm >= 2 else 3.5) - 1e-9:
2582
+ continue
2583
+ on_beat = abs(base_pos - round(base_pos)) < 1e-9
2584
+ ghost = 0.0 if on_beat else -2.5
2585
+ pan = 0.3 if k % 2 == 0 else -0.3
2586
+ var = bank.hats[(bi * 7 + k) % len(bank.hats)]
2587
+ drums.add(var, t0 + pos * beat, hat_db + ghost, pan)
2588
+ if has_hat and e >= 0.50 and cfg.get("clap"):
2589
+ for cidx, cb in enumerate(cfg.get("clap", ())):
2590
+ if phrase_end and cb >= 3.0:
2591
+ continue
2592
+ pos = float(cb)
2593
+ if fp_s:
2594
+ shift = _styled_clap_shift(fp_s, si, j, cidx)
2595
+ if shift and 0.0 <= pos + shift < float(BEATS_PER_BAR):
2596
+ pos += shift
2597
+ drum_ghosts += 1
2598
+ drums.add(bank.claps[(bi * 2 + int(round(pos))) % len(bank.claps)],
2599
+ t0 + pos * beat, -16.0 + 4.0 * e - 1.5 * float(m["drum"]), 0.08)
2600
+ if tier == "climax" and has_hat:
2601
+ for pos in (0.5, 1.5, 2.5, 3.5):
2602
+ if phrase_end and pos >= 3.5:
2603
+ continue
2604
+ drums.add(bank.hats_open[(bi + int(pos)) % len(bank.hats_open)],
2605
+ t0 + pos * beat, -21.0 + 3.0 * e, -0.2)
2606
+ if si > 0 and tier in ("drive", "climax") and has_kick:
2607
+ drums.add(bank.crashes[si % len(bank.crashes)], sec["start"],
2608
+ -10.0 + 2.0 * (1.0 - e))
2609
+ drums.add(bank.kick_big, sec["start"], -9.0)
2610
+ hits.append((sec["start"], 0.5))
2611
+ if tier == "climax":
2612
+ for j, bi in enumerate(sec["bars"]):
2613
+ if j > 0 and j % 8 == 0:
2614
+ drums.add(bank.crashes[(si + j) % len(bank.crashes)], bi * bar, -17.0)
2615
+ drums.buf *= _styled_gate_env(n, secs, drum_pres, bar, sr)[:, None]
2616
+ master += drums.buf
2617
+ drums.clear()
2618
+
2619
+ # ---- 3) 贝斯:型(whole/half/off8/16/dub)+ 风格音色 + 侧链避让 ----
2620
+ bass = _Bus(n, sr)
2621
+ bass_voice = _check_voice("bass", pack["voices"]["bass"])
2622
+ for si, sec in enumerate(secs):
2623
+ if not present["bass"][si]:
2624
+ continue
2625
+ e = sec["energy"]
2626
+ cfg = pack["drums"][sec["tier"]]
2627
+ pat = cfg.get("bass", "none")
2628
+ if pat == "none":
2629
+ continue
2630
+ bdb = -14.0 + 5.0 * e
2631
+ bright = _clip01(0.2 + 0.65 * e + 0.5 * mood_bright)
2632
+ nb = len(sec["bars"])
2633
+ bm = sec["breath"]
2634
+ k = 0
2635
+ for j, bi in enumerate(sec["bars"]):
2636
+ t0 = bi * bar
2637
+ chord = kval["chords"][sec["chords"][j]]
2638
+ root = chord["root"]
2639
+ phrase_end = (j % ph == ph - 1) and nb >= ph
2640
+ breath = phrase_end and bm >= 2
2641
+ if pat == "whole":
2642
+ bass.add(_bass_texture(bank, bass_voice, root, bar * 0.92, bright), t0, bdb)
2643
+ elif pat == "half":
2644
+ for pos, dd in ((0.0, 1.8), (2.0, 1.8)):
2645
+ if breath and pos >= 3.0:
2646
+ continue
2647
+ bass.add(_bass_texture(bank, bass_voice, root, dd * beat, bright),
2648
+ t0 + pos * beat, bdb)
2649
+ elif pat == "off8":
2650
+ for pos in (0.5, 1.5, 2.5, 3.5):
2651
+ if breath and pos >= 3.0:
2652
+ continue
2653
+ nt = _up(root, 1) if (k % 7 == 3) else root
2654
+ bass.add(_bass_texture(bank, bass_voice, nt, 0.42 * beat, bright),
2655
+ t0 + pos * beat, bdb)
2656
+ k += 1
2657
+ elif pat == "dub":
2658
+ bass.add(_bass_texture(bank, bass_voice, root, bar * 0.55, bright), t0, bdb - 1.0)
2659
+ if not breath:
2660
+ bass.add(_bass_texture(bank, bass_voice, _up(root, 1), bar * 0.30, bright),
2661
+ t0 + 2.5 * beat, bdb - 3.0)
2662
+ else: # "16":十六分切分
2663
+ for b in range(BEATS_PER_BAR):
2664
+ for off in (0.25, 0.5, 0.75):
2665
+ pos = b + off
2666
+ if breath and pos >= 3.0:
2667
+ continue
2668
+ nt = _up(root, 1) if (k % 11 == 7) else root
2669
+ bass.add(_bass_texture(bank, bass_voice, nt, 0.2 * beat, bright),
2670
+ t0 + pos * beat, bdb)
2671
+ k += 1
2672
+ bass.buf *= sc._duck_env(n, hits, depth=float(pack["duck"]["bass"]), tau=0.15)[:, None]
2673
+ bass.buf *= _styled_gate_env(n, secs, present["bass"], bar, sr)[:, None]
2674
+ master += bass.buf
2675
+ bass.clear()
2676
+
2677
+ # ---- 4) 铺底 pad / strings(受底鼓轻压;段落首小节慢起音;shine 叠高八度) ----
2678
+ pads = _Bus(n, sr)
2679
+ pad_voice = _check_voice("pad", pack["voices"]["pad"])
2680
+ attack_first = {"calm": 1.2, "body": 0.5, "drive": 0.24, "climax": 0.14}
2681
+ attack_next = {"calm": 0.42, "body": 0.14, "drive": 0.07, "climax": 0.05}
2682
+ for si, sec in enumerate(secs):
2683
+ if not present["pad"][si]:
2684
+ continue
2685
+ e = sec["energy"]
2686
+ tier = sec["tier"]
2687
+ pdb = -20.0 + 7.0 * e + 0.8 * mood_bright
2688
+ bright = _clip01(0.15 + 0.75 * e + mood_bright)
2689
+ for j, bi in enumerate(sec["bars"]):
2690
+ chord = kval["chords"][sec["chords"][j]]
2691
+ attack = attack_first[tier] if j == 0 else attack_next[tier]
2692
+ if pad_voice == "strings":
2693
+ tex = bank.strings(chord, bright, attack)
2694
+ else:
2695
+ tex = bank.pad(chord, bright, attack)
2696
+ pads.add(tex, bi * bar, pdb)
2697
+ if present["shine"][si]:
2698
+ pads.add(bank.pad(chord, _clip01(bright - 0.1), attack, octave=1),
2699
+ bi * bar, pdb - 6.0)
2700
+ pads.buf *= sc._duck_env(n, hits, depth=float(pack["duck"]["pad"]), tau=0.18)[:, None]
2701
+ pads.buf *= _styled_gate_env(n, secs, present["pad"], bar, sr)[:, None]
2702
+ master += pads.buf
2703
+ pads.clear()
2704
+
2705
+ # ---- 5) 琶音:步长来自 drums[arp],音色来自 voices[arp],带摇摆 ----
2706
+ keys = _Bus(n, sr)
2707
+ arp_voice = _check_voice("arp", pack["voices"]["arp"])
2708
+ for si, sec in enumerate(secs):
2709
+ if not present["arp"][si]:
2710
+ continue
2711
+ cfg = pack["drums"][sec["tier"]]
2712
+ step = cfg.get("arp")
2713
+ if not step:
2714
+ continue
2715
+ step = float(step)
2716
+ e = sec["energy"]
2717
+ adb = -25.0 + 8.0 * e + 0.5 * mood_bright
2718
+ bright = _clip01(0.25 + 0.6 * e + mood_bright)
2719
+ nb = len(sec["bars"])
2720
+ bm = sec["breath"]
2721
+ for j, bi in enumerate(sec["bars"]):
2722
+ t0 = bi * bar
2723
+ chord = kval["chords"][sec["chords"][j]]
2724
+ seq = [_up(nt, 2) for nt in chord["notes"]]
2725
+ seq = seq + seq[1:3][::-1]
2726
+ total = int(round(BEATS_PER_BAR / step))
2727
+ phrase_end = (j % ph == ph - 1) and nb >= ph
2728
+ breath = phrase_end and bm > 0
2729
+ for k in range(total):
2730
+ pos = k * step + _styled_swing_shift(swing, step, k)
2731
+ if breath and pos >= 3.0 - 1e-9:
2732
+ continue
2733
+ nt = seq[k % len(seq)]
2734
+ pan = 0.35 * math.sin(0.7 * k + 0.3 * j)
2735
+ keys.add(_arp_texture(bank, arp_voice, nt, bright, 0.3),
2736
+ t0 + pos * beat, adb, pan)
2737
+ keys.buf *= _styled_gate_env(n, secs, present["arp"], bar, sr)[:, None]
2738
+ master += keys.buf
2739
+ sc._add_delayed(master, keys.buf, float(space["delay_beats"]) * beat,
2740
+ float(space["delay_db"]), taps=int(space["taps"]), sr=sr)
2741
+ keys.clear()
2742
+
2743
+ # ---- 6) 主奏:motif + lead_cycle 每乐句轮换;片尾用 end 动机 ----
2744
+ lead = _Bus(n, sr)
2745
+ cycle = tuple(pack["lead_cycle"])
2746
+ phrase_i = 0
2747
+ lead_pres = list(present["melody"])
2748
+ if last_si >= 0 and secs[last_si]["energy"] >= 0.22:
2749
+ lead_pres[last_si] = True
2750
+ for si, sec in enumerate(secs):
2751
+ e = sec["energy"]
2752
+ nb = len(sec["bars"])
2753
+ if nb < 2:
2754
+ continue
2755
+ bright = _clip01(0.4 + 0.5 * e + mood_bright)
2756
+ if present["melody"][si]:
2757
+ mel_db = -17.0 + 4.0 * e + float(m["lead_db"])
2758
+ for pi, first in enumerate(range(0, nb, ph)):
2759
+ is_last_phrase = (si == last_si and pi == (nb - 1) // ph)
2760
+ if is_last_phrase:
2761
+ kind, motif = "end", pack["motif"]["end"]
2762
+ elif phrase_i % 2 == 0:
2763
+ kind, motif = "q", pack["motif"]["q"]
2764
+ else:
2765
+ kind, motif = "a", pack["motif"]["a"]
2766
+ voice = cycle[phrase_i % len(cycle)]
2767
+ t0 = sec["bars"][first] * bar
2768
+ motif_shifts += _emit_styled_motif(
2769
+ lead, bank, motif, kval, voice, t0, beat, mel_db, bright,
2770
+ fingerprint=fingerprint, style=style, kind=kind, mode=mode)
2771
+ phrase_i += 1
2772
+ elif si == last_si and e >= 0.22:
2773
+ # 片尾安静段:用第一个主奏音色把结局动机答完
2774
+ t_last = sec["bars"][0] * bar + max(0.0, (nb - 2) * bar)
2775
+ motif_shifts += _emit_styled_motif(
2776
+ lead, bank, pack["motif"]["end"], kval, cycle[0],
2777
+ t_last, beat, -19.0 + float(m["lead_db"]), bright,
2778
+ fingerprint=fingerprint, style=style, kind="end", mode=mode)
2779
+ lead.buf *= _styled_gate_env(n, secs, lead_pres, bar, sr)[:, None]
2780
+ master += lead.buf
2781
+ sc._add_delayed(master, lead.buf, float(space["delay_beats"]) * beat * 0.85,
2782
+ float(space["delay_db"]) - 3.0,
2783
+ taps=max(1, int(space["taps"]) - 1), sr=sr)
2784
+ lead.clear()
2785
+
2786
+ # ---- 7) shine:高音闪光(只在最亮的段出现) ----
2787
+ shine = _Bus(n, sr)
2788
+ for si, sec in enumerate(secs):
2789
+ if not present["shine"][si]:
2790
+ continue
2791
+ e = sec["energy"]
2792
+ sdb = -30.0 + 6.0 * e + 0.6 * mood_bright
2793
+ for j, bi in enumerate(sec["bars"]):
2794
+ chord = kval["chords"][sec["chords"][j]]
2795
+ hi = [_up(nt, 2) for nt in chord["notes"][1:3]]
2796
+ for q, pos in enumerate((0.5, 2.75)):
2797
+ shine.add(bank.glock(hi[(bi + q) % len(hi)], 0.9), bi * bar + pos * beat,
2798
+ sdb, 0.4 if q == 0 else -0.4)
2799
+ shine.buf *= _styled_gate_env(n, secs, present["shine"], bar, sr)[:, None]
2800
+ master += shine.buf
2801
+ shine.clear()
2802
+
2803
+ # ---- 8) 过门与效果(每个内部交界一小节) ----
2804
+ fx = _Bus(n, sr)
2805
+ for ti, tr in enumerate(plan["transitions"]):
2806
+ fill_start = tr["t"] - bar
2807
+ nxt_e = secs[ti + 1]["energy"]
2808
+ prev_e = secs[ti]["energy"]
2809
+ sixteenth = 0.25 * beat
2810
+ for k in range(int(round(bar / sixteenth))):
2811
+ p = k / max(1.0, (bar / sixteenth) - 1.0)
2812
+ tom = bank.toms[min(3, int(p * 4))]
2813
+ fx.add(tom, fill_start + k * sixteenth,
2814
+ -18.0 + 6.0 * p + (1.5 if k % 2 == 0 else 0.0), -0.35 + 0.7 * p)
2815
+ if p >= 0.6:
2816
+ fx.add(bank.snares[k % len(bank.snares)], fill_start + k * sixteenth,
2817
+ -20.0 + 5.0 * p, 0.1)
2818
+ fx.add(bank.swell(bar, ti, "styled"), fill_start, -15.0 + 2.0 * nxt_e)
2819
+ if nxt_e > prev_e + 0.10:
2820
+ fx.add(bank.riser(bar * 0.92, ti, "styled"), fill_start + bar * 0.08,
2821
+ -14.0 + 2.0 * nxt_e)
2822
+ if nxt_e >= 0.72:
2823
+ fx.add(bank.sub_boom(2.2, 55.0, 30.0), tr["t"], -9.0 - 2.0 * (1.0 - nxt_e))
2824
+ fx.add(bank.crashes[ti % len(bank.crashes)], tr["t"], -11.0)
2825
+ if nxt_e < prev_e - 0.15:
2826
+ fx.add(bank.crashes[(ti + 1) % len(bank.crashes)], tr["t"], -20.0)
2827
+ master += fx.buf
2828
+ fx.clear()
2829
+
2830
+ # ---- 9) 自动电平(段落间能量 -> dB 曲线)/ 吸气 / 去直流 / 淡入淡出 / 峰值 ----
2831
+ levels = sc._level_match(master, plan)
2832
+ sc._apply_sucks(master, plan["sucks"], sr)
2833
+ sc._de_dc(master)
2834
+ sc._apply_fades(master)
2835
+ peak = float(np.max(np.abs(master))) if n else 0.0
2836
+ if peak > 1e-9:
2837
+ master *= np.float32(_db_amp(TARGET_PEAK_DB) / peak)
2838
+ peak_db = float(20.0 * math.log10(max(float(np.max(np.abs(master))), 1e-12)))
2839
+ lufs = _approx_lufs(master, sr)
2840
+ dc = float(np.max(np.abs(master.mean(axis=0)))) if n else 0.0
2841
+ centroid = spectral_centroid(master, sr)
2842
+
2843
+ # ---- 10) 报告(version 2;字段与 legacy report 兼容,CLI 复用同一个格式化函数) ----
2844
+ rep = {
2845
+ "version": 2,
2846
+ "generator": "scorekit",
2847
+ "style": style,
2848
+ "style_label": str(pack.get("label", style)),
2849
+ "mood": mood,
2850
+ "bpm": round(float(bpm), 4),
2851
+ "bpm_hint": list(pack["bpm_hint"]),
2852
+ "key": key,
2853
+ "key_name": kval["name"],
2854
+ "key_in_style_pool": key in tuple(pack["keys"]),
2855
+ "sr": sr,
2856
+ "duration": round(dur, 3),
2857
+ "seed": int(sc.seed),
2858
+ "seed_effective": int(seed_eff),
2859
+ "fingerprint": "" if fingerprint is None else str(fingerprint),
2860
+ # v0.7:指纹变奏的实际发生数(审计用;无指纹时三项目全 0)
2861
+ "variation": {"chord_swaps": int(chord_swaps),
2862
+ "motif_shifts": int(motif_shifts),
2863
+ "drum_ghosts": int(drum_ghosts)},
2864
+ "bar_s": round(bar, 4),
2865
+ "beat_s": round(beat, 4),
2866
+ "phrase_bars": ph,
2867
+ "since": "v0.5",
2868
+ "sections": [
2869
+ {"name": s["name"], "start": round(s["start"], 3), "end": round(s["end"], 3),
2870
+ "energy": round(s["energy"], 3), "tier": s["tier"], "bars": len(s["bars"]),
2871
+ "target_db": round(s["target_db"], 2), "target_lufs": round(s["target_lufs"], 1),
2872
+ "layers": list(s["layers"]), "chords": list(s["chords"])}
2873
+ for s in secs
2874
+ ],
2875
+ "transitions": [dict(t) for t in plan["transitions"]],
2876
+ "sucks": [dict(d) for d in plan["sucks"]],
2877
+ "beats": list(plan["beats"]),
2878
+ "peak_dbfs": round(peak_db, 2),
2879
+ "lufs_approx": round(lufs, 1),
2880
+ "dc_max": round(dc, 9),
2881
+ "spectral_centroid_hz": round(centroid, 1),
2882
+ "render_s": round(time.perf_counter() - t_start, 3),
2883
+ "measured_sections": [
2884
+ {"name": s["name"], "start": round(s["start"], 3), "end": round(s["end"], 3),
2885
+ "energy": round(s["energy"], 3), "gain_db": round(lv["gain"], 2),
2886
+ "measured_db": round(lv["after"], 2)}
2887
+ for s, lv in zip(secs, levels)
2888
+ ],
2889
+ }
2890
+ return master, rep
2891
+
2892
+
2893
+ def spectral_centroid(x, sr: int = SR) -> float:
2894
+ """频谱质心(Hz):粗略量"亮度",用于验证不同风格不是同一首曲子。
2895
+
2896
+ 单声道下混 -> 去均值 -> 分块 rFFT -> 幅度加权平均频率。确定性、无随机、无三方依赖。
2897
+ """
2898
+ a = np.asarray(x)
2899
+ if a.ndim == 2:
2900
+ mono = a.astype(np.float64).mean(axis=1)
2901
+ else:
2902
+ mono = a.astype(np.float64).ravel()
2903
+ if len(mono) < 1024:
2904
+ return 0.0
2905
+ blk = 16384 if len(mono) >= 16384 else 1024
2906
+ hop = max(1, blk // 2)
2907
+ win = np.hanning(blk)
2908
+ freqs = np.fft.rfftfreq(blk, 1.0 / float(sr))
2909
+ acc_m = 0.0
2910
+ acc_p = 0.0
2911
+ for s in range(0, len(mono) - blk + 1, hop):
2912
+ seg = mono[s:s + blk]
2913
+ seg = seg - float(seg.mean())
2914
+ mag = np.abs(np.fft.rfft(seg * win))
2915
+ acc_m += float(np.dot(freqs, mag))
2916
+ acc_p += float(mag.sum())
2917
+ if acc_p <= 1e-12:
2918
+ return 0.0
2919
+ return float(acc_m / acc_p)
2920
+
2921
+
2922
+ def _music_style_lint() -> list:
2923
+ """风格表体检:返回问题列表(空 = 过)。selftest 第 17 条调用。"""
2924
+ bad: list = []
2925
+ need = ("bpm_hint", "keys", "progressions", "motif", "layers", "voices",
2926
+ "lead_cycle", "drums", "space", "phrase_bars", "duck",
2927
+ "level_span_db", "swing")
2928
+ for sid, pack in MUSIC_STYLES.items():
2929
+ missing = [fld for fld in need if fld not in pack]
2930
+ if missing:
2931
+ bad.append(f"{sid}: 缺字段 {'/'.join(missing)}")
2932
+ continue
2933
+ if not pack["bpm_hint"]:
2934
+ bad.append(f"{sid}: bpm_hint 为空")
2935
+ for kk in pack["keys"]:
2936
+ if kk not in KEYS_ALL:
2937
+ bad.append(f"{sid}: 调 {kk} 不在 KEYS_ALL")
2938
+ for tier in ("calm", "body", "drive"):
2939
+ if tier not in pack["progressions"]:
2940
+ bad.append(f"{sid}: progressions 缺 {tier}")
2941
+ continue
2942
+ for deg in pack["progressions"][tier]:
2943
+ if deg not in _DEGREE_BY_NAME:
2944
+ bad.append(f"{sid}.{tier}: 级数 {deg} 不存在")
2945
+ for mt in ("q", "a", "end"):
2946
+ if mt not in pack["motif"]:
2947
+ bad.append(f"{sid}: motif 缺 {mt}")
2948
+ continue
2949
+ for idx, ev in enumerate(pack["motif"][mt]):
2950
+ if len(ev) != 3:
2951
+ bad.append(f"{sid}.{mt}[{idx}]: 必须是 (拍, 级数, 时值拍)")
2952
+ continue
2953
+ if str(ev[1]) not in _DEGREE_BY_NAME:
2954
+ bad.append(f"{sid}.{mt}[{idx}]: 级数 {ev[1]} 不存在")
2955
+ if float(ev[2]) <= 0.0:
2956
+ bad.append(f"{sid}.{mt}[{idx}]: 时值必须 > 0")
2957
+ for slot in ("pad", "bass", "arp", "lead"):
2958
+ if pack["voices"].get(slot) not in _STYLE_VOICES[slot]:
2959
+ bad.append(f"{sid}.voices.{slot}={pack['voices'].get(slot)!r} 未知")
2960
+ for voice in pack["lead_cycle"]:
2961
+ if voice not in _STYLE_VOICES["lead"]:
2962
+ bad.append(f"{sid}.lead_cycle: 音色 {voice!r} 未知")
2963
+ for tier in ("calm", "body", "drive", "climax"):
2964
+ cfg = pack["drums"].get(tier) or {}
2965
+ if not cfg:
2966
+ bad.append(f"{sid}.drums: 缺 {tier}")
2967
+ continue
2968
+ for kb in cfg.get("kick", ()):
2969
+ if not (0.0 <= float(kb) < BEATS_PER_BAR):
2970
+ bad.append(f"{sid}.drums.{tier}: kick {kb} 越界")
2971
+ for cb in cfg.get("clap", ()):
2972
+ if not (0.0 <= float(cb) < BEATS_PER_BAR):
2973
+ bad.append(f"{sid}.drums.{tier}: clap {cb} 越界")
2974
+ hs = cfg.get("hat", None)
2975
+ if hs is not None and not (0.20 <= float(hs) <= 2.0):
2976
+ bad.append(f"{sid}.drums.{tier}: hat {hs} 不合理")
2977
+ if cfg.get("bass", "none") not in ("none", "whole", "half", "off8", "16", "dub"):
2978
+ bad.append(f"{sid}.drums.{tier}: bass 型 {cfg.get('bass')!r} 未知")
2979
+ asp = cfg.get("arp", None)
2980
+ if asp is not None and not (0.2 <= float(asp) <= 2.0):
2981
+ bad.append(f"{sid}.drums.{tier}: arp {asp} 不合理")
2982
+ if int(pack["phrase_bars"]) not in (4, 8):
2983
+ bad.append(f"{sid}: phrase_bars 只能是 4/8")
2984
+ if not (float(pack["level_span_db"]) > 0.0):
2985
+ bad.append(f"{sid}: level_span_db 必须 > 0")
2986
+ if not (0.0 <= float(pack["swing"]) <= 0.2):
2987
+ bad.append(f"{sid}: swing 必须 0~0.2")
2988
+ for fld in ("bass", "pad"):
2989
+ d = float(pack["duck"].get(fld, 0.0))
2990
+ if not (0.0 <= d < 0.9):
2991
+ bad.append(f"{sid}: duck.{fld}={d} 不合理")
2992
+ if float(pack["layers"].get("pad", 1.0)) > 1e-9:
2993
+ bad.append(f"{sid}: layers.pad 必须是 0.0")
2994
+ for nm in LAYER_ORDER:
2995
+ if nm not in pack["layers"]:
2996
+ bad.append(f"{sid}: layers 缺 {nm}")
2997
+ sp = pack["space"]
2998
+ if not (0.0 < float(sp.get("delay_beats", 0.0)) <= 4.0):
2999
+ bad.append(f"{sid}: space.delay_beats 必须 0~4 拍")
3000
+ if int(sp.get("taps", 0)) < 1:
3001
+ bad.append(f"{sid}: space.taps 必须 >= 1")
3002
+ return bad
3003
+
3004
+
3005
+ def _stylekit_crosscheck() -> list:
3006
+ """同目录有 stylekit.py 时交叉核对风格 id 与调池;没有就静默跳过(不算失败)。"""
3007
+ try:
3008
+ import stylekit as ST # noqa: F401
3009
+ except Exception: # noqa: BLE001
3010
+ return []
3011
+ bad: list = []
3012
+ for sid in MUSIC_STYLE_IDS:
3013
+ if sid == LEGACY_MUSIC_STYLE:
3014
+ continue
3015
+ if sid not in ST.STYLES:
3016
+ bad.append(f"stylekit 缺风格 {sid}")
3017
+ continue
3018
+ want = tuple(ST.STYLES[sid]["music"]["keys"])
3019
+ got = tuple(MUSIC_STYLES[sid]["keys"])
3020
+ if want != got:
3021
+ bad.append(f"{sid}: 调池不一致 {got} != {want}")
3022
+ return bad
3023
+
3024
+
3025
+ def _stylekit_available() -> bool:
3026
+ """同目录是否有可导入的 stylekit(没有就跳过交叉核对,不判失败)。"""
3027
+ try:
3028
+ import stylekit # noqa: F401
3029
+ return True
3030
+ except Exception: # noqa: BLE001
3031
+ return False
3032
+
1361
3033
  # ============================================================================
1362
3034
  # 模块级便捷函数
1363
3035
  # ============================================================================
@@ -1431,12 +3103,23 @@ def _merge_sections(anchors, sections, duration: float) -> list:
1431
3103
 
1432
3104
 
1433
3105
  def render(duration, bpm: float = 120.0, key: str = "Dm", anchors=None, sections=None,
1434
- seed: int = 7) -> tuple:
3106
+ seed: int = 7, style=None, mood: str = "steady", fingerprint=None,
3107
+ music_plan=None, pace=None) -> tuple:
1435
3108
  """一次性接口:合成整片配乐,返回 (samples, report)。
1436
3109
 
1437
3110
  anchors:timeline.json 的 [{id,kind,start,end}](自动按 kind 映射能量分段);
1438
3111
  sections:显式段落(绝对时间或 at 引用),在 anchors 之后追加/覆盖空隙。
3112
+
3113
+ v0.5:style=None / "legacy" 走 v0.4 原路径(逐样本与旧版一致;style/mood/fingerprint/
3114
+ music_plan/pace 全部忽略);其余 style(MUSIC_STYLE_IDS 里的 8 个)走 render_styled()。
3115
+ music_plan / pace 的语义见 render_styled:music_plan 非 None 时覆盖 bpm/key/mood/seed。
1439
3116
  """
3117
+ sid = _normalize_style_id(style)
3118
+ if sid is not None:
3119
+ return render_styled(duration, style=sid, bpm=bpm, key=key, mood=mood,
3120
+ anchors=anchors, sections=sections, seed=seed,
3121
+ fingerprint=fingerprint, music_plan=music_plan, pace=pace)
3122
+ # ---- 以下与 v0.4 一字不差:legacy 逐字节兼容是硬契约,别在这段里改任何东西 ----
1440
3123
  sc = Score(duration, bpm=bpm, key=key, seed=seed)
1441
3124
  for s in _merge_sections(anchors, sections, float(duration)):
1442
3125
  sc.section(s["name"], s["start"], s["end"], s["energy"])
@@ -1449,6 +3132,12 @@ def save(path, x, sr: int = SR) -> Path:
1449
3132
  """把配乐写成 24-bit PCM WAV(通道数自适应;峰值由 render 保证 ≤ -1 dBFS)。"""
1450
3133
  path = Path(path)
1451
3134
  arr = np.asarray(x)
3135
+ if arr.size and not np.all(np.isfinite(arr)):
3136
+ # NaN 经 np.rint(...).astype(np.int32) 会落到 INT_MIN(不是 0),24-bit 写出后是
3137
+ # 满幅负样本 —— 成片里一声爆响,且没有任何报错。与 filmkit.wav_write 同口径:报错。
3138
+ bad = int(arr.size - np.count_nonzero(np.isfinite(arr)))
3139
+ raise ValueError("scorekit.save: 采样里有 %d 个 NaN/Inf(%s)——配乐渲染有数值错误,"
3140
+ "拒绝写出损坏的 WAV" % (bad, path))
1452
3141
  if arr.ndim == 1:
1453
3142
  arr = np.stack([arr, arr], axis=1)
1454
3143
  _require(arr.ndim == 2 and arr.shape[1] in (1, 2), f"只支持单/双声道,收到 shape={arr.shape}")
@@ -1756,6 +3445,125 @@ def selftest() -> int:
1756
3445
  check("16. 集成形态:anchors+sections 同起点覆盖 / 无 end 自动补到片尾", ok_it,
1757
3446
  " | ".join(f"{b['name']}:{b['start']}-{b['end']}:e{b['energy']}" for b in merged))
1758
3447
 
3448
+ # 17) v0.5 配乐风格表完整性(9 风格;级数存在;调池在 KEYS_ALL;与 stylekit 交叉核对)
3449
+ lint_bad = _music_style_lint()
3450
+ cross_bad = _stylekit_crosscheck()
3451
+ check("17. 配乐风格表完整(9 风格 / 级数存在 / 调池在 KEYS_ALL)",
3452
+ not (lint_bad or cross_bad),
3453
+ "; ".join((lint_bad + cross_bad)[:3]) if (lint_bad or cross_bad)
3454
+ else f"{len(MUSIC_STYLES)} 风格,{len(_DEGREE_BY_NAME)} 个级数"
3455
+ + (";stylekit 调池一致" if _stylekit_available() else ";无 stylekit 可交叉核对"))
3456
+
3457
+ # 18) v0.5 大调 & 七和弦表(KEYS 仍是 v0.4 的 4 个小调)
3458
+ bad_major = []
3459
+ for kname, kv in KEYS_MAJOR.items():
3460
+ for deg in ("I", "ii", "iii", "IV", "V", "vi", "vii", "sus4",
3461
+ "Imaj7", "ii7", "iii7", "IVmaj7", "V7", "vi7", "i7"):
3462
+ if deg not in kv["chords"]:
3463
+ bad_major.append(f"{kname}.{deg} 缺失")
3464
+ for chord in kv["chords"].values():
3465
+ for nt in chord["notes"] + [chord["root"]]:
3466
+ if not _NOTE_RE.match(nt) or S.hz(nt) <= 0:
3467
+ bad_major.append(f"{kname}: 非法音名 {nt!r}")
3468
+ ok_major = ((not bad_major) and set(KEYS) == {"Dm", "Am", "Cm", "Em"}
3469
+ and len(KEYS_ALL) == len(KEYS) + len(KEYS_MAJOR) == 10)
3470
+ check("18. 大调 6 个 & 七和弦级数(KEYS 仍是 4 个小调)", ok_major,
3471
+ "; ".join(bad_major[:3]) if bad_major
3472
+ else f"{len(KEYS_ALL)} 个调,{len(KEYS_ALL['C']['chords'])} 个级数/调")
3473
+
3474
+ # 19) v0.5 逐风格 6 s 渲染:时长精确 / 有限值 / 峰值 / 同 seed 一致 / 风格间 PCM 不全等
3475
+ t_styled = time.perf_counter()
3476
+ style_ids = [sid for sid in MUSIC_STYLE_IDS if sid != LEGACY_MUSIC_STYLE]
3477
+ pcm = {}
3478
+ peaks = {}
3479
+ bad_style = []
3480
+ for sid in style_ids:
3481
+ pk = MUSIC_STYLES[sid]
3482
+ hint = pk["bpm_hint"]
3483
+ bpm_s = float(hint[len(hint) // 2])
3484
+ key_s = str(pk["keys"][0])
3485
+ try:
3486
+ x1, r1 = render_styled(6.0, style=sid, bpm=bpm_s, key=key_s, seed=7)
3487
+ x2, _r2 = render_styled(6.0, style=sid, bpm=bpm_s, key=key_s, seed=7)
3488
+ except Exception as exc: # 自测里也要报原因,不吞异常
3489
+ bad_style.append(f"{sid}: {type(exc).__name__}: {exc}")
3490
+ continue
3491
+ want_n = int(math.ceil(6.0 * SR - 1e-9))
3492
+ if x1.shape != (want_n, 2) or not bool(np.all(np.isfinite(x1))):
3493
+ bad_style.append(f"{sid}: shape={x1.shape} 或含非有限值")
3494
+ if not np.array_equal(x1, x2):
3495
+ bad_style.append(f"{sid}: 同 seed 两次不一致")
3496
+ peaks[sid] = 20.0 * math.log10(max(float(np.max(np.abs(x1))), 1e-12))
3497
+ if not (-3.5 <= peaks[sid] <= -1.0):
3498
+ bad_style.append(f"{sid}: 峰值 {peaks[sid]:.2f} dBFS 越界")
3499
+ if r1.get("version") != 2 or r1.get("style") != sid or "sections" not in r1:
3500
+ bad_style.append(f"{sid}: report 结构不对")
3501
+ pcm[sid] = x1
3502
+ same_pairs = []
3503
+ ids_ok = list(pcm)
3504
+ for i in range(len(ids_ok)):
3505
+ for j in range(i + 1, len(ids_ok)):
3506
+ if np.array_equal(pcm[ids_ok[i]], pcm[ids_ok[j]]):
3507
+ same_pairs.append(f"{ids_ok[i]}=={ids_ok[j]}")
3508
+ cen = {sid: spectral_centroid(x, SR) for sid, x in pcm.items()}
3509
+ spread = (max(cen.values()) - min(cen.values())) if cen else 0.0
3510
+
3511
+ # 19b) stylekit 的 music_plan 优先级:plan 里的 bpm/key/mood/seed 必须盖过显式参数
3512
+ plan_used = {"bpm": 123.0, "key": "A", "mood": "uplifting", "seed": 42,
3513
+ "seed_effective": 424242}
3514
+ try:
3515
+ _xp, rp = render_styled(4.0, style="vivid", bpm=90.0, key="D", mood="calm", seed=1,
3516
+ music_plan={"music": plan_used})
3517
+ ok_plan = (rp.get("bpm") == 123.0 and rp.get("key") == "A"
3518
+ and rp.get("mood") == "uplifting" and rp.get("seed_effective") == 424242)
3519
+ plan_detail = (f"plan -> {rp.get('bpm')}/{rp.get('key')}/{rp.get('mood')}/"
3520
+ f"seed {rp.get('seed_effective')}")
3521
+ except Exception as exc: # 自测里也要报原因
3522
+ ok_plan = False
3523
+ plan_detail = f"{type(exc).__name__}: {exc}"
3524
+
3525
+ # 19c) pace:min_dur+hold 只合并过碎段落,不改片长 / 时间轴
3526
+ stale_blocks = [
3527
+ {"name": "碎1", "start": 0.0, "end": 2.0, "energy": 0.3},
3528
+ {"name": "碎2", "start": 2.0, "end": 4.0, "energy": 0.6},
3529
+ {"name": "长", "start": 4.0, "end": 12.0, "energy": 0.5},
3530
+ ]
3531
+ paced = _apply_pace(stale_blocks, {"min_dur": 3.2, "hold": 0.2})
3532
+ ok_pace = (len(paced) == 2 and abs(paced[0]["end"] - 4.0) < 1e-9
3533
+ and abs(paced[0]["energy"] - 0.6) < 1e-9
3534
+ and abs(paced[-1]["start"] - 4.0) < 1e-9
3535
+ and abs(paced[-1]["end"] - 12.0) < 1e-9)
3536
+ try:
3537
+ xpace, rpace = render_styled(
3538
+ 6.0, style="vivid", bpm=126, key="D", seed=7,
3539
+ anchors=[{"id": "p%d" % i, "kind": "body", "start": i * 0.75,
3540
+ "end": (i + 1) * 0.75} for i in range(8)],
3541
+ pace={"min_dur": 3.0, "hold": 0.30})
3542
+ ok_pace = ok_pace and xpace.shape == (int(math.ceil(6.0 * SR - 1e-9)), 2)
3543
+ pace_detail = f"索引 {len(paced)} 段;6 s 片仍 {xpace.shape[0]} 采样,{len(rpace['sections'])} 段"
3544
+ except Exception as exc:
3545
+ ok_pace = False
3546
+ pace_detail = f"{type(exc).__name__}: {exc}"
3547
+
3548
+ ok_styled = ((not bad_style) and (not same_pairs) and len(pcm) == len(style_ids)
3549
+ and spread >= 100.0 and ok_plan and ok_pace)
3550
+ check("19. 8 风格各渲 6 s:时长/有限值/峰值/确定性/两两 PCM 不全等", ok_styled,
3551
+ ("; ".join((bad_style + same_pairs)[:3]) if (bad_style or same_pairs)
3552
+ else f"{len(pcm)} 风格,{time.perf_counter() - t_styled:.1f} s;"
3553
+ f"频谱质心 {min(cen.values()):.0f}~{max(cen.values()):.0f} Hz(跨度 {spread:.0f});"
3554
+ f"{plan_detail};{pace_detail}"))
3555
+
3556
+ # 20) v0.5 legacy 兼容:style=None / "legacy" / 任意 mood 都走 v0.4 原路径,逐样本一致
3557
+ xn, rn = render(6.0, bpm=120, key="Dm", seed=7)
3558
+ xl, rl = render(6.0, bpm=120, key="Dm", seed=7, style="legacy")
3559
+ xm, _rm = render(6.0, bpm=120, key="Dm", seed=7, style=None, mood="driving",
3560
+ fingerprint="whatever")
3561
+ rn_c = {k: v for k, v in rn.items() if k != "render_s"}
3562
+ rl_c = {k: v for k, v in rl.items() if k != "render_s"}
3563
+ ok_legacy = (np.array_equal(xn, xl) and np.array_equal(xn, xm) and rn_c == rl_c
3564
+ and rn.get("version") == 1)
3565
+ check("20. legacy 兼容:style=None / 'legacy' / 任意 mood+fingerprint 逐样本一致", ok_legacy,
3566
+ f"shape={xn.shape},version={rn.get('version')}")
1759
3567
  total = time.perf_counter() - t_all
1760
3568
  passed = sum(1 for _, ok, _ in rows if ok)
1761
3569
  failed = len(rows) - passed
@@ -1810,12 +3618,36 @@ def _parse_suck_list(items) -> list:
1810
3618
  return out
1811
3619
 
1812
3620
 
3621
+ def _format_style_list() -> str:
3622
+ """CLI --list-styles:列可用配乐风格(bpm_hint / 调池 / 主奏音色 / 乐句长度)。"""
3623
+ lines = ["可用配乐风格(--style;缺省 legacy = v0.4 逐样本兼容):"]
3624
+ for sid, pack in MUSIC_STYLES.items():
3625
+ lines.append(" %-10s %-8s bpm_hint %-16s 调池 %-20s 主奏 %-14s 乐句 %d 小节" % (
3626
+ sid, str(pack.get("label", "")),
3627
+ "/".join(str(b) for b in pack["bpm_hint"]),
3628
+ "/".join(str(k) for k in pack["keys"]),
3629
+ "/".join(str(v) for v in pack["lead_cycle"]),
3630
+ int(pack["phrase_bars"]),
3631
+ ))
3632
+ lines.append(" 情绪 --mood:" + "/".join(MOOD_IDS))
3633
+ return "\n".join(lines)
3634
+
3635
+
1813
3636
  def _format_report(rep: dict, wav_path: Path | None, report_path: Path | None) -> str:
1814
3637
  """CLI 中文摘要。"""
1815
3638
  lines = []
1816
3639
  lines.append(f"[scorekit] {rep['duration']:g} s / {rep['bpm']:g} BPM / {rep['key']}({rep['key_name']})"
1817
3640
  f" / 小节 {rep['bar_s']:g} s / seed {rep['seed']}")
3641
+ if rep.get("style"):
3642
+ lines.append(f" 配乐风格 {rep['style']}({rep.get('style_label', '')})"
3643
+ f" / 情绪 {rep.get('mood', 'steady')} / 有效 seed {rep.get('seed_effective', rep['seed'])}"
3644
+ f" / 频谱质心 {rep.get('spectral_centroid_hz', 0):.0f} Hz")
1818
3645
  lines.append(f" 段落 {len(rep['sections'])} 个,交界 {len(rep['transitions'])} 处,吸气 {len(rep['sucks'])} 处")
3646
+ var = rep.get("variation") or {}
3647
+ if any(int(var.get(k, 0) or 0) for k in ("chord_swaps", "motif_shifts", "drum_ghosts")):
3648
+ lines.append(" 指纹变奏:和弦替换 %d 处 / 动机偏移 %d 音 / 鼓型 ghost %d 处"
3649
+ % (int(var.get("chord_swaps", 0)), int(var.get("motif_shifts", 0)),
3650
+ int(var.get("drum_ghosts", 0))))
1819
3651
  for s in rep["sections"]:
1820
3652
  lines.append(f" {s['name']:<8} {s['start']:7.2f} – {s['end']:7.2f} s"
1821
3653
  f" energy {s['energy']:.2f} 目标 {s['target_lufs']:.1f} LUFS"
@@ -1839,9 +3671,17 @@ def main(argv=None) -> int:
1839
3671
  description="scorekit — 程序化配乐(numpy + sfxkit,无采样、确定性)",
1840
3672
  )
1841
3673
  ap.add_argument("--selftest", action="store_true", help="跑自测(不联网,逐条 PASS/FAIL)")
3674
+ ap.add_argument("--list-styles", action="store_true", help="列出可用配乐风格后退出")
1842
3675
  ap.add_argument("--duration", type=float, default=60.0, help="片长(秒),默认 60")
1843
- ap.add_argument("--bpm", type=float, default=120.0, help="BPM,默认 120")
1844
- ap.add_argument("--key", default="Dm", help=f"调性,可选 {'/'.join(KEYS)},默认 Dm")
3676
+ ap.add_argument("--style", default=None,
3677
+ help="配乐风格:" + "/".join(MUSIC_STYLE_IDS) + "(缺省 = legacy,与 v0.4 逐样本一致)")
3678
+ ap.add_argument("--mood", default="steady", help="情绪修饰:" + "/".join(MOOD_IDS))
3679
+ ap.add_argument("--fingerprint", default=None,
3680
+ help="内容指纹(v0.7:参与和声/动机/鼓型变奏;只影响 style 路径,legacy 忽略)")
3681
+ ap.add_argument("--bpm", type=float, default=None,
3682
+ help="BPM(缺省:legacy 120;风格路径取该风格 bpm_hint 的中位)")
3683
+ ap.add_argument("--key", default=None,
3684
+ help="调性,可选 " + "/".join(KEYS_ALL) + "(缺省:legacy Dm;风格路径取调池首个)")
1845
3685
  ap.add_argument("--seed", type=int, default=7, help="随机种子,默认 7")
1846
3686
  ap.add_argument("--energy", type=float, default=0.55, help="无 anchors/sections 时的单段能量,默认 0.55")
1847
3687
  ap.add_argument("--anchors", default=None, help="timeline.json 或锚点列表文件([{id,kind,start,end}])")
@@ -1853,27 +3693,47 @@ def main(argv=None) -> int:
1853
3693
 
1854
3694
  if args.selftest:
1855
3695
  return selftest()
1856
-
1857
- _require(args.key in KEYS, f"未知调性 {args.key!r};可选:{'/'.join(KEYS)}")
3696
+ if args.list_styles:
3697
+ print(_format_style_list())
3698
+ return 0
3699
+
3700
+ sid = _normalize_style_id(args.style)
3701
+ if sid is None:
3702
+ bpm = float(args.bpm) if args.bpm is not None else 120.0
3703
+ key = str(args.key) if args.key else "Dm"
3704
+ else:
3705
+ hint = MUSIC_STYLES[sid]["bpm_hint"]
3706
+ bpm = float(args.bpm) if args.bpm is not None else float(hint[len(hint) // 2])
3707
+ key = str(args.key) if args.key else str(MUSIC_STYLES[sid]["keys"][0])
3708
+ _require(key in KEYS_ALL, f"未知调性 {key!r};可选:{'/'.join(KEYS_ALL)}")
1858
3709
  anchors = _parse_anchors_file(args.anchors) if args.anchors else None
1859
3710
  sections = _parse_sections_file(args.sections) if args.sections else None
1860
- if anchors or sections:
1861
- merged = _merge_sections(anchors, sections, float(args.duration))
1862
- else:
1863
- merged = [{"name": "全片", "start": 0.0, "end": float(args.duration), "energy": args.energy}]
1864
- sc = Score(args.duration, bpm=args.bpm, key=args.key, seed=args.seed)
1865
- for s in merged:
1866
- sc.section(s["name"], s["start"], s["end"], s["energy"])
1867
- if anchors:
1868
- sc._anchors = [{"id": a.get("id", ""), "kind": a.get("kind", ""),
1869
- "start": float(a["start"]), "end": float(a["end"])} for a in anchors]
1870
- for t, db, dur in _parse_suck_list(args.suck):
1871
- sc.suck(t, db, dur)
3711
+ sucks = _parse_suck_list(args.suck)
1872
3712
 
1873
3713
  t0 = time.perf_counter()
1874
- wav = sc.render()
3714
+ if sid is None:
3715
+ # legacy:与 v0.4 完全同一段代码(逐字节兼容是硬契约,不要并进 styled 路径)
3716
+ if anchors or sections:
3717
+ merged = _merge_sections(anchors, sections, float(args.duration))
3718
+ else:
3719
+ merged = [{"name": "全片", "start": 0.0, "end": float(args.duration),
3720
+ "energy": args.energy}]
3721
+ sc = Score(args.duration, bpm=bpm, key=key, seed=args.seed)
3722
+ for s in merged:
3723
+ sc.section(s["name"], s["start"], s["end"], s["energy"])
3724
+ if anchors:
3725
+ sc._anchors = [{"id": a.get("id", ""), "kind": a.get("kind", ""),
3726
+ "start": float(a["start"]), "end": float(a["end"])} for a in anchors]
3727
+ for t, db, dur in sucks:
3728
+ sc.suck(t, db, dur)
3729
+ wav = sc.render()
3730
+ rep = sc.report()
3731
+ else:
3732
+ wav, rep = render_styled(args.duration, style=sid, bpm=bpm, key=key, mood=args.mood,
3733
+ anchors=anchors, sections=sections, seed=args.seed,
3734
+ fingerprint=args.fingerprint,
3735
+ sucks=[(t, db, d) for t, db, d in sucks])
1875
3736
  dt = time.perf_counter() - t0
1876
- rep = sc.report()
1877
3737
  rep["render_s"] = round(dt, 3)
1878
3738
  wav_path = Path(args.out) if args.out else None
1879
3739
  report_path = Path(args.report) if args.report else None