cortico-world-fish-sing 0.4.5 → 0.4.7

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/);版本号遵循语义化。
4
4
 
5
+ ## [0.4.7] - 2026-11-02
6
+
7
+ ### 新增
8
+ - **「测试通知」按钮**:训练页工具栏点一下立刻发一条测试通知,看它落在哪个渠道(QQ / 桌宠),不用等下一次训练结束才知道 QQ 通不通。
9
+
10
+ ### 修复
11
+ - 文本通知的 OneBot 超时从 120 秒收紧到 **15 秒**:SnowLuma 端口开着但不响应时,不会再让「训练完成」等两分钟才退桌宠(发语音条仍是 120 秒,mp3→SILK 转换本来就慢)。
12
+
13
+ ## [0.4.6] - 2026-11-02
14
+
15
+ ### 修复
16
+ - **新数据训练 loss 从第 0 步就是 NaN**(导入 16 首新歌后必现):数据准备把切片写成 **PCM_24 整型 wav**,而 RVC 训练用 `scipy.io.wavfile.read` 读音频——整型被当成 ±838 万的**原始整数**(不归一化),mel 炸到 1e11、判别器损失 1e18,fp16 下溢出成 NaN。老数据集是 float wav 所以一直没事。修复三件套:
17
+ - 数据准备改写 **FLOAT** wav(与 RVC 官方一致);
18
+ - `prepare` 装载时把整型 wav 统一转 float32(**自动修复已有实验和老数据集**,不用重跑数据准备);
19
+ - 低音增强的 40k 副本改写 `pcm_f32le`。
20
+ - 顺手修:全 1x 采样权重时不再生成"全 0.333"的伪权重表(0.4.0 引入的副产品,会白跑加权采样路径)。
21
+ - 测试:切片必须为 FLOAT、全 1x 权重不展开。
22
+
5
23
  ## [0.4.5] - 2026-11-02
6
24
 
7
25
  ### 修复
@@ -722,7 +722,9 @@ function mountTrain(ctx) {
722
722
  const pathIn = el('input', 'fs-tpath');
723
723
  pathIn.placeholder = '粘贴素材文件夹或单个文件路径,可多个用 ; 分隔';
724
724
  const scanBtn = el('button', 'fs-btn', '扫描');
725
- bar.append(pathIn, scanBtn);
725
+ const notifyTest = el('button', 'fs-btn', '测试通知');
726
+ notifyTest.title = '立刻发一条测试通知:QQ 通就发 QQ,不通就退桌宠——点了就知道渠道状态';
727
+ bar.append(pathIn, scanBtn, notifyTest);
726
728
 
727
729
  const dsBar = el('div', 'fs-bar');
728
730
  const dsSel = el('select', 'fs-btn');
@@ -1512,6 +1514,20 @@ function mountTrain(ctx) {
1512
1514
  appendLabel.textContent = appendChk.checked ? '追加到当前数据集' : '新建数据集';
1513
1515
  });
1514
1516
 
1517
+ notifyTest.addEventListener('click', async () => {
1518
+ notifyTest.disabled = true;
1519
+ notifyTest.textContent = '发送中…';
1520
+ try {
1521
+ const r = await ctx.invoke('trainNotifyTest');
1522
+ say((r && r.note) ? `通知:${r.note}${r.via ? `(${r.via})` : ''}` : '通知已发');
1523
+ } catch (e) {
1524
+ say(`测试通知失败:${(e && e.message) || e}`, true);
1525
+ } finally {
1526
+ notifyTest.disabled = false;
1527
+ notifyTest.textContent = '测试通知';
1528
+ }
1529
+ });
1530
+
1515
1531
  scanBtn.addEventListener('click', async () => {
1516
1532
  const raw = String(pathIn.value || '').trim();
1517
1533
  if (!raw) {
package/dist/webui.js CHANGED
@@ -722,7 +722,9 @@ function mountTrain(ctx) {
722
722
  const pathIn = el('input', 'fs-tpath');
723
723
  pathIn.placeholder = '粘贴素材文件夹或单个文件路径,可多个用 ; 分隔';
724
724
  const scanBtn = el('button', 'fs-btn', '扫描');
725
- bar.append(pathIn, scanBtn);
725
+ const notifyTest = el('button', 'fs-btn', '测试通知');
726
+ notifyTest.title = '立刻发一条测试通知:QQ 通就发 QQ,不通就退桌宠——点了就知道渠道状态';
727
+ bar.append(pathIn, scanBtn, notifyTest);
726
728
 
727
729
  const dsBar = el('div', 'fs-bar');
728
730
  const dsSel = el('select', 'fs-btn');
@@ -1512,6 +1514,20 @@ function mountTrain(ctx) {
1512
1514
  appendLabel.textContent = appendChk.checked ? '追加到当前数据集' : '新建数据集';
1513
1515
  });
1514
1516
 
1517
+ notifyTest.addEventListener('click', async () => {
1518
+ notifyTest.disabled = true;
1519
+ notifyTest.textContent = '发送中…';
1520
+ try {
1521
+ const r = await ctx.invoke('trainNotifyTest');
1522
+ say((r && r.note) ? `通知:${r.note}${r.via ? `(${r.via})` : ''}` : '通知已发');
1523
+ } catch (e) {
1524
+ say(`测试通知失败:${(e && e.message) || e}`, true);
1525
+ } finally {
1526
+ notifyTest.disabled = false;
1527
+ notifyTest.textContent = '测试通知';
1528
+ }
1529
+ });
1530
+
1515
1531
  scanBtn.addEventListener('click', async () => {
1516
1532
  const raw = String(pathIn.value || '').trim();
1517
1533
  if (!raw) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-fish-sing",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "description": "让她真的开口唱:B 站点歌或本地文件 → 分离 → 换声 → 混音,本机出声或发 QQ 语音条",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -36,7 +36,7 @@
36
36
  "local"
37
37
  ],
38
38
  "describe": "describe.json",
39
- "webUiClient": "dist/webui-4d01e72b.js"
39
+ "webUiClient": "dist/webui-a1576ab5.js"
40
40
  },
41
41
  "scripts": {
42
42
  "doctor": "node tools/doctor.mjs"
package/src/deliver.ts CHANGED
@@ -99,7 +99,12 @@ export function parseTarget(to: string): OneBotTarget | null {
99
99
  : { action: 'send_private_msg', params: { user_id: id }, label: `私聊 ${id}` };
100
100
  }
101
101
 
102
- async function callOneBot(opts: OneBotOptions, action: string, params: Record<string, unknown>): Promise<void> {
102
+ async function callOneBot(
103
+ opts: OneBotOptions,
104
+ action: string,
105
+ params: Record<string, unknown>,
106
+ timeoutMs = 120_000,
107
+ ): Promise<void> {
103
108
  const res = await fetch(`${opts.httpUrl.replace(/\/+$/, '')}/${action}`, {
104
109
  method: 'POST',
105
110
  headers: {
@@ -107,7 +112,7 @@ async function callOneBot(opts: OneBotOptions, action: string, params: Record<st
107
112
  ...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),
108
113
  },
109
114
  body: JSON.stringify(params),
110
- signal: AbortSignal.timeout(120_000),
115
+ signal: AbortSignal.timeout(timeoutMs),
111
116
  });
112
117
  const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
113
118
  if (!res.ok) throw new Error(`OneBot HTTP ${res.status}`);
@@ -126,8 +131,12 @@ export async function sendRecord(opts: OneBotOptions, target: OneBotTarget, file
126
131
  }
127
132
 
128
133
  export async function sendText(opts: OneBotOptions, target: OneBotTarget, text: string): Promise<void> {
129
- await callOneBot(opts, target.action, {
130
- ...target.params,
131
- message: [{ type: 'text', data: { text } }],
132
- });
134
+ // 文本通知给短超时:SnowLuma 端口开着但不响应时,别让"训练完成"等两分钟才退桌宠。
135
+ // 语音条(sendRecord)仍用 120 秒——大文件 + mp3→SILK 转换本来就慢。
136
+ await callOneBot(
137
+ opts,
138
+ target.action,
139
+ { ...target.params, message: [{ type: 'text', data: { text } }] },
140
+ 15_000,
141
+ );
133
142
  }
package/src/world.ts CHANGED
@@ -1171,6 +1171,15 @@ export class FishSingWorld implements World {
1171
1171
  return { text: text || `没生成:${exp} 只找到一个可用存档(中间档可能已被清理)` };
1172
1172
  }
1173
1173
 
1174
+ if (method === 'trainNotifyTest') {
1175
+ // 「QQ 通不通」不用等下一次训练结束才知道:手动发一条,看落在哪个渠道。
1176
+ const out = (await this.notifyEvent(
1177
+ '测试通知(唱歌插件)',
1178
+ '这是一条测试消息:收到就说明通知渠道通了。',
1179
+ )) as { via?: string; note?: string };
1180
+ return { via: out?.via ?? '', note: out?.note ?? '' };
1181
+ }
1182
+
1174
1183
  if (method === 'trainStop') {
1175
1184
  await this.worker.cancel();
1176
1185
  if (this.trainJob?.state === 'running') {
@@ -60,6 +60,8 @@ class DatasetSlicing(unittest.TestCase):
60
60
  # 音频内容验证:读回来时长要和 manifest 一致
61
61
  info = sf.info(str(out / slices[0]["file"]))
62
62
  self.assertAlmostEqual(info.duration, slices[0]["dur"], delta=0.05)
63
+ # 必须是 FLOAT:RVC 训练用 scipy.read 读,整型会被当成天文数字(mel 爆炸)
64
+ self.assertEqual(info.subtype, "FLOAT", "切片必须是 float wav")
63
65
 
64
66
  def test_self_check_rejects_empty(self):
65
67
  # 直接验证写盘自检:构造一个"声称 3.7s 但只有文件头"的切片 → build 必须报错
@@ -1,84 +1,89 @@
1
- """训练侧纯逻辑测试(无 GPU、无 ffmpeg 依赖)。跑法:python -m unittest discover -s tests -v"""
2
- import json
3
- import sys
4
- import tempfile
5
- import unittest
6
- from pathlib import Path
7
-
8
- ROOT = Path(__file__).resolve().parent.parent
9
- sys.path.insert(0, str(ROOT / "worker"))
10
-
11
- import trainer # noqa: E402
12
-
13
-
14
- class ExpandAugWeights(unittest.TestCase):
15
- """低音增强副本的采样权重摊薄。"""
16
-
17
- def test_inherit_and_divide(self):
18
- w = {"a.wav": 3.0, "b.wav": 1.0}
19
- e = trainer.expand_aug_weights(w, [-2, -4])
20
- # 源片权重不变
21
- self.assertEqual(e["a.wav"], 3.0)
22
- self.assertEqual(e["b.wav"], 1.0)
23
- # 副本继承 ÷ (副本数 + 1):3x 源 + 2 副本 → 各 1x
24
- self.assertAlmostEqual(e["aug-2_a.wav"], 1.0)
25
- self.assertAlmostEqual(e["aug-4_a.wav"], 1.0)
26
- self.assertAlmostEqual(e["aug-2_b.wav"], 1 / 3)
27
- self.assertAlmostEqual(e["aug-4_b.wav"], 1 / 3)
28
-
29
- def test_empty_cases(self):
30
- self.assertEqual(trainer.expand_aug_weights({}, [-2]), {})
31
- self.assertEqual(trainer.expand_aug_weights(None, [-2]), {})
32
- self.assertEqual(trainer.expand_aug_weights({"a.wav": 2.0}, []), {"a.wav": 2.0})
33
-
34
- def test_zero_shift_ignored(self):
35
- # 0 半音不是有效副本:[-2] 只有 1 个副本 → 3x 源片摊薄为 3/2
36
- e = trainer.expand_aug_weights({"a.wav": 3.0}, [0, -2])
37
- self.assertNotIn("aug0_a.wav", e)
38
- self.assertAlmostEqual(e["aug-2_a.wav"], 1.5)
39
-
40
-
41
- class BuildWeightsFile(unittest.TestCase):
42
- def test_writes_and_filters(self):
43
- with tempfile.TemporaryDirectory() as td:
44
- exp = Path(td)
45
- gt = exp / "0_gt_wavs"
46
- gt.mkdir()
47
- # 两个"完整"样本 + 一个缺特征的(特征 npy 用 stem,f0 npy 用全名)
48
- for name in ("x.wav", "y.wav"):
49
- (gt / name).write_bytes(b"RIFF")
50
- (exp / "3_feature768").mkdir(exist_ok=True)
51
- (exp / "3_feature768" / f"{name[:-4]}.npy").write_bytes(b"\x00")
52
- (exp / "2a_f0").mkdir(exist_ok=True)
53
- (exp / "2a_f0" / f"{name}.npy").write_bytes(b"\x00")
54
- (exp / "2b-f0nsf").mkdir(exist_ok=True)
55
- (exp / "2b-f0nsf" / f"{name}.npy").write_bytes(b"\x00")
56
- (gt / "broken.wav").write_bytes(b"RIFF") # 没有对应特征
57
- n = trainer.write_filelist(exp)
58
- self.assertEqual(n, 2)
59
- rows = (exp / "filelist.txt").read_text(encoding="utf8").splitlines()
60
- self.assertEqual(len(rows), 2)
61
- self.assertEqual(rows[0].count("|"), 4)
62
-
63
- # 权重:全 1 → 不写文件;非 1 → 写入 json
64
- self.assertIsNone(trainer.build_weights_file(exp, {"x.wav": 1.0, "y.wav": 1.0}))
65
- wfile = trainer.build_weights_file(exp, {"x.wav": 3.0})
66
- self.assertIsNotNone(wfile)
67
- data = json.loads(wfile.read_text(encoding="utf8"))
68
- self.assertEqual(data, {"x.wav": 3.0})
69
-
70
-
71
- class LogParsing(unittest.TestCase):
72
- def test_epoch_of(self):
73
- self.assertEqual(trainer._epoch_of("====> 轮次:42 loss=1.2"), 42)
74
- self.assertIsNone(trainer._epoch_of("没有轮次信息"))
75
-
76
- def test_loss_of(self):
77
- d = trainer._loss_of("loss_disc=1.5, loss_gen=2.5, loss_fm=0.3")
78
- self.assertEqual(d["loss_disc"], 1.5)
79
- self.assertEqual(d["loss_gen"], 2.5)
80
- self.assertIsNone(trainer._loss_of("无关日志"))
81
-
82
-
83
- if __name__ == "__main__":
84
- unittest.main()
1
+ """训练侧纯逻辑测试(无 GPU、无 ffmpeg 依赖)。跑法:python -m unittest discover -s tests -v"""
2
+ import json
3
+ import sys
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ ROOT = Path(__file__).resolve().parent.parent
9
+ sys.path.insert(0, str(ROOT / "worker"))
10
+
11
+ import trainer # noqa: E402
12
+
13
+
14
+ class ExpandAugWeights(unittest.TestCase):
15
+ """低音增强副本的采样权重摊薄。"""
16
+
17
+ def test_inherit_and_divide(self):
18
+ w = {"a.wav": 3.0, "b.wav": 1.0}
19
+ e = trainer.expand_aug_weights(w, [-2, -4])
20
+ # 源片权重不变
21
+ self.assertEqual(e["a.wav"], 3.0)
22
+ self.assertEqual(e["b.wav"], 1.0)
23
+ # 副本继承 ÷ (副本数 + 1):3x 源 + 2 副本 → 各 1x
24
+ self.assertAlmostEqual(e["aug-2_a.wav"], 1.0)
25
+ self.assertAlmostEqual(e["aug-4_a.wav"], 1.0)
26
+ self.assertAlmostEqual(e["aug-2_b.wav"], 1 / 3)
27
+ self.assertAlmostEqual(e["aug-4_b.wav"], 1 / 3)
28
+
29
+ def test_empty_cases(self):
30
+ self.assertEqual(trainer.expand_aug_weights({}, [-2]), {})
31
+ self.assertEqual(trainer.expand_aug_weights(None, [-2]), {})
32
+ self.assertEqual(trainer.expand_aug_weights({"a.wav": 2.0}, []), {"a.wav": 2.0})
33
+
34
+ def test_all_unit_weights_not_expanded(self):
35
+ # 全 1x 源权重:不该造副本权重表(否则会写出全 0.333 的伪加权表)
36
+ e = trainer.expand_aug_weights({"a.wav": 1.0}, [-2, -4])
37
+ self.assertEqual(e, {"a.wav": 1.0})
38
+
39
+ def test_zero_shift_ignored(self):
40
+ # 0 半音不是有效副本:[-2] 只有 1 个副本 → 3x 源片摊薄为 3/2
41
+ e = trainer.expand_aug_weights({"a.wav": 3.0}, [0, -2])
42
+ self.assertNotIn("aug0_a.wav", e)
43
+ self.assertAlmostEqual(e["aug-2_a.wav"], 1.5)
44
+
45
+
46
+ class BuildWeightsFile(unittest.TestCase):
47
+ def test_writes_and_filters(self):
48
+ with tempfile.TemporaryDirectory() as td:
49
+ exp = Path(td)
50
+ gt = exp / "0_gt_wavs"
51
+ gt.mkdir()
52
+ # 两个"完整"样本 + 一个缺特征的(特征 npy 用 stem,f0 npy 用全名)
53
+ for name in ("x.wav", "y.wav"):
54
+ (gt / name).write_bytes(b"RIFF")
55
+ (exp / "3_feature768").mkdir(exist_ok=True)
56
+ (exp / "3_feature768" / f"{name[:-4]}.npy").write_bytes(b"\x00")
57
+ (exp / "2a_f0").mkdir(exist_ok=True)
58
+ (exp / "2a_f0" / f"{name}.npy").write_bytes(b"\x00")
59
+ (exp / "2b-f0nsf").mkdir(exist_ok=True)
60
+ (exp / "2b-f0nsf" / f"{name}.npy").write_bytes(b"\x00")
61
+ (gt / "broken.wav").write_bytes(b"RIFF") # 没有对应特征
62
+ n = trainer.write_filelist(exp)
63
+ self.assertEqual(n, 2)
64
+ rows = (exp / "filelist.txt").read_text(encoding="utf8").splitlines()
65
+ self.assertEqual(len(rows), 2)
66
+ self.assertEqual(rows[0].count("|"), 4)
67
+
68
+ # 权重:全 1 → 不写文件;非 1 → 写入 json
69
+ self.assertIsNone(trainer.build_weights_file(exp, {"x.wav": 1.0, "y.wav": 1.0}))
70
+ wfile = trainer.build_weights_file(exp, {"x.wav": 3.0})
71
+ self.assertIsNotNone(wfile)
72
+ data = json.loads(wfile.read_text(encoding="utf8"))
73
+ self.assertEqual(data, {"x.wav": 3.0})
74
+
75
+
76
+ class LogParsing(unittest.TestCase):
77
+ def test_epoch_of(self):
78
+ self.assertEqual(trainer._epoch_of("====> 轮次:42 loss=1.2"), 42)
79
+ self.assertIsNone(trainer._epoch_of("没有轮次信息"))
80
+
81
+ def test_loss_of(self):
82
+ d = trainer._loss_of("loss_disc=1.5, loss_gen=2.5, loss_fm=0.3")
83
+ self.assertEqual(d["loss_disc"], 1.5)
84
+ self.assertEqual(d["loss_gen"], 2.5)
85
+ self.assertIsNone(trainer._loss_of("无关日志"))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ unittest.main()
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python
2
+ """对 dfy4 数据二分:找出哪些切片会让训练 loss 变 NaN。
3
+
4
+ 用法:python bisect_nan.py <名字1> <名字2> ...
5
+ 给一组 wav 文件名(不含扩展名也可),在临时实验里跑 1 轮,打印首个 loss。
6
+ """
7
+ import json
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ RVC = Path(r"D:/Coopanion/data/home/companion/data/fish-sing/runtime/rvc")
16
+ LOGS = RVC / "logs"
17
+ SRC = LOGS / "dfy4diag"
18
+ PY = Path(r"D:/Coopanion/data/home/companion/data/fish-sing/runtime/venv/Scripts/python.exe")
19
+ EXP = LOGS / "bisect"
20
+ SUBS = ("0_gt_wavs", "1_16k_wavs", "2a_f0", "2b-f0nsf", "3_feature768")
21
+
22
+
23
+ def build(names):
24
+ if EXP.exists():
25
+ shutil.rmtree(EXP)
26
+ EXP.mkdir(parents=True)
27
+ for sub in SUBS:
28
+ (EXP / sub).mkdir()
29
+ for sub in ("config.json",):
30
+ shutil.copy(SRC / sub, EXP / sub)
31
+ rows = []
32
+ for wav in (SRC / "0_gt_wavs").glob("*.wav"):
33
+ stem = wav.stem
34
+ if stem not in names:
35
+ continue
36
+ os.link(wav, EXP / "0_gt_wavs" / wav.name)
37
+ for sub, fmt in (("1_16k_wavs", "{}.wav"), ("2a_f0", "{}.wav.npy"),
38
+ ("2b-f0nsf", "{}.wav.npy"), ("3_feature768", "{}.npy")):
39
+ f = SRC / sub / fmt.format(stem)
40
+ os.link(f, EXP / sub / f.name)
41
+ rows.append(
42
+ f"{EXP / '0_gt_wavs' / wav.name}|{EXP / '3_feature768' / (stem + '.npy')}"
43
+ f"|{EXP / '2a_f0' / (wav.name + '.npy')}|{EXP / '2b-f0nsf' / (wav.name + '.npy')}|0"
44
+ )
45
+ (EXP / "filelist.txt").write_text("\n".join(rows), encoding="utf8")
46
+
47
+
48
+ def train_once():
49
+ log = Path(os.environ.get("TEMP", ".")) / "bisect_run.log"
50
+ env = os.environ.copy()
51
+ env["PYTHONPATH"] = str(RVC)
52
+ env["PYTHONIOENCODING"] = "utf-8"
53
+ env["FISHSING_RVC_ROOT"] = str(RVC)
54
+ with open(log, "w", encoding="utf-8") as fh:
55
+ subprocess.run(
56
+ [str(PY), "-m", "train.train", "-se", "10", "-te", "1",
57
+ "-pg", str(RVC / "assets/pretrained_v2/f0G40k.pth"),
58
+ "-pd", str(RVC / "assets/pretrained_v2/f0D40k.pth"),
59
+ "-bs", "4", "-e", "bisect", "-sr", "40k", "-sw", "0", "-v", "v2",
60
+ "-f0", "1", "-l", "0", "-c", "0"],
61
+ cwd=str(RVC), env=env, stdout=fh, stderr=subprocess.STDOUT,
62
+ )
63
+ txt = log.read_text(encoding="utf-8", errors="replace")
64
+ m = re.search(r"loss_disc=([^,]+)", txt)
65
+ return m.group(1) if m else "NO_LOSS"
66
+
67
+
68
+ if __name__ == "__main__":
69
+ names = set()
70
+ for a in sys.argv[1:]:
71
+ names.add(Path(a).stem)
72
+ build(names)
73
+ print(f"测试 {len(names)} 片 → loss_disc = {train_once()}", flush=True)
package/worker/dataset.py CHANGED
@@ -378,7 +378,10 @@ def build(sources, out_dir, params, progress, cancel) -> dict:
378
378
  name = f"{i:02d}_{j:03d}.wav"
379
379
  rel = f"slices/{name}"
380
380
  if drop is None:
381
- sf.write(str(out / rel), seg40, OUT_SR, subtype="PCM_24")
381
+ # 必须写 FLOAT:RVC 训练用 scipy.io.wavfile.read 读 0_gt_wavs,
382
+ # PCM_16/24 整型会被读成 ±3万/±838万 的整数(不归一化)→ mel 爆炸
383
+ # → 判别器损失 1e18 → fp16 训练 NaN(0.4.1 之后的真实事故)。
384
+ sf.write(str(out / rel), seg40, OUT_SR, subtype="FLOAT")
382
385
  written.append((out / rel, dur))
383
386
 
384
387
  records.append({
package/worker/trainer.py CHANGED
@@ -24,6 +24,8 @@ import sys
24
24
  import time
25
25
  from pathlib import Path
26
26
 
27
+ import soundfile as sf
28
+
27
29
  RVC_ROOT = Path(os.environ.get("FISHSING_RVC_ROOT", r"D:\AI\rvc"))
28
30
  RVC_PY = Path(os.environ.get("FISHSING_RVC_PY", str(RVC_ROOT / "venv" / "Scripts" / "python.exe")))
29
31
  FFMPEG = Path(os.environ.get("FISHSING_FFMPEG", r"D:\ffmpeg\bin\ffmpeg.exe"))
@@ -119,6 +121,26 @@ def find_checkpoint(exp: str):
119
121
  }
120
122
 
121
123
 
124
+ def _ensure_float_wav(path: Path) -> None:
125
+ """
126
+ 把 0_gt_wavs 里的整型 wav 统一转成 float32。
127
+
128
+ 为什么必须转:RVC 训练用 scipy.io.wavfile.read 读训练音频——PCM_16/24 整型
129
+ 会被读成 ±3万/±838万 的整数(不做归一化),mel 直接炸到 1e11,判别器损失
130
+ 到 1e18,fp16 下变 NaN(0.4.1 之后"新导入的 16 首歌 train 全 NaN"的真凶)。
131
+ 转换顺带断开与数据集切片的硬链接,只影响本实验。
132
+ """
133
+ try:
134
+ info = sf.info(str(path))
135
+ except Exception: # noqa: BLE001
136
+ return
137
+ if info.subtype == "FLOAT":
138
+ return
139
+ tmp = path.with_suffix(".f32tmp.wav")
140
+ run([FFMPEG, "-y", "-v", "error", "-i", str(path), "-c:a", "pcm_f32le", str(tmp)], "转 float wav")
141
+ os.replace(tmp, path)
142
+
143
+
122
144
  def prepare(exp, dataset_dir: Path, progress, cancel, keep_existing=True, augment_shifts=None, weights=None):
123
145
  """
124
146
  建实验目录并把切片铺成 RVC 需要的三层结构。
@@ -170,13 +192,15 @@ def prepare(exp, dataset_dir: Path, progress, cancel, keep_existing=True, augmen
170
192
  dst0 = gt / name
171
193
  dst1 = hi / name
172
194
  if dst0.exists() and dst1.exists():
195
+ _ensure_float_wav(dst0) # 老版本生成的 s16 副本也顺手修
173
196
  continue
174
197
  factor = 2 ** (s / 12)
175
198
  tempo = 2 ** (-s / 12)
176
- # 40k 副本:降调 + 补速度(asetrate 降调会拖长,atempo 拉回来)
199
+ # 40k 副本:降调 + 补速度(asetrate 降调会拖长,atempo 拉回来)。
200
+ # 必须 pcm_f32le——训练侧用 scipy 读,整型会被当成天文数字(见 _ensure_float_wav)。
177
201
  run([FFMPEG, "-y", "-v", "error", "-i", str(src),
178
202
  "-af", f"asetrate={sr_in}*{factor:.8f},aresample={sr_in},atempo={tempo:.8f}",
179
- "-c:a", "pcm_s16le", str(dst0)], f"低音增强 {s} 半音")
203
+ "-c:a", "pcm_f32le", str(dst0)], f"低音增强 {s} 半音")
180
204
  # 16k 单声道副本:从 40k 副本重采样(跟原切片同一套流程)
181
205
  run([FFMPEG, "-y", "-v", "error", "-i", str(dst0),
182
206
  "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(dst1)], "重采样 16k")
@@ -194,6 +218,7 @@ def prepare(exp, dataset_dir: Path, progress, cancel, keep_existing=True, augmen
194
218
  except OSError:
195
219
  shutil.copy2(src, dst0)
196
220
  added += 1
221
+ _ensure_float_wav(dst0) # 整型 wav → float(训练侧 scipy 不归一化整型)
197
222
  if not dst1.exists():
198
223
  run([FFMPEG, "-y", "-v", "error", "-i", str(src), "-ac", "1", "-ar", "16000",
199
224
  "-c:a", "pcm_s16le", str(dst1)], "重采样 16k")
@@ -283,6 +308,10 @@ def expand_aug_weights(weights: dict, augment_shifts: list) -> dict:
283
308
  shifts = [int(s) for s in (augment_shifts or []) if int(s) != 0]
284
309
  if not shifts or not weights:
285
310
  return weights or {}
311
+ # 源权重全是 1x 时不该造副本权重:会得到一堆 0.333 的"全均匀"权重表,
312
+ # 白白激活加权采样路径(0.4.0 夜里的事故现场)。
313
+ if all(abs(float(v) - 1.0) <= 1e-9 for v in weights.values()):
314
+ return dict(weights)
286
315
  div = len(shifts) + 1
287
316
  expanded = dict(weights)
288
317
  for s in shifts: