@dsh-gis/dsh-video-studio-skill 0.9.1 → 1.0.4

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 (63) hide show
  1. package/CHANGELOG.md +473 -0
  2. package/README.md +263 -327
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/package.json +9 -10
  5. package/schemas/design.schema.json +722 -0
  6. package/schemas/film.schema.json +31 -42
  7. package/schemas/proposal.schema.json +133 -0
  8. package/skills/video-studio/SKILL.md +1216 -1123
  9. package/skills/video-studio/assets/design_fixture.json +141 -0
  10. package/skills/video-studio/assets/film.json +2 -4
  11. package/skills/video-studio/assets/golden_frames.json +13 -10
  12. package/skills/video-studio/assets/scenes.py +153 -65
  13. package/skills/video-studio/assets/voice_loudness.json +16 -0
  14. package/skills/video-studio/references/appearance.md +123 -0
  15. package/skills/video-studio/references/audio-variation.md +74 -93
  16. package/skills/video-studio/references/audio.md +64 -66
  17. package/skills/video-studio/references/change-impact.md +5 -5
  18. package/skills/video-studio/references/{v08-quality.md → delivery-gates.md} +16 -18
  19. package/skills/video-studio/references/frame-qa.md +48 -16
  20. package/skills/video-studio/references/pipeline.md +4 -4
  21. package/skills/video-studio/references/pitfalls.md +22 -3
  22. package/skills/video-studio/references/proposal.md +160 -0
  23. package/skills/video-studio/references/quality-gates.md +11 -11
  24. package/skills/video-studio/references/scene-authoring.md +2 -2
  25. package/skills/video-studio/references/scene-grammar.md +40 -42
  26. package/skills/video-studio/references/sfx-design.md +8 -6
  27. package/skills/video-studio/references/web-engine.md +8 -8
  28. package/skills/video-studio/references/word-timeline.md +9 -9
  29. package/skills/video-studio/requirements.txt +9 -13
  30. package/skills/video-studio/scripts/designkit.py +2115 -0
  31. package/skills/video-studio/scripts/filmcheck.py +22 -48
  32. package/skills/video-studio/scripts/filmkit.py +2980 -2904
  33. package/skills/video-studio/scripts/gates.py +4 -4
  34. package/skills/video-studio/scripts/grammar.py +73 -13
  35. package/skills/video-studio/scripts/musicgen.py +2042 -0
  36. package/skills/video-studio/scripts/preflight.py +14 -7
  37. package/skills/video-studio/scripts/previewkit.py +848 -0
  38. package/skills/video-studio/scripts/propose.py +825 -0
  39. package/skills/video-studio/scripts/qa_frames.py +73 -39
  40. package/skills/video-studio/scripts/qaasr.py +26 -7
  41. package/skills/video-studio/scripts/qavmaf.py +89 -23
  42. package/skills/video-studio/scripts/render.py +545 -231
  43. package/skills/video-studio/scripts/scorekit.py +55 -1755
  44. package/skills/video-studio/scripts/selfcheck.py +815 -215
  45. package/skills/video-studio/scripts/sfxkit.py +27 -26
  46. package/skills/video-studio/scripts/stagewatch.py +24 -8
  47. package/skills/video-studio/scripts/stylekit.py +207 -888
  48. package/skills/video-studio/scripts/voicekit.py +508 -387
  49. package/skills/video-studio/scripts/webengine.py +71 -72
  50. package/tools/audio_similarity.py +64 -37
  51. package/tools/ci_check.py +20 -14
  52. package/tools/estimate.py +34 -29
  53. package/tools/golden_frames.py +72 -28
  54. package/tools/silhouette_qa.py +520 -168
  55. package/docs/demo-pil-sheet.png +0 -0
  56. package/docs/styles/demo-results.json +0 -76
  57. package/docs/styles/sheet-8-styles.png +0 -0
  58. package/docs/styles/sheet-ai.png +0 -0
  59. package/docs/styles/sheet-before-after.png +0 -0
  60. package/docs/styles/sheet-craft.png +0 -0
  61. package/docs/styles/sheet-night.png +0 -0
  62. package/skills/video-studio/assets/score_demo.json +0 -307
  63. package/skills/video-studio/references/style-packs.md +0 -283
@@ -1,74 +1,74 @@
1
1
  # -*- coding: utf-8 -*-
2
- """voicekit.py — 旁白声线(Voice Personas):让每部片的"谁在说话"也不一样。
2
+ """voicekit.py — 旁白声线:直接给 edge voice id + 语气档 + 响度补偿表。
3
3
 
4
- v0.5.0 新增。v0.4 的 render.py 把 script.voice / rate / pitch 三个单值一路传给
5
- filmkit.tts_batch,结果是所有片、所有段落都由同一个人用同一种语气念完 ——
6
- 用户的原话是「旁白声音都差不多、整体画风也差不多,希望随内容变化」。
4
+ 旁白不能全片一个人、一个语气念完:声线、语速、音高、音量与前后留白都要能逐句给,
5
+ 并且随内容变化。只把 script.voice / rate / pitch 三个单值传给 filmkit.tts_batch,
6
+ 全片就是同一个人用同一种语气念到底(听感即「旁白声音都差不多」)。
7
7
 
8
- 本模块只做「策展 + 计划」:给出每句该用哪个声线、什么语气、语速/音高/音量抖多少、
8
+ 声线只认裸 edge voice id
9
+ ------------------------
10
+ 声线一律写 edge voice id(zh-CN-YunxiNeural),映射只发生一次、就在设计里。
11
+ 多一层 persona 身份映射(写 narrator_male、真正下发给 edge-tts 的却是
12
+ zh-CN-YunyangNeural)时,任何一层没对齐,表现都是「配了却没生效」,
13
+ 而且要等听成片才发现。
14
+
15
+ 身份是数据,不该由一个正则或一张表决定:没有 persona 表,也没有
16
+ 「文本里有引号就偷偷换人」那套规则。
17
+
18
+ 每把音色的实测响度补偿**不能丢**:不补补偿,换音色就要人肉重新对电平,
19
+ 正是要根除的「改了不生效 / 要人调」。所以补偿独立成一张按 voice id 的数据表
20
+ VOICE_LOUDNESS(没有任何身份含义)。
21
+
22
+ 本模块只做「策展 + 计划」:给出每句用哪个音色、什么语气、语速/音高/音量抖多少、
9
23
  前后留白多少。真正的合成仍在 filmkit.tts(Lead 负责接线),因此本模块
10
24
  **不 import filmkit**(render.py 会同时 import 两者,互相 import 会成环),
11
25
  只依赖 stylekit + 标准库。
12
26
 
13
27
  三层结构
14
28
  --------
15
- VOICE_PERSONAS 9 个声线角色(谁在说话):voice id + 基础语速/音高/音量 + 响度补偿
29
+ VOICE_LOUDNESS 响度补偿(数据):每把音色实测的 level 补偿
16
30
  VOICE_TONES 6 档语气(怎么说):相对 deltas + 前后留白 lead/tail
17
31
  _rules() 文本规则(说什么):引号/数字/问叹/长短句/转折词 → 语气与微调
18
32
 
19
- 计划优先级(高到低)
33
+ 声线从哪来(高到低)
20
34
  --------------------
21
- lines[].persona / lines[].voice / lines[].tone(显式)
22
- > style_plan["voice"]["map"][kind](风格包)
23
- > 文本规则(引号/数字 → 语气)
24
- > kind 规则(hook/body/quote/outro 各自的缺省声线)
25
- > 默认 persona
35
+ lines[].voice(显式 edge id)
36
+ > script.voice.map / design.audio.voice.map 的 kind 映射
37
+ > style_plan["voice"]["map"][kind](风格包 / designkit.design_to_plan)
38
+ > script.voice.id / design.audio.voice.id / style_plan["voice"]["default"](主声线)
39
+ 没有任何来源就报错(并给出迁移路径)——设计必须明确「谁在说话」。
40
+
41
+ 声线一旦确定就**不再治理**:map 怎么写就怎么念,没有中间层在段边界偷偷换人、
42
+ 也没有按预算限制同一部片出现几把声音。想少换人就少写几个 kind,不需要中间层猜意图。
26
43
 
27
44
  确定性
28
45
  ------
29
- 所有抖动都来自 sha1(title|id|persona),禁 random / time / hash()(str hash 带盐)。
46
+ 所有抖动都来自 sha1(title|id|voice),禁 random / time / hash()(str hash 带盐)。
30
47
  同一份 film.json 两次 voice_plan() 完全相等;jitter=0 时与「无抖动」逐字段相等。
31
48
 
32
- legacy 兼容
33
- -----------
34
- style_plan["legacy"] 为 True(film.json 没有 style 字段)时不换人、不加抖动、不叠语气:
35
- 全部用 script 的 voice/rate/pitch 单值 + script 的 lead/tail,与 v0.4 逐字段一致。
36
- 这是硬契约:legacy 路径的任何变化都会让老项目音频变样、缓存全失效。
37
-
38
- 校准(实测定稿,换 voice id 必须重测)
39
- --------------------------------------
40
- 2026-11-09 在本机用 edge-tts 7.3.1 合成同一句校准文本
41
- 「这是一句用来校准的中文样本,长度大约二十个字。」(20 个汉字),
42
- 用 ffmpeg 解成 24k 单声道后测门限 RMS(20ms 帧,低于 -45 dBFS 的静音帧不计)。
43
- 目标响度取 9 个 persona 的中位数 -20.97 dBFS;gain_db = 目标 - 实测,夹在 ±3 dB:
44
- narrator_male Yunyang 4.56s 4.61cps -24.39dBFS -> +3.00
45
- narrator_female Xiaoxiao 4.63s 4.53cps -18.28dBFS -> -2.69
46
- warm_female HsiaoChen 5.33s 3.94cps -17.51dBFS -> -3.00(原始 -3.46,夹到 -3)
47
- bright_female Xiaoyi 4.73s 4.44cps -20.40dBFS -> -0.57
48
- authority_male Yunjian 5.21s 4.03cps -21.98dBFS -> +1.01
49
- young_male Yunxi 4.80s 4.38cps -22.91dBFS -> +1.94
50
- teen_male Yunxia 4.85s 4.33cps -21.27dBFS -> +0.30
51
- dialect_ne_female Xiaobei 5.47s 3.84cps -20.97dBFS -> 0.00
52
- dialect_sx_female Xiaoni 5.09s 4.13cps -20.63dBFS -> -0.34
53
- edge-tts 免费端点只提供上面 8 个 zh-CN 音色(另有 zh-TW/zh-HK,可用但带腔),
54
- 故 9 个 persona 复用 8 个 voice id:warm_female 用 zh-TW-HsiaoChenNeural
55
- (微软标注 "Warm, considerate",实测基频 194Hz 低于 Xiaoxiao 的 238Hz,确实更暖;
56
- 若目标观众只要大陆标准音,把它换成 zh-CN-XiaoxiaoNeural 并降速即可,其余字段不用改)。
49
+ 老结构
50
+ ------
51
+ 顶层 voice 单值与「没有 design 的 legacy 计划」都不受支持:voice_plan 直接抛
52
+ ValueError,消息里给三条可照抄的路径(design.audio.voice / lines[].voice / voice.map)。
53
+ 不静默回落是刻意的:静默回落 = 配音变了却没人知道,比报错难查得多。
57
54
 
58
55
  用法
59
56
  ----
60
57
  import voicekit as VK
61
58
  plan = VK.voice_plan(script, ST.resolve_script_style(script))
62
59
  VK.describe(plan)
63
- VK.spec_key(dict(plan[0], text=script["lines"][0]["text"])) # v2 缓存键
60
+ VK.spec_key(dict(plan[0], text=script["lines"][0]["text"])) # 合成缓存键
61
+ VK.calibrate_voice("zh-CN-YunxiNeural") # 联网实测;离线 measured=False,不抛
64
62
 
65
- python voicekit.py --list # 声线/语气表
63
+ python voicekit.py --list # 音色响度表 + 语气档
66
64
  python voicekit.py --plan film.json # 某份剧本的声线计划(可读表格)
67
- python voicekit.py --calibrate # 联网实测 dur/RMS/cps,打印建议 gain_db(失败 SKIP 返回 0)
65
+ python voicekit.py --calibrate --only zh-CN-YunxiNeural # 联网实测,打印该抄回的数
68
66
  """
69
67
  from __future__ import annotations
70
68
 
71
69
  import argparse
70
+ import array
71
+ import asyncio
72
72
  import hashlib
73
73
  import json
74
74
  import math
@@ -81,97 +81,75 @@ import tempfile
81
81
  import wave
82
82
 
83
83
  # ============================================================================
84
- # 一、声线(谁在说话)
84
+ # 一、响度补偿(数据,不是身份):换音色不用手调电平
85
85
  # ============================================================================
86
86
  #
87
- # 字段口径:
88
- # voice edge-tts 的 voice id("-" 分隔且以 Neural 结尾)
89
- # rate/pitch/volume 字符串,直接透传给 edge_tts.Communicate(只接受整数)
90
- # gain_db mix 侧给该句加的分贝(正 = 该音色偏轻,需要补),已按校准文本实测
91
- # desc 人话说明(打印 / --list 用)
92
- # narrate 能否被"自动"选来念长段叙述(方言/少年音只适合引用与点缀,设 False)
93
- # home 该声线的"主场"段落类型(hook/body/quote/outro),给 governor 与文档用
94
-
95
- PERSONA_IDS = (
96
- "narrator_male", "narrator_female", "warm_female", "bright_female",
97
- "authority_male", "young_male", "teen_male",
98
- "dialect_ne_female", "dialect_sx_female",
99
- )
100
-
101
- VOICE_PERSONAS = {
102
- "narrator_male": {
103
- "voice": "zh-CN-YunyangNeural", "rate": "+2%", "pitch": "+0Hz", "volume": "+0%",
104
- "gain_db": 3.0, "narrate": True, "home": "body",
105
- "desc": "新闻/纪录片男声,稳、清楚,默认叙述(实测最轻,+3dB 补偿)",
106
- },
107
- "narrator_female": {
108
- "voice": "zh-CN-XiaoxiaoNeural", "rate": "+5%", "pitch": "+0Hz", "volume": "+0%",
109
- "gain_db": -2.7, "narrate": True, "home": "body",
110
- "desc": "标准女声叙述,清澈不甜,报告/复盘/知识片(实测最响,-2.7dB)",
111
- },
112
- "warm_female": {
113
- "voice": "zh-TW-HsiaoChenNeural", "rate": "-2%", "pitch": "-1Hz", "volume": "+2%",
114
- "gain_db": -3.0, "narrate": True, "home": "outro",
115
- "desc": "软糯女声(台湾腔),低基频 194Hz,适合纸感/人文/深夜",
116
- },
117
- "bright_female": {
118
- "voice": "zh-CN-XiaoyiNeural", "rate": "+6%", "pitch": "+2Hz", "volume": "+3%",
119
- "gain_db": -0.6, "narrate": True, "home": "hook",
120
- "desc": "活泼女声,高基频 289Hz,适合活力/营销/上新",
121
- },
122
- "authority_male": {
123
- "voice": "zh-CN-YunjianNeural", "rate": "+2%", "pitch": "-2Hz", "volume": "+2%",
124
- "gain_db": 1.0, "narrate": True, "home": "hook",
125
- "desc": "有力男声,慢而沉,适合开场/观点/史诗(实测 3.96cps 最慢)",
126
- },
127
- "young_male": {
128
- "voice": "zh-CN-YunxiNeural", "rate": "+5%", "pitch": "+1Hz", "volume": "+1%",
129
- "gain_db": 1.9, "narrate": True, "home": "quote",
130
- "desc": "青年男声(v0.4 的缺省音色),适合引用、对话、年轻向内容",
131
- },
132
- "teen_male": {
133
- "voice": "zh-CN-YunxiaNeural", "rate": "+7%", "pitch": "+1Hz", "volume": "+2%",
134
- "gain_db": 0.3, "narrate": False, "home": "quote",
135
- "desc": "少年音,基频 282Hz,只适合引用/角色台词,别整片念",
136
- },
137
- "dialect_ne_female": {
138
- "voice": "zh-CN-liaoning-XiaobeiNeural", "rate": "+4%", "pitch": "+0Hz", "volume": "+0%",
139
- "gain_db": 0.0, "narrate": False, "home": "quote",
140
- "desc": "东北女声,自带喜感,适合引用/段子/接地气内容",
141
- },
142
- "dialect_sx_female": {
143
- "voice": "zh-CN-shaanxi-XiaoniNeural", "rate": "+3%", "pitch": "+0Hz", "volume": "+0%",
144
- "gain_db": -0.3, "narrate": False, "home": "quote",
145
- "desc": "陕西女声,质地厚,适合引用/方言故事/纪录片片段",
146
- },
87
+ # 为什么这张表必须有:
88
+ # 九把音色的实测响度跨度 6.0 dB(-3.0 ~ +3.0)。差别来自音色本身(基频、气声、
89
+ # 端点侧的归一化),跟台词、语气、机器负载都无关,但**换一把音色就会整体偏几 dB**。
90
+ # 不补补偿,每次换音色都要试听、手调 gain —— 那正是「改了不生效 / 要人调」。
91
+ #
92
+ # 口径:gain_db = 目标响度 - 实测 rms_db,夹在 ±3 dB(正 = 该音色偏轻,mix 侧补回来)。
93
+ # - 实测:2026-11-09 在本机用 edge-tts 7.3.1 合成同一句校准文本(CALIB_TEXT,21 个
94
+ # 汉字),ffmpeg 解成 24k 单声道,测 20ms 帧门限 RMS(低于 -45 dBFS 的静音帧不计);
95
+ # - 目标:CALIBRATION_LOG 里 9 条实测 rms_db 的中位数(-20.97 dBFS),由下方
96
+ # CALIB_TARGET_DB 现算,不另写第二个魔数。
97
+ #
98
+ # **换机 / 换 edge-tts 版本 / 换 voice id 都要重测**:同一把音色在不同机器、不同版本上
99
+ # 差 1~2 dB 很常见,把上次的数字跨机照抄会一句响一句轻。重测入口:
100
+ # python voicekit.py --calibrate(结果记 work/voice_calib.json,并打印该抄回的数)
101
+ VOICE_LOUDNESS = {
102
+ "zh-CN-YunyangNeural": 3.0, # 新闻/纪录片男声,实测最轻
103
+ "zh-CN-XiaoxiaoNeural": -2.7, # 标准女声,实测最响
104
+ "zh-TW-HsiaoChenNeural": -3.0, # 软糯女声(台湾腔),原始 -3.46,夹到 -3
105
+ "zh-CN-XiaoyiNeural": -0.6, # 活泼女声
106
+ "zh-CN-YunjianNeural": 1.0, # 有力男声
107
+ "zh-CN-YunxiNeural": 1.9, # 青年男声(最常用的旁白音色)
108
+ "zh-CN-YunxiaNeural": 0.3, # 少年音
109
+ "zh-CN-liaoning-XiaobeiNeural": 0.0, # 东北女声(本次校准的基准,补偿 0)
110
+ "zh-CN-shaanxi-XiaoniNeural": -0.3, # 陕西女声
147
111
  }
148
112
 
149
- # 校准日志:--calibrate 会用实测值对比这里,换 voice id 后重跑一次再改表
113
+ # 表里没有的音色按 0 dB 处理(不猜),voice_plan 的 reason 会标 unmeasured_voice:
114
+ # 让人一眼看出「这句没补过」,而不是以为补过了。
150
115
  CALIBRATED_ON = "2026-11-09"
151
116
  CALIB_TEXT = "这是一句用来校准的中文样本,长度大约二十个字。"
152
117
  CALIBRATION_LOG = {
153
- "narrator_male": {"dur": 4.56, "cps": 4.61, "rms_db": -24.39},
154
- "narrator_female": {"dur": 4.63, "cps": 4.53, "rms_db": -18.28},
155
- "warm_female": {"dur": 5.33, "cps": 3.94, "rms_db": -17.51},
156
- "bright_female": {"dur": 4.73, "cps": 4.44, "rms_db": -20.40},
157
- "authority_male": {"dur": 5.21, "cps": 4.03, "rms_db": -21.98},
158
- "young_male": {"dur": 4.80, "cps": 4.38, "rms_db": -22.91},
159
- "teen_male": {"dur": 4.85, "cps": 4.33, "rms_db": -21.27},
160
- "dialect_ne_female": {"dur": 5.47, "cps": 3.84, "rms_db": -20.97},
161
- "dialect_sx_female": {"dur": 5.09, "cps": 4.13, "rms_db": -20.63},
118
+ "zh-CN-YunyangNeural": {"dur": 4.56, "cps": 4.61, "rms_db": -24.39},
119
+ "zh-CN-XiaoxiaoNeural": {"dur": 4.63, "cps": 4.53, "rms_db": -18.28},
120
+ "zh-TW-HsiaoChenNeural": {"dur": 5.33, "cps": 3.94, "rms_db": -17.51},
121
+ "zh-CN-XiaoyiNeural": {"dur": 4.73, "cps": 4.44, "rms_db": -20.40},
122
+ "zh-CN-YunjianNeural": {"dur": 5.21, "cps": 4.03, "rms_db": -21.98},
123
+ "zh-CN-YunxiNeural": {"dur": 4.80, "cps": 4.38, "rms_db": -22.91},
124
+ "zh-CN-YunxiaNeural": {"dur": 4.85, "cps": 4.33, "rms_db": -21.27},
125
+ "zh-CN-liaoning-XiaobeiNeural": {"dur": 5.47, "cps": 3.84, "rms_db": -20.97},
126
+ "zh-CN-shaanxi-XiaoniNeural": {"dur": 5.09, "cps": 4.13, "rms_db": -20.63},
162
127
  }
163
128
 
129
+
130
+ def _median(values):
131
+ """中位数(偶数个取上中位):定目标响度,不为了一个数去 import statistics。"""
132
+ xs = sorted(float(v) for v in values)
133
+ return xs[len(xs) // 2] if xs else 0.0
134
+
135
+
136
+ CALIB_TARGET_DB = round(_median(r["rms_db"] for r in CALIBRATION_LOG.values()), 2)
137
+
164
138
  # ============================================================================
165
- # 二、语气(怎么说):deltas 叠在 persona 上;lead/tail 是 v0.4 基准附近的偏移量
139
+ # 二、语气(怎么说):deltas 叠在「裸 voice id」上;lead/tail 是基准行的偏移
166
140
  # ============================================================================
167
- # body 必须等于 v0.4 现状:lead 0.62 / tail 0.92 / 所有 delta = 0,legacy 才可能逐字段一致。
141
+ # body 是基准行:所有 delta = 0,lead/tail 就是 BODY_LEAD / BODY_TAIL。
142
+ # voice_plan 只在这个基准上加减,所以「某一句听起来不对」时先看 reason 里是 tone:xxx
143
+ # 还是 rule:xxx,改一处就够,不用同时去翻音色表和文本规则。
168
144
  BODY_LEAD = 0.62
169
145
  BODY_TAIL = 0.92
170
146
  TONE_IDS = ("body", "hook", "quote", "outro", "emphasis", "calm")
171
147
 
148
+ # gain_db 是**语气自己的**电平增量(强调句要更响),与 VOICE_LOUDNESS 的「音色补偿」
149
+ # 是两回事:前者是表演,后者是设备;voice_plan 里两者相加,各自都能单独解释。
172
150
  VOICE_TONES = {
173
151
  "body": {"rate_delta": 0, "pitch_delta": 0, "volume_delta": 0, "gain_db": 0.0,
174
- "lead": 0.62, "tail": 0.92, "desc": "正文,平稳(v0.4 基准)"},
152
+ "lead": 0.62, "tail": 0.92, "desc": "正文,平稳(基准行)"},
175
153
  "hook": {"rate_delta": 3, "pitch_delta": 1, "volume_delta": 2, "gain_db": 0.6,
176
154
  "lead": 0.48, "tail": 0.78, "desc": "开场,提一点速压一点留白,抓人"},
177
155
  "quote": {"rate_delta": -2, "pitch_delta": -1, "volume_delta": 1, "gain_db": 0.4,
@@ -184,13 +162,6 @@ VOICE_TONES = {
184
162
  "lead": 0.88, "tail": 1.25, "desc": "沉静,长留白,适合思辨/深夜"},
185
163
  }
186
164
 
187
- # kind 规则:风格包没给映射时的缺省声线(风格包优先)
188
- KIND_DEFAULT = {
189
- "hook": "authority_male", "body": "narrator_male",
190
- "quote": "narrator_female", "outro": "warm_female",
191
- }
192
-
193
- LEGACY_VOICE = "zh-CN-YunxiNeural" # 与 render.py 的 script.get("voice", ...) 缺省一致
194
165
  _RATE_LIMIT = (-15, 12) # 与 stylekit policy 的缺省一致
195
166
  _PITCH_LIMIT = (-8, 8)
196
167
  _VOL_LIMIT = (-10, 10)
@@ -200,7 +171,7 @@ _GAIN_LIMIT = 3.0
200
171
 
201
172
  try:
202
173
  import stylekit as _ST
203
- except Exception: # noqa: BLE001 — stylekit 缺失时走兜底解析
174
+ except Exception: # noqa: BLE001 — stylekit 缺失时只少了风格包这一层
204
175
  _ST = None
205
176
 
206
177
 
@@ -208,9 +179,9 @@ except Exception: # noqa: BLE001 — stylekit 缺失时
208
179
  # 三、小工具:参数解析/格式化、汉字计数、抖动
209
180
  # ============================================================================
210
181
  # 允许小数("+4.5%"):edge-tts 只收整数百分比,所以解析后按 _round_half_away 取整。
211
- # 以前正则只认整数,"+4.5%" 解析失败 → 静默回落 0 —— 而 0 与 "+0%" 在 spec_key 里
212
- # 是**同一个 TTS 缓存键**,于是"把语速从 0 调到 4.5%"完全没生效,还复用了旧音频。
213
- # 这是配置写对了却不生效里最难查的一类:没有报错、没有日志、听起来就是"没反应"。
182
+ # 正则只认整数时 "+4.5%" 解析失败 → 静默回落 0,而 0 与 "+0%" 在 spec_key 里
183
+ # 是**同一个 TTS 缓存键**,于是「把语速从 0 调到 4.5%」完全没生效,还复用了旧音频。
184
+ # 这是配置写对了却不生效里最难查的一类:没有报错、没有日志、听起来就是「没反应」。
214
185
  _PCT_RE = re.compile(r"^\s*([+-]?)(\d+(?:\.\d+)?)\s*%\s*$")
215
186
  _HZ_RE = re.compile(r"^\s*([+-]?)(\d+(?:\.\d+)?)\s*Hz\s*$")
216
187
 
@@ -262,7 +233,7 @@ def hanzi_count(text):
262
233
 
263
234
 
264
235
  def is_edge_voice(name):
265
- """形如 zh-CN-YunxiNeural 的原始 voice id(不是 persona 名)。"""
236
+ """形如 zh-CN-YunxiNeural 的原始 voice id(不是 persona 名 / 不是路径)。"""
266
237
  n = str(name or "").strip()
267
238
  return ("-" in n) and n.endswith("Neural")
268
239
 
@@ -280,7 +251,7 @@ def _clamp(v, lo, hi):
280
251
 
281
252
 
282
253
  def _jitter(title, lid, who):
283
- """sha1(title|id|persona) 派生确定性抖动:rate/pitch/lead/tail + 两个量化阈值。
254
+ """sha1(title|id|voice) 派生确定性抖动:rate/pitch/lead/tail + 两个量化阈值。
284
255
 
285
256
  rate/pitch 是浮点目标值(±1.5% / ±1Hz 再乘 policy.jitter),但 edge-tts 只收整数;
286
257
  若直接四舍五入,jitter=0.35 时 ±0.5 的小数会被吃光、抖动形同不存在。
@@ -297,7 +268,7 @@ def _jitter(title, lid, who):
297
268
 
298
269
 
299
270
  def _quantize(v, u):
300
- """确定性随机进位:`floor(v)+1` 的概率 = v 的小数部分,期望值仍是 v。
271
+ """确定性随机进位:floor(v)+1 的概率 = v 的小数部分,期望值仍是 v。
301
272
 
302
273
  u 来自 sha1(同一句永远同一结果),用来把浮点抖动量化成 edge-tts 能收的整数。
303
274
  v 本身是整数时(jitter=0)绝不进位,保证与「无抖动」逐字段相等。
@@ -310,10 +281,9 @@ def _quantize(v, u):
310
281
  # ============================================================================
311
282
  # 四、文本规则(说什么):全部确定性,命中即返回理由
312
283
  # ============================================================================
313
- # 引语起始符。**不含书名号 《(《)**:正文里出现"《设计模式》"是书名,不是引用某人在说话。
314
- # 实测踩过:把 《 算进引语后,"今天我们聊《设计模式》"这句的 tone 被判成 quote,
315
- # 进而触发 rule:quote:persona,把 persona 从 narrator_male 换成 narrator_female ——
316
- # 旁白中途换人,听感像换了主播(而这句根本没有人引语)。
284
+ # 引语起始符。**不含书名号《》**:正文里出现「《设计模式》」是书名,不是引用某人在说话。
285
+ # 把 《 算进引语,「今天我们聊《设计模式》」这句就会判成 quote 语气 ——
286
+ # 整句降速、留白加长,听感像突然换了频道(而这句根本没有人引语)。
317
287
  _QUOTE_OPEN = ('"', "\u201c", "\u300c", "\u300e")
318
288
  _QUOTE_WORDS = ("他说", "她说", "有人问", "所谓", "据称")
319
289
  _NUM_UNITS = ("%", "万", "亿", "年", "倍")
@@ -356,85 +326,120 @@ def _rules(text):
356
326
  # 五、计划:每句用谁、什么语气、多快多响多长留白
357
327
  # ============================================================================
358
328
  def _resolve(script, style_plan):
359
- """拿 stylekit 的计划;没有就调 stylekit 算;stylekit 也没有就兜底。"""
329
+ """拿风格计划:显式参数 > script["_style"](render 已解析过)> stylekit 现算 > {}。
330
+
331
+ 返回 {} 不是故障:声线来源是 design.audio.voice,本模块自己就能读;
332
+ stylekit 只负责风格包/节奏这一层,缺了它照样能出 voice 计划。
333
+ """
360
334
  if isinstance(style_plan, dict) and style_plan:
361
335
  return style_plan
336
+ cached = script.get("_style")
337
+ if isinstance(cached, dict) and cached:
338
+ return cached
362
339
  if _ST is not None:
363
340
  try:
364
341
  return _ST.resolve_script_style(script)
365
- except Exception: # noqa: BLE001 — 坏剧本交给 filmkit 报错
342
+ except Exception: # noqa: BLE001 — 坏剧本交给 filmcheck 报错
366
343
  pass
367
- vis = script.get("visual") if isinstance(script.get("visual"), dict) else {}
368
- voce = script.get("voice") if isinstance(script.get("voice"), dict) else {}
369
- legacy = ("style" not in script) and not vis.get("theme")
370
- return {
371
- "legacy": bool(legacy),
372
- "voice": {"map": {}, "default": voce.get("default"), "policy": {
373
- "auto": not legacy, "jitter": 0.0 if legacy else 0.35,
374
- "max_distinct": 2 if legacy else 3,
375
- "rate_range": list(_RATE_LIMIT), "pitch_range": list(_PITCH_LIMIT)}},
376
- "pacing": {"lead": float(script.get("lead", 0.55)),
377
- "tail": float(script.get("tail", 0.85))},
378
- }
344
+ return {}
379
345
 
380
346
 
381
- def _fmt_num(v):
382
- """计划里的 lead/tail 统一保留 3 位(避免 0.6200000000001 这种浮点尾巴)。"""
383
- return round(float(v) + 0.0, 3)
347
+ def _design_voice(script):
348
+ """读设计里的声线:返回 (主声线, {kind: id}, 策略 {auto, jitter})。
384
349
 
350
+ 为什么直接读 script["design"] 而不只依赖 style_plan:单测/验收会直接
351
+ voice_plan(script),此时没有 render.py 解析过的 _style;而 stylekit 对「没有
352
+ design」的剧本已经直接报错,_resolve 只能返回 {}。design.audio.voice 是声线的
353
+ 唯一事实来源,能读就读,别要求调用方先跑一遍 render。
385
354
 
386
- def _legacy_plan(script, lines, pace):
387
- """v0.4 路径:单值 voice/rate/pitch + script 的 lead/tail,无抖动无语气。"""
388
- voice = str(script.get("voice") or LEGACY_VOICE)
389
- rate = script.get("rate")
390
- pitch = script.get("pitch")
391
- rate_s = fmt_pct(parse_pct(rate)) if isinstance(rate, (int, float)) else str(rate or "+0%")
392
- pitch_s = fmt_hz(parse_hz(pitch)) if isinstance(pitch, (int, float)) else str(pitch or "+0Hz")
393
- lead = float(script.get("lead", pace.get("lead", 0.55)))
394
- tail = float(script.get("tail", pace.get("tail", 0.85)))
395
- rows = []
396
- for i, ln in enumerate(lines):
397
- ln = ln if isinstance(ln, dict) else {}
398
- rows.append({
399
- "id": str(ln.get("id") or ("l%02d" % (i + 1))),
400
- "kind": str(ln.get("kind") or "body"),
401
- "persona": None, "tone": "body", "voice": voice,
402
- "rate": rate_s, "pitch": pitch_s, "volume": "+0%", "gain_db": 0.0,
403
- "lead": _fmt_num(lead), "tail": _fmt_num(tail), "reason": "legacy",
404
- })
405
- return rows
355
+ 策略跟着设计走(与 designkit.design_to_plan 对齐):裸 id = 单声线、不抖动、
356
+ 不加文本规则;dict = 设计采样出来的多声线方案,auto=True、jitter 取设计值。
357
+ 本模块不 import designkit(那会多一层依赖),所以这三项在这里读一遍。
358
+ """
359
+ des = script.get("design") if isinstance(script.get("design"), dict) else {}
360
+ au = des.get("audio") if isinstance(des.get("audio"), dict) else {}
361
+ vo = au.get("voice")
362
+ if isinstance(vo, str):
363
+ return (vo.strip() or None), {}, {"auto": False, "jitter": 0.0}
364
+ if not isinstance(vo, dict):
365
+ return None, {}, {}
366
+ mode = str(vo.get("mode") or "").strip()
367
+ if mode == "wav":
368
+ raise ValueError(
369
+ "design.audio.voice.mode='wav':voicekit 只出 edge-tts 的声线计划,"
370
+ "wav 音色(录音/克隆)请直接交给混音侧,别从这里过。")
371
+ vid = str(vo.get("id") or "").strip() or None
372
+ raw = vo.get("map") if isinstance(vo.get("map"), dict) else {}
373
+ vmap = {}
374
+ for kind, v in raw.items():
375
+ if isinstance(v, dict):
376
+ v = v.get("id")
377
+ if v not in (None, ""):
378
+ vmap[str(kind)] = str(v).strip()
379
+ try:
380
+ jitter = max(0.0, float(vo.get("jitter", 0.0)))
381
+ except (TypeError, ValueError):
382
+ jitter = 0.0
383
+ return vid, vmap, {"auto": True, "jitter": jitter}
406
384
 
407
385
 
408
- def _pick_persona(line, kind, vmap, default, reasons):
409
- """返回 (persona 或 None, 是否显式, 原始 voice id 或 None)。"""
410
- for field in ("persona", "voice"):
411
- raw = line.get(field)
412
- if raw in (None, ""):
413
- continue
414
- name = str(raw).strip()
415
- if name in VOICE_PERSONAS:
416
- reasons.append("explicit:%s" % field)
417
- return name, True, None
418
- if is_edge_voice(name):
419
- reasons.append("explicit:%s" % field)
420
- return None, True, name
421
- reasons.append("unknown_persona:%s" % name)
422
- mapped = vmap.get(kind, vmap.get("*"))
423
- if mapped:
424
- name = str(mapped).strip()
425
- if name in VOICE_PERSONAS:
426
- reasons.append("map:%s" % kind)
427
- return name, False, None
428
- if is_edge_voice(name):
429
- reasons.append("map:%s" % kind)
430
- return None, False, name
431
- reasons.append("unknown_map:%s" % name)
432
- if default:
433
- reasons.append("default")
434
- return default, False, None
435
- name = KIND_DEFAULT.get(kind, "narrator_male")
436
- reasons.append("kind:%s" % kind)
437
- return name, False, None
386
+ def _script_voice(script):
387
+ """script.voice 写成 dict 时的形状:返回 (主声线, {kind: id})。"""
388
+ vo = script.get("voice")
389
+ if not isinstance(vo, dict):
390
+ return None, {}
391
+ vid = str(vo.get("id") or vo.get("default") or "").strip() or None
392
+ raw = vo.get("map") if isinstance(vo.get("map"), dict) else {}
393
+ vmap = {str(k): str(v).strip() for k, v in raw.items() if v not in (None, "")}
394
+ return vid, vmap
395
+
396
+
397
+ def _style_voice(sp):
398
+ """style_plan["voice"]:返回 ({kind: id}, 主声线)。"""
399
+ vsec = sp.get("voice") if isinstance(sp.get("voice"), dict) else {}
400
+ raw = vsec.get("map") if isinstance(vsec.get("map"), dict) else {}
401
+ vmap = {str(k): str(v).strip() for k, v in raw.items() if v not in (None, "")}
402
+ default = str(vsec.get("default") or "").strip() or None
403
+ return vmap, default
404
+
405
+
406
+ # 迁移说明只写一份:三处报错(非法声线 / 老结构 / map 值)都指向它,避免各处各写一套。
407
+ _MIGRATE = (
408
+ "声线现在一律写 edge voice id(形如 zh-CN-YunxiNeural)。迁移任选一条:\n"
409
+ " 1) design.json:audio.voice = {\"mode\": \"edge_id\", \"id\": \"zh-CN-YunxiNeural\"};"
410
+ "要分段换声线再加 map: {\"hook\": \"zh-CN-YunjianNeural\"};\n"
411
+ " 2) film.json:lines[].voice 逐句写 id;\n"
412
+ " 3) 风格包 / voice.map:值改成 edge voice id。\n"
413
+ "可用音色与实测响度补偿:python voicekit.py --list"
414
+ )
415
+
416
+
417
+ def _bad_voice(field, value):
418
+ return ValueError("%s = %r 不是 edge voice id,而 voicekit 从 D3 起已删掉 persona 身份表。\n%s"
419
+ % (field, value, _MIGRATE))
420
+
421
+
422
+ def _old_structure(script, sp, scalar=None):
423
+ """老结构(顶层 voice 单值 / 没有 design 的 legacy 计划)不受支持:直说怎么迁移。"""
424
+ bits = []
425
+ if scalar:
426
+ bits.append("顶层 voice = %r,单值声线" % scalar)
427
+ if sp.get("legacy"):
428
+ bits.append("风格计划判定为 legacy(film.json 里没有 design/style)")
429
+ return ValueError(
430
+ "这份剧本还是老结构(%s),而 voicekit 从 D3 起已删掉 legacy / persona 路径。\n%s"
431
+ % (";".join(bits) or "没有 design.audio.voice,也没有 lines[].voice / voice.map", _MIGRATE))
432
+
433
+
434
+ def _validate_voice_map(field, vmap):
435
+ for kind, vid in vmap.items():
436
+ if not is_edge_voice(vid):
437
+ raise _bad_voice("%s[%r]" % (field, kind), vid)
438
+
439
+
440
+ def _fmt_num(v):
441
+ """计划里的 lead/tail 统一保留 3 位(避免 0.6200000000001 这种浮点尾巴)。"""
442
+ return round(float(v) + 0.0, 3)
438
443
 
439
444
 
440
445
  def _pick_tone(line, kind, rules, use_rules, reasons):
@@ -454,74 +459,75 @@ def _pick_tone(line, kind, rules, use_rules, reasons):
454
459
  return "body"
455
460
 
456
461
 
457
- def _govern(cand, prev, kind, prev_kind, used, max_distinct, explicit, fallback=None,
458
- quote_rule=False):
459
- """换人治理:同段落不换人;换段可换,但要过 max_distinct 预算。
460
-
461
- 返回 (最终 persona, 附加 reason)。相邻两句不换人是防"广播剧"的关键:
462
- 同一 kind 的连续句子必须由同一把声音念;只有显式指定、或到了 hook/body/quote/outro
463
- 的段落边界(body->quote 是 spec 明说的允许点),才会换。
464
- 预算用尽时优先回到"正文声线"(fallback),避免收尾句被引用声线一路念到底。
465
- quote_rule=True 表示"这句文本有引号、该由 quote 声线念":这是 body->quote 的
466
- spec 允许点,不受同 kind 限制、也不占 max_distinct 预算(reason 记 governor:quote)。
467
- """
468
- if explicit or cand is None or prev is None:
469
- # 显式指定 / 风格包直接写了原始 voice id:一律放行,不参与换人治理
470
- return cand, ""
471
- if cand == prev:
472
- return cand, ""
473
- if quote_rule:
474
- return cand, "governor:quote"
475
- if kind == prev_kind:
476
- return prev, "governor:glue"
477
- if cand not in used and len(used) >= max_distinct:
478
- # 预算用尽:只有"正文声线已经在用"时才能回落,否则会偷偷多出第 max_distinct+1 个人
479
- if fallback and fallback in used and fallback != cand:
480
- return fallback, "governor:cap"
481
- return prev, "governor:cap"
482
- return cand, "governor:switch"
483
-
484
-
485
462
  def voice_plan(script, style_plan=None):
486
463
  """把剧本拆成逐句的旁白计划(纯函数、确定性,两次调用结果完全相等)。
487
464
 
488
465
  参数
489
466
  ----
490
467
  script film.json 解析后的 dict(只读,不修改)
491
- style_plan stylekit.resolve_script_style(script) 的返回值;None 时本模块自己算
468
+ style_plan stylekit.resolve_script_style() 或 designkit.design_to_plan() 的返回;
469
+ None 时本模块自己解析(design.audio.voice 优先,其次 stylekit)
492
470
 
493
471
  返回
494
472
  ----
495
473
  list[dict],每行:id / kind / persona / tone / voice / rate / pitch / volume /
496
474
  gain_db / lead / tail / reason。rate/pitch/volume 是可直接透传 edge-tts 的字符串。
475
+ persona 字段**保留但恒为 None**(老下游可能读它);voice 恒为 edge voice id。
497
476
  """
498
477
  script = script if isinstance(script, dict) else {}
499
478
  sp = _resolve(script, style_plan)
500
479
  lines = [ln for ln in (script.get("lines") or [])]
480
+ if not lines:
481
+ return [] # 空剧本给空计划;缺 lines 由 filmcheck 报
501
482
  vsec = sp.get("voice") if isinstance(sp.get("voice"), dict) else {}
502
483
  policy = vsec.get("policy") if isinstance(vsec.get("policy"), dict) else {}
503
484
  pace = sp.get("pacing") if isinstance(sp.get("pacing"), dict) else {}
504
485
 
505
- if sp.get("legacy"):
506
- return _legacy_plan(script, lines, pace)
507
-
508
- jitter = max(0.0, float(policy.get("jitter", 0.35)))
486
+ # ---- 声线来源:显式覆盖 > 设计 > 风格包(合并时后者先铺、前者覆盖)----
487
+ s_vid, s_map = _script_voice(script)
488
+ d_vid, d_map, d_pol = _design_voice(script)
489
+ p_map, p_default = _style_voice(sp)
490
+ vmap = {}
491
+ vmap.update(p_map)
492
+ vmap.update(d_map)
493
+ vmap.update(s_map)
494
+ default = s_vid or d_vid or p_default
495
+ for field, m in (("script.voice.map", s_map), ("design.audio.voice.map", d_map),
496
+ ("style_plan.voice.map", p_map)):
497
+ _validate_voice_map(field, m)
498
+ for field, vid in (("script.voice.id", s_vid), ("design.audio.voice.id", d_vid),
499
+ ("style_plan.voice.default", p_default)):
500
+ if vid and not is_edge_voice(vid):
501
+ raise _bad_voice(field, vid)
502
+
503
+ scalar = script.get("voice")
504
+ has_line_voice = any(isinstance(ln, dict) and ln.get("voice") for ln in lines)
505
+ if isinstance(scalar, str) and scalar.strip():
506
+ # 顶层单值 voice。声线事实来源只有 design.audio.voice(或逐句 voice),
507
+ # 再读它会和 design 打架,而「谁生效」取决于调用顺序 —— 最难查的一类。
508
+ raise _old_structure(script, sp, scalar.strip())
509
+ if not (default or vmap or has_line_voice):
510
+ # 没有任何来源时**不猜**:静默套 kind 缺省会让整片悄悄换声线。
511
+ # 宁可报错一次,让人把 design.audio.voice 补上。
512
+ if isinstance(script.get("design"), dict):
513
+ raise ValueError(
514
+ "design.audio.voice 没有给出声线(id 与 map 都为空):D3 起设计必须明确"
515
+ "「谁在说话」。\n" + _MIGRATE)
516
+ raise _old_structure(script, sp)
517
+
518
+ # 策略:显式 style_plan 优先;没有(例如直接 voice_plan(script))就用设计里的策略。
519
+ # jitter 缺省 0.0 —— 抖动必须是设计采样出来的,不能由计划层凭空加。
520
+ if not policy and d_pol:
521
+ policy = d_pol
522
+ jitter = max(0.0, float(policy.get("jitter", 0.0)))
509
523
  use_rules = _as_bool(policy.get("auto"), True)
510
- max_distinct = max(1, int(policy.get("max_distinct", 3)))
511
524
  rate_lim = tuple(policy.get("rate_range") or _RATE_LIMIT)
512
525
  pitch_lim = tuple(policy.get("pitch_range") or _PITCH_LIMIT)
513
- vmap = vsec.get("map") if isinstance(vsec.get("map"), dict) else {}
514
- default = str(vsec.get("default") or "").strip()
515
- default = default if default in VOICE_PERSONAS else ""
516
526
  base_lead = float(pace.get("lead", 0.55))
517
527
  base_tail = float(pace.get("tail", 0.85))
518
528
  title = str(script.get("title") or "")
519
- # 正文声线锚点:预算用尽时回落用它,让"旁白"始终是正文那把声音
520
- body_persona = vmap.get("body") if vmap.get("body") in VOICE_PERSONAS else None
521
- body_persona = body_persona or default or KIND_DEFAULT.get("body", "narrator_male")
522
529
 
523
- rows, used = [], []
524
- prev_persona, prev_kind = None, None
530
+ rows = []
525
531
  for i, ln in enumerate(lines):
526
532
  ln = ln if isinstance(ln, dict) else {}
527
533
  lid = str(ln.get("id") or ("l%02d" % (i + 1)))
@@ -530,43 +536,42 @@ def voice_plan(script, style_plan=None):
530
536
  rules = _rules(ln.get("text")) if use_rules else {
531
537
  "tone": "", "rate": 0, "volume": 0, "tail": 0.0, "reasons": []}
532
538
 
533
- cand, explicit, raw_voice = _pick_persona(ln, kind, vmap, default, reasons)
534
- # 文本规则也要能换人:kind 仍标 body 的「他说:『…』」不能还是正文那条嗓子,
535
- # 否则语气换了、声音没换,听感依旧是同一个人在念。显式 voice/tone 优先级更高。
536
- quote_rule = False
537
- if not explicit and rules["tone"] == "quote" and cand is not None and cand == body_persona:
538
- quote_p = vmap.get("quote") if vmap.get("quote") in VOICE_PERSONAS else None
539
- quote_p = quote_p or KIND_DEFAULT.get("quote", "narrator_female")
540
- if quote_p != cand:
541
- cand = quote_p
542
- quote_rule = True
543
- reasons.append("rule:quote:persona")
544
- final, gov = _govern(cand, prev_persona, kind, prev_kind, used, max_distinct,
545
- explicit, body_persona, quote_rule)
546
- if gov:
547
- reasons.append(gov)
548
- if final is not None and final not in used:
549
- used.append(final)
539
+ # 身份只有一个来源,写错就报错,不「悄悄回落到某个缺省声线」:
540
+ # 写错名会静默换人(听感变了但没有任何提示),是本项目最忌讳的坑。
541
+ raw_p = ln.get("persona")
542
+ if raw_p not in (None, ""):
543
+ raise _bad_voice("lines[%d].persona" % i, raw_p)
544
+ raw_v = ln.get("voice")
545
+ if raw_v not in (None, ""):
546
+ voice = str(raw_v).strip()
547
+ if not is_edge_voice(voice):
548
+ raise _bad_voice("lines[%d].voice" % i, raw_v)
549
+ reasons.append("explicit:voice")
550
+ else:
551
+ mapped = vmap.get(kind, vmap.get("*"))
552
+ if mapped:
553
+ voice = mapped
554
+ reasons.append("map:%s" % kind)
555
+ elif default:
556
+ voice = default
557
+ reasons.append("default")
558
+ else:
559
+ raise ValueError(
560
+ "声线映射没覆盖 lines[%d].kind=%r,也没有全片主声线:不知道这句该谁念。\n"
561
+ "补 design.audio.voice.id(全片主声线)或 map[%r]。\n%s"
562
+ % (i, kind, kind, _MIGRATE))
550
563
 
551
564
  tone_name = _pick_tone(ln, kind, rules, use_rules, reasons)
552
565
  tone = VOICE_TONES[tone_name]
553
566
 
554
- if final is not None:
555
- p = VOICE_PERSONAS[final]
556
- voice = p["voice"]
557
- rate_v = parse_pct(p["rate"]) + tone["rate_delta"]
558
- pitch_v = parse_hz(p["pitch"]) + tone["pitch_delta"]
559
- vol_v = parse_pct(p["volume"]) + tone["volume_delta"]
560
- gain = float(p["gain_db"]) + float(tone["gain_db"])
561
- else: # 显式原始 voice id:没有 persona 底子,只叠语气
562
- voice = raw_voice or LEGACY_VOICE
563
- rate_v = tone["rate_delta"]
564
- pitch_v = tone["pitch_delta"]
565
- vol_v = tone["volume_delta"]
566
- gain = float(tone["gain_db"])
567
-
568
- rate_v += rules["rate"]
569
- vol_v += rules["volume"]
567
+ # 音色补偿(设备)+ 语气补偿(表演);表里没有的音色按 0 dB 并把事实写进 reason。
568
+ gain = float(VOICE_LOUDNESS.get(voice, 0.0)) + float(tone["gain_db"])
569
+ if voice not in VOICE_LOUDNESS:
570
+ reasons.append("unmeasured_voice")
571
+
572
+ rate_v = tone["rate_delta"] + rules["rate"]
573
+ pitch_v = tone["pitch_delta"]
574
+ vol_v = tone["volume_delta"] + rules["volume"]
570
575
  if use_rules:
571
576
  reasons.extend(rules["reasons"])
572
577
 
@@ -575,7 +580,7 @@ def voice_plan(script, style_plan=None):
575
580
 
576
581
  u_rate, u_pitch = 0.0, 0.0
577
582
  if jitter > 0:
578
- jr, jp, jl, jt, u_rate, u_pitch = _jitter(title, lid, final or voice)
583
+ jr, jp, jl, jt, u_rate, u_pitch = _jitter(title, lid, voice)
579
584
  rate_v += jr * jitter
580
585
  pitch_v += jp * jitter
581
586
  lead += jl * jitter
@@ -593,7 +598,7 @@ def voice_plan(script, style_plan=None):
593
598
  reasons.append("clamp:volume")
594
599
 
595
600
  # edge-tts 只收整数:jitter>0 时用确定性随机进位(长期期望=浮点目标),
596
- # jitter=0 时退化为纯四舍五入,保证与无抖动逐字段相等。
601
+ # jitter=0 时退化为纯四舍五入,保证与「无抖动」逐字段相等。
597
602
  if jitter > 0:
598
603
  rate_s = "%+d%%" % _quantize(rate_c, u_rate)
599
604
  pitch_s = "%+dHz" % _quantize(pitch_c, u_pitch)
@@ -602,22 +607,18 @@ def voice_plan(script, style_plan=None):
602
607
  pitch_s = fmt_hz(pitch_c)
603
608
 
604
609
  rows.append({
605
- "id": lid, "kind": kind, "persona": final, "tone": tone_name,
610
+ "id": lid, "kind": kind, "persona": None, "tone": tone_name,
606
611
  "voice": voice, "rate": rate_s, "pitch": pitch_s,
607
612
  "volume": fmt_pct(vol_c), "gain_db": round(gain, 2),
608
613
  "lead": _fmt_num(_clamp(lead, _LEAD_LIMIT[0], _LEAD_LIMIT[1])),
609
614
  "tail": _fmt_num(_clamp(tail, _TAIL_LIMIT[0], _TAIL_LIMIT[1])),
610
615
  "reason": ";".join(reasons),
611
616
  })
612
- prev_persona = final if final is not None else prev_persona
613
- # 生效类型:引号句虽然 kind 标 body,但已经按 quote 声线念了,
614
- # 下一句普通正文才算"换段",否则会被同 kind 粘连规则永远锁在引用声线上。
615
- prev_kind = "quote" if quote_rule else kind
616
617
  return rows
617
618
 
618
619
 
619
620
  # ============================================================================
620
- # 六、缓存键(v2:trim 进 key,修 v0.4 的静默复用 bug)
621
+ # 六、缓存键(v2:trim 进 key,否则改 trim 会静默复用旧音频)
621
622
  # ============================================================================
622
623
  def _norm_pct(v, default="+0%"):
623
624
  if v in (None, ""):
@@ -634,7 +635,7 @@ def _norm_hz(v, default="+0Hz"):
634
635
  def spec_key(spec):
635
636
  """v2 合成缓存键:sha1("v2|text|voice|rate|pitch|volume|trim|trim_db")[:16]。
636
637
 
637
- 与 v0.4 的 tts_key(text|voice|rate|pitch)不复用:v0.4 把 trim 漏在 key 外,
638
+ 不复用旧的 tts_key(text|voice|rate|pitch):那套键把 trim 漏在 key 外,
638
639
  同一句改 trim/trim_db 会静默复用旧音频。spec 传一行计划 + text 即可:
639
640
  spec_key(dict(plan[0], text=line["text"]));trim/trim_db 缺省与 filmkit.tts 一致。
640
641
  """
@@ -652,56 +653,53 @@ def spec_key(spec):
652
653
 
653
654
 
654
655
  def plan_stats(plan):
655
- """计划摘要:用了几个 persona / 哪些语气 / 是否 legacy(测试与日志用)。"""
656
+ """计划摘要:用了几把声音 / 哪些语气(测试与日志用)。"""
656
657
  rows = [r for r in (plan or []) if isinstance(r, dict)]
657
- personas = []
658
- tones = []
658
+ voices, tones = [], []
659
659
  for r in rows:
660
- p, t = r.get("persona"), r.get("tone")
661
- if p and p not in personas:
662
- personas.append(p)
660
+ v, t = r.get("voice"), r.get("tone")
661
+ if v and v not in voices:
662
+ voices.append(v)
663
663
  if t and t not in tones:
664
664
  tones.append(t)
665
- return {"lines": len(rows), "personas": personas, "tones": tones,
666
- "distinct": len(personas),
667
- "legacy": bool(rows) and all(r.get("reason") == "legacy" for r in rows)}
665
+ return {"lines": len(rows), "voices": voices, "tones": tones, "distinct": len(voices)}
668
666
 
669
667
 
670
668
  # ============================================================================
671
669
  # 七、人读输出
672
670
  # ============================================================================
673
671
  def describe(plan):
674
- """把计划表打成人可读的多行文本(id/kind/persona/tone/voice/rate/lead/tail)。"""
672
+ """把计划表打成人可读的多行文本(id/kind/voice/tone/rate/pitch/vol/gain/lead/tail)。"""
675
673
  rows = [r for r in (plan or []) if isinstance(r, dict)]
676
- head = "%-8s %-7s %-18s %-9s %-28s %-6s %-6s %-6s" % (
677
- "id", "kind", "persona", "tone", "voice", "rate", "lead", "tail")
674
+ head = "%-8s %-7s %-28s %-9s %-6s %-6s %-6s %-6s %-6s %-6s" % (
675
+ "id", "kind", "voice", "tone", "rate", "pitch", "vol", "gain", "lead", "tail")
678
676
  out = [head, "-" * len(head)]
679
677
  for r in rows:
680
- out.append("%-8s %-7s %-18s %-9s %-28s %-6s %-6.2f %-6.2f" % (
681
- str(r.get("id", "")), str(r.get("kind", "")),
682
- str(r.get("persona") or "-"), str(r.get("tone", "")),
683
- str(r.get("voice", "")), str(r.get("rate", "")),
678
+ out.append("%-8s %-7s %-28s %-9s %-6s %-6s %-6s %+6.2f %-6.2f %-6.2f" % (
679
+ str(r.get("id", "")), str(r.get("kind", "")), str(r.get("voice", "")),
680
+ str(r.get("tone", "")), str(r.get("rate", "")), str(r.get("pitch", "")),
681
+ str(r.get("volume", "")), float(r.get("gain_db", 0.0)),
684
682
  float(r.get("lead", 0.0)), float(r.get("tail", 0.0))))
685
683
  return "\n".join(out)
686
684
 
687
685
 
688
686
  # ============================================================================
689
- # 八、校准:真合成、真实测,失败优雅降级(返回 0,不阻塞主链)
687
+ # 八、校准:真合成、真实测;离线优雅降级(不抛异常,不阻塞主链)
690
688
  # ============================================================================
691
- def _measure_wav(path):
692
- """读 24k 单声道 wav,返回 dur/cps/rms_db/peak_db(纯标准库,不用 numpy)。"""
689
+ def _measure_wav(path, text=CALIB_TEXT):
690
+ """读 24k 单声道 16-bit wav,返回 dur/cps/rms_db(纯标准库,不用 numpy)。"""
693
691
  with wave.open(path, "rb") as w:
694
692
  sr = w.getframerate()
695
693
  n = w.getnframes()
694
+ if w.getsampwidth() != 2:
695
+ raise ValueError("只接受 16-bit PCM wav(ffmpeg 要带 -sample_fmt s16)")
696
696
  raw = w.readframes(n)
697
- import array
698
697
  data = array.array("h")
699
698
  data.frombytes(raw)
700
699
  if sys.byteorder == "big":
701
700
  data.byteswap()
702
701
  total = len(data)
703
702
  dur = total / float(sr) if sr else 0.0
704
- peak = max((abs(v) for v in data), default=0) / 32768.0
705
703
  fl = max(1, int(0.02 * sr))
706
704
  hop = max(1, int(0.01 * sr))
707
705
  frames = []
@@ -715,73 +713,182 @@ def _measure_wav(path):
715
713
  frames.append(math.sqrt(acc / float(len(seg))) / 32768.0)
716
714
  gated = [x for x in frames if x > 10 ** (-45.0 / 20.0)]
717
715
  rms = math.sqrt(sum(x * x for x in gated) / len(gated)) if gated else 1e-6
718
- return {"dur": dur, "cps": hanzi_count(CALIB_TEXT) / dur if dur else 0.0,
719
- "rms_db": 20.0 * math.log10(rms + 1e-12),
720
- "peak_db": 20.0 * math.log10(peak + 1e-12)}
716
+ return {"dur": dur, "cps": hanzi_count(text) / dur if dur else 0.0,
717
+ "rms_db": 20.0 * math.log10(rms + 1e-12)}
718
+
719
+
720
+ def _gain_for(rms_db):
721
+ """实测 RMS -> 建议补偿(目标响度 - 实测,夹在 ±3 dB,保留 2 位)。"""
722
+ return round(_clamp(CALIB_TARGET_DB - float(rms_db), -_GAIN_LIMIT, _GAIN_LIMIT), 2)
723
+
724
+
725
+ _CALIB_TIMEOUT = 30.0 # 单条合成上限:没网时不能让主链挂死
726
+ _CALIB_CACHE = os.path.join("work", "voice_calib.json")
727
+ _CALIB_SCHEMA = 1
728
+
729
+
730
+ def _calib_path(cache_path=None):
731
+ return str(cache_path or _CALIB_CACHE)
732
+
733
+
734
+ def _load_calib(cache_path):
735
+ """读缓存 -> (校准文本, {voice: {rms_db, cps, dur}});读不了/结构不对 -> (None, {})。"""
736
+ try:
737
+ with open(cache_path, "r", encoding="utf-8") as f:
738
+ data = json.load(f)
739
+ except (OSError, ValueError):
740
+ return None, {}
741
+ if not isinstance(data, dict) or data.get("schema") != _CALIB_SCHEMA:
742
+ return None, {}
743
+ voices = data.get("voices")
744
+ return str(data.get("text") or ""), (voices if isinstance(voices, dict) else {})
745
+
746
+
747
+ def _store_calib(cache_path, text, row):
748
+ """只缓存**成功测量**:失败也写会把一次断网固化成「测过」,之后永远读到假数据。"""
749
+ _, voices = _load_calib(cache_path)
750
+ voices = dict(voices)
751
+ voices[row["voice"]] = {"rms_db": row["rms_db"], "cps": row["cps"], "dur": row["dur"]}
752
+ # target_db 记下来只为审计(换机后一眼看出上次按多少 dBFS 补的);
753
+ # 读缓存时 gain 仍然用**当前** CALIB_TARGET_DB 现算,改目标不用清缓存。
754
+ data = {"schema": _CALIB_SCHEMA, "text": text, "target_db": CALIB_TARGET_DB,
755
+ "voices": voices}
756
+ try:
757
+ d = os.path.dirname(os.path.abspath(cache_path))
758
+ os.makedirs(d, exist_ok=True)
759
+ with open(cache_path, "w", encoding="utf-8") as f:
760
+ json.dump(data, f, ensure_ascii=False, indent=1)
761
+ except OSError as e: # 缓存写不进去不影响本次结果,但要说出来
762
+ return "%s: %s" % (type(e).__name__, e)
763
+ return ""
764
+
765
+
766
+ async def _synthesize(edge_tts, text, voice, out_mp3):
767
+ """合成一句校准文本;wait_for 是防「没网时挂死」的硬上限。"""
768
+ await asyncio.wait_for(
769
+ edge_tts.Communicate(text, voice).save(out_mp3), timeout=_CALIB_TIMEOUT)
721
770
 
722
771
 
723
- def calibrate(personas=None, log=None):
724
- """逐个 persona 合成校准句,实测 dur/cps/门限 RMS,打印建议 gain_db。
772
+ def calibrate_voice(voice_id, cache_path=None, text=None):
773
+ """实测一把音色的响度补偿;能联网才真测,其余情况优雅降级(绝不抛异常)。
725
774
 
726
- 只在这里 import edge_tts(其余函数纯标准库,方便无网环境单测)。
727
- 没装 edge_tts / 没 ffmpeg / 没网:打印 SKIP 并返回 0,绝不让主链失败。
775
+ 参数
776
+ ----
777
+ voice_id edge voice id(zh-CN-YunxiNeural)
778
+ cache_path 结果缓存,默认 work/voice_calib.json;同一把音色下次直接读
779
+ text 校准文本,默认 CALIB_TEXT(改文本会让旧缓存失效并重测)
780
+
781
+ 返回 dict:
782
+ 测得 {'voice', 'rms_db', 'cps', 'dur', 'gain_db', 'measured': True[, 'cached': True]}
783
+ 降级 {'voice', 'rms_db': None, 'cps': None, 'gain_db': 表里的值,
784
+ 'measured': False, 'reason': '为什么没测成'}
785
+ gain_db 沿用口径:CALIB_TARGET_DB - 实测 rms_db,夹在 ±3 dB。
786
+
787
+ 为什么要缓存:edge-tts 是免费端点,校准句要真联网合成;每句计划都去测一遍既慢
788
+ 也不稳定。但**只缓存成功测量**——失败也写缓存的话,一次断网就会把「没测」固化成
789
+ 「测过」,下一台机器照抄一个假增益,比没补还糟。
728
790
  """
729
- log = log or (lambda s: None)
791
+ vid = str(voice_id or "").strip()
792
+ text = str(text or CALIB_TEXT)
793
+ cache = _calib_path(cache_path)
794
+ base = {"voice": vid, "rms_db": None, "cps": None, "dur": None,
795
+ "gain_db": float(VOICE_LOUDNESS.get(vid, 0.0)), "measured": False}
796
+
797
+ if not is_edge_voice(vid):
798
+ base["reason"] = ("不是 edge voice id:%r(persona 名已删除;写 zh-CN-XxxNeural)"
799
+ % vid)
800
+ return base
801
+
802
+ cached_text, voices = _load_calib(cache)
803
+ hit = voices.get(vid) if cached_text == text else None
804
+ try:
805
+ rms = float(hit["rms_db"]) if isinstance(hit, dict) else None
806
+ except (KeyError, TypeError, ValueError):
807
+ rms = None
808
+ if rms is not None:
809
+ try:
810
+ cps = float(hit.get("cps") or 0.0)
811
+ dur = float(hit.get("dur") or 0.0)
812
+ except (TypeError, ValueError):
813
+ cps, dur = 0.0, 0.0
814
+ base.update(rms_db=round(rms, 2), cps=round(cps, 2), dur=round(dur, 2),
815
+ gain_db=_gain_for(rms), measured=True, cached=True)
816
+ return base
817
+
730
818
  try:
731
819
  import edge_tts
732
- except Exception as e: # noqa: BLE001
733
- log("[SKIP] 没装 edge_tts(%s: %s),跳过校准" % (type(e).__name__, e))
734
- return 0
820
+ except Exception as e: # noqa: BLE001 — 没装就降级,不拖垮主链
821
+ base["reason"] = "没装 edge_tts(%s: %s)" % (type(e).__name__, e)
822
+ return base
735
823
  ffmpeg = shutil.which("ffmpeg")
736
824
  if not ffmpeg:
737
- log("[SKIP] 没找到 ffmpeg,无法把 mp3 解成 PCM 测 RMS,跳过校准")
738
- return 0
739
- ids = [p for p in (personas or PERSONA_IDS) if p in VOICE_PERSONAS]
825
+ base["reason"] = "没找到 ffmpeg,没法把 mp3 解成 PCM 测 RMS"
826
+ return base
827
+
740
828
  tmp = tempfile.mkdtemp(prefix="voicekit_cal_")
741
- rows = {}
742
829
  try:
743
- import asyncio
744
- for pid in ids:
745
- p = VOICE_PERSONAS[pid]
746
- mp3 = os.path.join(tmp, pid + ".mp3")
747
- wav = os.path.join(tmp, pid + ".wav")
748
-
749
- async def _go(_p=p, _mp3=mp3):
750
- await edge_tts.Communicate(CALIB_TEXT, _p["voice"], rate=_p["rate"],
751
- pitch=_p["pitch"], volume=_p["volume"]).save(_mp3)
752
-
753
- try:
754
- asyncio.run(_go())
755
- r = subprocess.run([ffmpeg, "-y", "-v", "error", "-i", mp3,
756
- "-ac", "1", "-ar", "24000", "-sample_fmt", "s16", wav],
757
- capture_output=True, text=True)
758
- if r.returncode != 0:
759
- raise RuntimeError((r.stderr or "")[-200:])
760
- m = _measure_wav(wav)
761
- rows[pid] = m
762
- log(" OK %-18s %-28s dur %.2fs cps %.2f rms %.2f dBFS"
763
- % (pid, p["voice"], m["dur"], m["cps"], m["rms_db"]))
764
- except Exception as e: # noqa: BLE001 — 单条失败不该中断整表
765
- log(" SKIP %-18s %s: %s" % (pid, type(e).__name__, str(e)[:110]))
830
+ mp3 = os.path.join(tmp, "cal.mp3")
831
+ wav = os.path.join(tmp, "cal.wav")
832
+ coro = _synthesize(edge_tts, text, vid, mp3)
833
+ try:
834
+ asyncio.run(coro)
835
+ except Exception as e: # noqa: BLE001 — 没网/端点不可用都走这里
836
+ # 事件循环有时根本起不来(asyncio.run 在 await 之前就抛),协程没人接;
837
+ # 不关掉的话「never awaited」警告会盖住真正的原因,误导排查方向。
838
+ coro.close()
839
+ base["reason"] = ("合成失败(多半是没网或 edge 端点临时不可用):%s: %s"
840
+ % (type(e).__name__, str(e)[:160]))
841
+ return base
842
+ try:
843
+ r = subprocess.run([ffmpeg, "-y", "-v", "error", "-i", mp3,
844
+ "-ac", "1", "-ar", "24000", "-sample_fmt", "s16", wav],
845
+ capture_output=True, text=True)
846
+ if r.returncode != 0:
847
+ raise RuntimeError((r.stderr or "")[-200:])
848
+ m = _measure_wav(wav, text)
849
+ except Exception as e: # noqa: BLE001 — 解码/测量失败同样降级
850
+ base["reason"] = "ffmpeg 解码或测量失败:%s" % str(e)[:160]
851
+ return base
852
+ got = {"voice": vid, "rms_db": round(m["rms_db"], 2), "cps": round(m["cps"], 2),
853
+ "dur": round(m["dur"], 2), "gain_db": _gain_for(m["rms_db"]),
854
+ "measured": True}
855
+ err = _store_calib(cache, text, got)
856
+ if err:
857
+ got["cache_error"] = err
858
+ return got
766
859
  finally:
767
860
  shutil.rmtree(tmp, ignore_errors=True)
768
- if not rows:
769
- log("[SKIP] 所有音色都合成失败(多半是没网或 edge 端点临时不可用),未产生校准值")
770
- return 0
771
- target = sorted(r["rms_db"] for r in rows.values())[len(rows) // 2]
861
+
862
+
863
+ def calibrate(voices=None, log=None):
864
+ """逐把音色实测,打印「实测 vs 表里」,并给出该抄回 VOICE_LOUDNESS 的数。
865
+
866
+ edge_tts 只在真测时 import(其余函数纯标准库,方便无网环境单测)。
867
+ 没装 edge_tts / 没 ffmpeg / 没网:逐条 SKIP,返回 0,绝不让主链失败。
868
+ """
869
+ log = log or (lambda s: None)
870
+ ids = [str(v).strip() for v in (voices or list(VOICE_LOUDNESS)) if str(v).strip()]
871
+ log("校准文本:%s(%d 个汉字)" % (CALIB_TEXT, hanzi_count(CALIB_TEXT)))
872
+ log("目标响度:%.2f dBFS(CALIBRATION_LOG 实测中位数);gain 夹在 ±%.1f dB"
873
+ % (CALIB_TARGET_DB, _GAIN_LIMIT))
772
874
  log("")
773
- log("目标响度(%d 个 persona 门限 RMS 中位数)= %.2f dBFS" % (len(rows), target))
774
- log("%-18s %-28s %6s %6s %8s %8s %8s" % (
775
- "persona", "voice", "dur", "cps", "rms", "建议gain", "当前gain"))
776
- for pid in rows:
777
- m = rows[pid]
778
- want = _clamp(target - m["rms_db"], -_GAIN_LIMIT, _GAIN_LIMIT)
779
- cur = float(VOICE_PERSONAS[pid]["gain_db"])
780
- log("%-18s %-28s %6.2f %6.2f %8.2f %+8.2f %+8.2f%s" % (
781
- pid, VOICE_PERSONAS[pid]["voice"], m["dur"], m["cps"], m["rms_db"],
782
- want, cur, "" if abs(want - cur) < 0.35 else " <-- 建议改表"))
875
+ ok = 0
876
+ for vid in ids:
877
+ r = calibrate_voice(vid)
878
+ if r["measured"]:
879
+ ok += 1
880
+ cur = float(VOICE_LOUDNESS.get(vid, 0.0))
881
+ log(" OK %-30s rms %7.2f dBFS cps %.2f gain %+6.2f 表 %+6.2f%s"
882
+ % (vid, r["rms_db"], r["cps"], r["gain_db"], cur,
883
+ "(缓存)" if r.get("cached") else ""))
884
+ else:
885
+ log(" SKIP %-30s %s" % (vid, r.get("reason")))
783
886
  log("")
784
- log("把上面「建议gain」抄回 VOICE_PERSONAS[pid]['gain_db'],并把 CALIBRATED_ON 改成今天;")
887
+ if not ok:
888
+ log("[SKIP] 没测到任何音色(多半是没网 / 没装 edge_tts / 没 ffmpeg);"
889
+ "VOICE_LOUDNESS 保持原样,主链不受影响")
890
+ return 0
891
+ log("把上面「gain」抄回 VOICE_LOUDNESS[voice],并把 CALIBRATED_ON 改成今天;")
785
892
  log("换 voice id 必须重跑本命令 —— 不同音色的响度差 3-7 dB,凭感觉调会一句响一句轻。")
786
893
  return 0
787
894
 
@@ -799,18 +906,24 @@ def _setup_stdio():
799
906
 
800
907
 
801
908
  def _cli_list():
802
- print("voicekit 声线表(v0.5.0;校准于 %s,edge-tts 免费端点只有 8 个 zh-CN 音色)"
909
+ print("voicekit 音色表(校准于 %s;edge-tts 免费端点只有 8 个 zh-CN 音色 + zh-TW/zh-HK)"
803
910
  % CALIBRATED_ON)
804
- print("%-18s %-28s %6s %7s %7s %8s %-8s %-8s %s" % (
805
- "persona", "voice", "rate", "pitch", "volume", "gain_db", "narrate", "home", "desc"))
806
- print("-" * 150)
807
- for pid in PERSONA_IDS:
808
- p = VOICE_PERSONAS[pid]
809
- print("%-18s %-28s %6s %7s %7s %+8.2f %-8s %-8s %s" % (
810
- pid, p["voice"], p["rate"], p["pitch"], p["volume"], p["gain_db"],
811
- "yes" if p["narrate"] else "no", p["home"], p["desc"]))
911
+ print("gain_db = 目标 %.2f dBFS - 实测 RMS,夹在 ±%.1f dB(正 = 该音色偏轻,mix 侧补回来)"
912
+ % (CALIB_TARGET_DB, _GAIN_LIMIT))
913
+ print("%-30s %8s %9s %7s %7s" % ("voice", "gain_db", "实测RMS", "dur", "cps"))
914
+ print("-" * 70)
915
+ for vid, gain in VOICE_LOUDNESS.items():
916
+ m = CALIBRATION_LOG.get(vid) or {}
917
+ print("%-30s %+8.2f %9s %7s %7s" % (
918
+ vid, gain,
919
+ ("%.2f" % m["rms_db"]) if m else "-",
920
+ ("%.2f" % m["dur"]) if m else "-",
921
+ ("%.2f" % m["cps"]) if m else "-"))
922
+ print("")
923
+ print("表里没有的音色按 0 dB 处理(不猜),voice_plan 的 reason 会标 unmeasured_voice。")
924
+ print("换机 / 换 edge-tts 版本 / 换 voice id 都要重测:python voicekit.py --calibrate")
812
925
  print("")
813
- print("语气档(body 必须等于 v0.4 基准:lead 0.62 / tail 0.92 / 所有 delta=0)")
926
+ print("语气档(body 是基准行:所有 delta = 0;lead/tail 相对它偏移)")
814
927
  print("%-10s %8s %9s %9s %8s %6s %6s %s" % (
815
928
  "tone", "rate", "pitch", "volume", "gain_db", "lead", "tail", "desc"))
816
929
  print("-" * 120)
@@ -820,8 +933,8 @@ def _cli_list():
820
933
  tid, t["rate_delta"], t["pitch_delta"], t["volume_delta"], t["gain_db"],
821
934
  t["lead"], t["tail"], t["desc"]))
822
935
  print("")
823
- print("注:warm_female 用 zh-TW-HsiaoChenNeural(台湾腔软糯女声);要大陆标准音就换成")
824
- print(" zh-CN-XiaoxiaoNeural 并把 rate 改成 '-3%',其余字段不用动。")
936
+ print("注:zh-TW-HsiaoChenNeural 是台湾腔软糯女声(微软标注 Warm);要大陆标准音就换")
937
+ print(" zh-CN-XiaoxiaoNeural,响度补偿按上表 -2.7 dB,其余字段不用动。")
825
938
  return 0
826
939
 
827
940
 
@@ -836,46 +949,54 @@ def _cli_plan(path):
836
949
  print("[剧本格式错误] %s 顶层必须是对象且含非空 lines" % path)
837
950
  return 2
838
951
  sp = _resolve(script, None)
839
- plan = voice_plan(script, sp)
952
+ try:
953
+ plan = voice_plan(script, sp)
954
+ except ValueError as e: # 配置错误要能照抄着改,不要 traceback
955
+ print("[声线配置错误] %s" % e)
956
+ return 2
957
+ voce = sp.get("voice") if isinstance(sp.get("voice"), dict) else {}
840
958
  print("剧本:%s(%d 句)" % (path, len(plan)))
841
- print("风格:%s legacy=%s voice.map=%s"
842
- % (sp.get("style", "?"), bool(sp.get("legacy")),
843
- json.dumps(sp.get("voice", {}).get("map", {}), ensure_ascii=False)))
959
+ print("风格:%s voice.map=%s" % (sp.get("style") or "-",
960
+ json.dumps(voce.get("map") or {}, ensure_ascii=False)))
844
961
  print("")
845
962
  print(describe(plan))
846
963
  print("")
847
- for r, ln in zip(plan, script["lines"]):
848
- print(" %-8s rate=%-5s pitch=%-6s vol=%-5s gain=%+5.2f lead=%-5.2f tail=%-5.2f %s"
849
- % (r["id"], r["rate"], r["pitch"], r["volume"], r["gain_db"],
964
+ for r in plan:
965
+ print(" %-8s voice=%-28s rate=%-5s pitch=%-6s vol=%-5s gain=%+5.2f"
966
+ " lead=%-5.2f tail=%-5.2f %s"
967
+ % (r["id"], r["voice"], r["rate"], r["pitch"], r["volume"], r["gain_db"],
850
968
  r["lead"], r["tail"], r["reason"]))
851
969
  st = plan_stats(plan)
852
970
  print("")
853
- print("声线 %d 种:%s" % (st["distinct"], ", ".join(st["personas"]) or "-"))
971
+ print("声线 %d 种:%s" % (st["distinct"], ", ".join(st["voices"]) or "-"))
854
972
  print("语气 %d 档:%s" % (len(st["tones"]), ", ".join(st["tones"]) or "-"))
855
- print("提示:同一份剧本两次 voice_plan() 结果完全相同;legacy 剧本走 v0.4 单值路径。")
973
+ print("提示:同一份剧本两次 voice_plan() 结果完全相同;persona 字段恒为 None"
974
+ "(只为兼容下游而保留)。")
856
975
  return 0
857
976
 
858
977
 
859
978
  def main(argv=None):
860
979
  _setup_stdio()
861
980
  ap = argparse.ArgumentParser(
862
- prog="voicekit.py", description="v0.5 旁白声线/语气计划(不合成,只出计划)")
863
- ap.add_argument("--list", action="store_true", help="列出声线表与语气档")
981
+ prog="voicekit.py", description="v1.0 旁白声线/语气计划(不合成,只出计划)")
982
+ ap.add_argument("--list", action="store_true", help="列出音色响度表与语气档")
864
983
  ap.add_argument("--plan", metavar="FILM_JSON", help="打印某份 film.json 的声线计划")
865
- ap.add_argument("--calibrate", action="store_true", help="联网实测各 persona 的 dur/RMS,打印建议 gain_db")
866
- ap.add_argument("--only", metavar="PERSONA", help="--calibrate 时只测这些 persona(逗号分隔)")
984
+ ap.add_argument("--calibrate", action="store_true",
985
+ help="联网实测各音色的 dur/RMS,打印建议 gain_db(失败 SKIP 返回 0)")
986
+ ap.add_argument("--only", metavar="VOICE_ID",
987
+ help="--calibrate 时只测这些 edge voice id(逗号分隔)")
867
988
  a = ap.parse_args(argv)
868
989
  if a.list:
869
990
  return _cli_list()
870
991
  if a.calibrate:
871
992
  only = [x.strip() for x in (a.only or "").split(",") if x.strip()] or None
872
993
  if only:
873
- unknown = [x for x in only if x not in VOICE_PERSONAS]
994
+ unknown = [x for x in only if not is_edge_voice(x)]
874
995
  if unknown:
875
- # 以前拼错 persona 会静默变成空集合 -> 打出"所有音色都合成失败(多半是没网)",
996
+ # 拼错名字会静默变成空集合 -> 打出「所有音色都合成失败(多半没网)」,
876
997
  # 把配置错误伪装成网络错误。这里先点名校验,给人话可照抄的可用清单。
877
- print("[未知 persona] %s;可用:%s"
878
- % ("、".join(unknown), " / ".join(PERSONA_IDS)), file=sys.stderr)
998
+ print("[未知音色] %s;可用:%s"
999
+ % ("、".join(unknown), " / ".join(VOICE_LOUDNESS)), file=sys.stderr)
879
1000
  return 2
880
1001
  return calibrate(only, log=print)
881
1002
  if a.plan: