Fix opening filler via lean tags and intro QC gate.
selftest / selftest (push) Canceled after 0s

Stop naming filler syllables in tags (they conditioned the model); default prefer_lean_tags; hard-fail intro_filler in QC; add plugins/ hook bus as thin microkernel extension point.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
swl
2026-10-10 12:49:25 +08:00
co-authored by Cursor
parent 0ab8d8ad4d
commit b1afe68f3c
20 changed files with 426 additions and 84 deletions
+2 -2
View File
@@ -8,9 +8,9 @@ alwaysApply: true
# songforge
1. **先读** `AGENTS_MIN.md`;不要默认加载整份 `AGENTS.md` / `ironlaw.py` / `qc_worker.py`。
2. 做歌流水线:`doctor_all` → `target` → 写词 → `check` → `gen` → `qc --baseline`。
2. 做歌流水线:`doctor_all` → `target` → 写词 → `check` → `gen` → `qc --baseline`。结束后按 `AGENTS_MIN.md`「生歌报告」模板向用户汇报。
3. 音频探测 / 转码 / 截取:只用 `songforge media info|convert|clip`(经 qc_python)。
4. 缺 `local.toml`、Comfy 不通、风格/歌名不清、想改模型或 QC 阈值 → **先问用户**。
5. **改代码铁律**:发现需改仓库代码时,先说明缺口与范围并**征求同意**;建议用户用 git 分支/commit/stash 备份,或新写插件/旁路少动核心;再问是否 commit、是否 push、推哪个 remote。未获许可不得改核心、不得提交/推送。用户同意收尾时再 commit+push。
6. 默认无衬音/无和声叠唱已由 tags 强制;不要手写 tags 覆盖铁律。
6. 禁止开曲衬词;默认 lean tags;**禁止**在 tags 点名 mm/ooh/嗯 等音节。扩展写 `plugins/`,少改 `core/`/`rules/`。
7. 勿提交 `.secrets/`、`config/local.toml`、`.venv/`;勿 `--force` push。
+29 -1
View File
@@ -16,7 +16,35 @@
2. ComfyUI 产出的 flac(路径在 manifest / catalog)
3. `qc --baseline` → **PASS**
`style_fam` / `style_conf` 是弱参考,**不要**当 PASS 条件,也**不要**对外说「风格已验证」。
`style_fam` / `style_conf` / 全曲 `filler_ratio` 是弱参考,**不要**当 PASS 条件,也**不要**对外说「风格已验证」。
**开曲衬词**(前奏窗 `intro_filler_*`)是硬门:嗯/呀/ooh 类开曲必须 FAIL 重 gen。
扩展目录:**`plugins/`**(见 `plugins/README.md`)。内核:`core/` + `rules/` + `cli/`。默认 `prefer_lean_tags=true`;勿在 tags 点名衬词音节。
### 生歌后给用户的报告(必填模板)
流水线结束后用此结构汇报;数字以 `qc` / `media info` / `manifest` 为准,勿编造。FAIL 时先给结论与失败项,再问用户听哪一版或是否重 gen。
```text
## 生歌报告
- 结论:PASS | FAIL
- 歌名 / 风格 / BPM / 设定时长:…
- run_id:…
- 音频路径:…(flac 绝对或仓内相对路径;可用 `media info` 补实测时长/采样率)
- 歌词:文件路径;`check` 音节数与放行区间;是否 chill/sparse
- QC(须 `--baseline`):
- verdict
- 时长(应在 150–200s)
- 实测 BPM 与设定对齐情况
- voice_nn:最近邻曲名 + similarity(null = 漏了 --baseline)
- filler_ratio:弱参考(偏高 → 建议听段落间隙/副歌是否有 ooh/叠唱)
- 弱参考(写进报告但勿当闸门):style_fam / style_conf
- 锁定核对:checkpoint + LoRA strength;shift / steps / cfg / temperature
- 种子 / 备注:重跑原因、异常日志一行摘要
- 建议下一步:试听重点段落;改词重 check;同参重 gen;若动过代码则问 commit/push
```
短版也可,但至少包含:**结论、run_id、flac 路径、QC verdict、voice_nn、建议下一步**。
---
+35 -2
View File
@@ -5,7 +5,24 @@
## 交付
`gen` 的 run_id + flac + `qc --baseline` → **PASS**(`style_fam` / `filler_ratio` 只是弱参考)。
硬条件:`gen` 的 run_id + flac + `qc --baseline` → **PASS**。
`style_fam` / `filler_ratio` 只是弱参考;**不要**对外说「风格已验证」。
生歌结束后,用下面模板向用户汇报(缺项写 `—`,FAIL 时停在「结论」并说明下一步):
```text
## 生歌报告
- 结论:PASS | FAIL
- 歌名 / 风格 / BPM / 设定时长:…
- run_id:…
- 音频路径:…(flac;可用 media info 补实测时长)
- 歌词:路径 + check 密度结果(音节/区间)
- QC:verdict;时长;实测 BPM(±18%);voice_nn;开曲衬词(intro_filler,硬门);filler_ratio(全曲弱参考)
- 弱参考(勿当闸门):style_fam / style_conf;全曲 filler_ratio
- 模型/采样:ckpt+LoRA(0.5/0.5);shift/steps/cfg/temperature(应与铁律一致)
- 种子 / 备注:…(重跑或异常时)
- 建议:听哪一段;是否重 gen / 只改词;是否 commit(若改过仓)
```
## 流水线
@@ -27,10 +44,26 @@ doctor_all → target → 写歌词 → check → gen → qc --baseline
| ckpt+LoRA | `ace_step_1.5_turbo_swl_fused` + `swl_voice_best_ep257`(0.5/0.5) |
| 采样 | shift=5.5 / steps=28 / cfg=2.0 / temperature=0.68 |
| 时长 | 150–200s;8 小节器乐前奏(CLI 注入) |
| 衬音 | 默认无填充、无 backup/合唱(tags 已强制) |
| 衬音 | **禁止开曲衬词**(嗯/呀/ooh…);默认 lean tags;QC 前奏窗衬词硬 FAIL |
| tags | `prefer_lean_tags=true`;勿 `--full-tags`(易诱发开曲衬词);禁点名音节 |
本机路径:`config/local.toml`。算法:`config/default.toml`。
## 微内核目录
| 层 | 路径 |
|----|------|
| 内核 | `core/`(引擎/路径/workflow)、`rules/`、`cli/` |
| 插件 | **`plugins/`**(钩子总线 + `builtin/` + 第三方) |
| 数据 | `input/lyrics/`、`data/runs/`、`config/` |
扩展优先写 `plugins/<name>.py` 或 `plugins/<name>/plugin.py`,少改内核。说明见 [`plugins/README.md`](plugins/README.md)。
## 音频栈(librosa 等)
- **已用**(经 `qc_python`,勿塞进轻量 `.venv`):librosa、soundfile、torch、torchaudio、demucs、whisper
- CLI:`media` / `qc` 走该栈;不要在 Agent 里手写探测脚本
## 音频窄接口(勿自写脚本)
```powershell
+6 -1
View File
@@ -88,7 +88,12 @@ cd songforge
| 采样 | shift=5.5 / steps=28 / cfg=2.0 / temperature=0.68 |
| 时长 | 完整歌 150–200 秒 |
| 前奏 | 8 小节器乐 hook;CLI 自动注入 |
| 衬音 | 默认无填充、无 backup/合唱(`RULE_NO_FILLER`);QC 有 `filler_ratio` 弱参考 |
| 衬音 | 禁止开曲衬词;默认 `prefer_lean_tags`;tags **禁止点名** mm/ooh/嗯;QC 前奏窗 `intro_filler` 硬 FAIL |
| 插件 | [`plugins/`](plugins/) 微内核外挂;内核在 `core/` + `rules/` + `cli/` |
### 音频库
`qc` / `media` 经 `qc_python` 使用:**librosa、soundfile、torch、torchaudio、demucs、whisper**。轻量 `.venv` 不装这些。
## 音频工具(Agent 优先用 CLI)
+8 -9
View File
@@ -1,24 +1,23 @@
# -*- coding: utf-8 -*-
"""songforge 核心包重写 - 修复相对导入与模块管理"""
"""songforge 微内核包。
层:cli → rules/lyrics → core → config;扩展在 plugins/(钩子总线)。
"""
import os
import sys
# 确保正确添加工程根目录
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# 统一重写 core/__init__.py -> core
from .core.workflow import build_workflow, convert, find_node, ROOT, WIDGET_MAP
from .core.errors import RuleViolation, LexiconError
from .rules.ironlaw import build_tags, build_lyrics, validate, TRIGGER
from .config.loader import load
__version__ = "1.0.0"
__version__ = "1.1.0"
# 保持微内核结构:CLI -> Rules -> Lyrics -> Core -> Log -> Config
__all__ = [
'build_workflow', 'convert', 'find_node', 'ROOT', 'WIDGET_MAP',
'RuleViolation', 'LexiconError',
'build_tags', 'build_lyrics', 'validate', 'TRIGGER',
'load'
"build_workflow", "convert", "find_node", "ROOT", "WIDGET_MAP",
"RuleViolation", "LexiconError",
"build_tags", "build_lyrics", "validate", "TRIGGER",
"load",
]
+27 -14
View File
@@ -66,11 +66,28 @@ def _extra_hint(cfg, dur):
return "(额外放行区间:%s)" % ", ".join("%d~%ds" % (a, b) for a, b in ex)
def resolve_lean(args, cfg):
"""是否走 lean tags。
默认 prefer_lean_tags=true(少注入 RULE_NEG,避免开曲衬词)。
--full-tags 强制完整否定句;--lean-tags 强制 lean。
"""
if bool(getattr(args, "full_tags", False)):
return False
if bool(getattr(args, "lean_tags", False)):
return True
return bool((cfg.get("rules") or {}).get("prefer_lean_tags", True))
def assemble(args, cfg, st, lyrics_raw, title):
"""套用铁律:生成 tags、补器乐前奏、清洗中文标记。"""
from ..plugins.hooks import bus
chill = bool(getattr(args, "chill_vocal", False))
inst = bool(getattr(args, "instrumental", False))
lean = bool(getattr(args, "lean_tags", False))
lean = resolve_lean(args, cfg)
bus.emit("before_build_tags", args=args, cfg=cfg, style=st,
chill=chill, instrumental=inst, lean=lean)
tags = ironlaw.build_tags(
style=st.get("style", ""), instruments=st.get("instruments", ""),
mood=st.get("mood", ""), extra=st.get("extra", ""),
@@ -82,8 +99,7 @@ def assemble(args, cfg, st, lyrics_raw, title):
lyrics = ironlaw.build_inst_lyrics(
st.get("intro_detail") or st.get("instruments"),
bars=ibars)
return tags, lyrics
if chill:
elif chill:
# chill 走独立结构体:器乐段整体排在人声段之前。
# 实测这只降低人声密度,并不推迟起点(chill 3 第一句仍在 0 秒),
# 标签侧的时间/时机约束同样无效。详见 ironlaw 顶部实测结论。
@@ -93,7 +109,7 @@ def assemble(args, cfg, st, lyrics_raw, title):
vocal_sections(lyrics_raw),
st.get("intro_detail") or st.get("instruments"),
bars=ibars, total_bars=cap["total_bars"])
return tags, lyrics
else:
lyrics = lyrics_raw
if not lyrics.lstrip().lower().startswith("[intro]"):
lyrics = ironlaw.build_lyrics(
@@ -101,18 +117,15 @@ def assemble(args, cfg, st, lyrics_raw, title):
st.get("intro_detail") or st.get("instruments"),
bars=ibars)
else:
# 已有 [intro] 头的歌词文件:强制把前奏小节数对齐到标签写的值。
# 标签写 16 小节而歌词头写 8 小节时,check_rules 会判两处不一致
# ——这是故意留的闸门,不是 bug。
# 已有 [intro] 头:对齐小节数 + 前奏括号 rhythm 过滤。
lyrics = ironlaw.force_intro_bars(lyrics, ibars)
# 前奏括号里的配器也要过 rhythm 过滤(2026-10-05 补)。
# 之前这条分支只改小节数,作者手写的 [Instrumental: ...] 直接
# 原样送进模型。ckfunk 批次的 8 首歌词前奏括号里就带着
# "half time feel" 这类非节奏组描述,而作者也可能写 pad、
# riser、sweep——intro_rhythm_only() 存在的全部理由就是把这些
# 空场信号从前奏里剔掉,只留节奏组。手写歌词不等于免检。
lyrics = ironlaw.filter_intro_bracket(lyrics)
lyrics = "\n".join(ironlaw.strip_cn_instrumental(lyrics.splitlines())) + "\n"
lyrics = "\n".join(
ironlaw.strip_cn_instrumental(lyrics.splitlines())) + "\n"
out = bus.emit("after_assemble", tags=tags, lyrics=lyrics,
args=args, cfg=cfg, style=st, lean=lean)
if isinstance(out, dict) and out.get("tags") and out.get("lyrics"):
return out["tags"], out["lyrics"]
return tags, lyrics
+4 -3
View File
@@ -15,7 +15,8 @@ from ..core.errors import ConfigError, ServerError
from ..lyrics import meter
from ..log.logger import Logger, Run
from ..rules import ironlaw
from .assemble import (_extra_hint, assemble, do_validate, duration_allowed)
from .assemble import (_extra_hint, assemble, do_validate, duration_allowed,
resolve_lean)
from .common import (ROOT, build_cfg, chill_intro_bars, gen_day_root, now_id,
read_lyrics, resolve_profile, runs_root, safe_name,
session_logger, style_of)
@@ -208,7 +209,7 @@ def cmd_check(args):
prof = resolve_profile(args)
errs, stats = do_validate(lyrics, tags, cfg, st, lexicon, strict=False,
instrumental=inst, profile=prof,
lean=bool(getattr(args, "lean_tags", False)))
lean=resolve_lean(args, cfg))
run.save_text("lyrics.txt", lyrics)
run.save_text("tags.txt", tags)
print("== 密度 ==")
@@ -260,7 +261,7 @@ def cmd_gen(args):
cfg, bool(getattr(args, "chill_vocal", False)))
errs, stats = do_validate(lyrics, tags, cfg, st, lexicon, strict=True,
instrumental=inst, profile=prof,
lean=bool(getattr(args, "lean_tags", False)))
lean=resolve_lean(args, cfg))
day_root = gen_day_root(cfg)
pmod.ensure_dir(day_root)
+6 -4
View File
@@ -81,8 +81,9 @@ def build_parser():
c.add_argument("--density-profile", dest="density_profile",
help="密度档:default(人声填满)/ sparse(音乐主导、人声点缀)")
c.add_argument("--lean-tags", dest="lean_tags", action="store_true",
help="精简正向标签:保留'前奏器乐+第一拍鼓'硬约束,"
"但不注入 RULE_NEG 那 20+ 条人声否定句")
help="强制 lean(默认已开启 prefer_lean_tags)")
c.add_argument("--full-tags", dest="full_tags", action="store_true",
help="注入完整 RULE_NEG(默认关闭;易诱发开曲衬词)")
c.set_defaults(func=cmds.cmd_check)
g = sub.add_parser("gen", help="生成歌曲")
@@ -114,8 +115,9 @@ def build_parser():
g.add_argument("--density-profile", dest="density_profile",
help="密度档:default(人声填满)/ sparse(音乐主导、人声点缀)")
g.add_argument("--lean-tags", dest="lean_tags", action="store_true",
help="精简正向标签:保留'前奏器乐+第一拍鼓'硬约束,"
"但不注入 RULE_NEG 那 20+ 条人声否定句")
help="强制 lean(默认已开启 prefer_lean_tags)")
g.add_argument("--full-tags", dest="full_tags", action="store_true",
help="注入完整 RULE_NEG(默认关闭;易诱发开曲衬词)")
g.add_argument("--dry-run", dest="dry_run", action="store_true",
help="只写 workflow 与 API 预览,不提交 ComfyUI")
g.set_defaults(func=cmds.cmd_gen)
+11 -1
View File
@@ -345,7 +345,17 @@ def _render(rep, args, rundir=None, cfg=None):
r.get("coverage", 0) * 100, r.get("filler_ratio", 0) * 100,
r.get("f0_med", 0),
r.get("f0_drift_st", 0), r.get("tempo_drift", 0) * 100))
print(" (衬词%% = ASR 语气/哼唱占比,弱参考,不单独否决)")
print(" (衬词%% = 全曲 ASR 语气占比,弱参考;开曲衬词见结论里 intro_filler 硬门)")
print("\n== 开曲衬词(硬门)==")
print("%-22s %8s %8s %8s"
% ("file", "前奏衬词", "前奏ASR", "衬词比"))
for r in rows:
if "error" in r:
continue
print("%-22s %8d %8d %7.0f%%"
% (r["file"][:22], r.get("intro_filler_n", 0),
r.get("intro_asr_n", 0),
float(r.get("intro_filler_ratio") or 0) * 100))
print("\n== 结论 ==")
npass = 0
+54 -13
View File
@@ -122,12 +122,15 @@ def _t_model_locked():
def _t_ironlaw():
tags = ironlaw.build_tags("Chinese pop")
# 默认路径现与 lean 对齐:完整 RULE_NEG 用 lean=False 测
tags = ironlaw.build_tags("Chinese pop", lean=False)
for kw in ("swlvoice", "8 bar instrumental intro hook", "no opening vocals",
"no pure vocal intro", "no humming",
"no pure vocal intro", "no wordless vocals",
"solo lead vocal only", "no backing vocals",
"sing only the exact words"):
assert kw in tags, "tags 缺少 %s" % kw
for bad in ("mm mm", "ooh ooh", "wu wu wu", "en en"):
assert bad not in tags.lower(), "tags 点名衬词音节 %s" % bad
assert "call and response" not in tags.lower() or \
"no call and response vocals" in tags.lower(), \
"MEMO 仍鼓励 call and response 且未禁叠唱"
@@ -143,12 +146,17 @@ def _t_ironlaw():
# 中文结构标记必须被拦
marked = lyrics.replace("[verse]", "[主歌]")
assert ironlaw.check_rules(marked, tags), "中文结构标记未被拦截"
# lean 也必须带衬音硬禁
# lean 也必须带衬音硬禁,且默认配置 prefer_lean
lean = ironlaw.build_tags("Chinese pop", lean=True)
for kw in ("solo lead vocal only", "no backing vocals"):
for kw in ("solo lead vocal only", "no backing vocals",
"no wordless vocals"):
assert kw in lean, "lean tags 缺少衬音禁令 %s" % kw
assert "no opening vocals" not in lean.lower(), \
"lean 不应注入 RULE_NEG 的 opening 否定堆"
cfg = loader.load({})
assert cfg["rules"].get("prefer_lean_tags") is True, "默认未开 prefer_lean_tags"
return [("铁律注入",
"8 小节前奏 + 无衬音/无和声叠唱 + lean 齐备,缺前奏/中文标记均被拦")]
"无音节点名 + lean 默认 + 无衬音/无和声,缺前奏/中文标记均被拦")]
def _t_sparse_profile():
@@ -204,11 +212,13 @@ def _t_instrumental():
mood="vast uplifting EDM",
extra="male low whisper vocal, hushed and intimate",
instrumental=True)
# 反人声条款必须在
# 反人声条款必须在(抽象禁令,不点名音节)
for kw in ("no vocals anywhere", "instrumental only", "no voice at all",
"no humming", "no choir", "no vocal sample", "swlvoice",
"no wordless vocals", "no choir", "no vocal sample", "swlvoice",
"8 bar instrumental intro hook"):
assert kw in tags, "纯器乐 tags 缺少 %s" % kw
for bad in ("mm mm", "ooh ooh", "wu wu wu"):
assert bad not in tags.lower(), "纯器乐 tags 点名音节 %s" % bad
# 关键回归点:风格字典的唱法描述绝不能混进来跟 "no vocals" 对撞。
for bad in ("whisper vocal", "sparse English words", "no belting"):
assert bad not in tags, "纯器乐 tags 混入了唱法描述: %s" % bad
@@ -488,17 +498,16 @@ def _t_chill_no_conflict():
"""
tags = ironlaw.build_tags(style="s", instruments="i", mood="m",
chill_vocal=True)
for bad in ("no humming", "no mm mm syllables", "no oh oh syllables",
"no droning sustained vowels"):
for bad in ("mm mm", "ooh ooh", "oh oh syllables", "wu wu wu", "en en"):
assert bad not in tags.lower(), \
"chill tags 含 %s,与要求的低音语气词直接冲突" % bad
"chill tags 点名衬词音节 %s" % bad
# 反过来,"稀疏低音语气词"必须真的在标签里,否则就退化成纯器乐了。
for need in ("male low whisper vocal", "low register vocal texture",
"soft breathy phrases"):
assert need in tags.lower(), "chill tags 丢了低音唱腔描述: %s" % need
return [("吟唱无冲突",
"no humming / no mm mm / no oh oh 三条禁令未回归")]
"未点名衬词音节,低音吟唱描述保留")]
def _t_chill_integration():
@@ -518,10 +527,12 @@ def _t_chill_integration():
class _A(object):
chill_vocal = True
instrumental = False
lean_tags = False
full_tags = False
raw = open(_CHILL_DEMO, encoding="utf-8").read()
tags2, lyrics2 = assemble(_A, cfg, st, raw, "selftest")
errs = ironlaw.check_rules(lyrics2, tags2)
errs = ironlaw.check_rules(lyrics2, tags2, lean=True)
assert not errs, "chill 集成校验不通过: %s" % errs
# 结构核心断言:第一个有人唱的段之前,纯器乐段必须占满前半段。
@@ -763,6 +774,35 @@ def _t_window():
"pop/punk/urbanhiphop 的 target 区间 == check 放行窗口,边界确实生效")]
def _t_plugins_and_lean_default():
"""微内核钩子已加载;默认 prefer_lean_tags;assemble 不注入 RULE_NEG 堆。"""
from ..plugins.hooks import bus
assert bus._handlers.get("after_assemble"), "intro_guard 未挂 after_assemble"
cfg = loader.load({})
assert cfg["rules"].get("prefer_lean_tags") is True
class _A(object):
chill_vocal = False
instrumental = False
lean_tags = False
full_tags = False
density_profile = None
st = {"bpm": 104, "duration": 180, "key": "F major",
"style": "Chinese pop", "instruments": "kick snare bass",
"mood": "bright", "extra": ""}
# 密度够过闸的短样
raw = ("[verse]\n" + "\n".join(
["街口的灯还亮着我往前走一步"] * 20))
tags, _ly = assemble(_A(), cfg, st, raw, "selftest")
assert "no opening vocals" not in tags.lower(), \
"默认 lean 仍注入了 RULE_NEG opening 堆"
assert "no wordless vocals" in tags.lower()
assert "mm mm" not in tags.lower()
return [("微内核与 lean 默认",
"plugins.after_assemble 已挂;默认 tags 为 lean 且无音节点名")]
def cmd_selftest(args):
from .common import session_logger
cfg = loader.load({})
@@ -773,7 +813,8 @@ def cmd_selftest(args):
_t_intro_instrument_filter, _t_chill_no_conflict,
_t_chill_integration,
_t_sparse_profile, _t_lexicon,
_t_density, _t_window, _t_regression, _t_parity, _t_fallback]
_t_density, _t_window, _t_regression, _t_parity, _t_fallback,
_t_plugins_and_lean_default]
npass = 0
print("== songforge selftest ==")
log.info("selftest 开始", cases=len(cases))
+3
View File
@@ -78,3 +78,6 @@ ideal_line_syllable = [3, 12]
[rules]
trigger_word = "swlvoice"
intro_bars = 8
# 默认走 lean tags:少注入 RULE_NEG,避免否定句膨胀诱发开曲衬词。
# 需要完整否定句时用 --full-tags。
prefer_lean_tags = true
+2 -1
View File
@@ -64,7 +64,8 @@ DEFAULTS = {
"ideal_line_syllable": [3, 12],
}
}},
"rules": {"trigger_word": "swlvoice", "intro_bars": 8},
"rules": {"trigger_word": "swlvoice", "intro_bars": 8,
"prefer_lean_tags": True},
}
+4 -3
View File
@@ -30,9 +30,10 @@ python songforge\songforge.py <命令> [选项]
1. 先读 [`AGENTS_MIN.md`](../AGENTS_MIN.md);不够再读 [`AGENTS.md`](../AGENTS.md)。
2. 没有 `local.toml`、Comfy 没起、风格/歌名/歌词来源不清 → **先问用户**,不要猜路径或改铁律。
3. 需改仓库代码时:先征求同意;建议 git 备份或新插件旁路;问清是否 commit/push、推哪个 remote。
4. 交付以 `qc --baseline` PASS 为准;不要把 `style_fam` / `filler_ratio` 说成硬闸门。
5. 探测/转码/截取用 `songforge media`,不要整读 `qc_worker.py`。
3. 需改仓库代码时:先征求同意;建议 git 备份或新插件旁路(目录 `plugins/`);问清是否 commit/push、推哪个 remote。
4. 交付以 `qc --baseline` PASS 为准;开曲衬词(`intro_filler`)是硬门;`style_fam` / 全曲 `filler_ratio` 仍是弱参考。
5. 探测/转码/截取用 `songforge media`(librosa/soundfile 在 `qc_python`),不要整读 `qc_worker.py`。
6. 默认 `prefer_lean_tags`;不要随意 `--full-tags`(否定句膨胀会诱发开曲衬词)。
---
+17
View File
@@ -0,0 +1,17 @@
# plugins — 扩展目录(微内核外挂)
| 路径 | 用途 |
|------|------|
| `plugins/hooks.py` | 钩子总线(内核只 `emit`,不 import 业务插件) |
| `plugins/builtin/` | 内置插件(随仓发布) |
| `plugins/<name>.py` | 单文件插件 |
| `plugins/<name>/plugin.py` | 包式插件入口 |
## 钩子
- `before_build_tags`
- `after_assemble`(可返回 `{"tags","lyrics"}`)
- `before_qc_judge` / `after_qc_judge`(QC 子进程侧另见 qc_worker)
内核层:`core/`(引擎/路径/workflow)、`rules/`(铁律)、`cli/`(命令)。
业务扩展优先写插件,少改内核。
+9
View File
@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
"""songforge 插件层(微内核扩展点)。
核心(kernel)在 core/ + rules/ + cli/;本目录只放可插拔扩展。
内置插件见 plugins/builtin/;第三方放 plugins/<name>/plugin.py。
"""
from .hooks import bus, load_plugins
__all__ = ["bus", "load_plugins"]
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""内置插件包。"""
+17
View File
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""开曲衬词守卫:在 tags 组装后做一次音节点名扫描(双保险)。"""
from ..hooks import bus
from ...core.errors import RuleViolation
_BAD = ("mm mm", "ooh ooh", "oh oh syllables", "wu wu wu",
"en en", "ng ng", "woo woo")
@bus.on("after_assemble")
def _guard_syllable_names(tags, lyrics, **_kw):
low = (tags or "").lower()
hits = [b for b in _BAD if b in low]
if hits:
raise RuleViolation(
"tags 点名衬词音节 %s(会诱发开曲衬词)" % ", ".join(hits))
return None
+94
View File
@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
"""薄钩子总线:内核不知道插件细节,只按名字广播。
钩子约定(均可选):
before_build_tags kwargs: args, cfg, style, chill, instrumental, lean
after_assemble kwargs: tags, lyrics, args, cfg, style, lean
-> 可返回 {"tags":..., "lyrics":...} 覆盖
before_qc_judge kwargs: result, expect, soft -> 可追加 why 列表
after_qc_judge kwargs: verdict, why, result
插件目录:
plugins/builtin/*.py 内置,默认加载
plugins/<name>/plugin.py 第三方包式
plugins/<name>.py 单文件(非 hooks/__init__)
"""
import importlib
import os
import pkgutil
import sys
import traceback
_HERE = os.path.dirname(os.path.abspath(__file__))
_LOADED = False
class HookBus(object):
def __init__(self):
self._handlers = {}
def on(self, name):
def deco(fn):
self._handlers.setdefault(name, []).append(fn)
return fn
return deco
def emit(self, name, **kwargs):
last = None
for fn in self._handlers.get(name, []):
try:
ret = fn(**kwargs)
if ret is not None:
last = ret
except Exception:
traceback.print_exc()
return last
bus = HookBus()
def load_plugins(extra_dirs=None):
"""发现并 import 插件(幂等)。"""
global _LOADED
if _LOADED:
return
_LOADED = True
roots = [_HERE]
if extra_dirs:
roots.extend(extra_dirs)
# 保证 songforge.plugins 可被 import
parent = os.path.dirname(_HERE)
if parent not in sys.path:
sys.path.insert(0, parent)
# builtin
builtin = os.path.join(_HERE, "builtin")
if os.path.isdir(builtin):
for info in pkgutil.iter_modules([builtin]):
if info.name.startswith("_"):
continue
try:
importlib.import_module(
"songforge.plugins.builtin.%s" % info.name)
except Exception:
traceback.print_exc()
# 顶层单文件 / 子包 plugin.py
for name in sorted(os.listdir(_HERE)):
if name.startswith("_") or name in ("builtin", "hooks.py",
"__init__.py", "README.md"):
continue
path = os.path.join(_HERE, name)
try:
if name.endswith(".py"):
mod = "songforge.plugins.%s" % name[:-3]
importlib.import_module(mod)
elif os.path.isdir(path) and os.path.isfile(
os.path.join(path, "plugin.py")):
importlib.import_module(
"songforge.plugins.%s.plugin" % name)
except Exception:
traceback.print_exc()
# 首次 import hooks 时加载内置插件
load_plugins()
+24 -19
View File
@@ -18,6 +18,9 @@ from songforge.core.errors import LexiconError, RuleViolation
TRIGGER = "swlvoice"
# ⚠ 禁止在 tags 里点名衬词音节(mm / ooh / en / wu / 嗯 / 呀…)。
# 实测:否定句里写出这些音节会把它们喂进条件通道,开曲反而「必出」衬词;
# 标签越长开头人声越响(r≈+0.513)。用抽象禁令 + 正向器乐描述。
RULE_INTRO = (
"8 bar instrumental intro hook before any vocals, "
"instrumental opening, no singing in the first 8 bars, "
@@ -25,9 +28,9 @@ RULE_INTRO = (
"the intro has a catchy instrumental melody hook, "
"the intro bass line and synth melody are the most memorable catchy element, "
"rhythmic drums from the very first beat, "
"intro is instrumental only, no voice, no lyrics, no humming, "
"no vocal ad-lib in the opening, no wu wu wu, no woo woo, "
"no mm mm, no en en, no ng ng, no mouth sounds, no grunting, "
"intro is instrumental only, no voice, no lyrics, "
"no vocal ad-lib in the opening, no wordless vocals in the opening, "
"no mouth sounds in the opening, "
"the opening features a strong instrumental melody line, "
"synth lead melody plays from the very beginning, "
"instrumental melody carries the intro hook"
@@ -35,21 +38,19 @@ RULE_INTRO = (
# 注意:绝对不要加 "no long empty instrumental"。它与"必须有 8 小节器乐前奏"
# 直接矛盾,模型为消除"空"而把前奏填满人声。这个坑踩过,别加回来。
# 默认路径已改 prefer_lean_tags:尽量不注入本段;若注入也禁止点名音节。
RULE_NEG = (
"no opening vocals, no pure vocal intro, no a cappella opening, "
"no vocal intro, no singing until after the instrumental hook, "
"no spoken intro, no rap intro talk, no intro talking, "
"no humming, no mm mm syllables, no oh oh syllables, "
"no wu wu wu, no woo woo, no ooh ooh, no sustained wu vowel, "
"no en en en, no ng ng ng, no mouth sounds, no grunting, no breathing sounds, "
"no eh ah ah filler, no vocal ad-libs, no droning sustained vowels, "
"no yodeling, no melisma, no crooning, no R&B ballad vocal style, "
"no wordless vocals in the opening, no vocal ad-libs in the opening, "
"no mouth sounds in the opening, no breathing sounds as melody, "
"no yodeling, no melisma filler, no crooning intro, "
"no overly long intro, no excessive drum solo, "
"no slow start, no fade in, "
"no beatless intro, no unaccompanied vocal, no a cappella, "
"no singing chinese instruction words, no vocalizing text labels, "
"no wordless vocalization, no non-verbal vocal sounds, "
"no vocal pad, no vocal texture, no ambient vocal, "
"no vocal pad in the opening, no ambient vocal in the opening, "
"no background vocal in the opening, no choir in the intro, "
"no vocal harmonies in the intro, no vocal layer in the opening"
)
@@ -76,7 +77,8 @@ RULE_NO_FILLER = (
"solo lead vocal only, "
"no backing vocals, no backup singers, no choir, "
"no vocal doubles, no harmony stack, no call and response vocals, "
"no wordless vocals between sections"
"no wordless vocals between sections, "
"no wordless vocals in the opening"
)
RULE_HARMONY = (
@@ -346,7 +348,7 @@ STEM_INST_LYRICS = ("[intro]\n[inst]\n[inst]\n[verse]\n[inst]\n[inst]\n"
"[chorus]\n[inst]\n[inst]\n[bridge]\n[inst]\n[outro]")
STEM_INST_TAGS = (
"pure instrumental track, no vocals anywhere, "
"no singing, no voice, no humming, no vocal ad-lib, "
"no singing, no voice, no wordless vocals, no vocal ad-lib, "
"instrumental only, this is a backing track with no lead vocal, "
"drums bass and chords only, drums enter on the very first beat"
)
@@ -531,7 +533,7 @@ RULE_INST_MEMO = (
RULE_INST_NEG = (
"no vocals anywhere, no singing, no voice, no lead vocal, no backing vocal, "
"no humming, no mm mm syllables, no oh oh syllables, no vocal ad-lib, "
"no wordless vocals, no vocal ad-lib, "
"no whisper, no spoken word, no rap, no choir, no vocal sample, "
"no a cappella, instrumental only, this is a backing track, "
"drums bass synths chords and lead melodies only, "
@@ -1073,15 +1075,18 @@ def check_rules(lyrics, tags, lean=False):
if kw == "swlvoice" or need_neg:
if kw not in low:
errs.append("tags 缺少 '%s'" % kw)
# RULE_NO_FILLER 在 lean 下也必须存在:它是唯一一条约束整首歌
# 人声只唱歌词、不唱衬音的规则。lean 跳过 RULE_NEG 是因为前奏否定句
# 膨胀,但衬音禁令跟前奏无关,不能一起跳过。
# 2026-10-08:从负面禁词(no ooh / no 嗯嗯)改为正面强制
# "sing only the exact words",校验关键词也跟着改。
# RULE_NO_FILLER:禁止点名音节;用抽象词校验。
for kw in ("sing only the exact words", "instrumental only",
"solo lead vocal only", "no backing vocals"):
"solo lead vocal only", "no backing vocals",
"no wordless vocals"):
if kw not in low:
errs.append("tags 缺少 '%s'(衬音禁令,lean 下也必须存在)" % kw)
# 禁止把衬词音节写进 tags(会诱发开曲必出衬词)
for bad in ("mm mm", "ooh ooh", "oh oh syllables", "wu wu wu",
"en en", "ng ng", "woo woo"):
if bad in low:
errs.append("tags 点名衬词音节 '%s'(会诱发开曲衬词,请用 "
"no wordless vocals)" % bad)
# 器乐前奏小节数:普通歌曲 8 小节,chill 吟唱 8 小节,纯器乐 8 小节。
# 三种模式现在统一 8 小节(chill 曾试过 16,实测对人声起点毫无作用)。
# 这里仍然只校验"写了且在 4~32 范围内",不写死具体数字:
+64 -3
View File
@@ -81,6 +81,11 @@ HARD = dict(
# (Whisper 段落起点最多会早报 0.5s 左右),不是用来放水进水点的。
intro_onset_rel=1.0,
onset_grace=1.2, # 秒,ASR 时间戳容差
# ---- 开曲衬词硬门(vocal_onset 只看真唱,会漏掉 嗯/呀/ooh)----
# 前奏窗内 ASR 汉字/英文词若绝大多数是衬词,或衬词绝对量过大 → FAIL。
# 阈值刻意偏严:用户要求「不能出开曲衬词」;Whisper 偶发单字可被 min 挡住。
intro_filler_min_chars=6, # 前奏窗内至少累计这么多衬词字/词才判
intro_filler_ratio=0.55, # 衬词占前奏窗 ASR 单元比例
# ---- 歌词感知分类阈值(见文件头坑位 6/7)----
# lyric_hit >= 0.34 -> 真唱;instr_hit >= 0.40 -> 生成指令泄漏。
# 这两个数是在 8 首已认可老歌 + 本批 8 首上交叉验证出来的:
@@ -368,7 +373,7 @@ into over under again very so no yes
# 口径必须和歌词召回分开:mm / yeah / okay 这类在歌里是 legit 的
# 律动衬词,但绝不能算成"真的唱出内容了"。
EN_FILLER = frozenset("""
oh ah uh um mm hmm mhm okay ok yeah yep
oh ah uh um mm hmm mhm mmm ooo ooh woo yeah yep yo ya la na da hey
""".split())
@@ -422,7 +427,8 @@ def asr(wav, sr, lang="zh"):
# 语气词/无意义哼唱。Whisper 对纯伴奏段落会吐出成百上千个"嗯""啊",
# 实测 pop 前奏被吐 112 个"嗯"、hiphop 前奏 223 个"啊",去重后只有 1 个
# 字符。这些既不能算歌词,也不能算人声进入点。
FILLER = set("嗯啊哦噢喔呃哎唉嘿咦哟唔唷哼嘻嘿")
# 开曲衬词硬门会单独统计前奏窗内的这些字(含恩/昂/呀/咿)。
FILLER = set("嗯啊哦噢喔呃哎唉嘿咦哟唔唷哼嘻嘿恩昂呀咿喔吶呐")
def real_cjk(text):
@@ -700,6 +706,37 @@ def filler_ratio(asr_text, lang="zh"):
return n / float(len(chars))
def intro_filler_stats(segs, intro_sec, lang="zh"):
"""前奏时间窗内的衬词统计(硬门用)。
vocal_onset / head_chars 只看「真唱实义词」,会故意丢掉 嗯/呀/ooh,
导致开曲衬词满天飞仍 PASS。这里单独扫前奏窗 ASR。
"""
total = 0
fill = 0
samples = []
for s in segs or []:
if float(s.get("t0", 0)) >= float(intro_sec):
continue
t = s.get("text") or ""
if _is_en(lang):
units = _en_words(_strip_tags(t))
f = [w for w in units if w in EN_FILLER]
else:
units = list(cjk(t))
f = [c for c in units if c in FILLER]
total += len(units)
fill += len(f)
if f:
samples.append((round(float(s.get("t0", 0)), 2),
"".join(f)[:24] if not _is_en(lang)
else " ".join(f)[:24]))
ratio = (fill / float(total)) if total else 0.0
return dict(intro_filler_n=fill, intro_asr_n=total,
intro_filler_ratio=round(ratio, 4),
intro_filler_samples=samples[:4])
def coverage(asr_text, lyrics, lang="zh"):
"""ASR 召回率:ASR 里命中的歌词单元 / 歌词正文单元。
@@ -890,8 +927,15 @@ def measure(path, expect=None, cache_dir=None, with_asr=True):
if half > vsr else 0.0
cov = coverage(txt, lyr, lang) if with_asr else 0.0
# 衬词占比:弱参考,不单独导致 FAIL(与 style_fam 同级)
# 全曲衬词占比:弱参考;前奏窗衬词:硬门(见 judge)
fill_r = filler_ratio(txt, lang) if with_asr else 0.0
intro_sec = 8.0
if expect.get("bpm") and expect.get("intro_bars"):
intro_sec = (float(expect["intro_bars"]) * 60.0
/ float(expect["bpm"]) * 4.0)
ifest = intro_filler_stats(segs, intro_sec, lang) if with_asr else \
dict(intro_filler_n=0, intro_asr_n=0, intro_filler_ratio=0.0,
intro_filler_samples=[])
# ---- 风格分类:只看混音轨,不掺 demucs(见 qc_style 文件头坑位 4)
svec, sraw = qc_style.features(path, expect_bpm=expect.get("bpm"))
@@ -919,6 +963,10 @@ def measure(path, expect=None, cache_dir=None, with_asr=True):
f0_drift_st=round(f0_drift_st, 2),
asr_chars=len(tokens(txt, lang)), asr_segs=len(segs),
coverage=round(cov, 4), filler_ratio=round(fill_r, 4),
intro_filler_n=ifest["intro_filler_n"],
intro_asr_n=ifest["intro_asr_n"],
intro_filler_ratio=ifest["intro_filler_ratio"],
intro_filler_samples=ifest["intro_filler_samples"],
asr_head=txt[:120],
voice_self=round(float(e_self), 4),
flatness=round(sraw.get("flatness", 0.0), 4),
@@ -1020,6 +1068,19 @@ def judge(rows, baseline):
unit = "词" if _is_en(r.get("lang", e.get("lang"))) else "汉字"
why.append("前 2s 就已唱出 %d 个%s,疑似纯人声/spoken 开头"
% (r["head_chars_0_2"], unit))
# ---- 铁律一-b:禁止开曲衬词(嗯/呀/ooh…)
# vocal_onset 只看真唱,会漏掉衬词;此处扫前奏窗 ASR。
ifn = int(r.get("intro_filler_n") or 0)
ifr = float(r.get("intro_filler_ratio") or 0.0)
if ifn >= HARD["intro_filler_min_chars"] and \
ifr >= HARD["intro_filler_ratio"]:
samp = r.get("intro_filler_samples") or []
tip = ("; ".join("%ss:%s" % (a, b) for a, b in samp[:2])
if samp else "")
why.append("开曲衬词 %d 单元占比 %.0f%%(≥%d 且 ≥%.0f%%)%s"
% (ifn, ifr * 100, HARD["intro_filler_min_chars"],
HARD["intro_filler_ratio"] * 100,
(":" + tip) if tip else ""))
# ---- 铁律二:8 小节器乐前奏(完整 8 小节,不是 55%)
# 原来判的是 vocal_onset < want * 0.55,等于"第 4~5 小节进 sang
# 也算过",把铁律降级成建议。现在按完整 8 小节判,只留