Add songforge as independent repo with path layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
swl
2026-10-09 19:18:33 +08:00
co-authored by Cursor
commit f39deb1848
52 changed files with 10289 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
# archive/full-snapshot 可含 flac/cache;该分支仅本地备份,禁止默认 push
+45
View File
@@ -0,0 +1,45 @@
# --- 本机覆盖(勿提交)---
config/local.json
# --- 过程与缓存(保留 .gitkeep 占位)---
data/**
!data/.gitkeep
!data/runs/
!data/runs/.gitkeep
!data/tmp/
!data/tmp/.gitkeep
tmp/
cache/**
!cache/.gitkeep
runs/
index/catalog.jsonl
index/by_day/
# --- 音频 / 误放报告 ---
*.flac
*.wav
*.mp3
qc.json
# --- 大体量归档(进 archive 分支,不进 main)---
_archive/
.bak/
bak/
# --- Python ---
__pycache__/
*.py[cod]
*.egg-info/
.pytest_cache/
.codebase-index/
# --- 编辑器 / OS ---
.DS_Store
Thumbs.db
.idea/
.vscode/
*.swp
# --- 索引占位 ---
!index/.gitkeep
!input/lyrics/.gitkeep
+130
View File
@@ -0,0 +1,130 @@
# songforge — Agent 生歌手册
> 远程 / channel Agent 读这份文件即可做歌。上下文不够时**重新打开本文件**,不要凭记忆改参数。
> 人类规范全文见 `../生歌规则.md`。行为冲突时以那份 + `config/default.json` 为准。
## 0. 你是谁、要交什么
你是 songforge 流水线操作员。交付物是:
1. 一次 `gen` 的 `run_id`
2. ComfyUI 产出的 flac
3. `qc --baseline` 结论为 **PASS**
`style_fam` 只是弱参考,不要把它当 PASS 条件,也不要对外说「风格已验证」。
## 1. 工作目录(硬)
```text
cd D:\CodeFiles\Thinking\ComfyUI-MiniMaxH3\user\default\workflows
```
唯一入口:
```text
python songforge\songforge.py <命令>
```
禁止:手写 tags / 手写前奏 / 改 workflow JSON 调参 / 换 YuE2·Music3·aio / 放宽 QC 阈值。
## 2. 强制流水线(按顺序)
```text
doctor → target → 写歌词 → check → gen → qc --baseline
```
```powershell
python songforge\songforge.py doctor
python songforge\songforge.py target --style pop --bpm 104 --dur 180
# 按 target 打印的放行区间写歌词(勿手写 [intro] / tags)
python songforge\songforge.py check --style pop --title 歌名 --lyrics-file <路径.txt> --bpm 104 --dur 180
python songforge\songforge.py gen --style pop --title 歌名 --lyrics-file <路径.txt> --bpm 104 --dur 180
python songforge\songforge.py qc --run <run_id> --baseline
```
- `check` 不过 → **只改歌词**,不准改 shift/steps/cfg/temperature
- `doctor` 服务不可达 → 先起 ComfyUI(`http://127.0.0.1:8188`)
- `qc` 必须带 `--baseline`;`--run` 用 `gen-...` 或 `songforge\data\runs\<日>\gen-...` 均可
- 索引:`python songforge\songforge.py catalog` / `catalog --rebuild`
## 3. 硬锁定(不可谈判)
| 项 | 值 |
|----|-----|
| checkpoint | `ace_step_1.5_turbo_swl_fused.safetensors` |
| LoRA | `swl_voice_best_ep257.safetensors`(0.5 / 0.5) |
| 采样 | shift=5.5 / steps=28 / cfg=2.0 / temperature=0.68 |
| 时长 | 完整歌 **150–200** 秒(默认跟风格字典;pop 常 180) |
| 前奏 | 8 小节器乐 hook,第一拍进鼓;CLI `assemble` 自动注入 |
改算法参数只动 `config/default.json`;本机路径用 `config/local.json`(gitignore)。不要改 `data/runs/` 里的 JSON。
配置优先级:
```text
命令行 > SONGFORGE_* > config/local.json > config/default.json > DEFAULTS
```
## 4. 目录地图(项目 vs 数据)
路径键在 `config/default.json` → `paths`。相对 `user/default/workflows`:
| 级别 | 用途 | 默认路径 |
|------|------|----------|
| 项目 | 歌词投放 | `songforge/input/lyrics/` |
| 项目 | QC/风格基线 | `songforge/config/baseline/` |
| 项目 | 规范文档 | `生歌规则.md` / `AGENTS.md` / `docs/使用手册.md` |
| 数据 | 正式运行 | `songforge/data/runs/YYYY-MM-DD/gen-*/` |
| 数据 | 临时会话 | `songforge/data/tmp/YYYY-MM-DD/` |
| 数据 | 全局索引 | `songforge/index/catalog.jsonl` |
| 数据 | QC/风格缓存 | `songforge/cache/qc/` `cache/style/` |
| 外部 | 音频成品 | `<ComfyUI>/output/MyMusic/`(`local.json` 可改) |
本机路径写 `config/local.json`(从 `local.json.example` 复制):`comfy_root` / `qc_python` / `music_dir`。
## 5. 写歌词要点
1. 先 `target`,正文音节落进放行区间(偏稀 → 模型用拖腔填空)。
2. **不要**写 `[intro]` / Instrumental 前奏 / tags——`assemble` 会注入。
3. 段落用 `[verse]` `[chorus]` 等英文结构标记。
4. 默认密度档 = 人声填满;英文低音吟唱用 `--chill-vocal`(自动 sparse)。
可用素材示例(区间已合适):
```text
songforge\_archive\lyrics_corpus\拍一下.txt
```
## 6. 失败速查
| 现象 | 动作 |
|------|------|
| doctor FAIL 服务 | 启动 ComfyUI |
| check 密度失败 | 改歌词到 target 区间 |
| gen 提交失败 | 跑 `selftest`;用 `--dry-run` 看 payload |
| qc voice_nn=null | 漏了 `--baseline` |
| qc FAIL | 修歌/重 gen,**不**改阈值 |
| CLI 崩溃 | `--dry-run` 或 fallback 旧 `remake_v5.py`(勿删) |
怀疑 CLI 坏了:
```powershell
python songforge\songforge.py selftest
```
## 7. 上下文不够时
1. 重读本文件第 1–3 节。
2. 打开 `songforge/config/default.json` 核对模型/采样/paths。
3. 打开本次 `runs/<run_id>/run.log` 与 `manifest.json`。
4. 不要发明新采样参数或新模型名。
## 8. 最小验收清单
```text
[ ] doctor 全绿(模型锁定 + 采样在带内)
[ ] check OK
[ ] gen 产出 flac,时长在 150–200
[ ] qc --baseline → [PASS]
[ ] 未改阈值、未换模型
```
+78
View File
@@ -0,0 +1,78 @@
# songforge
本地创作者用的 AI 歌曲生成 CLI。固定模型 + 铁律注入 + 密度硬校验 + QC 验收,稳定产出带专属声线的完整歌曲。
本目录是**独立 Git 仓**(`main` 只跟踪项目资产;大体量过程数据在 `archive/full-snapshot`,勿默认 push)。
| 文档 | 给谁 |
|------|------|
| [`AGENTS.md`](AGENTS.md) | **远程 / channel Agent**(上下文不够时重读这份做歌) |
| [`../生歌规则.md`](../生歌规则.md) | 参数/铁律/踩坑唯一规范 |
| [`docs/使用手册.md`](docs/使用手册.md) | 人类操作手册 |
## 30 秒上手
工作目录必须是 `user/default/workflows`:
```powershell
cd D:\CodeFiles\Thinking\ComfyUI-MiniMaxH3\user\default\workflows
python songforge\songforge.py doctor
python songforge\songforge.py target --style pop --bpm 104 --dur 180
python songforge\songforge.py check --style pop --title 歌名 --lyrics-file songforge\input\lyrics\歌名.txt
python songforge\songforge.py gen --style pop --title 歌名 --lyrics-file songforge\input\lyrics\歌名.txt
python songforge\songforge.py qc --run gen-<时间戳> --baseline
python songforge\songforge.py catalog --limit 20
```
`qc` 必须带 `--baseline`。首次本机复制 `config/local.json.example` → `config/local.json` 填 Comfy 根与 QC Python。
## 硬约束(摘要)
| 项 | 值 |
|----|-----|
| 模型 | `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–200 秒 |
| 前奏 | 8 小节器乐 hook;CLI 自动注入 |
| 配置 | 算法锁 `config/default.json`;本机路径 `config/local.json` |
## 项目资产 vs 过程数据
| 级别 | 路径 | 是否进 `main` |
|------|------|----------------|
| 项目 | `cli/` `core/` `config/*.json`(除 local) `config/baseline/` `workflows/` `docs/` | 是 |
| 本机 | `config/local.json` | 否(gitignore) |
| 过程 | `data/runs/YYYY-MM-DD/gen-*/` `data/tmp/` | 否 |
| 索引 | `index/catalog.jsonl` | 否(可 `--rebuild`) |
| 缓存 | `cache/qc` `cache/style` | 否 |
| 音频 | ComfyUI `output/MyMusic/` | 不在包内 |
```
songforge/
AGENTS.md / README.md / songforge.py
config/ # default + styles + lexicon + local.example
baseline/ # qc_baseline*.json + style_ref.json
local.json # 本机路径(勿提交)
cli/ core/ rules/ lyrics/
input/lyrics/ # 新歌词投放
data/runs/YYYY-MM-DD/ # gen 正式产物
data/tmp/YYYY-MM-DD/ # doctor/check 会话
index/catalog.jsonl # 全局元数据索引
cache/ # QC / 风格特征
docs/ _archive/
```
## 配置优先级
```
命令行 > SONGFORGE_* 环境变量 > config/local.json > config/default.json > DEFAULTS
```
模型与采样铁律只在 `default.json`,不要放进 local。
## 日志
- `gen` → `data/runs/<日>/<run_id>/run.log`(JSONL)
- `doctor` / `check` → `data/tmp/<日>/<cmd>-*/run.log`
- `--log-level` / `--quiet` 全局生效
+24
View File
@@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
"""songforge 核心包重写 - 修复相对导入与模块管理"""
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"
# 保持微内核结构:CLI -> Rules -> Lyrics -> Core -> Log -> Config
__all__ = [
'build_workflow', 'convert', 'find_node', 'ROOT', 'WIDGET_MAP',
'RuleViolation', 'LexiconError',
'build_tags', 'build_lyrics', 'validate', 'TRIGGER',
'load'
]
View File
+1
View File
@@ -0,0 +1 @@
from .main import main
+139
View File
@@ -0,0 +1,139 @@
# -*- coding: utf-8 -*-
"""铁律组装与校验:tags / 前奏注入 / 密度闸门。"""
import re
from ..core.errors import RuleViolation
from ..lyrics import meter
from ..rules import ironlaw
from .common import chill_intro_bars, resolve_profile
def split_sections(lyrics_raw):
"""把裸歌词切成 [(tag, text)],识别不出标记时整段当 [verse]。"""
secs = []
cur_tag, buf = None, []
for ln in lyrics_raw.split("\n"):
s = ln.strip()
if s.startswith("[") and s.endswith("]"):
if cur_tag and buf:
secs.append((cur_tag, "\n".join(buf).strip()))
cur_tag, buf = s, []
elif s:
buf.append(s)
if cur_tag and buf:
secs.append((cur_tag, "\n".join(buf).strip()))
if not secs:
secs = [("[verse]", lyrics_raw.strip())]
return secs
def vocal_sections(lyrics_raw):
"""只取真正有人唱的段:丢掉所有只挂 [inst] 的纯器乐占位。
chill 重排时器乐占位要全部重新生成,先从原始歌词剥掉,
否则同一段器乐会被写两遍,第二遍反而把人声提前拉回来。
"""
out = []
for tag, text in split_sections(lyrics_raw):
t = text.strip()
if not t or re.fullmatch(r"\[?inst\]?|\[Instrumental[^\]]*\]", t, re.I):
continue
out.append((tag, text))
return out or [("[verse]", "")]
def duration_allowed(cfg, dur):
"""时长闸门:主区间 + 显式白名单区间。
主区间 150~200s 来自 35 首已验证实歌,不能为短时长题材放宽。
短视频/口水歌这类确实需要 100~130s,但没有实歌背书,
所以走 config.song.duration_extra_ranges 显式列出。
"""
lo, hi = cfg["song"]["duration_range"]
if lo <= dur <= hi:
return True
for a, b in cfg["song"].get("duration_extra_ranges") or []:
if a <= dur <= b:
return True
return False
def _extra_hint(cfg, dur):
"""报错时列出当前生效的额外区间,省一次查配置。"""
ex = cfg["song"].get("duration_extra_ranges") or []
if not ex:
return ""
return "(额外放行区间:%s)" % ", ".join("%d~%ds" % (a, b) for a, b in ex)
def assemble(args, cfg, st, lyrics_raw, title):
"""套用铁律:生成 tags、补器乐前奏、清洗中文标记。"""
chill = bool(getattr(args, "chill_vocal", False))
inst = bool(getattr(args, "instrumental", False))
lean = bool(getattr(args, "lean_tags", False))
tags = ironlaw.build_tags(
style=st.get("style", ""), instruments=st.get("instruments", ""),
mood=st.get("mood", ""), extra=st.get("extra", ""),
chill_vocal=chill, instrumental=inst, lean=lean)
ibars = chill_intro_bars(cfg, chill)
# 纯器乐:没有可唱正文,歌词体直接由结构标记铺出来,
# 密度闸门对纯器乐不适用(见 do_validate)。
if inst and not lyrics_raw.lstrip().lower().startswith("[intro]"):
lyrics = ironlaw.build_inst_lyrics(
st.get("intro_detail") or st.get("instruments"),
bars=ibars)
return tags, lyrics
if chill:
# chill 走独立结构体:器乐段整体排在人声段之前。
# 实测这只降低人声密度,并不推迟起点(chill 3 第一句仍在 0 秒),
# 标签侧的时间/时机约束同样无效。详见 ironlaw 顶部实测结论。
cfg_lyrics = meter.pick(cfg["lyrics"], resolve_profile(args))
cap = meter.capacity(st["duration"], st["bpm"], cfg_lyrics)
lyrics = ironlaw.build_chill_lyrics(
vocal_sections(lyrics_raw),
st.get("intro_detail") or st.get("instruments"),
bars=ibars, total_bars=cap["total_bars"])
return tags, lyrics
lyrics = lyrics_raw
if not lyrics.lstrip().lower().startswith("[intro]"):
lyrics = ironlaw.build_lyrics(
split_sections(lyrics_raw),
st.get("intro_detail") or st.get("instruments"),
bars=ibars)
else:
# 已有 [intro] 头的歌词文件:强制把前奏小节数对齐到标签写的值。
# 标签写 16 小节而歌词头写 8 小节时,check_rules 会判两处不一致
# ——这是故意留的闸门,不是 bug。
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"
return tags, lyrics
def do_validate(lyrics, tags, cfg, st, lexicon, strict=True,
instrumental=False, profile=None, lean=False):
errs = []
errs += ironlaw.check_rules(lyrics, tags, lean=lean)
errs += ironlaw.check_lexicon(lyrics, lexicon)
cfg_lyrics = meter.pick(cfg["lyrics"], profile)
if instrumental:
# 纯器乐没有可唱正文,"歌词过少/过多/每句音节"三条全部不适用。
# 只保留结构与词典校验,密度统计仅作诊断记录。
derr = []
stats = meter.analyse(lyrics, st["duration"], st["bpm"], cfg_lyrics)
else:
derr, stats = meter.check(lyrics, st["duration"], st["bpm"], cfg_lyrics)
errs += derr
if strict and errs:
raise RuleViolation("校验未通过:\n - " + "\n - ".join(errs))
return errs, stats
# ---------------------------------------------------------------- commands
+429
View File
@@ -0,0 +1,429 @@
# -*- coding: utf-8 -*-
"""CLI 命令实现:doctor / styles / target / check / gen / runs / show。"""
import datetime
import json
import os
import random
from ..config import loader
from ..core import catalog as catmod
from ..core import paths as pmod
from ..core import workflow as wfmod
from ..core.engine import Engine
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 .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)
def cmd_doctor(args):
cfg = build_cfg(args)
run, log = session_logger(args, cfg, "doctor")
layout = pmod.path_layout(cfg)
root = layout["comfy_root"]
log.info("doctor 开始", server=cfg["engine"]["server"])
print("== 路径 ==")
print(" ComfyUI 根 %s" % root)
print(" workflows %s" % ROOT)
print(" runs %s (按日 YYYY-MM-DD/)" % layout["runs"])
print(" tmp %s" % layout["tmp"])
print(" lyrics %s" % layout["lyrics"])
print(" baseline %s" % layout["baseline"])
print(" catalog %s" % layout["catalog"])
print(" qc_cache %s" % layout["qc_cache"])
print(" 音频输出 %s" % layout["audio_out"])
local_cfg = os.path.join(ROOT, "songforge", "config", "local.json")
print(" local.json %s" % ("有" if os.path.isfile(local_cfg) else "无(可用 local.json.example)"))
print("== 根目录卫生 ==")
pkg = layout["pkg"]
junk = []
for name in pmod.ROOT_JUNK_NAMES:
p = os.path.join(pkg, name)
if os.path.isfile(p):
junk.append(name)
for name in ("qc_baseline.json", "qc_baseline_old.json", "style_ref.json"):
if os.path.isfile(os.path.join(pkg, name)):
junk.append(name + "(应在 config/baseline/)")
if junk:
print(" [WARN] 包根有过程/错位文件: %s" % ", ".join(junk))
else:
print(" [ok] 包根无过程垃圾")
print("== ComfyUI ==")
ok, info = Engine(cfg["engine"]["server"]).health()
if not ok:
print(" [FAIL] %s" % info)
print(" 排查:确认 ComfyUI 已启动且端口 8188 可访问")
log.error("ComfyUI 不可达", detail=str(info))
log.close()
return 2
print(" [ok] %s 显存 %.1fGB 队列 运行%d/等待%d"
% (info["device"], info["vram_total_gb"],
info["queue_running"], info["queue_pending"]))
print(" [ok] ComfyUI %s" % info["comfyui_version"])
print("== 模型 ==")
ck = pmod.model_path(root, "checkpoints", cfg["model"]["checkpoint"])
lora = pmod.model_path(root, "loras", cfg["model"]["lora"])
tpl = os.path.join(ROOT, cfg["paths"]["workflow_template"])
rc = 0
for label, p in (("checkpoint", ck), ("lora", lora),
("template", tpl)):
good = os.path.exists(p)
print(" [%s] %-11s %s" % ("ok" if good else "FAIL", label, p))
if not good:
rc = 2
if cfg["model"]["checkpoint"] in cfg["model"]["denied_checkpoints"]:
print(" [FAIL] 当前 checkpoint 在禁用名单里:%s"
% cfg["model"]["checkpoint"])
rc = 2
else:
print(" [ok] 模型锁定 %s + %s"
% (cfg["model"]["checkpoint"], cfg["model"]["lora"]))
print("== 铁律 ==")
for k in ("swlvoice", "8 bar instrumental intro hook", "no opening vocals"):
good = k in ironlaw.build_tags("test")
print(" [%s] %s" % ("ok" if good else "FAIL", k))
if not good:
rc = 2
print("== 采样 ==")
bad = (cfg["sampler"]["shift"] < 5.0
or cfg["sampler"]["steps"] < 24
or cfg["sampler"]["cfg"] < 1.5
or not (0.60 <= cfg["encode"]["temperature"] <= 0.70))
print(" [%s] shift=%s steps=%s cfg=%s temperature=%s"
% ("FAIL" if bad else "ok", cfg["sampler"]["shift"],
cfg["sampler"]["steps"], cfg["sampler"]["cfg"],
cfg["encode"]["temperature"]))
if bad:
print(" 偏离已验证参数:shift 5.0~5.5 / steps 24~28 / cfg 2.0"
" / temperature 0.62~0.68")
rc = 2
print("== 时长区间 ==")
lo, hi = cfg["song"]["duration_range"]
good = lo <= 150 and hi >= 200
print(" [%s] 允许 %d~%d 秒(理想 150~200)"
% ("ok" if good else "WARN", lo, hi))
print("== 配置 ==")
print(" 服务器=%s" % cfg["engine"]["server"])
for key in ("runs", "tmp", "tmp_today", "lyrics", "qc_cache",
"style_cache", "index", "baseline"):
pmod.ensure_dir(layout[key])
log.info("doctor 结束", rc=rc, log_dir=run.dir)
log.close()
return rc
def cmd_styles(args):
data = loader.styles()
print("%-12s %5s %-11s %5s %s" % ("风格", "BPM", "调性", "时长", "说明"))
for k, v in sorted(data.items()):
if k.startswith("_"):
continue
print("%-12s %5s %-11s %5s %s"
% (k, v["bpm"], v["key"], v["duration"], v["style"]))
return 0
def cmd_target(args):
cfg = build_cfg(args)
if args.style:
st = style_of(cfg, args.style, args)
else:
st = {"bpm": args.bpm or 94, "duration": args.dur or 165}
if getattr(args, "bpm", None):
st["bpm"] = args.bpm
if getattr(args, "dur", None):
st["duration"] = args.dur
prof = resolve_profile(args)
inst = bool(getattr(args, "instrumental", False))
cfg_lyrics = meter.pick(cfg["lyrics"], prof)
if args.style:
print("风格 %s" % args.style)
print("时长 %ds BPM %d" % (st["duration"], st["bpm"]))
if inst:
stt = meter.analyse("", st["duration"], st["bpm"], cfg_lyrics)
print(" [纯器乐] 无人声,整首 %.0f 小节全部留给器乐"
% stt["total_bars"])
print(" 器乐结构段:intro / breakdown / build / drop / "
"post-drop / final drop / outro")
print(" 可唱歌词目标:0 音节")
return 0
stt = meter.analyse("", st["duration"], st["bpm"], cfg_lyrics)
print(" 总小节 %.0f 前奏 %d 小节 可唱 %.0f 小节"
% (stt["total_bars"], cfg_lyrics["intro_bars"], stt["sing_bars"]))
if prof:
print(" [密度档] %s(可唱小节占比 %.0f%%)"
% (prof, cfg_lyrics["sing_bar_ratio"] * 100))
mid, lo, hi = meter.target_words(st["duration"], st["bpm"], cfg_lyrics)
print(" 理论音节容量 %d ~ %d" % (stt["lo"], stt["hi"]))
print(" 建议正文字数:%d 字左右(放行区间 %d ~ %d)" % (mid, lo, hi))
print(" 平均每句:%d ~ %d 音节(硬上限 %d)"
% (cfg_lyrics["ideal_line_syllable"][0],
cfg_lyrics["ideal_line_syllable"][1],
cfg_lyrics["line_syllable_max"]))
return 0
def cmd_check(args):
cfg = build_cfg(args)
run, log = session_logger(args, cfg, "check")
lexicon = loader.lexicon()
raw = read_lyrics(args)
st = style_of(cfg, args.style, args)
tags, lyrics = assemble(args, cfg, st, raw, args.title or "check")
inst = bool(getattr(args, "instrumental", False))
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)))
run.save_text("lyrics.txt", lyrics)
run.save_text("tags.txt", tags)
print("== 密度 ==")
print(" 时长 %ds BPM %d 调性 %s" % (st["duration"], st["bpm"], st["key"]))
if inst:
print(" [纯器乐] 无可唱歌词,密度闸门不适用")
elif prof:
print(" [密度档] %s(可唱小节占比 %.0f%%)"
% (prof, meter.pick(cfg["lyrics"], prof)["sing_bar_ratio"] * 100))
print(" 正文字节 %d 音节 / %d 句 / 平均每句 %.1f 音节"
% (stats["syllables"], stats["lines"], stats["per_line"]))
if inst:
print(" 密度闸门 N/A(纯器乐无歌词,放行区间不适用)")
else:
print(" 理论容量 %d ~ %d 放行区间 %d ~ %d"
% (stats["lo"], stats["hi"], stats["win_lo"], stats["win_hi"]))
print("== 结果 ==")
if errs:
for e in errs:
print(" [FAIL] %s" % e)
log.warn("check 未通过", errors=len(errs), syllables=stats["syllables"])
log.close()
return 1
print(" [OK] 通过,可提交生成")
log.info("check 通过", syllables=stats["syllables"],
win="%d-%d" % (stats.get("win_lo", 0), stats.get("win_hi", 0)),
log_dir=run.dir)
log.close()
return 0
def cmd_gen(args):
cfg = build_cfg(args)
lexicon = loader.lexicon()
title = args.title or "untitled"
st = style_of(cfg, args.style, args)
raw = read_lyrics(args)
lo, hi = cfg["song"]["duration_range"]
if not duration_allowed(cfg, st["duration"]):
raise ConfigError("时长 %ds 超出允许区间 %d~%ds%s"
% (st["duration"], lo, hi,
_extra_hint(cfg, st["duration"])))
tags, lyrics = assemble(args, cfg, st, raw, title)
inst = bool(getattr(args, "instrumental", False))
prof = resolve_profile(args)
ibars = chill_intro_bars(
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)))
day_root = gen_day_root(cfg)
pmod.ensure_dir(day_root)
run_id = now_id("gen", day_root)
run = Run(run_id, day_root)
log = Logger(run, level=args.log_level, quiet=args.quiet)
log.info("开始生成", title=title, style=args.style, bpm=st["bpm"],
dur=st["duration"], key=st["key"], seeds=args.seeds)
# 纯器乐与英文低声吟唱都强制走英文 language:
# 1) chill-vocal 的歌词正文本来就是英文;
# 2) instrumental 没有歌词,但 language 节点仍会影响音色/咬字倾向,
# 不统一会让 instrumental vs chill 的 A/B 多出一个隐藏变量
# (早期 InstPure 就是因为漏传 --language en 走了默认中文,
# 跟 chill 版对比时无法归因)。
lang = "en" if (getattr(args, "chill_vocal", False)
or inst) else cfg["song"]["language"]
if getattr(args, "language", None):
lang = args.language
log.info("密度校验通过", syllables=stats["syllables"],
lines=stats["lines"], per_line=round(stats["per_line"], 2),
win="N/A" if inst else "%d-%d" % (stats["win_lo"],
stats["win_hi"]),
cap_ratio=round(stats["fill"], 3),
instrumental=inst, density_profile=prof or "default")
template = wfmod.load_template(cfg["paths"]["workflow_template"])
prefix = cfg["paths"]["output_prefix"]
fmt = cfg["paths"]["output_format"]
seed_base = args.seed if args.seed else random.randint(1, 2 ** 31 - 1)
seeds = [seed_base + i for i in range(args.seeds)] if args.seeds > 1 \
else [seed_base]
# 永久命名规则:歌名-【seed号】-【特征】-日期戳
# 特征从风格名中提取,日期戳格式 YYMMDD
date_stamp = datetime.datetime.now().strftime("%y%m%d")
style_tag = args.style if len(args.style) <= 12 else args.style[:12]
safe_title = safe_name(title)
run.save_text("lyrics.txt", lyrics)
run.save_text("tags.txt", tags)
built = []
for i, sd in enumerate(seeds):
# 永久命名规则:歌名-【sN】-【风格特征】-YYMMDD
sub = "%s/%s-s%d-%s-%s" % (prefix, safe_title, i + 1, style_tag, date_stamp)
wf = wfmod.build_workflow(
template, title=title, tags=tags, lyrics=lyrics, seed=sd,
bpm=st["bpm"], duration=st["duration"], keyscale=st["key"],
sampler=cfg["sampler"], encode=cfg["encode"], model=cfg["model"],
output_prefix=sub, output_format=fmt,
language=lang,
timesignature=cfg["song"]["time_signature"])
wf_path = run.path("wf_%s_s%d.json" % (safe_title, i + 1))
with open(wf_path, "w", encoding="utf-8") as f:
json.dump(wf, f, ensure_ascii=False, indent=1)
built.append((sd, wf, wf_path, sub))
log.info("workflow 已写入", file=os.path.basename(wf_path), seed=sd)
if args.dry_run:
api = wfmod.render(built[0][1])
run.save_json("payload_preview.json", api)
print("\n[dry-run] 未提交 ComfyUI。已产出:")
print(" 歌词 %d 音节 / %d 句 / 平均每句 %.1f 音节"
% (stats["syllables"], stats["lines"], stats["per_line"]))
print(" 时长 %ds BPM %d %s" % (st["duration"], st["bpm"], st["key"]))
print(" workflow %s" % built[0][2])
print(" API 预览 %s" % run.path("payload_preview.json"))
print(" 实际输出将写到 %s"
% pmod.music_dir(cfg, pmod.comfy_root(cfg=cfg)))
# dry-run 也写入索引,便于目录浏览
man_dry = dict(
run_id=run.run_id, title=title, style=args.style,
bpm=st["bpm"], key=st["key"], duration=st["duration"],
results=[dict(seed=seeds[0], files=[])],
created=datetime.datetime.now().isoformat(timespec="seconds"),
dry_run=True)
run.save_json("manifest.json", man_dry)
catmod.append_entry(cfg, catmod.entry_from_gen(run.dir, man_dry))
log.info("dry-run 结束", seeds=seeds)
log.close()
return 0
eng = Engine(cfg["engine"]["server"], timeout=cfg["engine"]["timeout_sec"],
poll_interval=cfg["engine"]["poll_interval_sec"],
submit_retries=cfg["engine"]["submit_retries"], logger=log)
ok, info = eng.health()
if not ok:
raise ServerError("ComfyUI 不可达: %s" % info)
results = []
for sd, wf, wf_path, sub in built:
pid = eng.submit_retry(wfmod.render(wf))
log.info("已提交", seed=sd, prompt_id=pid)
def prog(tick, secs, sd=sd):
log.debug("等待中", seed=sd, tick=tick, elapsed=secs)
outs, rec = eng.wait(pid, on_progress=prog)
log.info("完成", seed=sd, files=outs)
results.append(dict(seed=sd, prompt_id=pid, files=outs,
workflow=os.path.basename(wf_path)))
cro = pmod.comfy_root(cfg=cfg)
manifest = dict(
run_id=run.run_id, title=title, style=args.style,
bpm=st["bpm"], key=st["key"], duration=st["duration"],
language=lang,
chill_vocal=bool(getattr(args, "chill_vocal", False)),
instrumental=inst,
density_profile=prof or "default",
intro_bars=ibars,
sampler=cfg["sampler"], encode=cfg["encode"], model=cfg["model"],
density=stats, results=results,
output_dir=pmod.music_dir(cfg, cro),
created=datetime.datetime.now().isoformat(timespec="seconds"),
)
mpath = run.save_json("manifest.json", manifest)
catmod.append_entry(cfg, catmod.entry_from_gen(run.dir, manifest))
log.info("全部完成", run=run.run_id, manifest=os.path.basename(mpath))
print("\n生成完成 run_id=%s" % run.run_id)
print(" 时长 %ds BPM %d %s 种子 %s"
% (st["duration"], st["bpm"], st["key"], seeds))
if inst:
print(" [纯器乐] 无可唱歌词,密度闸门不适用")
else:
print(" 字数 %d 音节 放行区间 %d~%d 平均每句 %.1f 音节"
% (stats["syllables"], stats["win_lo"], stats["win_hi"],
stats["per_line"]))
for r in results:
print(" seed=%s -> %s" % (r["seed"], ", ".join(r["files"] or ["无输出"])))
print(" 产物目录: %s" % run.dir)
print(" 音频输出: %s" % manifest["output_dir"])
log.close()
return 0
def cmd_runs(args):
cfg = loader.load({})
rows = catmod.list_entries(cfg, day=getattr(args, "day", None),
limit=args.limit)
if not rows:
# 无索引时回退扫盘
path, n = catmod.rebuild(cfg)
print("索引为空,已 rebuild -> %s (%d 条)" % (path, n))
rows = catmod.list_entries(cfg, day=getattr(args, "day", None),
limit=args.limit)
if not rows:
print("还没有任何运行记录")
return 0
print("%-26s %-12s %-10s %5s %5s %-6s %s"
% ("run_id", "日期", "标题", "BPM", "时长", "QC", "风格"))
for d in rows:
print("%-26s %-12s %-10s %5s %5s %-6s %s"
% (d.get("run_id", "?"), d.get("date") or "-",
(d.get("title") or "?")[:10], d.get("bpm"),
d.get("duration"), d.get("qc_verdict") or "-",
d.get("style") or ""))
return 0
def cmd_show(args):
cfg = loader.load({})
rundir = catmod.find_run_dir(runs_root(cfg), args.run_id)
if not rundir:
print("找不到 run: %s" % args.run_id)
return 2
m = os.path.join(rundir, "manifest.json")
with open(m, encoding="utf-8") as f:
print(json.dumps(json.load(f), ensure_ascii=False, indent=1))
return 0
def cmd_catalog(args):
cfg = loader.load({})
if args.rebuild:
path, n = catmod.rebuild(cfg)
print("rebuild %s (%d 条)" % (path, n))
return 0
rows = catmod.list_entries(cfg, day=args.day, limit=args.limit)
if not rows:
print("索引为空。可先: songforge catalog --rebuild")
return 0
for d in rows:
print("%s %s %s bpm=%s dur=%s qc=%s %s"
% (d.get("date"), d.get("run_id"), d.get("title"),
d.get("bpm"), d.get("duration"),
d.get("qc_verdict") or "-", d.get("style")))
return 0
+161
View File
@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*-
"""CLI 共用:配置组装、风格解析、运行 ID、时长闸门。"""
import datetime
import os
import re
from ..config import loader
from ..core import paths as pmod
from ..core import workflow as wfmod
from ..core.errors import ConfigError
from ..log.logger import Logger, Run
ROOT = wfmod.ROOT
# chill 吟唱(第三张专辑)的前奏小节数。
#
# 这里曾是 16:想靠"加长前奏 + 前 20 秒纯器乐"把人声压下去。
# 实测 InstLowChill2 完全无效——vocals stem 仍然从 0.0 秒开始唱。
# 原因见 ironlaw.RULE_CHILL_INTRO 的注释:ACE-Step 按歌词体的结构标记顺序
# 分配段落,不按时长,标签里写多少小节都不起作用。
# 现在三种模式统一 8 小节,和标签、歌词头三处保持一致。
# 结构重排只降低人声密度,不推迟起点(见 ironlaw 顶部实测结论)。
CHILL_INTRO_BARS = 8
def safe_name(s):
s = re.sub(r'[\\/:*?"<>|]', "_", s).strip()
return s or "untitled"
def now_id(prefix, root=None):
"""生成运行 ID,并把 runs/<run_id>/ 目录原子占位,返回 run_id。
旧实现只到秒,连跑三首会落进同一个 runs 目录,lyrics.txt / tags.txt /
manifest.json 互相覆盖,运行记录直接失效。这里做三层保险:
1. 毫秒时间戳,保证连续调用几乎不会撞;
2. os.makedirs(exist_ok=False) 原子占位,同毫秒内也只有一个能拿到;
3. 真撞上就加序号自增,绝不覆盖已有目录。
"""
base = "%s-%s" % (
prefix,
datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3],
)
if not root:
return base
for n in range(0, 100):
cand = base if n == 0 else "%s-%d" % (base, n + 1)
try:
os.makedirs(os.path.join(root, cand), exist_ok=False)
return cand
except FileExistsError:
continue
raise RuntimeError("无法为 %s 分配运行目录(root=%s)" % (prefix, root))
def build_cfg(args):
ov = {}
if getattr(args, "server", None):
ov["engine.server"] = args.server
if getattr(args, "shift", None) is not None:
ov["sampler.shift"] = args.shift
if getattr(args, "steps", None) is not None:
ov["sampler.steps"] = args.steps
if getattr(args, "cfg", None) is not None:
ov["sampler.cfg"] = args.cfg
if getattr(args, "temperature", None) is not None:
ov["encode.temperature"] = args.temperature
if getattr(args, "enc_cfg", None) is not None:
ov["encode.cfg_scale"] = args.enc_cfg
if getattr(args, "template", None):
ov["paths.workflow_template"] = args.template
if getattr(args, "runs_dir", None):
ov["paths.runs_dir"] = args.runs_dir
if getattr(args, "language", None):
ov["song.language"] = args.language
return loader.load(ov)
def style_of(cfg, name, args):
"""命令行覆盖优先于风格字典。"""
st = dict(loader.styles().get(name) or {})
if not st:
raise ConfigError("未知风格 '%s',用 `songforge styles` 查看全部" % name)
if getattr(args, "bpm", None):
st["bpm"] = args.bpm
if getattr(args, "key", None):
st["key"] = args.key
if getattr(args, "dur", None):
st["duration"] = args.dur
if getattr(args, "instruments", None):
st["instruments"] = args.instruments
if getattr(args, "mood", None):
st["mood"] = args.mood
return st
def resolve_profile(args):
"""决定用哪个密度档。
chill-vocal(英文低声吟唱)默认走 sparse:那一档的可唱小节只占 25%,
允许整首只有几组 ooh ooh / mmm。之前它借用 default 档,而 default 档是
按"人声填满全曲"反推的,会把 84 音节的低音吟唱判成"歌词过少",
逼着写满 254 音节——那正是"只有人声没有音乐"的直接来源。
"""
prof = getattr(args, "density_profile", None)
if prof:
return prof
if getattr(args, "chill_vocal", False):
return "sparse"
return None
def read_lyrics(args):
if args.lyrics_file:
with open(args.lyrics_file, encoding="utf-8") as f:
return f.read()
if args.lyrics:
return args.lyrics.replace("\\n", "\n")
if getattr(args, "instrumental", False):
# 纯器乐没有可唱正文,由 assemble 用结构标记自动铺一段。
return ""
raise ConfigError("必须提供 --lyrics-file 或 --lyrics")
def chill_intro_bars(cfg, chill):
"""chill 吟唱的前奏长度。
这里曾试过 16 小节:想靠"加长前奏 + 前 20 秒纯器乐"把人声压下去。
实测两版(InstLowChill2 / 3)证明标签侧写多少小节都不起作用,
ACE-Step 按歌词体结构标记顺序分配段落,不按时长描述。
现在前奏回到 8 小节,和标签、歌词头三处保持一致。
注意:不要再把这个函数当成"推迟人声"的手段。实测(chill 3)
即使器乐段整体排在人声段之前,第一句真唱仍然落在 0 秒。
人声起点无法靠 prompt 控制,只能靠 sparse 密度档把真唱压到稀疏,
并用音频 QC 验证。
"""
return CHILL_INTRO_BARS if chill else int(cfg["rules"]["intro_bars"])
def session_logger(args, cfg, prefix):
"""非 gen 命令的会话日志:落到 data/tmp/YYYY-MM-DD/<prefix>-ts/。"""
layout = pmod.path_layout(cfg)
day_root = layout["tmp_today"]
pmod.ensure_dir(day_root)
rid = now_id(prefix, day_root)
run = Run(rid, day_root)
log = Logger(run,
level=getattr(args, "log_level", "info"),
quiet=getattr(args, "quiet", False))
return run, log
def runs_root(cfg):
return pmod.under_workflows(cfg["paths"]["runs_dir"])
def gen_day_root(cfg):
"""data/runs/YYYY-MM-DD/"""
return pmod.day_subdir(runs_root(cfg))
+164
View File
@@ -0,0 +1,164 @@
# -*- coding: utf-8 -*-
"""songforge CLI 驱动(薄调度层)。
命令:
doctor / styles / target / check / gen / runs / show / catalog / qc / selftest
设计约束:所有业务参数来自配置/命令行,本文件不写死任何模型或采样常量。
实现见 common / assemble / commands / selftest / qc。
"""
import argparse
import sys
from ..core.errors import (LyricDensityError, RuleViolation, SongForgeError)
from . import commands as cmds
from . import selftest as stmod
def build_parser():
p = argparse.ArgumentParser(
prog="songforge",
description="ACE-Step 生歌引擎。配置优先级:命令行 > 环境变量 > "
"local.json > default.json")
p.add_argument("--server", help="ComfyUI 地址")
p.add_argument("--log-level", default="info",
choices=["debug", "info", "warn", "error"])
p.add_argument("--quiet", action="store_true")
sub = p.add_subparsers(dest="cmd")
d = sub.add_parser("doctor", help="环境自检")
d.add_argument("--shift", type=float)
d.add_argument("--steps", type=int)
d.add_argument("--cfg", type=float)
d.add_argument("--template")
d.add_argument("--runs-dir", dest="runs_dir")
d.set_defaults(func=cmds.cmd_doctor)
s = sub.add_parser("styles", help="列出风格字典")
s.set_defaults(func=cmds.cmd_styles)
st = sub.add_parser("selftest", help="全链路自检(不连 ComfyUI 生成)")
st.set_defaults(func=stmod.cmd_selftest)
t = sub.add_parser("target", help="死心塌地字数目标")
t.add_argument("--style", help="用风格字典的 bpm/时长;可再被 --bpm/--dur 覆盖")
t.add_argument("--bpm", type=int)
t.add_argument("--dur", type=int)
t.add_argument("--key")
t.add_argument("--chill-vocal", dest="chill_vocal", action="store_true",
help="英文低声吟唱:自动按 sparse 档(音乐主导)算目标字数")
t.add_argument("--instrumental", action="store_true",
help="纯器乐:算纯器乐结构下的器乐容量(无可唱歌词)")
t.add_argument("--density-profile", dest="density_profile",
help="密度档:default(人声填满)/ sparse(音乐主导、人声点缀)")
t.set_defaults(func=cmds.cmd_target)
c = sub.add_parser("check", help="纯本地校验,不连 ComfyUI")
c.add_argument("--style", required=True)
c.add_argument("--lyrics-file", dest="lyrics_file")
c.add_argument("--lyrics")
c.add_argument("--title")
c.add_argument("--bpm", type=int)
c.add_argument("--key")
c.add_argument("--dur", type=int)
c.add_argument("--instruments")
c.add_argument("--mood")
c.add_argument("--shift", type=float)
c.add_argument("--steps", type=int)
c.add_argument("--cfg", type=float)
c.add_argument("--temperature", type=float)
c.add_argument("--enc-cfg", dest="enc_cfg", type=float)
c.add_argument("--template")
c.add_argument("--runs-dir", dest="runs_dir")
c.add_argument("--language")
c.add_argument("--chill-vocal", dest="chill_vocal", action="store_true",
help="英文低声吟唱模式:放开 humming/melisma,"
"人声退到点缀位,突出音乐本身")
c.add_argument("--instrumental", action="store_true",
help="纯器乐:整首无人声,只测 prompt 对乐器的控制力。"
"不需要 --lyrics-file")
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+ 条人声否定句")
c.set_defaults(func=cmds.cmd_check)
g = sub.add_parser("gen", help="生成歌曲")
g.add_argument("--style", required=True)
g.add_argument("--lyrics-file", dest="lyrics_file", required=False)
g.add_argument("--lyrics")
g.add_argument("--title", required=True)
g.add_argument("--bpm", type=int)
g.add_argument("--key")
g.add_argument("--dur", type=int)
g.add_argument("--instruments")
g.add_argument("--mood")
g.add_argument("--seeds", type=int, default=1)
g.add_argument("--seed", type=int)
g.add_argument("--shift", type=float)
g.add_argument("--steps", type=int)
g.add_argument("--cfg", type=float)
g.add_argument("--temperature", type=float)
g.add_argument("--enc-cfg", dest="enc_cfg", type=float)
g.add_argument("--template")
g.add_argument("--runs-dir", dest="runs_dir")
g.add_argument("--language")
g.add_argument("--chill-vocal", dest="chill_vocal", action="store_true",
help="英文低声吟唱模式:放开 humming/melisma,"
"人声退到点缀位,突出音乐本身(第三张专辑用)")
g.add_argument("--instrumental", action="store_true",
help="纯器乐:整首无人声,只测 prompt 对乐器的控制力。"
"不需要 --lyrics-file")
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+ 条人声否定句")
g.add_argument("--dry-run", dest="dry_run", action="store_true",
help="只写 workflow 与 API 预览,不提交 ComfyUI")
g.set_defaults(func=cmds.cmd_gen)
r = sub.add_parser("runs", help="列出历史运行")
r.add_argument("--limit", type=int, default=20)
r.add_argument("--day", help="只列某一天 YYYY-MM-DD")
r.set_defaults(func=cmds.cmd_runs)
w = sub.add_parser("show", help="查看某次运行")
w.add_argument("run_id")
w.set_defaults(func=cmds.cmd_show)
cat = sub.add_parser("catalog", help="全局索引(歌名/风格/BPM/QC)")
cat.add_argument("--limit", type=int, default=50)
cat.add_argument("--day", help="只列某一天 YYYY-MM-DD")
cat.add_argument("--rebuild", action="store_true",
help="从 data/runs 扫描重建 catalog.jsonl")
cat.set_defaults(func=cmds.cmd_catalog)
from .qc import add_qc
add_qc(sub)
return p
def main(argv=None):
argv = argv if argv is not None else sys.argv[1:]
parser = build_parser()
args = parser.parse_args(argv)
if not getattr(args, "func", None):
parser.print_help()
return 1
try:
return args.func(args) or 0
except (RuleViolation, LyricDensityError) as e:
print("\n[校验不通过]\n%s" % e)
return 1
except SongForgeError as e:
detail = getattr(e, "detail", "")
print("\n[错误] %s" % e)
if detail:
print(" 详情: %s" % detail)
return 2
if __name__ == "__main__":
sys.exit(main())
+423
View File
@@ -0,0 +1,423 @@
# -*- coding: utf-8 -*-
"""songforge qc —— 生成后验收。
songforge qc --run <run_id> 验收某次运行产出的所有 FLAC
songforge qc --run <run_id> --baseline 额外跑 8 首已认可老歌作对照
songforge qc --file <flac> --dur 165 直接验收单个文件
songforge qc --baseline-only --save-baseline
校准一次并把软阈值固化到
songforge/qc_baseline.json
设计约束:主 CLI 是零重依赖的(只吃标准库),librosa/torch/demucs/whisper
全在 ComfyUI venv 里。所以本命令只做三件事:
1. 组 job(纯 dict/json)
2. 用 venv python 起一个子进程跑 qc_worker.py
3. 渲染报告 + 落盘 qc.json
测量逻辑一行都不在这里,避免主链路被音频栈拖死。
坑位记录:
- 不要试图在主进程 import librosa。主入口跑在系统 Python(3.10,无 librosa),
硬 import 会让整个 songforge 直接不可用。
- worker 输出的 JSON 前面有进度打印,用 ###JSON### 哨兵切分,
不要直接 json.loads 整个 stdout。
- venv python 路径要能自动定位:先看 SONGFORGE_QC_PYTHON,再找
ComfyUI 根同级/上级常见的 comfyui-venv,找不到就明确报错而不是静默跳过。
- 老歌基线必须带歌词正文(qc_baseline_old.json),否则 coverage 恒为 0,
派生出的"召回 >= 0%"是假放行,比没有基线更危险。
"""
import argparse
import glob
import json
import os
import subprocess
from ..config import loader
from ..core import catalog as catmod
from ..core import paths as pmod
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
WORKER = os.path.join(ROOT, "songforge", "tools", "qc_worker.py")
def _cfg():
return loader.load({})
def _baseline_paths(cfg=None):
cfg = cfg or _cfg()
base = pmod.under_workflows(
cfg["paths"].get("baseline_dir") or "songforge/config/baseline")
return (os.path.join(base, "qc_baseline_old.json"),
os.path.join(base, "qc_baseline.json"),
os.path.join(base, "style_ref.json"))
def _comfy_root(cfg=None):
return pmod.comfy_root(cfg=cfg or _cfg())
def find_qc_python(cfg=None):
"""定位带 librosa/torch/demucs 的那个 python。"""
cfg = cfg or _cfg()
configured = (cfg.get("paths") or {}).get("qc_python")
if configured and os.path.isfile(configured):
return os.path.abspath(configured)
env = os.environ.get("SONGFORGE_QC_PYTHON")
if env and os.path.isfile(env):
return os.path.abspath(env)
cands = []
drive = os.environ.get("SystemDrive", "C:")
cands += [
r"C:\comfyui-venv\Scripts\python.exe",
os.path.join(drive, r"\comfyui-venv\Scripts\python.exe"),
]
root = _comfy_root(cfg)
for base in (os.path.dirname(root), os.path.dirname(os.path.dirname(root)),
os.path.join(root, "venv"), root):
cands.append(os.path.join(base, "Scripts", "python.exe"))
for p in os.environ.get("PATH", "").split(os.pathsep):
if p.lower().endswith("scripts") and os.path.isdir(p):
cands.append(os.path.join(p, "python.exe"))
for c in cands:
if os.path.isfile(c):
try:
r = subprocess.run(
[c, "-c", "import librosa,torch,demucs,soundfile"],
capture_output=True, timeout=180)
if r.returncode == 0:
return os.path.abspath(c)
except (OSError, subprocess.SubprocessError):
continue
return None
def _normalize_run_id(run):
run = (run or "").strip().rstrip("/\\")
if not run:
return run
cand = run
if cand.endswith("manifest.json"):
cand = os.path.dirname(cand)
if os.path.isdir(cand) and os.path.isfile(os.path.join(cand, "manifest.json")):
return os.path.basename(os.path.abspath(cand))
return os.path.basename(run.replace("/", os.sep))
def _read_manifest(run_id):
cfg = _cfg()
rid = _normalize_run_id(run_id)
runs = pmod.under_workflows(cfg["paths"]["runs_dir"])
rundir = catmod.find_run_dir(runs, rid)
if not rundir:
# 兼容旧路径 songforge/runs/<id>
legacy = os.path.join(ROOT, "songforge", "runs", rid, "manifest.json")
if os.path.isfile(legacy):
with open(legacy, encoding="utf-8") as f:
return json.load(f), os.path.dirname(legacy)
return None, None
with open(os.path.join(rundir, "manifest.json"), encoding="utf-8") as f:
return json.load(f), rundir
def _baseline_items():
base_old, _, _ = _baseline_paths()
if not os.path.isfile(base_old):
print("[错误] 缺少 %s" % base_old)
print(" 先跑 tools/make_baseline.py 从 remake_v5.py 抽歌词基线。")
return []
with open(base_old, encoding="utf-8") as f:
return json.load(f).get("items", [])
def _old_files(music):
out = []
for it in _baseline_items():
p = os.path.join(music, it["file"])
if os.path.isfile(p):
out.append(dict(path=p, title=it["title"], group="old",
lyrics=it["lyrics"], bpm=it.get("bpm"),
duration=it.get("duration")))
else:
print(" [skip] 基线缺失 %s" % it["file"])
return out
def cmd_qc(args):
cfg = _cfg()
base_old, base_json, style_ref = _baseline_paths(cfg)
music = args.music_dir or pmod.music_dir(cfg)
ref = args.ref or os.path.join(
_comfy_root(cfg), "input", "voice_samples", "materials_D60927.wav")
files = []
rundir = None
if args.run:
man, rundir = _read_manifest(args.run)
if not man:
print("找不到 run: %s" % args.run)
return 2
names = []
for r in man.get("results", []):
for fn in r.get("files") or []:
names.append(fn)
if not names:
names = glob.glob("%s_s*_00001.flac"
% (man.get("title") or args.run))
lyr = ""
lp = os.path.join(rundir, "lyrics.txt")
if os.path.isfile(lp):
with open(lp, encoding="utf-8") as f:
lyr = f.read()
for fn in names:
base = os.path.basename(fn)
hit = None
for cand in (fn, os.path.join("MyMusic", fn),
os.path.join(music, base)):
if os.path.isabs(cand) and os.path.isfile(cand):
hit = cand
break
if os.path.isfile(cand):
hit = cand
break
if hit is None:
hit = os.path.join(music, base)
files.append(dict(
path=hit, title=man.get("title"), style=man.get("style", ""),
group="new", duration=man.get("duration"),
bpm=man.get("bpm"), intro_bars=man.get("intro_bars", 8),
lang=man.get("language", "zh"),
lyrics=lyr))
if not files:
print("run %s 没有可验收的音频" % args.run)
return 2
for fn in args.file or []:
files.append(dict(path=fn, title=os.path.splitext(
os.path.basename(fn))[0], group="new",
duration=args.dur, bpm=args.bpm,
intro_bars=args.intro_bars, lang=args.lang, lyrics=""))
if args.baseline or args.baseline_only:
files = _old_files(music) + files
if not files:
print("没有要验收的文件")
return 2
missing = [f["path"] for f in files if not os.path.isfile(f["path"])]
if missing and not args.allow_missing:
for m in missing:
print(" [FAIL] 文件不存在 %s" % m)
return 2
py = find_qc_python(cfg)
if not py:
print("[错误] 找不到带 librosa/torch/demucs 的 Python。")
print(" 用 config/local.json 的 qc_python 或 SONGFORGE_QC_PYTHON 指定")
return 2
print("QC python %s" % py)
_cache = pmod.under_workflows(cfg["paths"]["qc_cache_dir"])
pmod.ensure_dir(_cache)
job = dict(comfy_root=_comfy_root(cfg), music_dir=music, ref=ref,
files=files, asr=not args.no_asr,
cache_dir=_cache,
style_ref=style_ref if os.path.isfile(style_ref) else None,
# 坑位:--save-baseline 必须不让 worker 读旧基线。
baseline_file=None if args.save_baseline else
(base_json if os.path.isfile(base_json) else None))
env = dict(os.environ)
env["SONGFORGE_COMFY_ROOT"] = _comfy_root(cfg)
env["PYTHONIOENCODING"] = "utf-8"
print("测量中(首次要加载 demucs + whisper + CAMPPlus,请耐心)...")
if not job["style_ref"]:
print("[提示] 没有 style_ref.json,风格判定不会运行"
"(先跑 tools/make_style_ref.py)")
cmd = [py, WORKER, json.dumps(job, ensure_ascii=False)]
try:
r = subprocess.run(cmd, capture_output=True, env=env, timeout=args.timeout)
except subprocess.TimeoutExpired:
print("[错误] QC 超时(%ds)" % args.timeout)
return 2
out = r.stdout.decode("utf-8", "replace")
if "###JSON###" not in out:
print(out[-2000:])
print(r.stderr.decode("utf-8", "replace")[-2000:])
print("[错误] worker 没有产出结果")
return 2
rep = json.loads(out.split("###JSON###", 1)[1].strip())
if args.save_baseline:
pmod.ensure_dir(os.path.dirname(base_json))
with open(base_json, "w", encoding="utf-8") as f:
json.dump(dict(base=rep["baseline"], soft=rep["soft"],
note="由 songforge qc --baseline-only --save-baseline "
"在 8 首已认可老歌上校准,不要手改"), f,
ensure_ascii=False, indent=1)
print("\n基线已固化: %s" % base_json)
return _render(rep, args, rundir=rundir, cfg=cfg)
def _render(rep, args, rundir=None, cfg=None):
base, soft, verd = rep["baseline"], rep["soft"], rep["verdicts"]
rows = rep["rows"]
cfg = cfg or _cfg()
print("\n== 基线(%d 首已认可老歌)==" % base.get("n_old", 0))
if base.get("n_old"):
print(" 歌词召回 中位 %.0f%% 声线最近邻 中位 %.3f 自相似 %.3f"
% (base.get("coverage", 0) * 100, base.get("voice_floor", 0),
base.get("voice_self", 0)))
print(" 动态 %.1f dB 质心 %.0f Hz F0漂移 P90 %.1f 半音"
% (base.get("dynamic_db", 0), base.get("centroid", 0),
base.get("f0_drift_st", 0)))
print(" 放行线:召回>=%.0f%% 声线NN>=%.3f 自相似>=%.3f 动态>=%.1fdB"
% (soft.get("coverage", 0) * 100, soft.get("voice_nn", 0),
soft.get("voice_self", 0), soft.get("dyn_lo", 0)))
print(" 质心>=%.0fHz F0漂移<=%.1f半音 速度漂移<=%.1f%%"
% (soft.get("centroid_lo", 0), soft.get("f0_drift_st_max", 0),
soft.get("tempo_drift_max", 0) * 100))
print(" 实测速度 vs 设定 BPM 容差 ±%.0f%%"
% (18.0,))
else:
print(" [WARN] 没有老歌基线,本次只跑硬阈值,软阈值不可信")
print("\n== 风格分类 ==")
sr = rows[0].get("style_trusted") if rows else None
print(" 语料可信度:%s" % ("可信(分组留一通过)" if sr
else ("不可信,只当参考" if sr is not None
else "未运行")))
print("%-22s %-7s %6s %-22s %-7s"
% ("file", "判定", "置信", "最像历史作品", "其风格"))
for r in rows:
if "error" in r or not r.get("style_fam"):
continue
print("%-22s %-7s %5.0f%% %-22s %-7s"
% (r["file"][:22], r["style_fam"],
r.get("style_conf", 0) * 100, r.get("style_like", "?")[:22],
r.get("style_like_family", "")))
print("\n== 明细 ==")
print("%-22s %6s %6s %6s %6s %6s %7s %7s %7s %6s"
% ("file", "dur", "peak", "lufs", "dyn", "cent", "bpm设定", "bpm实测",
"人声进", "泄漏"))
for r in rows:
if "error" in r:
print("%-22s ERROR %s" % (r["file"][:22], r["error"][:70]))
continue
want = (r.get("expect") or {}).get("bpm") or 0
print("%-22s %6.1f %6.3f %6.1f %6.1f %6.0f %7s %7.1f %7s %6d"
% (r["file"][:22], r["duration"], r["peak"], r["lufs"],
r["dynamic_db"], r["centroid_hz"],
want or "-", r.get("tempo_med", 0),
"-" if r.get("vocal_onset") is None
else "%.1f" % r["vocal_onset"],
r.get("leak_segs", 0)))
for r in rows:
if r.get("leaks"):
print("\n 指令泄漏明细 %s:" % r["file"][:22])
for lk in r["leaks"]:
# 命中证据优先打实证短语;只有短语为空(纯集合重合)
# 才退回打指令词命中率。
hit = lk.get("leak_phrase") or "指令词命中 %3.0f%%" % (
(lk.get("instr_hit") or 0) * 100)
print(" t0=%6.2fs %s %s"
% (lk["t0"], hit, lk.get("text", "")))
print("\n== 声线 / 歌词 ==")
print("%-22s %-14s %8s %7s %7s %6s %6s %7s"
% ("file", "最近邻老歌", "NN相似", "自相似", "cov", "f0中位",
"f0漂移", "t漂移"))
for r in rows:
if "error" in r:
continue
print("%-22s %-14s %8.3f %7.3f %6.1f%% %6.1f %5.1fst %6.1f%%"
% (r["file"][:22], (r.get("voice_nn") or "-")[:14],
r.get("voice_nn_sim", 0), r.get("voice_self", 0),
r.get("coverage", 0) * 100, r.get("f0_med", 0),
r.get("f0_drift_st", 0), r.get("tempo_drift", 0) * 100))
print("\n== 结论 ==")
npass = 0
for v in verd:
print(" [%s] %s" % (v["verdict"], v["file"]))
if v["verdict"] == "PASS":
npass += 1
for w in v.get("why", []):
print(" - %s" % w)
outp = args.out
if not outp:
if rundir:
base_dir = rundir
elif args.run:
runs = pmod.under_workflows(cfg["paths"]["runs_dir"])
found = catmod.find_run_dir(runs, _normalize_run_id(args.run))
base_dir = found or pmod.tmp_today(cfg)
else:
base_dir = pmod.tmp_today(cfg)
outp = os.path.join(base_dir, "qc.json")
os.makedirs(os.path.dirname(outp) or ".", exist_ok=True)
with open(outp, "w", encoding="utf-8") as f:
json.dump(rep, f, ensure_ascii=False, indent=1)
print("\n报告: %s" % outp)
if args.run and verd:
new_names = set()
for row in rows:
if row.get("group") == "new" or (
row.get("group") is None and "error" not in row):
new_names.add(os.path.basename(str(row.get("file") or "")))
new_v = [v for v in verd
if os.path.basename(str(v.get("file") or "")) in new_names] \
or verd
n_ok = sum(1 for v in new_v if v.get("verdict") == "PASS")
if n_ok == len(new_v):
verdict_str = "PASS"
elif n_ok == 0:
verdict_str = "FAIL"
else:
verdict_str = "PARTIAL"
try:
catmod.update_qc_verdict(cfg, _normalize_run_id(args.run),
verdict_str)
except Exception as e:
print("[WARN] catalog 更新失败: %s" % e)
if not verd:
print("本次只有基线校准,没有待验收新歌 -> 退出码 0")
return 0
return 0 if npass == len(verd) else 1
def add_qc(sub):
q = sub.add_parser("qc", help="生成后验收(时长/声线/歌词/开头器乐/音频质量)")
q.add_argument("--run", help="验收某次 run 产出的 FLAC")
q.add_argument("--file", action="append", help="直接验收文件,可多次")
q.add_argument("--baseline", action="store_true",
help="额外测 8 首已认可老歌,一并派生软阈值")
q.add_argument("--baseline-only", dest="baseline_only",
action="store_true", help="只跑老歌基线(校准用)")
q.add_argument("--save-baseline", dest="save_baseline",
action="store_true", help="把本次派生阈值固化到 qc_baseline.json")
q.add_argument("--music-dir", dest="music_dir")
q.add_argument("--ref", help="声线参考音频")
q.add_argument("--dur", type=int, help="期望时长(秒),用于时长校验")
q.add_argument("--bpm", type=int)
q.add_argument("--intro-bars", dest="intro_bars", type=int, default=8)
q.add_argument("--lang", dest="lang", default="zh",
choices=["zh", "en"],
help="歌词语种,决定 ASR 语种与召回口径。"
"英文歌必须传 en,否则 ASR 按中文解码、召回恒为 0。")
q.add_argument("--no-asr", dest="no_asr", action="store_true")
q.add_argument("--timeout", type=int, default=7200)
q.add_argument("--allow-missing", dest="allow_missing", action="store_true")
q.add_argument("--out")
q.set_defaults(func=cmd_qc)
return q
+788
View File
@@ -0,0 +1,788 @@
# -*- coding: utf-8 -*-
"""全链路自检(不连 ComfyUI 生成)。"""
import os
import re
import sys
from ..config import loader
from ..core import paths as pmod
from ..core import workflow as wfmod
from ..lyrics import meter
from ..rules import ironlaw
from .assemble import assemble, do_validate
from .common import ROOT, now_id
# 第三张专辑的低音吟唱 demo 歌词,稀疏档与 chill 集成自测都读它。
# 素材库迁到 _archive/lyrics_corpus 后,selftest 仍读包内 probe。
# 旧文件名 02_InstLowChill.txt 已不在树里,以现有 03 为准。
_CHILL_DEMO = os.path.join(
ROOT, "songforge", "lyrics", "probe", "03_InstLowChill6.txt")
def _t_runid():
"""运行 ID 必须唯一。
旧实现只到秒,连跑三首会落进同一个 runs 目录,lyrics.txt / tags.txt /
manifest.json 互相覆盖,dry-run 记录直接失效。这里既验唯一性,
也验真实目录里连续三次分配不冲突。
"""
layout = pmod.path_layout(loader.load({}))
scratch = os.path.join(layout["tmp"], "selftest_runid")
if os.path.isdir(scratch):
for f in os.listdir(scratch):
p = os.path.join(scratch, f)
if os.path.isdir(p):
os.rmdir(p)
os.rmdir(scratch)
os.makedirs(scratch)
try:
ids = [now_id("t", scratch) for _ in range(3)]
# 目录必须已被原子占位,防止后续写入互相覆盖
assert all(os.path.isdir(os.path.join(scratch, i)) for i in ids), \
"运行目录未占位: %s" % ids
finally:
for f in os.listdir(scratch):
os.rmdir(os.path.join(scratch, f))
os.rmdir(scratch)
assert len(set(ids)) == 3, "运行 ID 冲突: %s" % ids
# 模拟目录已存在时必须自增,而不是覆盖旧记录
base = now_id("t", None)
assert len(base) > len("t-20261004-041513"), \
"运行 ID 缺少微秒段: %s" % base
root2 = os.path.join(layout["tmp"], "selftest_runid2")
if os.path.isdir(root2):
for f in os.listdir(root2):
os.rmdir(os.path.join(root2, f))
os.rmdir(root2)
os.makedirs(root2)
try:
# now_id 已原子占位,这里再取一次必须自动自增,而不是复用旧目录
first = now_id("t", root2)
second = now_id("t", root2)
finally:
for d in os.listdir(root2):
os.rmdir(os.path.join(root2, d))
os.rmdir(root2)
assert first != second, "目录已存在时未自增: %s / %s" % (first, second)
return [("运行 ID 唯一", "连跑三次 %s ~ %s 互不冲突" % (ids[0], ids[-1]))]
def _t_path_layout():
"""配置里的目录键必须能解析,且与 DEFAULTS 对齐。"""
cfg = loader.load({})
p = cfg["paths"]
for key in ("runs_dir", "tmp_dir", "lyrics_dir", "qc_cache_dir",
"style_cache_dir", "output_prefix", "baseline_dir",
"catalog_file"):
assert key in p and p[key], "paths.%s 缺失" % key
layout = pmod.path_layout(cfg)
runs_n = layout["runs"].replace("\\", "/")
tmp_n = layout["tmp"].replace("\\", "/")
assert runs_n.endswith("songforge/data/runs"), "runs 路径异常: %s" % runs_n
assert tmp_n.endswith("songforge/data/tmp"), "tmp 路径异常: %s" % tmp_n
assert os.path.isdir(layout["baseline"]), "baseline 目录缺失: %s" % layout["baseline"]
for name in ("qc_baseline.json", "qc_baseline_old.json", "style_ref.json"):
assert os.path.isfile(os.path.join(layout["baseline"], name)), \
"缺少基线文件 %s" % name
return [("目录布局", "data/runs|tmp + baseline + catalog 已从 config.paths 解析")]
def _t_paths():
root = pmod.comfy_root()
assert os.path.isdir(os.path.join(root, "models", "checkpoints")), \
"ComfyUI 根目录推导错误: %s" % root
return [("ComfyUI 根推导", root)]
def _t_config_priority():
os.environ["SONGFORGE_SHIFT"] = "4.4"
try:
cfg = loader.load({})
assert abs(cfg["sampler"]["shift"] - 4.4) < 1e-6, "环境变量未生效"
cfg = loader.load({"sampler.shift": 6.0})
assert abs(cfg["sampler"]["shift"] - 6.0) < 1e-6, "命令行未覆盖环境变量"
finally:
os.environ.pop("SONGFORGE_SHIFT", None)
base = loader.load({})["sampler"]["shift"]
assert abs(base - 5.5) < 1e-6, "默认 shift 被污染: %s" % base
return [("配置优先级 命令行>环境>配置", "shift 5.5 -> 4.4 -> 6.0")]
def _t_model_locked():
cfg = loader.load({})
ck = cfg["model"]["checkpoint"]
assert ck == "ace_step_1.5_turbo_swl_fused.safetensors", "checkpoint 被换: %s" % ck
assert cfg["model"]["lora"] == "swl_voice_best_ep257.safetensors", "LoRA 被换"
assert ck not in cfg["model"]["denied_checkpoints"], "当前模型在禁用名单"
return [("模型锁定", ck + " + " + cfg["model"]["lora"])]
def _t_ironlaw():
tags = ironlaw.build_tags("Chinese pop")
for kw in ("swlvoice", "8 bar instrumental intro hook", "no opening vocals",
"no pure vocal intro", "no humming"):
assert kw in tags, "tags 缺少 %s" % kw
lyrics = ironlaw.build_lyrics(
[("[verse]", "第一句歌词\n第二句歌词")], "kick and snare", bars=8)
assert lyrics.lstrip().startswith("[intro]"), "未强制器乐前奏"
assert "[Instrumental: 8 bar" in lyrics, "前奏未写明 8 小节"
assert not ironlaw.check_rules(lyrics, tags), ironlaw.check_rules(lyrics, tags)
# 缺前奏必须被拦
no_intro = "[verse]\n没有前奏直接唱"
assert ironlaw.check_rules(no_intro, tags), "缺器乐前奏未被拦截"
# 中文结构标记必须被拦
marked = lyrics.replace("[verse]", "[主歌]")
assert ironlaw.check_rules(marked, tags), "中文结构标记未被拦截"
return [("铁律注入", "8 小节器乐前奏 + 反人声条款齐备,缺前奏/中文标记均被拦")]
def _t_sparse_profile():
"""稀疏档必须真的放行"只有几句英文语气词"的写法,且仍然拦得住异常值。
背景:第三张专辑人声压过音乐,根因之一是 default 密度档按"人声填满全曲"
反推(175s/124BPM 下限 254 音节),把 84 音节的低音吟唱判成"歌词过少",
于是每次都被迫写满整首,人声自然盖过器乐。sparse 档就是为了给出
"可唱小节只占 25%" 的合法区间。
"""
cfg = loader.load({})["lyrics"]
sparse = meter.pick(cfg, "sparse")
assert sparse["sing_bar_ratio"] < cfg["sing_bar_ratio"], \
"sparse 档可唱小节占比没有低于 default,音乐主导无从体现"
assert sparse["ideal_line_syllable"][0] < cfg["ideal_line_syllable"][0], \
"sparse 档句子下限没有放宽,mmm / ooh 这类短句仍会被拦"
dur, bpm = 175, 124
_, lo, hi = meter.target_words(dur, bpm, sparse)
# 直接用真实 demo 歌词做样本,而不是抄一份内联的:
# 抄的内联文本一漂移,测试就测不到真正要生成的那份文件了。
probe = _CHILL_DEMO
assert os.path.exists(probe), "找不到低音 demo 歌词 %s" % probe
with open(probe, encoding="utf-8") as f:
body = f.read()
syl = meter.syllable(meter.only_lyrics(body))
assert meter.check(body, dur, bpm, cfg)[0], \
"default 档居然放行了稀疏歌词,档间没有区分度"
errs, st = meter.check(body, dur, bpm, sparse)
assert not errs, "sparse 档误杀了低音语气词写法: %s" % errs
assert lo <= syl <= hi, \
"sparse 放行区间 %d~%d 与实测 %d 音节不一致" % (lo, hi, syl)
# 过短仍要拦:sparse 不是"无限制放宽"
thin = ("[intro]\n[Instrumental: 8 bar]\n[verse]\nmmm\nooh\n")
assert any("过少" in e for e in meter.check(thin, dur, bpm, sparse)[0]), \
"sparse 档放过短歌词"
# 过多仍要拦:写成满首人声时 sparse 也必须报错,否则会退回旧病
fat = ("[intro]\n[Instrumental: 8 bar]\n[verse]\n"
+ "\n".join(["mmm mmm low and slow"] * 90))
assert any("过多" in e for e in meter.check(fat, dur, bpm, sparse)[0]), \
"sparse 档放过多歌词,音乐主导会被稀释"
return [("稀疏密度档",
"sparse 放行 %d~%d 音节(default 拒绝同一份),过少过多仍被拦"
% (lo, hi))]
def _t_instrumental():
"""纯器乐模式的标签必须自洽,且不与风格字典的唱法描述对撞。"""
tags = ironlaw.build_tags(
style="English melodic future bass", instruments="huge supersaw lead",
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",
"8 bar instrumental intro hook"):
assert kw in tags, "纯器乐 tags 缺少 %s" % kw
# 关键回归点:风格字典的唱法描述绝不能混进来跟 "no vocals" 对撞。
for bad in ("whisper vocal", "sparse English words", "no belting"):
assert bad not in tags, "纯器乐 tags 混入了唱法描述: %s" % bad
# 器乐正向要求必须在(这里只校验铁律常量层,风格字典自带的配器词不算)
for kw in ("long instrumental passages", "extended instrumental breakdown",
"huge powerful drop", "instrumental sections are the main focus",
"drums and bass carry the track"):
assert kw in tags, "纯器乐 tags 缺少器乐主导描述 %s" % kw
# 绝不能出现把器乐段填满的条款(这会让模型加人声)
assert "no long empty instrumental" not in tags, \
"纯器乐 tags 含 no long empty instrumental,会逼模型填人声"
assert "no long empty instrumental" not in ironlaw.RULE_CHILL_MEMO, \
"吟唱 tags 含 no long empty instrumental,会逼模型填人声"
# 前奏不能是"先器乐后人声"那句:纯器乐里它等于命令模型把人声加回来
assert "vocals enter only after" not in tags, \
"纯器乐 tags 仍含 'vocals enter only after the instrumental hook'"
assert "no breakdown" not in tags, \
"纯器乐 tags 含 no breakdown,与 extended instrumental breakdown 冲突"
# 歌词体必须是纯结构标记,没有可唱正文
lyrics = ironlaw.build_inst_lyrics("huge supersaw", bars=8)
assert lyrics.lstrip().startswith("[intro]"), "纯器乐歌词未以 [intro] 开头"
body = meter.only_lyrics(lyrics)
assert body.strip() == "", "纯器乐歌词体出现可唱正文: %r" % body[:80]
assert meter.syllable(body) == 0, "纯器乐歌词体音节数非 0"
# 结构段名不能是 [verse] / [chorus]:ACE-Step 见到这两个标记就会按
# "有人唱的段落"来铺,即使下面只挂 [inst] 也容易把人声请回来。
for bad_tag in ("[verse]", "[chorus]"):
assert bad_tag not in lyrics.lower(), \
"纯器乐歌词体含 %s,会重新诱导人声" % bad_tag
for good_tag in ("[drop]", "[breakdown]", "[build]"):
assert good_tag in lyrics.lower(), "纯器乐歌词体缺少 %s 段" % good_tag
# 结构铁律照旧生效
assert not ironlaw.check_rules(lyrics, tags), ironlaw.check_rules(lyrics, tags)
# 密度闸门必须让行纯器乐
cfg = loader.load({})
errs, _ = do_validate(lyrics, tags, cfg,
{"duration": 175, "bpm": 124}, {}, strict=False,
instrumental=True)
assert not errs, "纯器乐被密度闸门拦下: %s" % errs
# chill 模式的稳定条款也不能再要求 no breakdown
chill_tags = ironlaw.build_tags(style="future bass",
extra="male low whisper vocal",
chill_vocal=True)
assert "no breakdown" not in chill_tags, \
"chill tags 含 no breakdown,与 quiet breakdown 冲突"
# 声线稳定性约束已被实测证明是反效果:标签里每多一句谈人声,
# 人声越从 0 秒就进。chill 现在只保留乐器/调性的稳定性要求。
assert "consistent vocal timbre" not in chill_tags, \
"chill tags 又开始强调人声稳定性,实测会退回 0 秒开唱"
assert "consistent instrumentation in every section" in chill_tags, \
"chill tags 丢了配器稳定性约束"
return [("纯器乐模式", "反人声标签自洽、无唱法对撞、无 no breakdown、"
"结构体不诱发人声、密度闸门让行")]
def _t_chill_delay():
"""chill 模式:验证标签与结构两侧自洽(不退化成纯器乐,也不退回 0 秒开唱)。
五轮实测踩出来的结论:
chill 1 8 小节前奏 + "vocals enter only after…"
-> vocals stem 从 0.0 秒就有能量
chill 2 标签加长到 16 小节 + "first 20 seconds are entirely instrumental"
+ "the human voice does not enter until the second drop"
-> 第一句仍然落 0.0 秒,标签侧时间约束全部无效
chill 3 结构重排 + 强人声描述
-> 稀疏低音语气词,能量 +45~50 dB,歌词重合 0.98
(当前唯一确认真唱的一版)
chill 4 标签彻底不讨论人声(复用纯器乐反人声条款)
-> 人声归零,等同纯器乐
chill 5 只保留音色质感,删掉密度/时机描述
-> 人声同样归零。此前把 ASR 的 4 段当成"少量真唱"是误判:
文本 "oh new healing / lömpe Minor" 歌词里根本没有,
能量只 +11 dB、ASR 覆盖率 100%,是持续 pad 幻听。
关键结论:标签侧写时长/时机对人声起点零作用;唯一旋钮是
"密度与时机类人声描述的多少",而它降下去不是"延后"而是"消失"。
所以自测只能守住"结构占位存在 + 标签不退回纯器乐",
人声起点必须靠音频 QC(ab_vocal_curve.py / ab_is_real_voice.py)判定。
"""
tags = ironlaw.build_tags(style="English melodic future bass",
instruments="huge supersaw lead",
mood="vast uplifting emotional EDM",
extra="male low whisper vocal, "
"hushed and intimate, sparse English words",
chill_vocal=True)
# 人声仍然允许存在,不能把 chill 误改成纯器乐
for kw in ("male low whisper vocal", "hushed and intimate",
"low register vocal texture", "soft breathy phrases",
"instrumental sections are the main focus",
"long instrumental passages",
"instrumental breakdown and instrumental drop sections"):
assert kw in tags, "chill tags 缺少器乐主导描述 %s" % kw
# 人声禁落器乐段
for kw in ("no singing in any breakdown", "no singing over the first drop",
"no long vocal phrases", "no choir"):
assert kw in tags, "chill tags 缺少段落归属约束 %s" % kw
# chill 不能退回普通前奏规则:那句只说"稍后进人声",实测拦不住
assert "vocals enter only after the instrumental hook has played" not in tags, \
"chill tags 退回 RULE_INTRO,实测 0 秒开唱"
# ---- 五轮实测收敛出来的核心断言 ----
# InstLowChill / 2 / 3 / 4 / 5 五版量出一条干净的梯度,证明 prompt 对
# 人声的控制力是真实存在的,旋钮 = "标签里有多少句在描述人声":
# chill 2 强人声描述 + 16 小节前奏
# -> ASR 23 段,voc/acc 0.483,人声压过音乐
# chill 3 结构重排 + 强人声描述
# -> 稀疏低音语气词,voc/acc 0.376,唯一确认真唱的一版
# chill 4 标签彻底不讨论人声(复用纯器乐反人声条款)
# -> 人声归零,等同纯器乐
# chill 5 只留音色质感,删掉密度/时机描述
# -> 人声同样归零(ASR 全是持续 pad 幻听)
#
# 时机类措辞必须继续禁掉:chill 2/3 都写了
# "second half / enters late / first 20 seconds",第一句全部落 0.0 秒。
for bad in ("voice enters", "the human voice", "no voice in the first",
"until the second drop", "in the second half of the track",
"first 20 seconds"):
assert bad not in tags.lower(), \
"chill tags 又开始讨论人声进场时机(%s),实测会退回 0 秒开唱" % bad
# 密度类措辞必须保留:这是 chill 3 唯一产生真唱的东西,
# 删掉(chill 5)人声直接归零,不是延后而是消失。
for kw in ("voice is sparse and low volume", "used only as sparse texture",
"sparse english words", "mostly instrumental between phrases"):
assert kw in tags.lower(), \
"chill tags 丢了密度触发词 %s,实测会退回纯器乐" % kw
# 风格字典的 extra 绝不能混进来(六句里五句在谈人声)。
# 这里不再靠关键词黑名单(因为 chill 自己现在也用同几个密度词,
# 黑名单会误伤),改用哨兵值:故意传一个只在 extra 里的短语,
# 结果里出现就说明 extra 泄漏了。
probe = "zzz-extra-leak-probe"
tags_probe = ironlaw.build_tags(style="s",
instruments="i", mood="m",
extra=probe,
chill_vocal=True)
assert probe not in tags_probe.lower(), "chill 分支把风格字典 extra 混进来了"
# 但也不能把人声彻底禁掉,否则就是纯器乐、不是吟唱。
# 注意只匹配纯器乐专属的反人声条款:
# - 不能用裸 "no singing":"no singing in any breakdown" 含这个子串,
# 那是吟唱要的人声约束。
# - 不能用 "instrumental only":它来自 "intro is instrumental only",
# 那是前奏必须保留的约束。
for kw in ("no vocals anywhere", "no voice at all", "no lead vocal",
"no backing vocal", "this is a backing track",
"drums bass synths chords and lead melodies only"):
assert kw not in tags.lower(), \
"chill tags 含纯器乐条款 %s,吟唱被人声禁令吞掉" % kw
return [("吟唱标签梯度",
"时机类措辞全部禁掉,密度触发词保留,"
"风格字典 extra 未泄漏")]
def _t_groove_first_beat():
"""器乐前奏必须从第 0 秒就有底鼓和贝斯,不能是空场。
这里有一个被实测推翻过的旧结论,必须留在注释里免得又走回去:
上一轮认定"前 15 秒是空场",依据是 ab_lowfreq.py 报的
-68~-75 dBFS。那份数据是错的——它把滤波器的瞬态响应和单帧跳变
当成了整段电平。ab_bands.py / ab_head_rhythm.py 复测(dBFS,
head = 前 16 秒,mid = 16~32 秒):
GroovePure head sub -66.0 / mid sub -55.8
head full -32.7 / mid full -25.0
也就是说开头有音乐(full band 只低 7.7 dB,hat/snare 瞬态齐备),
缺的只是 sub/kick。所以真正要修的是"前奏要有节奏组",
不是"开头别是空场",而"空场"这个说法本身就是误判。
修法(见 ironlaw.intro_rhythm_only):前奏括号只保留节奏组,
剔除 pad / riser / reverb / lead。这一条比堆禁令有效——
GroovePure 已经证明四条禁令(no ambient intro / no pad only intro /
no beatless intro / no white noise riser in the opening)全部无效。
"""
for flag, kw in ((False, "instrumental"), (True, "chill")):
tags = ironlaw.build_tags(style="English melodic future bass",
instruments="huge supersaw lead",
mood="vast uplifting emotional EDM",
chill_vocal=flag,
instrumental=not flag)
for need in ("full four on the floor groove from the very first beat",
"kick drum, sub bass and walking bass on bar one",
"no pad only intro", "no beatless intro",
"no riser in the opening"):
assert need in tags.lower(), \
"%s tags 缺第一拍 groove 约束: %s" % (kw, need)
# 普通有声歌曲也一并受益:RULE_INTRO 同样要保证鼓从第一拍进。
assert "rhythmic drums from the very first beat" in \
ironlaw.build_tags("test").lower(), "普通歌曲前奏丢了第一拍底鼓"
return [("第一拍 groove",
"chill/纯器乐都要求底鼓+贝斯从第 0 拍进,"
"并点名禁掉 pad only / beatless / riser 空场信号")]
def _t_intro_instrument_filter():
"""前奏括号必须过滤掉 pad/riser/reverb/lead,只留节奏组。
这是本轮真正起作用的改动。上一轮只在标签里堆禁令,GroovePure 实测
无效(开头 sub 仍 -66.0 dBFS,中段 -55.8 dBFS),因为真正的病灶是
歌词体那一行:
[Instrumental: 8 bar instrumental intro hook, huge supersaw lead,
sidechain compressed pad, punchy electro kick, crisp clap,
trap snare, white noise riser, big reverb, melodic drop, ...]
空场信号(lead/pad/riser/reverb)4 个,节奏组(kick/clap/snare)3 个,
3:4 输了,模型就把前奏铺成 ambient。
所以这里守三件事:
1) 过滤后必须还留着 kick(不能把节奏组也误删成空括号);
2) pad / riser / reverb / lead 一个都不能留在前奏括号里;
3) 标签侧的 instruments 段保持原样——drop 段本来就要 pad 和 lead,
只过滤前奏括号,不能把整首歌的配器改掉。
"""
src = ("huge supersaw lead, sidechain compressed pad, "
"punchy electro kick, crisp clap, trap snare, "
"white noise riser, big reverb, melodic drop")
got = ironlaw.intro_rhythm_only(src)
low = got.lower()
assert "kick" in low, "前奏括号把底鼓也过滤掉了: %r" % got
for bad in ("pad", "riser", "reverb", "supersaw", "lead", "noise"):
assert bad not in low, "前奏括号残留空场信号 %s: %r" % (bad, got)
# 加法兜底:kick 和 bass 两条必须显式出现在前奏括号里。
# 上一轮漏了这一条,风格字典里一条贝斯都没写,过滤后只剩三条中高频,
# 结果两版新音频开头 sub 比全曲峰值低 53.5 / 31.2 dB。
assert "bass" in low, "前奏括号没有 bass:%r" % got
# 空 / 中文 / 全被过滤掉 -> 必须回落到默认节奏组,不能留空括号
for probe in ("", None, "ambient pad, huge supersaw lead, big reverb"):
fb = ironlaw.intro_rhythm_only(probe)
assert "kick" in fb.lower(), "前奏括号回落失败 %r -> %r" % (probe, fb)
assert "bass" in fb.lower(), "回落值缺 bass %r -> %r" % (probe, fb)
for bad in ("pad", "riser", "reverb", "supersaw", "lead"):
assert bad not in fb.lower(), "回落值带空场信号 %s: %r" % (bad, fb)
# 回落值不能是 DEFAULT_INSTRUMENT:它含 "chord stabs",而 "chord stab"
# 就在 _RHYTHM_DROP 里,回落会把刚剔除掉的空场信号塞回前奏。
assert "stab" not in ironlaw.DEFAULT_INTRO_RHYTHM.lower(), \
"前奏回落值含 chord stab,与过滤规则自相矛盾"
# 标签侧不受影响:instruments 段必须还是原样
tags = ironlaw.build_tags(style="s", instruments=src, mood="m",
instrumental=True)
assert "white noise riser" in tags, \
"过滤逻辑泄漏到了标签侧,drop 段会丢掉 riser"
assert "sidechain compressed pad" in tags, \
"过滤逻辑泄漏到了标签侧,drop 段会丢掉 pad"
# 歌词体里前奏那一行必须既没有 riser/pad,又必须有 bass
lyr = ironlaw.build_inst_lyrics(src, bars=8)
head = lyr.split("\n")[1].lower()
assert "riser" not in head and "pad" not in head, \
"纯器乐歌词体前奏行仍带空场信号: %s" % head
assert "bass" in head, "纯器乐歌词体前奏行缺 bass: %s" % head
lyr2 = ironlaw.build_chill_lyrics([("[verse]", "ooh")], src, bars=8,
total_bars=90)
head2 = lyr2.split("\n")[1].lower()
assert "riser" not in head2 and "pad" not in head2, \
"吟唱歌词体前奏行仍带空场信号: %s" % head2
assert "bass" in head2, "吟唱歌词体前奏行缺 bass: %s" % head2
return [("前奏配器过滤",
"前奏括号剔除 pad/riser/reverb/lead,并强制补齐 kick+bass,"
"标签侧配器保持原样")]
def _t_chill_no_conflict():
"""chill 标签里绝不能出现和"低音英文语气词"直接冲突的禁令。
这三条(no humming / no mm mm syllables / no oh oh syllables)第一次改
chill 铁律就是为了解开这个冲突,加回来等于自己把要求唱的内容禁掉。
"""
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"):
assert bad not in tags.lower(), \
"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():
"""chill 集成路径:assemble + check_rules 必须同时通过。
上一轮 14/14 全绿却照样生成失败,原因是这个自测只调 build_tags(),
没走 assemble() + check_rules(),于是标签与歌词头小节数不一致这种
集成冲突根本测不出来。集成层的坑必须在这里测。
"""
cfg = loader.load({})
st = {"bpm": 124, "duration": 175, "key": "A minor",
"style": "English melodic future bass",
"instruments": "huge supersaw lead",
"mood": "vast uplifting emotional EDM",
"extra": "male low whisper vocal, sparse English words"}
class _A(object):
chill_vocal = True
instrumental = False
raw = open(_CHILL_DEMO, encoding="utf-8").read()
tags2, lyrics2 = assemble(_A, cfg, st, raw, "selftest")
errs = ironlaw.check_rules(lyrics2, tags2)
assert not errs, "chill 集成校验不通过: %s" % errs
# 结构核心断言:第一个有人唱的段之前,纯器乐段必须占满前半段。
# 注意这只保证"器乐占位存在",不保证人声起点被推后——实测两者无关。
# 音频层是否真的晚进,必须用 ab_vocal_curve.py / ab_is_real_voice.py 验。
lines = [l.strip() for l in lyrics2.split("\n") if l.strip()]
vocal_tags = ("[verse]", "[chorus]", "[hook]", "[bridge]", "[pre-chorus]")
first_v = next((i for i, l in enumerate(lines)
if l.lower() in vocal_tags), None)
assert first_v is not None, "chill 结构体里找不到任何人声段"
head = [l.lower() for l in lines[:first_v]]
# 只数"纯器乐段",不能把 [inst] 占位和段名一起算进去。
# 旧写法把两者相加,一个 breakdown 组就被算成 2,报出"8 个器乐段",
# 实际上只有 4 组——测试描述在骗人,验收语义必须按组算。
inst_secs = [h for h in head
if h in ("[breakdown]", "[build]", "[drop]", "[post-drop]")]
n_inst = len(inst_secs)
assert n_inst >= 4, \
"chill 第一个器乐段之前只有 %d 组纯器乐段,人声会紧跟 intro 进来" % n_inst
# 每个纯器乐段名后面必须真的挂 [inst],否则模型会当成有人唱的段
for i, h in enumerate(head):
if h in ("[breakdown]", "[build]", "[drop]", "[post-drop]"):
assert i + 1 < len(head) and head[i + 1] == "[inst]", \
"chill 器乐段 %s 后面没挂 [inst],会被当成可唱段" % h
# 器乐占位不能重复:原始歌词里的 [inst] 段已经重排过,
# 再留一遍会让人声提前回来
assert head.count("[inst]") <= n_inst, "chill 结构体器乐占位异常重复"
# 前奏小节数:标签与歌词头必须一致
mh = re.search(r"\[instrumental:[^\]]*?(\d+)\s*bar", lyrics2, re.I)
mt = re.search(r"(\d+)\s*bar instrumental intro", tags2.lower())
assert mh and mt and mh.group(1) == mt.group(1), \
"chill 标签 %s 小节与歌词头 %s 小节不一致" % (
mt.group(1) if mt else "?", mh.group(1) if mh else "?")
# 反向闸门:两者不一致必须被拦下
short_tags = tags2.replace("%s bar instrumental intro" % mt.group(1),
"16 bar instrumental intro", 1)
errs = ironlaw.check_rules(lyrics2, short_tags)
assert any("必须一致" in e for e in errs), \
"tags 与歌词头前奏小节数不一致未被拦截"
# 前奏小节数缺失也必须被拦
errs = ironlaw.check_rules(lyrics2, re.sub(r"\d+\s*bar instrumental",
"instrumental", tags2))
assert any("小节数" in e for e in errs), "tags 未写前奏小节数未被拦截"
return [("吟唱结构占位",
"人声段之前留了 %d 组纯器乐段(只管密度,不管起点),"
"标签侧完全不讨论人声进场时机" % n_inst)]
def _t_lexicon():
lex = loader.lexicon()
assert "长板" in (lex["banned"].get("longboard") or []), "禁用词表缺 长板"
good = "[intro]\n[Instrumental: 8 bar]\n[verse]\n我在街头双翘上起跳"
assert not ironlaw.check_lexicon(good, lex), ironlaw.check_lexicon(good, lex)
bad = "[intro]\n[verse]\n我戴着头盔冲下坡"
errs = ironlaw.check_lexicon(bad, lex)
assert errs, "禁用词未被拦截"
return [("身份词典", "街头双翘通过 / 长板类禁用词 %d 条被拦" % len(errs))]
def _t_density():
cfg = loader.load({})["lyrics"]
st = loader.styles()["pop"]
cap = meter.capacity(st["duration"], st["bpm"], cfg)
assert cap["hi"] > cap["lo"] > 0, "容量区间异常"
# 过短必须被拦
too_thin = "[intro]\n[Instrumental: 8 bar]\n[verse]\n太短了"
assert meter.check(too_thin, st["duration"], st["bpm"], cfg)[0], "过短未拦"
# 过多必须被拦
too_fat = "[intro]\n[Instrumental: 8 bar]\n[verse]\n" + \
"\n".join(["这一句有十二个字刚刚好"] * 300)
assert meter.check(too_fat, st["duration"], st["bpm"], cfg)[0], "过多未拦"
# 按 target_words 反推合规歌词,必须放行(防止阈值过严误杀)
mid, lo, hi = meter.target_words(st["duration"], st["bpm"], cfg)
line = "这一句刚好十二个字的样子" # 12 音节
nlines = max(1, int(mid / 12))
body = "\n".join([line] * nlines)
ok = "[intro]\n[Instrumental: 8 bar]\n[verse]\n" + body
errs, stt = meter.check(ok, st["duration"], st["bpm"], cfg)
assert not errs, "按 target 写的合规歌词被误杀: %s" % errs
return [("时长对应硬校验",
"%ds/%dBPM 容量 %d~%d,目标 %d 字,过短/过多均被拦,合规放行"
% (st["duration"], st["bpm"], cap["lo"], cap["hi"], mid))]
def _t_regression():
"""实歌回归:8 首用户已生成并认可的歌必须全部通过密度校验。
这是阈值校准的锚点。原来按理论值(每拍2.6~4.4音节、每句下限7)设阈值,
结果这 8 首全部被判"歌词过少"(填充率只有 26%~43%),说明阈值从未
对齐过真实输出。任何阈值改动都必须先过这一关。
"""
old_dir = r"c:\Users\孙文龙\.trae-cn\work\6ab523de391489c168050edc"
if not os.path.isdir(old_dir):
return [("实歌回归", "FAIL 找不到 remake_v5.py 目录")]
sys.path.insert(0, old_dir)
try:
import remake_v5 as old
except Exception as e:
return [("实歌回归", "FAIL 无法导入 remake_v5 (%s)" % e)]
cfg = loader.load({})["lyrics"]
bad = []
worst_pl = 99.0
for title, seed, bpm, key, dur, inst in old.META:
lyrics = old.build_song(title)[2]
errs, st = meter.check(lyrics, dur, bpm, cfg)
worst_pl = min(worst_pl, st["per_line"])
if errs:
bad.append("%s: %s" % (title, errs[0].split(":")[0]))
if bad:
return [("实歌回归", "FAIL %d/%d 首被误杀 -> %s"
% (len(bad), len(old.META), " | ".join(bad)))]
assert worst_pl >= cfg["ideal_line_syllable"][0], \
"实测最短平均句长 %.1f 已低于配置下限 %.1f,阈值与实歌脱节" % (
worst_pl, cfg["ideal_line_syllable"][0])
return [("实歌回归", "8 首已验证实歌全部通过(最短平均句长 %.1f 音节)"
% worst_pl)]
def _t_parity():
"""与旧脚本 remake_v5.py 的 API prompt 逐字段对比。"""
old_dir = r"c:\Users\孙文龙\.trae-cn\work\6ab523de391489c168050edc"
sys.path.insert(0, old_dir)
try:
import remake_v5 as old
except Exception as e:
return [("旧脚本 parity", "跳过:无法导入 remake_v5 (%s)" % e)]
title = "身体先听懂"
owf, otags, olyrics = old.build_song(title)
oapi = old.convert(owf)
cfg = loader.load({})
template = wfmod.load_template(cfg["paths"]["workflow_template"])
m = [x for x in old.META if x[0] == title][0]
_, oseed, obpm, okey, odur, oinst = m
nwf = wfmod.build_workflow(
template, title=title, tags=otags, lyrics=olyrics, seed=oseed,
bpm=obpm, duration=odur, keyscale=okey, sampler=cfg["sampler"],
encode=cfg["encode"], model=cfg["model"],
output_prefix="MyMusic/parity_%s" % title, output_format="flac",
language="zh", timesignature="4")
napi = wfmod.render(nwf)
if set(oapi) != set(napi):
return [("旧脚本 parity", "FAIL 节点集不同 %s vs %s"
% (sorted(oapi), sorted(napi)))]
diffs = []
for nid in sorted(oapi, key=int):
for k in sorted(set(oapi[nid]["inputs"]) | set(napi[nid]["inputs"])):
a = oapi[nid]["inputs"].get(k)
b = napi[nid]["inputs"].get(k)
if k in ("tags", "lyrics"):
# 新版 build_tags 措辞不同,只校验关键铁律都在
for kw in ("swlvoice", "8 bar instrumental intro hook"):
if (kw in str(a)) != (kw in str(b)):
diffs.append("节点%s.%s 铁律不一致" % (nid, k))
continue
if k == "filename_prefix":
continue # 输出前缀本就故意不同
if a != b:
diffs.append("节点%s.%s: 旧=%r 新=%r" % (nid, k, a, b))
if diffs:
return [("旧脚本 parity", "FAIL %d 处不同:%s"
% (len(diffs), " | ".join(diffs[:6])))]
return [("旧脚本 parity", "核心 API payload 与 remake_v5.py 等价(%d 节点;"
"filename_prefix 与歌词措辞为有意差异)" % len(oapi))]
def _t_fallback():
"""fallback 资产必须仍在原位。"""
root = pmod.comfy_root()
need = [
os.path.join(ROOT, "song_rules.py"),
os.path.join(ROOT, "urbanhiphop-身体先听懂.json"),
pmod.output_dir(root, "MyMusic"),
]
missing = [p for p in need if not os.path.exists(p)]
bak_root = os.path.join(ROOT, "bak")
stamps = sorted(os.listdir(bak_root)) if os.path.isdir(bak_root) else []
if missing:
return [("fallback 资产", "FAIL 缺失 %s" % missing)]
if not stamps:
return [("fallback 资产", "FAIL bak 目录为空")]
return [("fallback 资产", "song_rules.py / 模板 / output/MyMusic 就位,bak %d 份"
% len(stamps))]
def _t_window():
"""target_words 报的区间必须与 check 实际放行窗口一致。
这是最容易出"文档说能过、实际过不了"的地方:容量 [lo,hi] 是理论值,
但 check 还叠加了填充率红线,真正生效的窗口必须两者取交。
"""
cfg = loader.load({})["lyrics"]
for name in ("pop", "punk", "urbanhiphop"):
st = loader.styles()[name]
dur, bpm = st["duration"], st["bpm"]
mid, lo, hi = meter.target_words(dur, bpm, cfg)
assert lo <= mid <= hi, "%s 目标字数 %d 不在放行区间 %d~%d" % (
name, mid, lo, hi)
cap = meter.capacity(dur, bpm, cfg)
assert cap["lo"] <= hi and lo <= cap["hi"], \
"%s 放行区间 %d~%d 超出理论容量 %d~%d" % (
name, lo, hi, int(cap["lo"]), int(cap["hi"]))
# 窗口两端必须真的被 check 拦/放,边界不能只存在于文档里
line = "这一句刚好十二个字的样子"
def build(n):
return ("[intro]\n[Instrumental: 8 bar]\n[verse]\n"
+ "\n".join([line] * n))
n_mid = max(1, int(mid / 12))
ok_errs, _ = meter.check(build(n_mid), dur, bpm, cfg)
assert not ok_errs, "%s 按目标字数写的歌词被误杀: %s" % (name, ok_errs)
# 少一个字就该报"过少",多一个字就该报"过多",容差必须小
few = meter.check(build(max(1, int((lo - 30) / 12))), dur, bpm, cfg)[0]
assert any("过少" in e for e in few), \
"%s 低于放行下限却未报过少: %s" % (name, few)
many = meter.check(build(int((hi + 30) / 12) + 1), dur, bpm, cfg)[0]
assert any("过多" in e for e in many), \
"%s 高于放行上限却未报过多: %s" % (name, many)
return [("字数窗口自洽",
"pop/punk/urbanhiphop 的 target 区间 == check 放行窗口,边界确实生效")]
def cmd_selftest(args):
from .common import session_logger
cfg = loader.load({})
run, log = session_logger(args, cfg, "selftest")
cases = [_t_runid, _t_paths, _t_path_layout, _t_config_priority,
_t_model_locked, _t_ironlaw,
_t_instrumental, _t_chill_delay, _t_groove_first_beat,
_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]
npass = 0
print("== songforge selftest ==")
log.info("selftest 开始", cases=len(cases))
for fn in cases:
try:
notes = fn()
for name, detail in notes:
# 测试函数用返回文本表达失败时,必须显式识别,不能算作通过
bad = bool(re.search(r"\bFAIL\b|\bERR\b|失败", str(detail)))
print(" [%s] %-22s %s"
% ("FAIL" if bad else "ok", name, detail))
if bad:
raise AssertionError(detail)
npass += 1
except AssertionError as e:
print(" [--] %-22s %s" % (fn.__name__[3:], e or "断言失败"))
log.warn("case 失败", case=fn.__name__, err=str(e))
except Exception as e:
print(" [ERR] %-22s %s: %s"
% (fn.__name__[3:], type(e).__name__, e))
log.error("case 异常", case=fn.__name__, err=str(e))
print("== 结果 ==")
print(" %d/%d 通过" % (npass, len(cases)))
log.info("selftest 结束", passed=npass, total=len(cases), log_dir=run.dir)
log.close()
return 0 if npass == len(cases) else 1
# ---------------------------------------------------------------- parser
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""配置包。JSON 为单一事实来源,避免引入 tomllib 之类的额外依赖。"""
+22
View File
@@ -0,0 +1,22 @@
{
"base": {
"n_old": 8,
"coverage": 0.5065,
"voice_self": 0.9379,
"voice_floor": 0.8861,
"dynamic_db": 10.56,
"centroid": 1815.6,
"f0_drift_st": 1.5,
"tempo_drift": 0.0
},
"soft": {
"coverage": 0.4305,
"voice_nn": 0.8661,
"voice_self": 0.868,
"dyn_lo": 7.22,
"centroid_lo": 1367.6,
"f0_drift_st_max": 2.5,
"tempo_drift_max": 0.05
},
"note": "由 songforge qc --baseline-only --save-baseline 在 8 首已认可老歌上校准,不要手改"
}
+77
View File
@@ -0,0 +1,77 @@
{
"note": "8 首用户已认可老歌的基线资料,由 tools/make_baseline.py 从 remake_v5.py 抽取",
"items": [
{
"title": "亮灯就跳",
"file": "v5_亮灯就跳_swl_00001.flac",
"bpm": 100,
"key": "F# minor",
"duration": 112,
"group": "old",
"lyrics": "亮灯就跳 亮灯就跳\n手举起来 脚踩下来\n全世界看见\n鞋底擦出火星子\n一步踩到点上\n他们说我在装\n我说我这叫登场\n夜是我的舞台\n光打在我肩膀\n心里的火 烧出了边\n一 二 三 四 灯亮了\n五 六 七 八 我先到\n左脚右脚 在打仗\n同手同脚 叫对称\n别眨眼 现在开始\n这一条街 我最闪亮"
},
{
"title": "干饭魂",
"file": "v5_干饭魂_swl_00001.flac",
"bpm": 112,
"key": "G major",
"duration": 115,
"group": "old",
"lyrics": "干饭魂 干饭魂\n碗一端 世界安静了\n吃饭都是人上人\n上午十点半 我还在工位\n魂已经先飘到食堂门口\n报表它不会自己写\n饭它会自己凉\n谁挡在我前面\n我跟谁急一场\n筷子功 夹遍南北菜\n风卷残云 你刚动筷我已结束\n火锅咕嘟咕嘟\n那是世界最美的节奏\n吃饱了才有力气温"
},
{
"title": "快乐废物指南",
"file": "v5_快乐废物指南_swl_00001.flac",
"bpm": 116,
"key": "A major",
"duration": 118,
"group": "old",
"lyrics": "快乐废物 快乐废物\n第一条 先睡饱\n闹钟吵不过我的懒觉\n闹钟响了第三遍\n我假装我没听见\n手机亮了二十条\n全是明天见\n老板说要奋斗\n我点了个赞 翻个身\n第二条 吃最好\n什么KPI 给我靠边靠\n一天二十四小时\n睡觉占八小时\n我再吃三小时\n还剩两小时发呆\n怎么了 犯法了吗\n我不偷不抢不坑不骗\n第三条 别烦恼\n我就是最棒的废物"
},
{
"title": "拜师记",
"file": "v5_拜师记_swl_00001.flac",
"bpm": 92,
"key": "Eb major",
"duration": 115,
"group": "old",
"lyrics": "师父他太狠\n一个isolation定三帧\n我学得膝盖疼\n多跳 别怕出丑\n三年前我四肢健全\n走路带风以为行\n直到我推开那扇门\n看见我师父的身影\n他一顶帽子压低\n眼神扫过像点名\n他脚一滑 地板都得让路\n他手一挥 空气学会跳舞\n一个wave 从指尖滚到肩\n我嘴张成大圆盘\n我的师父他是神\n街舞urban样样真\n慢 半拍 慢 半拍\n慢 半拍 就对了\n我也能像你一样神"
},
{
"title": "晒太阳",
"file": "v5_晒太阳_swl_00001.flac",
"bpm": 88,
"key": "C major",
"duration": 112,
"group": "old",
"lyrics": "晒太阳 晒太阳\n把烦恼晒光\n心是暖的\n窗帘拉开一半\n阳光爬上床\n今天不设闹钟\n让它响不到\n外套挂在门口\n鞋摆成一双\n出门不为别的\n就为晒一晒\n今天什么都不想\n一 二 三 四 慢慢晃过来\n五 六 七 八 影子跟着我\n不用比谁快\n我就慢慢走\n阳光落肩上\n什么都不用求\n风一吹 什么都不为难"
},
{
"title": "晚风不加班",
"file": "v5_晚风不加班_swl_00001.flac",
"bpm": 86,
"key": "D minor",
"duration": 112,
"group": "old",
"lyrics": "晚风不加班\n风里没有KPI\n今晚不聊deadline\n地铁到站我挤上去\n手机震动没心思看\n今日KPI又爆表\n清单长得看不见\n可是傍晚的风一吹\n心里那堵墙就塌了半截\n我们都是普通人\n但今晚不普通\n一 二 三 四 慢慢数别急\n五 六 七 八 呼吸还来得及\n把鞋脱了\n让脚趾碰到草地\n明天的事 明天再说"
},
{
"title": "跳起来",
"file": "v5_跳起来_swl_00001.flac",
"bpm": 124,
"key": "E major",
"duration": 110,
"group": "old",
"lyrics": "跳起来 跳起来\n别管多累\n手脚甩开就对了\n闹钟一响我就弹起来\n枕头甩到一旁\n今天的身体有点痒\n想出门晒太阳\n地铁里站着打拍子\n忍不住要开口\n心情放飞\n左一下 右一下\n一 二 三 四 蹦起来\n五 六 七 八 甩开摆\n左 右 左 右 转身再回来\n一句 一句 别停嗨\n衣服挑最亮的那件\n鞋子踩得响亮的"
},
{
"title": "身体先听懂",
"file": "v5_身体先听懂_swl_00001.flac",
"bpm": 94,
"key": "F minor",
"duration": 115,
"group": "old",
"lyrics": "身体先听懂\n一拍 一拍 又一拍\n往下踩 往下踩\n灯亮了 我先不动\n肩膀先知道 往哪沉\n右手抬到一半停\n那个停顿 也算一声\n跟着重心 别跟声音\n慢半拍 才是对的\n一 二 三 四 从脚下数\n五 六 七 八 重心往右\n不用想 不用编\n身体比脑子 先跑一圈\n一个动作 三千遍\n肌肉自己 会归位\n停下 就继续走"
}
]
}
File diff suppressed because it is too large Load Diff
+96
View File
@@ -0,0 +1,96 @@
{
"_comment": "songforge 唯一事实来源。改这里,不要改脚本里的硬编码常量。",
"engine": {
"server": "http://127.0.0.1:8188",
"timeout_sec": 3600,
"poll_interval_sec": 10,
"submit_retries": 3
},
"model": {
"checkpoint": "ace_step_1.5_turbo_swl_fused.safetensors",
"lora": "swl_voice_best_ep257.safetensors",
"lora_model_strength": 0.5,
"lora_clip_strength": 0.5,
"denied_checkpoints": [
"yue2_3b_int8_convrot.safetensors",
"ace_step_1.5_turbo_aio.safetensors"
]
},
"sampler": {
"shift": 5.5,
"sampling": "flow",
"steps": 28,
"cfg": 2.0,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1.0
},
"encode": {
"cfg_scale": 3.0,
"temperature": 0.68,
"top_p": 0.88,
"top_k": 50,
"min_p": 0.02,
"generate_audio_codes": true,
"timesignature": "4"
},
"paths": {
"_comment": "相对路径均相对 user/default/workflows。本机绝对路径放 local.json(gitignore)。音频在 ComfyUI/output/<output_prefix>/。过程物按日落在 data/runs|tmp/YYYY-MM-DD/。",
"workflow_template": "urbanhiphop-身体先听懂.json",
"runs_dir": "songforge/data/runs",
"tmp_dir": "songforge/data/tmp",
"lyrics_dir": "songforge/input/lyrics",
"qc_cache_dir": "songforge/cache/qc",
"style_cache_dir": "songforge/cache/style",
"index_dir": "songforge/index",
"catalog_file": "songforge/index/catalog.jsonl",
"baseline_dir": "songforge/config/baseline",
"comfy_root": null,
"qc_python": null,
"music_dir": null,
"output_prefix": "MyMusic",
"output_format": "flac"
},
"song": {
"language": "zh",
"time_signature": "4",
"duration_range": [150, 200],
"_duration_extra_comment": "duration_extra_ranges 供短视频/口水歌等场景显式放行短时长,不削弱主区间。主区间是 35 首已验证实歌的经验范围,短时长没有对应实歌背书,所以必须显式列出而不是直接放宽。",
"duration_extra_ranges": [[100, 130]]
},
"lyrics": {
"_comment": "死心塌地时长对应关系。阈值由 8 首已验证可生成的歌实测反推,不是理论值;改前先跑 selftest 实歌回归。",
"_calibrated_on": "remake_v5.py 的 8 首实歌:每可唱小节 4.56~7.64 音节(均值 6.17),每句 5.9~7.4 音节(均值 6.7)",
"sing_bar_ratio": 0.70,
"intro_bars": 8,
"syllable_per_bar_min": 4.40,
"syllable_per_bar_max": 7.80,
"line_syllable_max": 12,
"ideal_line_syllable": [5, 12],
"_profile_comment": "密度档。default = 人声填满整首(中文说唱/流行)。sparse = 音乐主导、人声点缀(英文低声吟唱/纯器乐周边)。",
"_profile_why": "default 档是按 8 首'人声填满全曲'的实歌反推的。直接拿它校验第三张那种'音乐当主角、人声只是点缀'的写法,会把只有几句 ooh ooh 的低音吟唱判成歌词过少,逼着写满 254 音节以上——结果就是'只有人声没有音乐',正好和目标相反。所以稀疏写法必须用另一套阈值,不能共用。",
"profiles": {
"sparse": {
"_comment": "稀疏档:可唱小节只占 25%(其余留给器乐),句子下限放宽到 3 音节,允许 ooh ooh / mmm 这类短语气词。",
"sing_bar_ratio": 0.25,
"syllable_per_bar_min": 4.40,
"syllable_per_bar_max": 7.80,
"line_syllable_max": 12,
"ideal_line_syllable": [3, 12]
}
}
},
"rules": {
"trigger_word": "swlvoice",
"intro_bars": 8
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"_comment": "身份词典与禁用词。用户是街头双翘滑手(street skateboarding),不是长板。",
"identity": {
"persona": "街头滑手",
"board": "双翘滑板(街头双翘)",
"en_terms": ["skateboard", "skateboarding", "skatepark", "skater"],
"scene": ["街头", "广场", "水泥地", "马路牙子", "地下通道", "天台", "刷街"],
"verb": ["刷街", "滑行", "起板", "压板", "转向", "落地", "刹停", "推板"],
"tone": ["轻松", "倔", "自由", "不装"]
},
"banned": {
"_comment": "禁止出现在歌词里的词。命中即 check 报错。原因是《鸟巢滑手》曾误写为长板/护具设定,与本人身份不符。",
"longboard": ["长板", "长板的轮子", "长板的孩子", "longboard", "长板滑板", "护具", "护膝", "头盔", "上山", "速降", "下坡", "carve", "slide", "长板赛道"],
"misidentity": ["滑板少年" ]
},
"warnings": {
"_comment": "不报错但提醒。",
"near_miss": ["轮子转起来", "板面", "水泥地"]
}
}
+179
View File
@@ -0,0 +1,179 @@
# -*- coding: utf-8 -*-
"""配置加载与覆盖。
优先级:命令行 > 环境变量 > local.json > default.json > 内置 DEFAULTS。
local.json 放本机绝对路径(gitignore),见 local.json.example。
"""
import copy
import json
import os
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
CONFIG_DIR = os.path.join(ROOT, "songforge", "config")
DEFAULTS = {
"engine": {"server": "http://127.0.0.1:8188", "timeout_sec": 3600,
"poll_interval_sec": 10, "submit_retries": 3},
"model": {"checkpoint": "ace_step_1.5_turbo_swl_fused.safetensors",
"lora": "swl_voice_best_ep257.safetensors",
"lora_model_strength": 0.5, "lora_clip_strength": 0.5,
"denied_checkpoints": ["yue2_3b_int8_convrot.safetensors",
"ace_step_1.5_turbo_aio.safetensors"]},
"sampler": {"shift": 5.5, "sampling": "flow", "steps": 28, "cfg": 2.0,
"sampler_name": "euler", "scheduler": "simple", "denoise": 1.0},
"encode": {"cfg_scale": 3.0, "temperature": 0.68, "top_p": 0.88,
"top_k": 50, "min_p": 0.02, "generate_audio_codes": True,
"timesignature": "4"},
"paths": {"workflow_template": "urbanhiphop-身体先听懂.json",
"runs_dir": "songforge/data/runs",
"tmp_dir": "songforge/data/tmp",
"lyrics_dir": "songforge/input/lyrics",
"qc_cache_dir": "songforge/cache/qc",
"style_cache_dir": "songforge/cache/style",
"index_dir": "songforge/index",
"catalog_file": "songforge/index/catalog.jsonl",
"baseline_dir": "songforge/config/baseline",
"comfy_root": None,
"qc_python": None,
"music_dir": None,
"output_prefix": "MyMusic",
"output_format": "flac"},
"song": {"language": "zh", "time_signature": "4",
"duration_range": [150, 200],
"duration_extra_ranges": [[100, 130]]},
"lyrics": {"sing_bar_ratio": 0.70, "intro_bars": 8,
"syllable_per_bar_min": 4.40, "syllable_per_bar_max": 7.80,
"line_syllable_max": 12, "ideal_line_syllable": [5, 12],
"profiles": {
"sparse": {
"sing_bar_ratio": 0.25,
"syllable_per_bar_min": 4.40,
"syllable_per_bar_max": 7.80,
"line_syllable_max": 12,
"ideal_line_syllable": [3, 12],
}
}},
"rules": {"trigger_word": "swlvoice", "intro_bars": 8},
}
def _deep_merge(base, patch):
for k, v in patch.items():
if k.startswith("_"):
continue
if isinstance(v, dict) and isinstance(base.get(k), dict):
_deep_merge(base[k], v)
else:
base[k] = v
return base
def _read(name):
p = os.path.join(CONFIG_DIR, name)
if not os.path.exists(p):
return {}
with open(p, encoding="utf-8") as f:
return json.load(f)
def load(overrides=None):
"""返回最终配置 dict。overrides 是 {'sampler.shift': 5.5} 这种点号路径。"""
cfg = copy.deepcopy(DEFAULTS)
_deep_merge(cfg, _read("default.json"))
_deep_merge(cfg, _read("local.json"))
_deep_merge(cfg, _env_overrides())
if overrides:
for path, val in overrides.items():
if val is None:
continue
_set(cfg, path, val)
return cfg
def _set(cfg, path, val):
keys = path.split(".")
node = cfg
for k in keys[:-1]:
node = node.setdefault(k, {})
node[keys[-1]] = val
_ENV_MAP = {
"SONGFORGE_SERVER": "engine.server",
"SONGFORGE_TIMEOUT": "engine.timeout_sec",
"SONGFORGE_CHECKPOINT": "model.checkpoint",
"SONGFORGE_LORA": "model.lora",
"SONGFORGE_LORA_STRENGTH": "model.lora_model_strength",
"SONGFORGE_SHIFT": "sampler.shift",
"SONGFORGE_STEPS": "sampler.steps",
"SONGFORGE_CFG": "sampler.cfg",
"SONGFORGE_ENC_CFG": "encode.cfg_scale",
"SONGFORGE_TEMPERATURE": "encode.temperature",
"SONGFORGE_TOP_P": "encode.top_p",
"SONGFORGE_TOP_K": "encode.top_k",
"SONGFORGE_MIN_P": "encode.min_p",
"SONGFORGE_TEMPLATE": "paths.workflow_template",
"SONGFORGE_RUNS": "paths.runs_dir",
"SONGFORGE_TMP": "paths.tmp_dir",
"SONGFORGE_LYRICS_DIR": "paths.lyrics_dir",
"SONGFORGE_QC_CACHE": "paths.qc_cache_dir",
"SONGFORGE_STYLE_CACHE": "paths.style_cache_dir",
"SONGFORGE_OUTPUT_PREFIX": "paths.output_prefix",
"SONGFORGE_LANGUAGE": "song.language",
"SONGFORGE_COMFY_ROOT": "paths.comfy_root",
"SONGFORGE_QC_PYTHON": "paths.qc_python",
"SONGFORGE_MUSIC_DIR": "paths.music_dir",
}
_NUMERIC = {"engine.timeout_sec", "model.lora_model_strength",
"model.lora_clip_strength", "sampler.shift", "sampler.steps",
"sampler.cfg", "sampler.denoise", "encode.cfg_scale",
"encode.temperature", "encode.top_p", "encode.top_k",
"encode.min_p", "lyrics.sing_bar_ratio", "lyrics.intro_bars",
"lyrics.syllable_per_bar_min", "lyrics.syllable_per_bar_max",
"lyrics.line_syllable_max"}
def _env_overrides():
out = {}
for env_key, path in _ENV_MAP.items():
raw = os.environ.get(env_key)
if raw is None or raw == "":
continue
if path in _NUMERIC:
try:
raw = float(raw)
if raw.is_integer() and path not in ("sampler.shift",
"sampler.cfg",
"encode.cfg_scale",
"encode.temperature",
"encode.top_p",
"encode.min_p",
"lyrics.sing_bar_ratio",
"model.lora_model_strength",
"model.lora_clip_strength"):
raw = int(raw)
except ValueError:
continue
elif raw.lower() in ("true", "false"):
raw = raw.lower() == "true"
node = out
keys = path.split(".")
for k in keys[:-1]:
node = node.setdefault(k, {})
node[keys[-1]] = raw
return out
def styles():
return _read("styles.json")
def lexicon():
return _read("lexicon.json")
def baseline_path(name):
"""config/baseline/<name> 绝对路径。"""
return os.path.join(CONFIG_DIR, "baseline", name)
+11
View File
@@ -0,0 +1,11 @@
{
"_comment": "复制为 local.json(已 gitignore)。只放本机绝对路径,勿提交。",
"paths": {
"comfy_root": "D:/CodeFiles/Thinking/ComfyUI-MiniMaxH3",
"qc_python": "C:/comfyui-venv/Scripts/python.exe",
"music_dir": "D:/CodeFiles/Thinking/ComfyUI-MiniMaxH3/output/MyMusic"
},
"engine": {
"server": "http://127.0.0.1:8188"
}
}
+549
View File
@@ -0,0 +1,549 @@
{
"_comment": "风格字典。style 供 --style 引用;bpm/key 为推荐值,可被命令行覆盖。",
"urbanhiphop": {
"style": "Chinese urban hiphop",
"bpm": 94,
"key": "F minor",
"duration": 165,
"instruments": "hard attacking kick, crisp layered snare, tight closed hi-hats with triplet rolls, aggressive sub bass, stabbing brass hits, neon synth stabs, wide stereo hook",
"mood": "precise rhythmic groove, sharp and tight, punchy snares",
"extra": "male rap with baritone tone, mid low register, controlling clean vocal tone, crisp clear pronunciation"
},
"chillhiphop": {
"style": "Chinese chill hiphop",
"bpm": 92,
"key": "C major",
"duration": 165,
"instruments": "soft round kick, brushed hi-hat, walking bass, warm rhodes chords, mellow keys",
"mood": "warm relaxed groove, gentle and easy",
"extra": "male singing with soft baritone tone, mid low register, clean controlled vocal tone"
},
"partyyrap": {
"style": "Chinese party hiphop",
"bpm": 126,
"key": "E minor",
"duration": 160,
"instruments": "bright four on the floor kick, crisp snare, sixteenth hi-hats, bouncing 808 bass, synth arpeggio, brass stab",
"mood": "explosive high energy, maximum bounce",
"extra": "male rap with baritone tone, mid low register, crisp clear pronunciation"
},
"pop": {
"style": "Chinese pop",
"bpm": 104,
"key": "F major",
"duration": 180,
"instruments": "tight punchy kick, crisp clap snare, modern synth bass, glossy electric piano, wide layered synths, claps",
"mood": "warm emotional groove, lifting chorus, clear contrast",
"extra": "clear male singing voice, stable tone, expressive but controlled"
},
"punk": {
"style": "Chinese punk rock",
"bpm": 168,
"key": "E minor",
"duration": 155,
"instruments": "driving distorted power chords, crashing cymbals, fast eighth note drums, punchy bass, roaring guitar riff",
"mood": "relentless high energy, aggressive and fast, shouted chorus",
"extra": "male vocal with gritty mid range, aggressive delivery, clear pronunciation"
},
"funkhiphop": {
"style": "Chinese funky hiphop",
"bpm": 118,
"key": "G major",
"duration": 160,
"instruments": "four on the floor kick, clapping and cowbell, walking bass, jazzy rhodes chords, funk guitar chops, brass stabs",
"mood": "playful bouncy groove, tight and groovy",
"extra": "male rap with baritone tone, mid low register, crisp clear pronunciation"
},
"discofunk": {
"style": "Chinese disco funk",
"bpm": 120,
"key": "A major",
"duration": 160,
"instruments": "four on the floor kick, handclaps and cowbell, walking bass, wah guitar, bright brass section, synth arpeggio",
"mood": "carefree party energy, playful and bouncy",
"extra": "male singing with bright tone, playful delivery, clear pronunciation"
},
"emopunk": {
"style": "Chinese emotional punk rock",
"bpm": 152,
"key": "A minor",
"duration": 175,
"instruments": "clean chiming guitars, driving bass, steady rock drums, wide reverb, melodic lead line",
"mood": "slow burning build, restrained verse and loud chorus",
"extra": "male singing with clear mid range, honest emotional delivery"
},
"jazzhiphop": {
"style": "Chinese jazz hiphop",
"bpm": 92,
"key": "Eb major",
"duration": 160,
"instruments": "groovy electric piano, walking bass, brass accents, shuffle drums, pocket groove, tight snare",
"mood": "smooth pocket groove, laid back but crisp",
"extra": "male rap with baritone tone, mid low register, crisp clear pronunciation"
},
"guofeng": {
"style": "Chinese traditional style hiphop",
"bpm": 99,
"key": "F minor",
"duration": 200,
"instruments": "erhu, pipa, bamboo flute, 808 sub bass, trap hats, traditional percussion",
"mood": "modern traditional fusion, cinematic and steady",
"extra": "male rap with baritone tone, mid low register, clear pronunciation"
},
"folk": {
"style": "Chinese folk ballad",
"bpm": 76,
"key": "G major",
"duration": 175,
"instruments": "nylon string acoustic guitar fingerpicking, warm upright bass, brushed snare, subtle piano, natural room reverb",
"mood": "intimate warm storytelling, gentle and honest, close mic",
"extra": "male singing with warm soft tenor tone, close to microphone, gentle restrained delivery, clear pronunciation"
},
"poppunk": {
"style": "Chinese pop punk",
"bpm": 156,
"key": "D major",
"duration": 158,
"instruments": "punchy palm muted power chords, driving bass, fast crisp drums, bright lead guitar riff, claps on chorus",
"mood": "upbeat catchy and bright, fast but singable, youthful",
"extra": "male singing with clear bright tone, energetic but controlled, crisp clear pronunciation"
},
"indie": {
"style": "Chinese indie pop",
"bpm": 112,
"key": "A major",
"duration": 172,
"instruments": "clean electric guitar arpeggio, analog synth pad, warm bass, real drum kit, subtle tremolo",
"mood": "dreamy nostalgic and warm, gently swaying",
"extra": "male singing with soft airy tone, gentle close mic delivery, clear pronunciation"
},
"electronic": {
"style": "Chinese future bass electro",
"bpm": 128,
"key": "F minor",
"duration": 168,
"instruments": "big supersaw synth lead, sidechained pad, punchy electro kick, trap snare, white noise riser, wide reverb",
"mood": "vast emotional build, euphoric and bright, festival anthem",
"extra": "male singing with clear bright tone, soaring controlled delivery, crisp clear pronunciation"
},
"lofi": {
"style": "Chinese chillhop lofi",
"bpm": 82,
"key": "C major",
"duration": 168,
"instruments": "dusty jazz chords, upright bass, soft rimshot, vinyl crackle, mellow rhodes, subtle swing",
"mood": "laid back nostalgic calm, late night quiet",
"extra": "male singing with soft low tone, relaxed and close, clear pronunciation"
},
"poprap": {
"_comment": "甜系中文 pop rap。tags 靠正向措辞自然带出鼓组,lean 模式不注入 RULE_NEG 那 20+ 条人声否定句。旧版 dy10_心动预警 的 lean tags 是 13 子句,本风格经 ironlaw 注入后约 43 子句。",
"style": "Chinese pop rap",
"bpm": 110,
"key": "C major",
"duration": 112,
"instruments": "bouncy kick and snare, sweet piano arpeggio, bright synth chords, hand claps, soft bass",
"mood": "sweet and bubbly, romantic crush feeling, upbeat and cute",
"extra": "male rap with clear tone, playful delivery, light and sweet, crisp clear pronunciation"
},
"poprap2": {
"_comment": "甜系 pop rap 第二首,节奏更跳一点,hook 更口语。",
"style": "Chinese pop rap",
"bpm": 114,
"key": "D major",
"duration": 112,
"instruments": "bouncy kick and snare, sweet piano arpeggio, bright synth chords, hand claps, soft bass",
"mood": "sweet and playful, cheeky and cute, upbeat and light",
"extra": "male rap with clear tone, playful delivery, light and sweet, crisp clear pronunciation"
},
"poprap3": {
"_comment": "甜系 pop rap 第三首,稍抒情一点,副歌更开阔。",
"style": "Chinese pop rap",
"bpm": 106,
"key": "A major",
"duration": 112,
"instruments": "bouncy kick and snare, sweet piano arpeggio, bright synth chords, hand claps, soft bass",
"mood": "sweet and warm, gentle crush feeling, bright and hopeful",
"extra": "male rap with clear tone, warm delivery, light and sweet, crisp clear pronunciation"
},
"funkdance": {
"_comment": "街舞编舞导向 funk。动作引导词写进 instruments 与 extra:downbeat 停顿、popping 咬点、groove 起伏。lean 模式使用,正向措辞。",
"style": "Chinese funk dance groove",
"bpm": 106,
"key": "E minor",
"duration": 160,
"instruments": "punchy four on the floor kick, dry crisp snare, tight closed hi-hats, short slap bass, clavinet stabs, wah guitar, tambourine, hand claps",
"mood": "bouncy playful groove, clear strong downbeat accents, light and easy groove, danceable pocket",
"extra": "male singing with clear warm tone, playful rhythmic delivery, crisp clear pronunciation, short punchy phrases on the downbeat"
},
"funkdance2": {
"_comment": "funk 第二首:更跳更复古,James Brown 式的连续十六分贝斯线。",
"style": "Chinese funk retro groove",
"bpm": 112,
"key": "A major",
"duration": 160,
"instruments": "hard four on the floor kick, crisp rimshot snare, tight hi-hats with sixteenth rolls, deep elastic bass, clavinet short stabs, brass stab accents, tambourine",
"mood": "explosive vintage groove, punchy and driving, playful rhythmic stop and start",
"extra": "male rap with warm clear tone, playful delivery, crisp clear pronunciation, short punchy phrases"
},
"funkdance3": {
"_comment": "funk 第三首:中速偏 chill,适合 isolations 编排,律动留白多。",
"style": "Chinese chill funk groove",
"bpm": 96,
"key": "D major",
"duration": 160,
"instruments": "round punchy kick, brushed snare, soft closed hi-hats, round walking bass, jazzy rhodes chords, muted trumpet accents, light tambourine",
"mood": "smooth pocket groove, laid back and warm, gentle swing, easy going bounce",
"extra": "male singing with soft clear tone, warm relaxed delivery, crisp clear pronunciation"
},
"funkdance4": {
"_comment": "funk 第四首:明快大调,适合 waacking / locking 快速手臂与定点。",
"style": "Chinese funk disco groove",
"bpm": 122,
"key": "G major",
"duration": 160,
"instruments": "bright four on the floor kick, crisp clap snare, tight hi-hats, elastic slap bass, clavi short stabs, bright brass accents, hand claps",
"mood": "bright cheerful groove, fast playful accents, crisp and clean, dance floor ready",
"extra": "male singing with bright clear tone, energetic playful delivery, crisp clear pronunciation, short punchy phrases"
},
"funkdance5": {
"_comment": "funk 第五首:带一点 trap 底鼓的现代 funk,hook 更抓耳,适合编舞短视频。",
"style": "Chinese modern funk groove",
"bpm": 114,
"key": "F minor",
"duration": 160,
"instruments": "hard four on the floor kick, layered crisp snare, tight closed hi-hats, deep sub and elastic bass, clavinet stabs, wah guitar short hits, hand claps",
"mood": "heavy on the downbeat, dark warm groove, catchy stop and start pocket, confident bounce",
"extra": "male singing with clear low tone, confident rhythmic delivery, crisp clear pronunciation, short punchy phrases on the downbeat"
},
"vocalchill": {
"_comment": "第三张专辑用:英文低声吟唱/哼唱,突出音乐本身,接近 Avicii 那种大编制 EDM + 克制人声。",
"style": "English melodic future bass, EDM, instrumental focus",
"bpm": 124,
"key": "A minor",
"duration": 175,
"instruments": "punchy electro kick, deep sub bass and walking bass, crisp clap, trap snare, huge supersaw lead, sidechain compressed pad, white noise riser, big reverb, melodic drop",
"mood": "vast uplifting emotional EDM, instrumental section showcase, euphoria then release",
"extra": "male low whisper vocal, hushed and intimate, sparse English words, mostly instrumental between phrases, no belting, no big singing"
},
"_comment_cuckoo": "===== cuckoo 编舞批次(2026-10-05)=====",
"ckfunk": {
"_comment": "中文 108 主体档。James Brown 的 The One:kick 落在 beat 1 最重,十六分 ghost note 铺满小节。108 是 funk 中心速度,也是 urban 团体齐舞命中率最高的一档。",
"style": "Chinese funk dance groove",
"bpm": 108,
"key": "E minor",
"duration": 160,
"instruments": "heavy four on the floor kick on beat one, dry crisp snare with ghost notes on every sixteenth, tight closed hi-hats accenting the offbeats, short slap bass with thumb pops and octave jumps, clavinet chicken scratch stabs, wah guitar short chops, tambourine and hand claps",
"mood": "bouncy playful groove, clear strong downbeat accents, stop and start pocket, light and easy, danceable",
"extra": "male singing with clear warm tone, playful rhythmic delivery, crisp clear pronunciation, short punchy phrases landing on the downbeat"
},
"ckfunkretro": {
"_comment": "中文 112 复古档。十六分音符滚奏 hi-hat + rimshot,James Brown 式连续贝斯线,适合大开大合的 frame。",
"style": "Chinese funk retro groove",
"bpm": 112,
"key": "A major",
"duration": 160,
"instruments": "hard four on the floor kick, crisp rimshot snare, tight hi-hats with sixteenth rolls, deep elastic slap bass line, clavinet short stabs, brass stab accents on the offbeat, tambourine",
"mood": "explosive vintage groove, punchy and driving, playful rhythmic stop and start",
"extra": "male singing with warm clear tone, playful delivery, crisp clear pronunciation, short punchy phrases"
},
"ckchillfunk": {
"_comment": "中文 98 chill 档。留白多、摆动大,适合 isolations 编排和慢速数拍教学,对应《两难》那种慢速解析路线。",
"style": "Chinese chill funk groove",
"bpm": 98,
"key": "D major",
"duration": 160,
"instruments": "round punchy kick, brushed snare, soft closed hi-hats, round walking bass, jazzy rhodes chords, muted trumpet accents, light tambourine, gentle swing",
"mood": "smooth pocket groove, laid back and warm, gentle swing, easy going bounce",
"extra": "male singing with soft clear tone, warm relaxed delivery, crisp clear pronunciation"
},
"cktrapfunk": {
"_comment": "中文 122 快速档。trap 底鼓 + funk 十六分,体感按 half-time 走,适合抖音短视频卡点快闪。",
"style": "Chinese modern trap funk groove",
"bpm": 122,
"key": "F minor",
"duration": 160,
"instruments": "hard four on the floor kick hitting on every single beat, layered crisp snare, tight closed hi-hats, deep sub bass and elastic bass pumping on every beat, clavinet short stabs, wah guitar short hits, hand claps, half time feel",
"mood": "heavy on the downbeat, dark warm groove, catchy stop and start pocket, confident bounce",
"extra": "male singing with clear low tone, confident rhythmic delivery, crisp clear pronunciation, short punchy phrases on the downbeat"
},
"ckfunken": {
"_comment": "英文 110 主体档。同 ckfunk 的鼓组,英文咬字需要更松的元音,所以 extra 写 melismatic 一点点、phrasing 更 swing。",
"style": "English funk dance groove",
"bpm": 110,
"key": "F minor",
"duration": 160,
"instruments": "heavy four on the floor kick hitting on every single beat, dry crisp snare with ghost notes, tight closed hi-hats accenting the offbeats, short slap bass with thumb pops pumping on every beat, clavinet chicken scratch stabs, wah guitar chops, tambourine and hand claps",
"mood": "bouncy playful groove, clear strong downbeat accents, stop and start pocket, danceable",
"extra": "male singing with clear warm tone, playful rhythmic phrasing, crisp clear English pronunciation, short punchy phrases landing on the downbeat"
},
"ckfunkdisco": {
"_comment": "英文 118 复古 disco 档。对应《Talk Dirty》那种快卡点,brass stab 更亮,十六分更密。",
"style": "English funk disco groove",
"bpm": 118,
"key": "A major",
"duration": 160,
"instruments": "bright four on the floor kick, crisp clap snare, tight hi-hats with sixteenth rolls, elastic slap bass, clavi short stabs, bright brass stab accents, hand claps",
"mood": "bright cheerful groove, fast playful accents, crisp and clean, dance floor ready",
"extra": "male singing with bright clear tone, energetic playful delivery, crisp clear English pronunciation, short punchy phrases"
},
"ckrbslow": {
"_comment": "英文 96 slow R&B 档。对应《想想念念》《还是会想你》那条抒情编舞线:isolations、延伸细腻动作、情绪拉满。",
"style": "English slow R&B groove with funk drums",
"bpm": 96,
"key": "E minor",
"duration": 160,
"instruments": "round punchy kick, brushed snare, soft closed hi-hats, round walking bass, warm rhodes chords, muted trumpet accents, light tambourine, gentle swing",
"mood": "smooth warm pocket groove, laid back and tender, gentle swing, emotional and easy going",
"extra": "male singing with soft warm tone, tender relaxed delivery, crisp clear English pronunciation, smooth legato phrasing"
},
"cktrapfunken": {
"_comment": "英文 124 快速档。trap 底鼓 + funk 十六分,体感 half-time,适合快手 waacking 和定点。",
"style": "English modern trap funk groove",
"bpm": 124,
"key": "G minor",
"duration": 160,
"instruments": "hard four on the floor kick hitting on every single beat, layered crisp snare, tight closed hi-hats, deep sub bass and elastic bass pumping on every beat, clavinet short stabs, wah guitar short hits, hand claps, half time feel",
"mood": "heavy on the downbeat, dark confident groove, catchy stop and start pocket, fast bounce",
"extra": "male singing with clear low tone, confident rhythmic delivery, crisp clear English pronunciation, short punchy phrases on the downbeat"
},
"_comment_birthday": "===== 一棠生日·术力口三版(2026-10-05)=====",
"vocaloid_fb": {
"_comment": "术力口生日 V1:高速可爱 future bass,最具 Vocaloid 感的一版。lean 模式使用,中日双语歌词。",
"style": "Chinese Vocaloid style future bass, J-pop electro",
"bpm": 160,
"key": "F major",
"duration": 118,
"instruments": "four on the floor kick, bright snare rolls, fast sixteenth note hi-hats, bouncy synth bass, glittery arpeggio, supersaw lead, xylophone-like bell melody, hand claps, cute chiptune accents",
"mood": "bright and hyper cute, happy birthday celebration, energetic and bouncy, youthful 10s vibe, sparkling and uplifting",
"extra": "cute high pitched female singing voice, Vocaloid style vocal, bright girlish tone, clear Japanese and Mandarin pronunciation, cheerful energetic delivery, catchy melodic phrases"
},
"vocaloid_euro": {
"_comment": "术力口生日 V2:日系 Eurobeat / 高速蹦迪感,副歌洗脑。lean 模式使用,中日双语。",
"style": "Japanese Eurobeat style J-pop, dance pop",
"bpm": 155,
"key": "D major",
"duration": 118,
"instruments": "fast four on the floor kick, powerful snare, rolling sixteenth hi-hats, driving synth bass, bright brass stabs, retro synth lead, piano staccato, tambourine, hand claps on every beat",
"mood": "explosive high energy, happy party feeling, catchy singalong chorus, upbeat and joyful, celebratory dance floor vibe",
"extra": "bright powerful female singing voice, clear energetic tone, Japanese and Mandarin bilingual vocals, strong catchy chorus, upbeat rhythmic delivery"
},
"vocaloid_jpop": {
"_comment": "术力口生日 V3:稍抒情 J-pop,旋律好听,适合全家一起唱。lean 模式使用,中日双语。",
"style": "Japanese pop ballad, J-pop style",
"bpm": 128,
"key": "E major",
"duration": 122,
"instruments": "warm acoustic guitar strumming, gentle piano arpeggio, soft kick and snare, warm bass, strings pad, glockenspiel melody, light tambourine, warm brass accents on chorus",
"mood": "warm heartfelt emotion, gentle and sincere, uplifting chorus, sweet birthday blessing, family friendly and touching",
"extra": "warm clear female singing voice, sweet gentle tone, Japanese and Mandarin bilingual vocals, emotional but controlled delivery, clear pronunciation, singalong melody"
},
"_comment_insomnia": "===== 失眠三部曲(2026-10-06)=====",
"insomnia1_rnb": {
"_comment": "失眠三部曲 1/3《三点半》:都市抒情 R&B,凌晨空房间的空旷感。中低音叙事,气声多,不推满。shift=5.0 贴少年音中低音区。",
"style": "Chinese emotional R&B ballad",
"bpm": 78,
"key": "C minor",
"duration": 175,
"instruments": "soft deep sub bass on every beat, gentle rim click rhythm, warm piano arpeggios, atmospheric synth pad, subtle vinyl crackle, spacious reverb, slow grooving",
"mood": "late night quiet, lonely and introspective, empty room echo, gentle melancholy, slow burning emotion",
"extra": "male singing with soft youthful tone, mid low register, intimate close mic delivery, breathy and fragile, gentle restrained emotion, clear pronunciation, no belting, no high notes"
},
"insomnia2_emo": {
"_comment": "失眠三部曲 2/3《旧号码》:Emo R&B 慢板,情绪最低点。钢琴为主,弦乐铺底,鼓点极度克制。shift=5.0 贴中低音脆弱感。",
"style": "Chinese emo R&B slow ballad",
"bpm": 72,
"key": "A minor",
"duration": 200,
"instruments": "slow piano chords, deep sub bass on every beat, soft string pad, minimal brushed snare, spacious reverb, ambient texture",
"mood": "deep sadness, heartbroken and tender, quiet crying feeling, restrained verse and emotional chorus, intimate vulnerability",
"extra": "male singing with soft fragile youthful tone, mid low register, intimate close mic, breathy delivery, trembling vulnerable emotion, gentle crying tone, no belting, no high notes, clear pronunciation"
},
"insomnia3_folk": {
"_comment": "失眠三部曲 3/3《天又亮了》:民谣 R&B,清晨麻木的温柔。木吉他 + 轻拍军鼓,情绪是'熬过去了'的平静。shift=5.0。时长 200s 给叙事留呼吸。",
"style": "Chinese folk R&B, morning after vibe",
"bpm": 85,
"key": "G major",
"duration": 200,
"instruments": "warm acoustic guitar fingerpicking, soft sub bass on every beat, brushed snare, gentle synth pad, light tambourine, natural room reverb, morning ambient feel",
"mood": "calm resignation, gentle acceptance, quiet hope, numb but soft, morning after a long night, bittersweet warmth",
"extra": "male singing with soft warm youthful tone, mid low register, gentle honest delivery, intimate close mic, restrained emotion, clear pronunciation, no belting, no high notes"
},
"_comment_edm": "===== 甜嗓电音三部曲(2026-10-06)中 + 英 =====",
"edm1_chudian": {
"_comment": "甜嗓电音 1/6《触电》:明快 EDM-pop,一见钟情的甜。BPM 128,大调,合成器钩子 + 弹跳鼓点。shift=5.2 提亮少年音。",
"style": "Chinese EDM pop, upbeat electro pop",
"bpm": 128,
"key": "C major",
"duration": 195,
"instruments": "four on the floor kick, bright snare on 2 and 4, fast sixteenth hi-hats, bouncy synth bass, catchy synth lead hook, bright pluck arpeggio, piano stabs, wide stereo chorus, sidechained pads",
"mood": "sweet energetic, bubbly happy feeling, butterflies in stomach, first love excitement, catchy singalong chorus, youthful upbeat vibe",
"extra": "male singing with bright sweet youthful tone, mid high register, energetic delivery, clear pronunciation, catchy melodic chorus, upbeat rhythmic feel, Justin Bieber style pop vocal, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm2_pin dao": {
"_comment": "甜嗓电音 2/6《专属频道》:R&B 电音,暧昧拉扯感。BPM 120,中速,808 + 合成器铺垫。shift=5.0。",
"style": "Chinese R&B electro pop, mid tempo",
"bpm": 120,
"key": "E major",
"duration": 195,
"instruments": "trap style 808 bass, crisp snare rolls, fast hi-hat triplets, warm rhodes chords, shiny synth pluck, soft pad, sidechained sub bass",
"mood": "flirty and playful, sweet tension, crush feeling, smooth grooving, catchy melodic hooks, confident swagger mixed with vulnerability",
"extra": "male singing with smooth sweet youthful tone, mid register, rhythmic delivery, clear pronunciation, catchy chorus with melodic hooks, modern pop R&B vocal style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm3_yehang": {
"_comment": "甜嗓电音 3/6《夜航》:最嗨 EDM 副歌,深夜公路释放感。BPM 138,synth-pop + EDM drop。shift=5.2。",
"style": "Chinese EDM pop, synthwave dance pop, big chorus",
"bpm": 138,
"key": "D major",
"duration": 200,
"instruments": "powerful four on the floor kick, massive snare, fast rolling hi-hats, driving synth bass, big supersaw lead, retro synth arpeggio, wide stereo pad, build up risers, impactful drop",
"mood": "euphoric freedom, night driving adrenaline, big emotional chorus, uplifting release, triumphant feeling, neon lights energy, dance floor ready",
"extra": "male singing with bright powerful youthful tone, mid high register, energetic belting on chorus, clear pronunciation, big catchy hooks, modern pop EDM vocal style, Justin Bieber Purpose era vibe, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm4_electric": {
"_comment": "甜嗓电音 4/6《Electric Touch》:英文甜系 EDM-pop,一见钟情。BPM 128,Justin Bieber 风格。shift=5.2。",
"style": "EDM pop, upbeat electro pop, Justin Bieber style",
"bpm": 128,
"key": "C major",
"duration": 195,
"instruments": "four on the floor kick, bright snare, fast sixteenth hi-hats, bouncy synth bass, catchy synth lead hook, pluck arpeggio, piano stabs, wide stereo chorus, sidechained pads",
"mood": "sweet energetic, bubbly happy, butterflies in stomach, first love excitement, catchy singalong chorus, youthful upbeat vibe, radio friendly pop",
"extra": "male singing with bright sweet youthful tone, mid high register, energetic delivery, clear English pronunciation, catchy melodic chorus, upbeat rhythmic feel, modern pop vocal style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm5_frequency": {
"_comment": "甜嗓电音 5/6《Frequency》:英文 R&B 电音,暧昧律动。BPM 120,R&B + electro。shift=5.0。",
"style": "R&B electro pop, mid tempo, modern pop R&B",
"bpm": 120,
"key": "E major",
"duration": 195,
"instruments": "trap style 808 bass, crisp snare rolls, fast hi-hat triplets, warm rhodes chords, shiny synth pluck, soft pad, sidechained sub bass, snap on backbeat",
"mood": "flirty and playful, sweet tension, crush feeling, smooth grooving, catchy melodic hooks, confident swagger mixed with vulnerability, modern pop vibe",
"extra": "male singing with smooth sweet youthful tone, mid register, rhythmic delivery, clear English pronunciation, catchy chorus with melodic hooks, modern pop R&B vocal style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm6_neon": {
"_comment": "甜嗓电音 6/6《Neon Drive》:英文 synthwave pop,最炸副歌。BPM 138,霓虹之夜。shift=5.2。",
"style": "synthwave pop, EDM pop, retro futuristic, big chorus",
"bpm": 138,
"key": "D major",
"duration": 200,
"instruments": "powerful four on the floor kick, massive snare, fast rolling hi-hats, driving synth bass, big supersaw lead, retro synth arpeggio, wide stereo pad, build up risers, impactful drop, neon synth sounds",
"mood": "euphoric freedom, night driving adrenaline, big emotional chorus, uplifting release, triumphant feeling, neon lights energy, dance floor ready, retro 80s vibe meets modern pop",
"extra": "male singing with bright powerful youthful tone, mid high register, energetic belting on chorus, clear English pronunciation, big catchy hooks, modern pop EDM vocal style, The Weeknd meets Justin Bieber vibe, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"_comment_trending": "===== 平台热门电音 5 首(2026-10-06)3 热门 + 2 爱情 =====",
"trend1_miaozhen": {
"_comment": "热门 1/5《秒针》:UK Garage/DnB PinkPantheress 风格。快碎拍+甜嗓轻语,TikTok 爆款。BPM 160,A minor。shift=5.2。",
"style": "UK garage pop, drum and bass inspired, PinkPantheress style, fast breakbeat pop",
"bpm": 160,
"key": "A minor",
"duration": 180,
"instruments": "fast 2-step breakbeat, chopped amen break, bouncy sub bass, bright synth stabs, atmospheric pad, retro 2000s garage feel, sidechained bass, crisp hi-hats, snare on backbeat",
"mood": "anxious crush feeling, waiting for reply, sweet nervousness, fast paced but gentle delivery, nostalgic Y2K vibe, TikTok viral energy, short catchy phrases",
"extra": "male singing with sweet soft youthful tone, mid high register, light breathy delivery, almost whispered verses, catchy melodic chorus, fast rhythmic phrasing, clear pronunciation, PinkPantheress style vocal, British pop feel, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"trend2_riluo": {
"_comment": "热门 2/5《日落大道》:Amapiano/Afrobeats pop。非洲律动+log drum+口哨旋律。BPM 112,F major。shift=5.0。",
"style": "Amapiano pop, Afrobeats dance pop, warm groove",
"bpm": 112,
"key": "F major",
"duration": 195,
"instruments": "log drum bass, soft shaker pattern, conga percussion, warm rhodes chords, guitar pluck melody, whistle hook, smooth pad, sidechained sub bass, gentle four on the floor, tambourine",
"mood": "warm summer evening, romantic sunset walk, feel good groove, gentle danceable, sweet and relaxed, African dance pop meets Chinese pop, infectious rhythm",
"extra": "male singing with warm sweet youthful tone, mid register, smooth groovy delivery, clear pronunciation, catchy melodic hooks, warm intimate feel, modern Afro pop vocal style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"trend3_xinhao": {
"_comment": "热门 3/5《信号干扰》:Hyperpop/Bass DJ。重低音 drop+电子音效+洗脑 hook。抖音 DJ 风。BPM 140,E minor。shift=5.2。",
"style": "hyperpop, bass heavy DJ pop, Chinese TikTok DJ style, electronic dance pop",
"bpm": 140,
"key": "E minor",
"duration": 190,
"instruments": "massive bass drop, punchy four on the floor kick, aggressive snare, fast hi-hat rolls, distorted synth lead, riser build ups, impactful drop section, sidechained everything, electronic sound effects, sub bass wobble",
"mood": "anxious and catchy, dramatic tension, electronic energy, club ready, TikTok viral, mysterious atmosphere, dramatic build and release, dark but sweet",
"extra": "male singing with bright sweet youthful tone, mid high register, energetic rhythmic delivery, clear pronunciation, catchy repetitive hooks, spoken word elements, modern hyperpop vocal style, Charli XCX meets Chinese pop, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"trend4_xiaoyuzhou": {
"_comment": "爱情 1/2《小宇宙》:UK Garage sweet pop。甜系 2-step 情歌,两个人的小世界。BPM 130,G major。shift=5.2。",
"style": "UK garage sweet pop, 2-step love song, gentle electronic pop",
"bpm": 130,
"key": "G major",
"duration": 190,
"instruments": "2-step garage beat, shuffled hi-hats, warm sub bass, bright synth chords, pluck arpeggio, soft pad, piano stabs, gentle sidechain, sweet melody, romantic feel",
"mood": "sweet romantic, cozy intimate, two people in their own world, warm and fuzzy, gentle danceable, cute and innocent love, feel good",
"extra": "male singing with sweet warm youthful tone, mid high register, gentle tender delivery, clear pronunciation, catchy melodic chorus, sweet love song vocal, Justin Bieber early era vibe, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"trend5_gaobai": {
"_comment": "爱情 2/2《告白前夜》:Synth-pop 电子情歌。告白前的紧张期待。BPM 100,D major。shift=5.0。",
"style": "synth pop ballad, electronic love song, emotional pop",
"bpm": 100,
"key": "D major",
"duration": 200,
"instruments": "warm synth pad, gentle electronic kick, soft snare, arpeggiated synth, sub bass, piano chords, dreamy atmosphere, light hi-hats, building synth layers, emotional strings, spacious reverb",
"mood": "nervous anticipation, tender vulnerability, night before confession, sleepless and lovesick, sweet anxiety, hopeful but scared, emotional climax, heartfelt",
"extra": "male singing with sweet tender youthful tone, mid register, emotional delivery, clear pronunciation, building from soft verse to emotional chorus, breathy verses, heartfelt chorus, gentle falsetto touches, modern synth pop vocal, The Weeknd ballad style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"moto_yehang": {
"_comment": "夜航摩托车版:引擎轰鸣 + synthwave 飞驰感。BPM 145,D major。shift=5.2。摩托车公路飞驰。",
"style": "synthwave rock pop, motorcycle highway driving, energetic electronic rock",
"bpm": 145,
"key": "D major",
"duration": 200,
"instruments": "driving four on the floor kick, powerful snare, fast rolling hi-hats, roaring synth bass like engine rev, big supersaw lead, retro synth arpeggio, wide stereo pad, guitar power chords, build up risers, impactful drop, wind sound effect, road trip energy",
"mood": "euphoric freedom, motorcycle highway adrenaline, wind in face, big emotional chorus, uplifting release, triumphant feeling, night ride energy, dance floor ready, retro 80s meets modern pop",
"extra": "male singing with bright powerful youthful tone, mid high register, energetic belting on chorus, clear pronunciation, big catchy hooks, modern pop EDM vocal style, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm3_yehang_vox": {
"_comment": "夜航声线优先版:降BPM到128、C大调、中低音区,最大限度还原参考声线。shift=4.0。",
"style": "synthwave pop, night drive electronic pop, mid tempo EDM pop",
"bpm": 128,
"key": "C major",
"duration": 200,
"instruments": "four on the floor kick, crisp snare, steady rolling hi-hats, warm synth bass, soft supersaw lead, retro arpeggio, wide stereo pad, gentle build ups, emotional drop, dreamy atmosphere, reverb and delay",
"mood": "euphoric freedom, night drive feeling, wind in hair, emotional release, uplifting but intimate, nostalgic synthwave vibe, warm energy, modern pop sensibility",
"extra": "male singing with natural youthful tone, mid register, conversational delivery, clear pronunciation, melodic chorus, preserve exact voice timbre and color, true to reference voice, natural breathing, smooth phrasing, no belting, no screaming, no vocal acrobatics, stay in natural vocal range, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"edm6_neon_vox": {
"_comment": "Neon Drive声线优先版:降BPM到128、C大调、中低音区,英文演唱最大限度还原参考声线。shift=4.0。",
"style": "synthwave pop, neon night drive electronic pop, mid tempo EDM pop",
"bpm": 128,
"key": "C major",
"duration": 200,
"instruments": "four on the floor kick, crisp snare, steady rolling hi-hats, warm synth bass, soft supersaw lead, retro arpeggio, wide stereo pad, gentle build ups, emotional drop, dreamy atmosphere, reverb and delay",
"mood": "euphoric freedom, neon night drive feeling, city lights, emotional release, uplifting but intimate, nostalgic synthwave vibe, warm energy, modern pop sensibility",
"extra": "male singing with natural youthful tone, mid register, conversational delivery, clear English pronunciation, melodic chorus, preserve exact voice timbre and color, true to reference voice, natural breathing, smooth phrasing, no belting, no screaming, no vocal acrobatics, stay in natural vocal range, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"trend3_xinhao_pro": {
"_comment": "信号干扰Pro版:Hyperpop + Bass House 升级版,编曲更炸更有层次,drop 更有冲击力。BPM 140,E minor。shift=5.2。100% 男声独唱。",
"style": "hyperpop bass house, aggressive electronic pop, glitchy EDM",
"bpm": 140,
"key": "E minor",
"duration": 200,
"instruments": "massive sub bass drop, punchy four on the floor kick, aggressive snare rolls, fast hi-hat triplets, distorted synth lead, glitchy synth stabs, supersaw chords, riser build ups, impactful drops, synth brass hits, pluck arpeggios, heavy sidechain compression, stereo widening, fm bass, 808 sub bass, breakdown with piano, second drop bigger than first, epic build",
"mood": "chaotic energy, emotional turbulence, signal distortion feeling, aggressive but catchy, intense chorus, glitchy vibe, futuristic electronic, dance floor banger, headbanging energy, triumphant drop",
"extra": "male singing with bright sweet youthful tone, mid high register, energetic rhythmic delivery, clear pronunciation, catchy repetitive hooks, spoken word sections that build into singing, powerful chorus, modern hyperpop vocal style, Charli XCX meets 100 gecs energy but male voice, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops, no vocal samples"
},
"futureremix": {
"_comment": "Future House EDM 通用:弹跳合成贝斯+supersaw+drop结构。128 BPM,F minor,时长168s。",
"style": "modern future house EDM, bouncy club electronic, big room dance",
"bpm": 128,
"key": "F minor",
"duration": 168,
"instruments": "punchy four on the floor kick, bouncy offbeat synth bass, deep sub bass, crisp claps, tight closed hi-hats, driving future house bassline, wide supersaw chords, plucky synth lead melody, offbeat bass stabs, heavy sidechain compression, white noise build, euphoric drop, second drop bigger than first, club dance groove",
"mood": "euphoric club energy, high voltage night drive, dance floor rush, sweet crush turned explosive, uplifting release, bouncy and hyped, anthemic festival feeling, nonstop momentum",
"extra": "male singing with bright energetic tone, punchy rhythmic delivery, clear pronunciation, catchy repeating hook, strong anthemic chorus, modern EDM vocal style, forward and confident, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
},
"test_filler_fix": {
"_comment": "衬音修复测试 demo:90s 短时长,验证 lean 模式下 RULE_NO_FILLER 是否生效。",
"style": "future house electronic pop, upbeat EDM pop",
"bpm": 128,
"key": "C major",
"duration": 130,
"instruments": "punchy four on the floor kick, bouncy offbeat synth bass, crisp claps, tight closed hi-hats, warm supersaw chords, plucky synth lead, heavy sidechain, euphoric drop",
"mood": "upbeat euphoric, dance floor energy, sweet and catchy, uplifting release",
"extra": "male singing with bright sweet youthful tone, mid high register, energetic rhythmic delivery, clear pronunciation, catchy hooks, solo male vocal only, no female vocals, no backup vocals, no choir, no duet, no vocal chops"
}
}
View File
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
"""全局索引 catalog.jsonl:只存元数据,可从 runs 重建。"""
import json
import os
import re
from . import paths as pmod
def catalog_path(cfg):
p = cfg["paths"].get("catalog_file") or "songforge/index/catalog.jsonl"
return pmod.under_workflows(p)
def day_dir(runs_root, day=None):
"""runs_root/YYYY-MM-DD/"""
import datetime
if not day:
day = datetime.date.today().isoformat()
return os.path.join(runs_root, day)
def allocate_run_dir(runs_root, run_id, day=None):
"""占位 data/runs/YYYY-MM-DD/<run_id>/,返回绝对路径。"""
d = day_dir(runs_root, day)
pmod.ensure_dir(d)
path = os.path.join(d, run_id)
os.makedirs(path, exist_ok=False)
return path
def find_run_dir(runs_root, run_id):
"""在按日目录、_migrated、扁平根下查找 run 目录。"""
rid = (run_id or "").strip().rstrip("/\\")
if not rid:
return None
if os.path.isdir(rid) and os.path.isfile(os.path.join(rid, "manifest.json")):
return os.path.abspath(rid)
base = os.path.basename(rid.replace("/", os.sep))
if not os.path.isdir(runs_root):
return None
# 直接子目录(兼容旧扁平)
cand = os.path.join(runs_root, base)
if os.path.isfile(os.path.join(cand, "manifest.json")):
return cand
# 按日
for day in os.listdir(runs_root):
day_path = os.path.join(runs_root, day)
if not os.path.isdir(day_path):
continue
cand = os.path.join(day_path, base)
if os.path.isfile(os.path.join(cand, "manifest.json")):
return cand
# _migrated 下也可能套一层
if day in ("_migrated",):
for sub in os.listdir(day_path):
cand = os.path.join(day_path, sub)
if os.path.basename(cand) == base and \
os.path.isfile(os.path.join(cand, "manifest.json")):
return cand
# 全树兜底
for root, dirs, files in os.walk(runs_root):
if os.path.basename(root) == base and "manifest.json" in files:
return root
return None
def _entry_from_manifest(rundir, man):
results = man.get("results") or []
seeds = [r.get("seed") for r in results if r.get("seed") is not None]
files = []
for r in results:
for fn in r.get("files") or []:
files.append(fn)
day = None
m = re.search(r"(\d{4}-\d{2}-\d{2})", rundir.replace("\\", "/"))
if m:
day = m.group(1)
elif man.get("created"):
day = str(man["created"])[:10]
return {
"run_id": man.get("run_id") or os.path.basename(rundir),
"date": day,
"title": man.get("title"),
"style": man.get("style"),
"bpm": man.get("bpm"),
"key": man.get("key"),
"duration": man.get("duration"),
"seeds": seeds,
"qc_verdict": man.get("qc_verdict"),
"audio_files": files,
"path": rundir.replace("\\", "/"),
}
def append_entry(cfg, entry):
path = catalog_path(cfg)
pmod.ensure_dir(os.path.dirname(path))
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
return path
def update_qc_verdict(cfg, run_id, verdict):
"""重写 catalog:更新匹配 run_id 的 qc_verdict。"""
path = catalog_path(cfg)
if not os.path.isfile(path):
return
rows = []
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
except ValueError:
continue
if row.get("run_id") == run_id:
row["qc_verdict"] = verdict
rows.append(row)
with open(path, "w", encoding="utf-8") as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
def rebuild(cfg):
"""扫描 runs_dir,重写 catalog.jsonl。"""
runs_root = pmod.under_workflows(cfg["paths"]["runs_dir"])
entries = []
if os.path.isdir(runs_root):
for root, dirs, files in os.walk(runs_root):
if "manifest.json" not in files:
continue
mp = os.path.join(root, "manifest.json")
try:
with open(mp, encoding="utf-8") as f:
man = json.load(f)
except (ValueError, OSError):
continue
entries.append(_entry_from_manifest(root, man))
entries.sort(key=lambda e: (e.get("date") or "", e.get("run_id") or ""))
path = catalog_path(cfg)
pmod.ensure_dir(os.path.dirname(path))
with open(path, "w", encoding="utf-8") as f:
for e in entries:
f.write(json.dumps(e, ensure_ascii=False) + "\n")
return path, len(entries)
def list_entries(cfg, day=None, limit=50):
path = catalog_path(cfg)
if not os.path.isfile(path):
return []
out = []
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
except ValueError:
continue
if day and row.get("date") != day:
continue
out.append(row)
out.reverse()
return out[:limit]
def entry_from_gen(rundir, manifest):
return _entry_from_manifest(rundir, manifest)
+120
View File
@@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""ComfyUI 执行引擎:提交、轮询、重试、结果回收。只用标准库。"""
import json
import time
import urllib.error
import urllib.request
from .errors import JobFailed, ServerError
class Engine(object):
def __init__(self, server, timeout=3600, poll_interval=10,
submit_retries=3, logger=None):
self.server = server.rstrip("/")
self.timeout = timeout
self.poll_interval = poll_interval
self.submit_retries = submit_retries
self.log = logger
def _log(self, level, msg, **kw):
if self.log:
self.log.log(level, msg, **kw)
def _get(self, path, timeout=15):
url = self.server + path
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
raise ServerError("GET %s 返回 %s" % (path, e.code), e.read().decode()[:400])
except Exception as e:
raise ServerError("GET %s 失败: %s" % (path, e))
def _post(self, path, payload, timeout=60):
url = self.server + path
req = urllib.request.Request(
url, data=payload.encode("utf-8"),
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
raise ServerError("POST %s 返回 %s" % (path, e.code),
e.read().decode()[:600])
except Exception as e:
raise ServerError("POST %s 失败: %s" % (path, e))
def health(self):
"""返回 (ok, info)。不抛异常,供 doctor 使用。"""
try:
stats = self._get("/system_stats")
except ServerError as e:
return False, str(e)
dev = (stats.get("devices") or [{}])[0]
info = {
"device": dev.get("name", "?"),
"vram_total_gb": round(dev.get("vram_total", 0) / 1024 ** 3, 1),
"comfyui_version": stats.get("system", {}).get("comfyui_version", "?"),
}
q = self._get("/queue")
info["queue_running"] = len(q.get("queue_running") or [])
info["queue_pending"] = len(q.get("queue_pending") or [])
return True, info
def queue(self):
return self._get("/queue")
def submit(self, prompt_json):
"""prompt_json 可以是 dict(API prompt)或 JSON 字符串。
最终 POST /prompt 的 body 是 {"prompt": <prompt对象>}。"""
if isinstance(prompt_json, str):
prompt_json = json.loads(prompt_json)
payload = self._post("/prompt", json.dumps({"prompt": prompt_json}, ensure_ascii=False))
pid = payload.get("prompt_id")
if not pid:
raise ServerError("提交成功但未返回 prompt_id",
json.dumps(payload, ensure_ascii=False)[:400])
return pid
def submit_retry(self, prompt_json):
last = None
for attempt in range(1, self.submit_retries + 1):
try:
return self.submit(prompt_json)
except ServerError as e:
last = e
self._log("warn", "提交失败(%d/%d): %s"
% (attempt, self.submit_retries, e))
if attempt < self.submit_retries:
time.sleep(3 * attempt)
raise last
def wait(self, pid, on_progress=None):
"""轮询直到任务结束。返回 (outputs, errors)。"""
t0 = time.time()
tick = 0
while time.time() - t0 < self.timeout:
time.sleep(self.poll_interval)
tick += 1
h = self._get("/history/" + pid)
if pid not in h:
if on_progress:
on_progress(tick, int(time.time() - t0))
continue
rec = h[pid]
errs = [m for m in rec.get("status", {}).get("messages", [])
if m[0] == "execution_error"]
outs = [a.get("filename") for o in rec.get("outputs", {}).values()
for a in o.get("audio", [])]
if errs:
raise JobFailed("任务执行失败: %s" % pid,
json.dumps(errs, ensure_ascii=False)[:600])
return outs, rec
raise JobFailed("等待超时(%ds): %s" % (self.timeout, pid))
def object_info(self, class_type):
try:
return self._get("/object_info/" + class_type)
except ServerError:
return {}
+38
View File
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
"""内核异常。cli_driver 只捕获这些,不吞系统异常。"""
class SongForgeError(Exception):
"""所有内核错误的基类。"""
class ConfigError(SongForgeError):
"""配置非法,或试图使用被禁用的模型。"""
class RuleViolation(SongForgeError):
"""违反生歌铁律。"""
class LyricDensityError(RuleViolation):
"""歌词字数与目标时长不匹配(死心塌地时长对应关系)。"""
class LexiconError(RuleViolation):
"""歌词命中身份禁用词。"""
class ServerError(SongForgeError):
"""ComfyUI 不可达或返回异常。"""
def __init__(self, msg, detail=""):
super().__init__(msg)
self.detail = detail
class JobFailed(SongForgeError):
"""任务在 ComfyUI 侧执行失败。"""
def __init__(self, msg, detail=""):
super().__init__(msg)
self.detail = detail
+119
View File
@@ -0,0 +1,119 @@
# -*- coding: utf-8 -*-
"""路径解析。ComfyUI 根优先配置/环境变量,再自动探测。"""
import datetime
import os
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
_MARKERS = (
os.path.join("models", "checkpoints"),
os.path.join("custom_nodes"),
os.path.join("user", "default"),
)
def comfy_root(explicit=None, cfg=None):
"""返回 ComfyUI 根目录绝对路径。"""
if explicit:
return os.path.abspath(explicit)
if cfg:
cr = (cfg.get("paths") or {}).get("comfy_root")
if cr:
return os.path.abspath(cr)
env = os.environ.get("SONGFORGE_COMFY_ROOT")
if env:
return os.path.abspath(env)
cur = ROOT
for _ in range(6):
hits = sum(1 for m in _MARKERS if os.path.isdir(os.path.join(cur, m)))
if hits >= 2:
return cur
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
return os.path.dirname(os.path.dirname(os.path.dirname(ROOT)))
def model_path(root, *parts):
return os.path.join(root, "models", *parts)
def user_default(root):
return os.path.join(root, "user", "default")
def output_dir(root, prefix="MyMusic"):
return os.path.join(root, "output", *prefix.split("/"))
def music_dir(cfg=None, root=None):
"""音频成品目录:paths.music_dir 或 ComfyUI/output/<output_prefix>。"""
if cfg:
md = (cfg.get("paths") or {}).get("music_dir")
if md:
return os.path.abspath(md)
root = root or comfy_root(cfg=cfg)
return output_dir(root, cfg["paths"].get("output_prefix", "MyMusic"))
root = root or comfy_root()
return output_dir(root, "MyMusic")
def under_workflows(rel, root=None):
if not rel:
raise ValueError("路径为空")
if os.path.isabs(rel):
return os.path.normpath(rel)
base = root if root is not None else ROOT
return os.path.normpath(os.path.join(base, rel))
def ensure_dir(path):
os.makedirs(path, exist_ok=True)
return path
def today_iso():
return datetime.date.today().isoformat()
def day_subdir(base, day=None):
"""base/YYYY-MM-DD/"""
return os.path.join(base, day or today_iso())
def tmp_today(cfg, day=None):
"""paths.tmp_dir/YYYY-MM-DD/,确保存在。"""
base = under_workflows(cfg["paths"]["tmp_dir"])
return ensure_dir(day_subdir(base, day))
def path_layout(cfg):
"""从配置展开本包目录布局(绝对路径)。"""
p = cfg["paths"]
cro = comfy_root(cfg=cfg)
return {
"workflows": ROOT,
"comfy_root": cro,
"runs": under_workflows(p["runs_dir"]),
"tmp": under_workflows(p["tmp_dir"]),
"tmp_today": day_subdir(under_workflows(p["tmp_dir"])),
"lyrics": under_workflows(p["lyrics_dir"]),
"qc_cache": under_workflows(p["qc_cache_dir"]),
"style_cache": under_workflows(p["style_cache_dir"]),
"index": under_workflows(p.get("index_dir") or "songforge/index"),
"catalog": under_workflows(
p.get("catalog_file") or "songforge/index/catalog.jsonl"),
"baseline": under_workflows(
p.get("baseline_dir") or "songforge/config/baseline"),
"audio_out": music_dir(cfg, cro),
"pkg": under_workflows("songforge"),
}
# 根目录不应出现的过程文件(doctor WARN)
ROOT_JUNK_NAMES = ("qc.json", "run.log", "manifest.json")
+208
View File
@@ -0,0 +1,208 @@
# -*- coding: utf-8 -*-
"""songforge 核心包 - 工作流构建器"""
import copy
import json
import os
import re
from .errors import ConfigError
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# UI widgets_values 顺序 -> API inputs 键名。按节点类型分别声明,避免混用。
WIDGET_MAP = {
"CheckpointLoaderSimple": ["ckpt_name"],
"LoraLoader": ["lora_name", "strength_model", "strength_clip"],
"ModelSamplingAuraFlow": ["shift", "sampling"],
"EmptyAceStep1.5LatentAudio": ["seconds", "batch_size"],
"TextEncodeAceStepAudio1.5": [
"tags", "lyrics", "seed", "bpm", "duration", "timesignature",
"language", "keyscale", "generate_audio_codes", "cfg_scale",
"temperature", "top_p", "top_k", "min_p",
],
"KSampler": ["seed", "control_after_generate", "steps", "cfg",
"sampler_name", "scheduler", "denoise"],
"SaveAudio": ["filename_prefix"],
"SaveAudioAdvanced": ["filename_prefix", "format"],
"VAEDecodeAudio": [],
}
def load_template(path_or_name):
"""path_or_name 可以是 workflows 下的文件名,也可以是绝对路径。"""
p = path_or_name
if not os.path.isabs(p):
p = os.path.join(ROOT, p)
if not os.path.exists(p):
raise ConfigError("workflow 模板不存在: %s" % p)
with open(p, encoding="utf-8") as f:
return json.load(f)
def convert(ui_wf):
"""UI 格式 workflow dict -> API prompt dict。"""
links = ui_wf["links"]
# 兼容两种格式:ComfyUI 对象数组 (dict) 或 元组列表 [id, origin, target, ...]
if links and isinstance(links[0], dict):
link_src = {l["id"]: [l["origin_id"], l["origin_slot"]] for l in links}
else:
link_src = {l[0]: [l[1], l[2]] for l in links}
api = {}
for n in ui_wf["nodes"]:
cls = n["type"]
keys = WIDGET_MAP.get(cls)
inputs = {}
if keys:
wv = n.get("widgets_values", [])
if len(wv) < len(keys):
raise ConfigError(
"节点 %s (%s) 的 widgets_values 只有 %d 项,期望 %d 项;"
"模板可能被手改过"
% (n.get("id"), cls, len(wv), len(keys)))
for k, v in zip(keys, wv):
inputs[k] = v
for inp in n.get("inputs", []):
lid = inp.get("link")
if lid is not None and lid in link_src:
src = link_src[lid]
inputs[inp["name"]] = [str(src[0]), src[1]]
api[str(n["id"])] = {"class_type": cls, "inputs": inputs}
return api
def find_node(ui_wf, class_type):
for n in ui_wf["nodes"]:
if n["type"] == class_type:
return n
return None
def render(wf_result):
"""build_workflow 返回的 dict -> API prompt。"""
if isinstance(wf_result, dict) and "workflow" in wf_result and "class_type" not in wf_result:
return convert(wf_result["workflow"])
return convert(wf_result)
def build_workflow(template, *, title, tags, lyrics, seed, bpm, duration,
keyscale, sampler, encode, model, output_prefix,
output_format, language="zh", timesignature="4"):
"""按节点类型定位并写入参数。不依赖固定节点 ID。
model["lora"] 为空 / None 时直接跳过 LoraLoader:
我们用的 ace_step_1.5_turbo_swl_fused.safetensors 本身就是
"""
from ..config.loader import load
from ..rules.ironlaw import build_tags as _build_tags, build_lyrics, validate
from ..rules.ironlaw import build_chill_lyrics
# 1. 解析歌词章节
sections = []
lines = lyrics.split('\n')
current_tag = None
current_content = []
for line in lines:
line = line.strip()
if not line:
continue
tag_match = re.match(r'^\[(\w+(?:[-]\w+)?)\]$', line)
if tag_match:
if current_tag is not None and current_content:
sections.append((current_tag, '\n'.join(current_content)))
current_tag = tag_match.group(1)
current_content = []
else:
if current_tag is not None:
current_content.append(line)
if current_tag is not None and current_content:
sections.append((current_tag, '\n'.join(current_content)))
has_intro = lyrics.lstrip().lower().startswith('[intro]')
# 5. 组合工作流
workflow = copy.deepcopy(template)
# 从配置文件加载默认参数(single source of truth)
config = load()
model_cfg = config.get("model", {})
sampler_cfg = config.get("sampler", {})
encode_cfg = config.get("encode", {})
paths_cfg = config.get("paths", {})
# 合并参数来源: CLI/函数传入 > config > 硬coded 安全兜底
ckpt_name = model.get("checkpoint") or model_cfg.get("checkpoint", "ace_step_1.5_turbo_swl_fused.safetensors")
lora_name = model.get("lora") or model_cfg.get("lora", "")
lora_model_strength = model.get("lora_model_strength", model_cfg.get("lora_model_strength", 0.5))
lora_clip_strength = model.get("lora_clip_strength", model_cfg.get("lora_clip_strength", 0.5))
shift = sampler.get("shift", sampler_cfg.get("shift", 5.5))
sampling = sampler.get("sampling", sampler_cfg.get("sampling", "flow"))
steps = sampler.get("steps", sampler_cfg.get("steps", 28))
cfg = sampler.get("cfg", sampler_cfg.get("cfg", 2.0))
sampler_name = sampler.get("sampler_name", sampler_cfg.get("sampler_name", "euler"))
scheduler = sampler.get("scheduler", sampler_cfg.get("scheduler", "simple"))
denoise = sampler.get("denoise", sampler_cfg.get("denoise", 1.0))
batch_size = sampler.get("batch_size", sampler_cfg.get("batch_size", 1))
cfg_scale = encode.get("cfg_scale", encode_cfg.get("cfg_scale", 3.0))
temperature = encode.get("temperature", encode_cfg.get("temperature", 0.68))
top_p = encode.get("top_p", encode_cfg.get("top_p", 0.88))
top_k = encode.get("top_k", encode_cfg.get("top_k", 50))
min_p = encode.get("min_p", encode_cfg.get("min_p", 0.02))
generate_audio_codes = encode.get("generate_audio_codes", encode_cfg.get("generate_audio_codes", True))
output_format = output_format or paths_cfg.get("output_format", "flac")
# 遍历节点设置参数
for n in workflow["nodes"]:
if n["type"] == "CheckpointLoaderSimple":
n["widgets_values"] = [ckpt_name]
elif n["type"] == "LoraLoader":
# 设置 LoRA 加载器参数
if "widgets_values" in n:
n["widgets_values"] = [lora_name, lora_model_strength, lora_clip_strength]
elif n["type"] == "ModelSamplingAuraFlow":
if "widgets_values" in n:
n["widgets_values"] = [shift, sampling]
elif n["type"] == "EmptyAceStep1.5LatentAudio":
if "widgets_values" in n:
n["widgets_values"] = [duration, batch_size]
elif n["type"] == "TextEncodeAceStepAudio1.5":
if "widgets_values" in n:
# 构建 widgets_values: tags, lyrics, seed, bpm, duration, timesignature,
# language, keyscale, generate_audio_codes, cfg_scale, temperature, top_p, top_k, min_p
n["widgets_values"] = [
tags,
lyrics,
seed,
bpm,
duration,
timesignature,
language,
keyscale,
generate_audio_codes,
cfg_scale,
temperature,
top_p,
top_k,
min_p,
]
elif n["type"] == "KSampler":
if "widgets_values" in n:
n["widgets_values"] = [seed, "fixed", steps, cfg,
sampler_name, scheduler, denoise]
elif n["type"] == "SaveAudioAdvanced":
if "widgets_values" in n:
n["widgets_values"] = [output_prefix, output_format]
elif n["type"] == "SaveAudio":
if "widgets_values" in n:
n["widgets_values"] = [output_prefix]
return {
"success": True,
"workflow": workflow,
"lyrics": lyrics,
"tags": tags,
"has_intro": has_intro,
}
View File
View File
View File
+269
View File
@@ -0,0 +1,269 @@
# songforge 使用手册
本手册讲「怎么跑」。参数铁律、踩坑与版本史见上级目录 [`生歌规则.md`](../../生歌规则.md)(唯一规范)。
工作目录始终:
```powershell
cd D:\CodeFiles\Thinking\ComfyUI-MiniMaxH3\user\default\workflows
```
入口:
```powershell
python songforge\songforge.py <命令> [选项]
```
音频栈(librosa/torch 等)在 `C:\comfyui-venv\Scripts\python.exe`;主 CLI 用系统 Python,`qc` 会自动起子进程调用 venv。
---
## 1. 标准流水线
```text
doctor → target → 写歌词 → check → gen → qc --baseline
```
| 步 | 命令 | 失败时 |
|----|------|--------|
| 体检 | `doctor` | 先起 ComfyUI;缺模型按提示补齐 |
| 查字数 | `target --style pop --bpm 104 --dur 180` | 按打印区间写歌词 |
| 校验 | `check --style … --title … --lyrics-file …` | **只改歌词**,不许改采样参数 |
| 生成 | `gen …` | 看 `data/runs/<日>/<id>/run.log`;服务挂了再 `doctor` |
| 验收 | `qc --run gen-… --baseline` | FAIL 修歌/重跑,不放宽阈值 |
| 索引 | `catalog` / `catalog --rebuild` | 查歌名/风格/BPM/QC 结论 |
`qc` 报告里的 `style_fam` / `style_conf` 是弱参考,**不会**单独导致 FAIL。对外不要把 PASS 说成「风格已验证」——当前风格物理保证主要是实测 BPM 对齐。
---
## 2. 命令详解
### 2.1 doctor
检查:服务可达、GPU、锁定 checkpoint/LoRA、采样参数、时长区间。
```powershell
python songforge\songforge.py doctor
python songforge\songforge.py doctor --server http://127.0.0.1:8188
```
### 2.2 styles
列出 `config/styles.json` 里可用的 `--style` 键及默认 bpm/key/duration。
```powershell
python songforge\songforge.py styles
```
### 2.3 target
按 BPM、时长、密度档算出音节放行区间(硬校验同源公式)。
```powershell
python songforge\songforge.py target --style pop --bpm 104 --dur 180
python songforge\songforge.py target --bpm 92 --dur 165 --profile sparse
```
常用:`--style` / `--bpm` / `--dur` / `--profile`(`sparse` = 人声点缀档)。
### 2.4 check
纯本地:铁律词条、前奏注入结果、词典、密度窗口。不连 ComfyUI。
```powershell
python songforge\songforge.py check --style pop --title 夜班 --lyrics-file songforge\_archive\lyrics_corpus\某歌.txt
```
与 `gen` 共用同一套 `assemble` + `do_validate`,check 过再 gen,避免白跑。
### 2.5 gen
组装 tags/歌词(自动注入 8 小节器乐前奏与铁律)→ 写 workflow → 提交 ComfyUI → 写 manifest。
```powershell
python songforge\songforge.py gen `
--style pop --title 夜班 `
--lyrics-file path\to\lyrics.txt `
--seeds 1
```
| 参数 | 说明 |
|------|------|
| `--style` | 风格键,必填 |
| `--title` | 歌名,必填 |
| `--lyrics-file` / `--lyrics` | 二选一 |
| `--bpm` `--key` `--dur` | 覆盖风格默认 |
| `--instruments` `--mood` | 覆盖风格描述 |
| `--seeds` | 多 seed 选优(默认 1) |
| `--seed` | 起始 seed |
| `--dry-run` | 只写 workflow / payload_preview,不提交 |
| `--language` | zh / ja / en |
| `--instrumental` | 纯器乐(密度闸门不适用) |
| `--chill-vocal` | 低音吟唱路径 |
| `--lean-tags` | 精简 tags 路径 |
| `--profile sparse` | 稀疏密度档 |
| `--log-level` / `--quiet` | 日志 |
产出目录:`songforge\data\runs\YYYY-MM-DD\gen-YYYYMMDD-HHMMSS-mmm\`
| 文件 | 内容 |
|------|------|
| `run.log` | JSONL 结构化日志 |
| `lyrics.txt` | 最终歌词(含注入前奏) |
| `tags.txt` | 最终 tags(含铁律) |
| `wf_*.json` | 提交用 UI workflow |
| `manifest.json` | seed / prompt_id / 输出路径 / intro_bars 等 |
| `payload_preview.json` | 仅 `--dry-run` |
| `qc.json` | `qc --run` 后写入 |
音频在 ComfyUI:`output\MyMusic\`(可用 `local.json` 的 `music_dir` 覆盖)。
### 2.6 qc
验收。测量在 `tools/qc_worker.py`,由 venv Python 子进程执行。
```powershell
python songforge\songforge.py qc --run gen-20261009-120000-123 --baseline
python songforge\songforge.py qc --run songforge\data\runs\2026-10-09\gen-20261009-120000-123 --baseline
python songforge\songforge.py qc --file D:\path\to\song.flac --dur 165 --baseline
```
| 参数 | 说明 |
|------|------|
| `--run` | run_id,或 `data/runs/...` 路径(两者都行) |
| `--file` | 直接验单个 flac |
| `--baseline` | **交付必带**:与 8 首已认可老歌对照声线 |
| `--baseline-only` / `--save-baseline` | 校准/固化软阈值(维护用) |
本机路径:`config/local.json` 的 `qc_python` / `comfy_root`;或环境变量 `SONGFORGE_QC_PYTHON`、`SONGFORGE_COMFY_ROOT`。
### 2.7 runs / show / catalog
```powershell
python songforge\songforge.py runs
python songforge\songforge.py catalog --day 2026-10-09
python songforge\songforge.py catalog --rebuild
python songforge\songforge.py show gen-20261009-120000-123
```
### 2.8 selftest
不连 ComfyUI 生成,跑配置优先级、模型锁定、铁律、密度、回归等。怀疑 CLI 坏了再跑。
```powershell
python songforge\songforge.py selftest
```
---
## 3. 配置与目录
### 3.0 目录(项目 vs 数据)
| 级别 | 用途 | 默认(相对 workflows) |
|------|------|------------------------|
| 项目 | 新歌词 | `songforge/input/lyrics/` |
| 项目 | QC/风格基线 | `songforge/config/baseline/` |
| 本机 | 绝对路径覆盖 | `songforge/config/local.json`(gitignore) |
| 数据 | gen 产物 | `songforge/data/runs/YYYY-MM-DD/` |
| 数据 | 临时日志 | `songforge/data/tmp/YYYY-MM-DD/` |
| 数据 | 全局索引 | `songforge/index/catalog.jsonl` |
| 数据 | QC 缓存 | `songforge/cache/qc/` |
| 外部 | 音频成品 | `<ComfyUI>/output/MyMusic/` |
Agent 远程做歌请读 `songforge/AGENTS.md`。
### 3.1 该改哪里
| 想改 | 文件 |
|------|------|
| 模型 / 采样 / 时长区间 / 相对路径 | `config/default.json` |
| 本机 Comfy 根 / QC Python / 音乐目录 | `config/local.json`(从 example 复制) |
| 风格 bpm/key/乐器/情绪 | `config/styles.json` |
| 禁词 | `config/lexicon.json` |
| QC 软阈值 | `config/baseline/qc_baseline.json`(工具校准,勿手拍) |
| workflow 节点拓扑 | 配置里的模板名(在 workflows 根下) |
**不要**为改参数去改 `data/runs/` 里某次生成的 JSON——下次 `gen` 会按模板+配置重写。
### 3.2 优先级
```text
命令行 > SONGFORGE_* 环境变量 > config/local.json > config/default.json > DEFAULTS
```
常用环境变量:`SONGFORGE_SERVER`、`SONGFORGE_COMFY_ROOT`、`SONGFORGE_QC_PYTHON`、`SONGFORGE_MUSIC_DIR`、`SONGFORGE_SHIFT`、`SONGFORGE_RUNS`。
### 3.3 已锁定默认(勿随意改)
```json
"model.checkpoint": "ace_step_1.5_turbo_swl_fused.safetensors",
"model.lora": "swl_voice_best_ep257.safetensors",
"sampler": { "shift": 5.5, "steps": 28, "cfg": 2.0 },
"encode.temperature": 0.68,
"song.duration_range": [150, 200]
```
`denied_checkpoints` 含 aio / yue2;doctor 会拦。
---
## 4. 歌词怎么写
1. 先 `target` 拿音节区间,正文填进区间(偏稀 → 模型用拖腔填空)。
2. **不要**手写 `[intro]` / Instrumental 前奏 / tags——`assemble` 会注入。
3. 段落用 `[verse]` `[chorus]` 等结构标记即可。
4. `check` 不过 → 改字数或结构,不要动 shift/steps。
密度档:
- 默认:人声填满(中文说唱/流行)
- `--profile sparse`:音乐主导、人声点缀(勿用默认档硬套)
---
## 5. 日志
`log/logger.py`:控制台一行可读 + `runs/<run_id>/run.log` JSONL。
字段示例:`ts`、`run_id`、`level`、`msg`,以及 `seed` / `prompt_id` / `title` 等。
```powershell
python songforge\songforge.py gen ... --log-level debug
python songforge\songforge.py gen ... --quiet
```
排错优先打开对应 `run.log` 和 `manifest.json`,不要只看控制台最后一行。
---
## 6. 失败速查
| 现象 | 处理 |
|------|------|
| doctor 服务不可达 | 启动 ComfyUI(8188) |
| check 密度不匹配 | 改歌词到 target 区间 |
| gen KeyError / 提交失败 | 用 CLI,勿手转 API;跑 `selftest` |
| 改了参数没生效 | 是否改了 workflow JSON?应改 `config/*.json` |
| qc 声线 FAIL 且 voice_nn=null | 漏了 `--baseline` |
| 开头仍是人声 | 看规范第 0 章;重 gen,勿放宽 QC |
| CLI 本身崩溃 | `--dry-run` 拿 workflow 到手跑;或 fallback 旧 `remake_v5.py`(勿删) |
改规则/配置前先备份:
```powershell
python songforge\tools\backup.py --note "说明" --from-root D:\CodeFiles\Thinking\ComfyUI-MiniMaxH3 AGENTS.md 生歌规则.md
```
---
## 7. 与规范文档的分工
| 文档 | 职责 |
|------|------|
| `生歌规则.md` | 铁律、模型、采样、密度公式、踩坑、版本 |
| `README.md` | 项目入口、30 秒上手 |
| `docs/使用手册.md` | 命令、目录、配置操作、流水线 |
行为冲突时以 `生歌规则.md` + `config/default.json` 为准;手册只描述当前 CLI 行为。
View File
+1
View File
@@ -0,0 +1 @@
+11
View File
@@ -0,0 +1,11 @@
# 歌词投放目录
新歌词 `.txt` 放这里,生成时:
```powershell
cd D:\CodeFiles\Thinking\ComfyUI-MiniMaxH3\user\default\workflows
python songforge\songforge.py check --style pop --title 歌名 --lyrics-file songforge\input\lyrics\歌名.txt
```
历史素材库在 `../_archive/lyrics_corpus/`(只读)。
不要手写 `[intro]` / tags,CLI 会注入。
+66
View File
@@ -0,0 +1,66 @@
[hook]
楼下那条街
灯比人更早亮
楼下那条街
走到天亮也不慌
[verse]
早高峰挤成沙丁鱼
耳机里没有音乐
新闻又在讲
谁的账户少了
我妈说隔壁的娃
买房了 我还在漂
我说妈 别急
我在这儿挺好的
[rap]
一二三四 别数了
五六七八 你困不困
房租 水电 通勤
三行数字压着人
我滑过整个广场
风从耳边过去
心里那点堵 散了
[hook]
楼下那条街
灯比人更早亮
楼下那条街
走到天亮也不慌
[verse]
同事问我打算
我说我打算先睡
简历投了三十份
只回了两个
不是我不努力
是城市太拥挤
有人住在我楼上
有人挤在我心里
[chorus]
楼下那条街
灯比人更早亮
楼下那条街
走到天亮也不慌
楼下那条街
总有一盏灯亮着
[rap]
如果明天会更好
那就再睡五分钟
如果明天不会
那就现在唱出声
这条街的人
等我这一脚
[chorus]
楼下那条街
灯比人更早亮
楼下那条街
走到天亮也不慌
[outro]
灯还没关
我还没走
+65
View File
@@ -0,0 +1,65 @@
[hook]
灯还亮着 灯还亮着
有人在等你回来
灯还亮着 灯还亮着
这一天还算温柔
[verse]
六点的闹钟响了
我躺着刷了三分钟
城市还在下雨
伞挤不过人群
昨天的方案被否了
机器写得比我快
我删掉那一段
留下笨的那版
[pre-chorus]
地铁挤成一张纸
工位挤成一格
我数着格子往前走
脚步没有停
[chorus]
灯还亮着 灯还亮着
有人在等你回来
灯还亮着 灯还亮着
这一天还算温柔
[verse]
房租又涨了一点
我把窗台的花挪了挪
外卖三十八块
吃完就早点睡
妈妈打来视频
我说明天一定回
挂了以后站一会
才敢关灯睡
[pre-chorus]
日子排成一队
队里没有我
但我还站着
就还在往前走
[chorus]
灯还亮着 灯还亮着
有人在等你回来
灯还亮着 灯还亮着
这一天还算温柔
[bridge]
如果世界一直在催
如果答案还没来
那就先把这盏灯
留给自己等待
[chorus]
灯还亮着 灯还亮着
总有人在等你回来
灯还亮着 灯还亮着
我们都不算失败
[outro]
灯还亮着
别急着睡
+68
View File
@@ -0,0 +1,68 @@
[verse]
闹钟响了三遍
我从床上弹起来
外卖车在楼下等
雨点砸在水花里
今天不想开会
只想快点到广场
换上那双旧板鞋
今天要练到天亮
[chorus]
去它妈的班
去它妈的会
下班才是我的
开始的时间
去它妈的班
去它妈的会
这一块水泥地
才是我的位置
[verse]
方案又被打回
说我不接地气
城市的灯太亮了
照不全我自己
房租卡在月底
工资卡在月初
中间那段日子
只能靠一顿饱饭
[chorus]
去它妈的班
去它妈的会
下班才是我的
开始的时间
去它妈的班
去它妈的会
这一块水泥地
才是我的位置
[rap]
一二三四 板子落地
五六七八 汗往下滴
不管它写什么
不管谁在看
一个动作三千遍
肌肉自己会归位
他们说我没出息
我在水泥上走出曲线
[chorus]
去它妈的班
去它妈的会
下班才是我的
开始的时间
去它妈的班
去它妈的会
这一块水泥地
才是我的位置
[bridge]
天台的风很大
我在这儿站一会
原来不做什么
也能站很久
[outro]
来啊 板子给我
View File
+89
View File
@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
"""结构化日志:控制台可读 + JSONL 落盘。run_id 贯穿一次运行的所有记录。
每次运行的日志写到 runs/<run_id>/run.log(JSONL),便于出问题时回溯。
"""
import datetime
import json
import os
import sys
LEVELS = {"debug": 10, "info": 20, "warn": 30, "error": 40}
class Run(object):
"""一次运行的上下文:run_id、目录、产物清单。"""
def __init__(self, run_id, root):
self.run_id = run_id
self.dir = os.path.join(root, run_id)
os.makedirs(self.dir, exist_ok=True)
def path(self, name):
return os.path.join(self.dir, name)
def save_json(self, name, obj):
p = self.path(name)
with open(p, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=1)
return p
def save_text(self, name, text):
p = self.path(name)
with open(p, "w", encoding="utf-8") as f:
f.write(text)
return p
class Logger(object):
def __init__(self, run=None, level="info", quiet=False, stream=None,
log_path=None):
self.run = run
self.level = LEVELS.get(level, 20)
self.quiet = quiet
self.stream = stream or sys.stdout
self._fh = None
path = log_path
if path is None and run:
path = run.path("run.log")
if path:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
self._fh = open(path, "w", encoding="utf-8")
def log(self, level, msg, **fields):
if LEVELS.get(level, 20) < self.level:
return
ts = datetime.datetime.now().strftime("%H:%M:%S")
rid = self.run.run_id if self.run else "-"
extra = " ".join("%s=%s" % (k, v) for k, v in fields.items())
line = "%s [%s] run=%s %s%s" % (
ts, level.upper(), rid, msg,
(" " + extra) if extra else "")
if level in ("warn", "error"):
print(line, file=self.stream, flush=True)
elif not self.quiet:
print(line, file=self.stream, flush=True)
if self._fh:
rec = dict(ts=datetime.datetime.now().isoformat(timespec="seconds"),
run_id=rid, level=level, msg=msg, **fields)
self._fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
self._fh.flush()
def debug(self, msg, **f):
self.log("debug", msg, **f)
def info(self, msg, **f):
self.log("info", msg, **f)
def warn(self, msg, **f):
self.log("warn", msg, **f)
def error(self, msg, **f):
self.log("error", msg, **f)
def close(self):
if self._fh:
self._fh.close()
self._fh = None
View File
+224
View File
@@ -0,0 +1,224 @@
# -*- coding: utf-8 -*-
"""歌词容量与时长对应关系。
这是"死心塌地"的部分:不看模型表现,只按音乐结构算出这段时间到底能唱多少字,
填字必须落进区间,否则 check 直接报错,不给侥幸。
推导:
每小节秒数 = 60 / BPM * 每小节拍数
总小节 = 时长 / 每小节秒数
可唱小节 = (总小节 - 前奏小节) * 可唱比例
音节容量 = 可唱小节 * 每小节音节区间
填充率 = 实际音节 / 容量上限(仅诊断用,不作为放行闸门)
阈值来源(重要):
syllable_per_bar_* 与 ideal_line_syllable 不是理论推导,而是用 remake_v5.py 里
8 首用户已实际生成并认可的歌反推出来的真实工作区间:
每可唱小节音节 4.56 ~ 7.64 (均值 6.17)
每句音节 5.9 ~ 7.4 (均值 6.7)
改这两个数之前请先跑 selftest 的"实歌回归",否则会误杀已验证可生成的歌词。
历史坑:曾按理论值设成"每拍 2.6~4.4 音节、每句下限 7",结果 8 首实歌
全部被判歌词过少(实测每拍只有 1.14~1.91 音节)。理论值不能当阈值用。
"""
import math
import re
from ..core.errors import LyricDensityError
SEC_RE = re.compile(r"^\[(intro|instrumental|verse|pre-?chorus|chorus|hook|"
r"rap|bridge|break|breakdown|build|drop|final drop|"
r"post-?drop|outro|final hook|final chorus)\]",
re.I)
def lyric_len(text):
cn = sum(1 for c in text if "\u4e00" <= c <= "\u9fff")
en = len(re.findall(r"[A-Za-z][A-Za-z'\-]*", text))
return cn, en
def kana_count(text):
"""假名音节数:平假名 + 片假名 + 半角浊音。
为什么必须单独计数(中日混合歌词实测踩到的坑):
lyric_len 只认汉字和英文字母,日文假名一个都不数。
"お誕生日おめでとう 一棠ちゃん" 这行真实可唱约 13 音节,
原实现只算得到 5 个汉字 + 1 个英文字(2),少算一大截,
于是 check 把一份写满的正常歌词误判成"歌词过少",
写词的人只能靠加无意义的字去凑数,越凑越空洞。
排除两类字符,它们不独立占音节:
1. 小书写假名 ぁぃぅぇぉゃゅょゎ ァィゥェォャュョヮ ヵヶ
以及促音 っ —— 它们依附在前一个音节上。
2. 长音符号 ー ゝゞヽヾ —— 它们延长前一个音,不新增音节。
"""
small = (u"\u3041\u3043\u3045\u3047\u3049\u3063"
u"\u3083\u3085\u3087\u308e"
u"\u30a1\u30a3\u30a5\u30a7\u30a9\u30c3"
u"\u30e3\u30e5\u30e7\u30ee\u30f5\u30f6"
u"\u30fc\u309d\u309e\u30fd\u30fe")
body = "".join(c for c in text if c not in small)
return len(re.findall(r"[\u3041-\u309F\u30A0-\u30FF\uFF66-\uFF9F]", body))
def syllable(text):
"""可唱近似音节数:汉字*1 + 英文词*2 + 假名*1。"""
cn, en = lyric_len(text)
return cn + en * 2 + kana_count(text)
def only_lyrics(text):
"""剥掉结构标记与 [Instrumental: ...] 描述,只留真正被唱的正文。"""
out = []
for ln in text.split("\n"):
s = ln.strip()
if not s or s.startswith("["):
continue
out.append(s)
return "\n".join(out)
def sections(text):
"""按结构标记切段,返回 [(tag, body_text)]。"""
out = []
tag = "unknown"
buf = []
for ln in text.split("\n"):
s = ln.strip()
if s.startswith("["):
m = SEC_RE.match(s)
if m:
if buf:
out.append((tag, "\n".join(buf).strip()))
tag = m.group(1).lower()
buf = []
continue
buf.append(ln)
if buf:
out.append((tag, "\n".join(buf).strip()))
return out
def bars(duration, bpm, beats_per_bar=4):
return duration / (60.0 / bpm * beats_per_bar)
def pick(cfg_lyrics, profile=None):
"""按档取出密度阈值。
default 档直接用 lyrics 顶层字段(保持向后兼容);
其它档从 lyrics.profiles.<name> 覆盖顶层同名字段后返回。
这样加档不用改任何计算公式,只加配置。
"""
if not profile or profile == "default":
return cfg_lyrics
prof = (cfg_lyrics.get("profiles") or {}).get(profile)
if not prof:
raise LyricDensityError(
"未知密度档 '%s',可选:default / %s"
% (profile, ", ".join(sorted((cfg_lyrics.get("profiles") or {})))))
out = dict(cfg_lyrics)
out.update({k: v for k, v in prof.items() if not k.startswith("_")})
out["_profile"] = profile
return out
def capacity(duration, bpm, cfg_lyrics):
"""返回该时长/BPM 下的音节区间与结构量。
区间由"每可唱小节音节数"决定,这是唯一闸门;填充率只做诊断。
"""
beats = 4 # time_signature 固定 4 拍
total = bars(duration, bpm, beats)
sing = max(1.0, (total - cfg_lyrics["intro_bars"])
* cfg_lyrics["sing_bar_ratio"])
lo = sing * cfg_lyrics["syllable_per_bar_min"]
hi = sing * cfg_lyrics["syllable_per_bar_max"]
return dict(total_bars=total, sing_bars=sing, lo=lo, hi=hi,
beats_per_bar=beats)
def window(duration, bpm, cfg_lyrics):
"""check 实际放行的音节窗口(整数化)。
对外所有"该写多少字"的表述都必须来自这里,避免文档与代码不一致。
"""
cap = capacity(duration, bpm, cfg_lyrics)
lo, hi = cap["lo"], cap["hi"]
if hi < lo:
lo = hi = cap["lo"]
return int(math.ceil(lo)), int(math.floor(hi))
def analyse(lyrics, duration, bpm, cfg_lyrics):
body = only_lyrics(lyrics)
syl = syllable(body)
lines = [l for l in body.split("\n") if l.strip()]
cap = capacity(duration, bpm, cfg_lyrics)
wlo, whi = window(duration, bpm, cfg_lyrics)
fill = syl / cap["hi"] if cap["hi"] else 0.0
per_line = syl / len(lines) if lines else 0.0
return dict(syllables=syl, lines=len(lines), per_line=round(per_line, 1),
fill=round(fill, 3), total_bars=round(cap["total_bars"], 1),
sing_bars=round(cap["sing_bars"], 1),
lo=int(cap["lo"]), hi=int(cap["hi"]),
win_lo=wlo, win_hi=whi)
def target_words(duration, bpm, cfg_lyrics):
"""给写词的人用的目标字数区间(死心塌地填字依据)。
返回 (建议字数, 下限, 上限)。下限上限与 check 实际放行窗口完全一致。
建议字数取实测均值 6.17 音节/小节对应的位置,不取理论中点,
因为理论中点会把歌写得比已验证作品明显更稀或明显更密。
"""
cap = capacity(duration, bpm, cfg_lyrics)
wlo, whi = window(duration, bpm, cfg_lyrics)
mid = cap["sing_bars"] * 6.17 # 实测工作区均值
mid = max(wlo, min(mid, whi))
return int(mid), wlo, whi
def check(lyrics, duration, bpm, cfg_lyrics):
"""死心塌地校验。返回问题列表,空列表代表通过。"""
st = analyse(lyrics, duration, bpm, cfg_lyrics)
errs = []
if st["syllables"] == 0:
errs.append("正文为空,没有任何可唱歌词")
return errs, st
if st["syllables"] < st["win_lo"]:
errs.append(
"歌词过少:%d 音节(放行下限 %d,还缺约 %d)。"
"%ds / %dBPM 共 %.0f 小节,前奏占 %d 小节,实际可唱 %.0f 小节,"
"按实测密度需要 %d~%d 音节。字太少模型会硬拉长音、抢拍、吞字。"
% (st["syllables"], st["win_lo"], st["win_lo"] - st["syllables"],
duration, bpm, st["total_bars"], cfg_lyrics["intro_bars"],
st["sing_bars"], st["win_lo"], st["win_hi"]))
elif st["syllables"] > st["win_hi"]:
errs.append(
"歌词过多:%d 音节(放行上限 %d,超出约 %d)。"
"实际可唱 %.0f 小节,按实测密度上限只到 %d 音节。"
"字太多会加速、丢字、句尾被吃掉。"
% (st["syllables"], st["win_hi"],
st["syllables"] - st["win_hi"],
st["sing_bars"], st["win_hi"]))
if st["per_line"] > cfg_lyrics["line_syllable_max"]:
errs.append("平均每句 %.1f 音节,超过上限 %d,换气点不足,容易抢拍"
% (st["per_line"], cfg_lyrics["line_syllable_max"]))
elif st["per_line"] < cfg_lyrics["ideal_line_syllable"][0]:
errs.append("平均每句 %.1f 音节偏少(实测下限约 %.1f),句子太碎,"
"容易出现拖腔填充"
% (st["per_line"],
cfg_lyrics["ideal_line_syllable"][0]))
return errs, st
def enforce(lyrics, duration, bpm, cfg_lyrics):
errs, st = check(lyrics, duration, bpm, cfg_lyrics)
if errs:
raise LyricDensityError(
"歌词与时长不匹配(死心塌地时长对应关系):\n - "
+ "\n - ".join(errs))
return st
+34
View File
@@ -0,0 +1,34 @@
[verse]
ooh ooh
mmm mmm
ooh ooh
low and slow
[chorus]
ooh
let it go
ooh ooh
hold me tight
[post-drop]
mmm
under the light
mmm mmm
without a doubt
[chorus]
ooh ooh
let it go
ooh ooh
hold me tight
[bridge]
mmm
ooh ooh
mmm
ooh ooh
[outro]
ooh
mmm
ooh
View File
+1133
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
"""songforge CLI 入口(被 ComfyUI 升级清空后重建)。
python songforge\songforge.py doctor
python songforge\songforge.py gen --style pop --title 夜班 --lyrics-file a.txt
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from songforge.cli.main import main # noqa: E402
if __name__ == "__main__":
sys.exit(main())
+208
View File
@@ -0,0 +1,208 @@
# -*- coding: utf-8 -*-
"""带时间戳的备份工具。任何文档/配置/脚本更新前必须先跑它。
python songforge/tools/backup.py 生歌规则.md LLM_Wiki.md
python songforge/tools/backup.py --note "加 songforge CLI 章节" AGENTS.md
python songforge/tools/backup.py --from-root D:\\CodeFiles\\Thinking\\ComfyUI-MiniMaxH3
python songforge/tools/backup.py --restore bak\\20261004-120000
python songforge/tools/backup.py --list
产物:workflows/bak/<YYYYMMDD-HHMMSS-毫秒>/<原相对路径>
恢复:python songforge/tools/backup.py --restore <备份目录>
坑位记录:
- 早期版本把路径压平成 "目录__文件.bak",文件一多就分不清谁是谁,
且 AGENTS.md 在仓库根、不在 workflows 下,会退化成 ..__..__..__AGENTS.md.bak。
现在保留完整目录树:workflows 内的文件按相对路径存放,
仓库根的文件统一放在 <ROOT>/ 下,一眼能看出来源。
- 路径分隔符统一转成 "/",Windows 与 Linux 读 manifest 结果一致。
"""
import datetime
import json
import os
import shutil
import sys
WF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))) # .../user/default/workflows
BAK = os.path.join(WF_ROOT, "bak")
def stamp():
"""毫秒精度:同一秒内连续备份两次不会互相覆盖。"""
return datetime.datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3]
def comfy_root():
"""workflows 的上三级 = ComfyUI 根。"""
return os.path.dirname(
os.path.dirname(
os.path.dirname(WF_ROOT)
)
)
def rel_under(path):
"""返回可还原、正斜杠的相对路径。
- workflows 内:songforge/cli/main.py
- ComfyUI 根: ROOT__/AGENTS.md
- 根之外: ABS__/D/somewhere/file.md
"""
path = os.path.abspath(path)
for base, prefix in ((WF_ROOT, ""), (comfy_root(), "ROOT__/")):
rel = os.path.relpath(path, base)
if not rel.startswith(".."):
return prefix + rel.replace(os.sep, "/")
rel = path.replace(":", "").replace(os.sep, "/").lstrip("/")
return "ABS__/" + rel
def backup(paths, note=""):
"""复制文件到 bak/<时间戳>/,保留原目录树,返回备份目录。"""
# 坑位:原来用 exist_ok=True,同一毫秒内连续两次备份会落进同一目录,
# 上一次的 _manifest.json 直接被覆盖,恢复时就少了一份。改成原子创建。
base = stamp()
for n in range(0, 100):
cand = os.path.join(BAK, base if n == 0 else "%s-%d" % (base, n + 1))
try:
os.makedirs(cand, exist_ok=False)
dst_dir = os.path.abspath(cand)
break
except FileExistsError:
continue
else:
raise RuntimeError("无法在 %s 下分配备份目录" % BAK)
items = []
for p in paths:
p = os.path.abspath(p)
if not os.path.exists(p):
print(" [skip] 不存在: %s" % p)
continue
rel = rel_under(p)
dst = os.path.join(dst_dir, *rel.split("/"))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(p, dst)
items.append(dict(src=p, bak=dst, rel=rel,
size=os.path.getsize(dst)))
print(" [ok] %s" % rel)
with open(os.path.join(dst_dir, "_manifest.json"), "w",
encoding="utf-8") as f:
json.dump(dict(stamp=os.path.basename(dst_dir), note=note,
items=items), f, ensure_ascii=False, indent=1)
print("备份完成 -> %s (%d 个文件)" % (dst_dir, len(items)))
return dst_dir
def restore(bak_dir):
"""按 manifest 把文件拷回原位。"""
bak_dir = os.path.abspath(bak_dir)
mpath = os.path.join(bak_dir, "_manifest.json")
if not os.path.exists(mpath):
print("找不到 manifest: %s" % mpath)
return 1
with open(mpath, encoding="utf-8") as f:
m = json.load(f)
for it in m["items"]:
if not os.path.exists(it["bak"]):
print(" [miss] 备份件丢失: %s" % it["bak"])
continue
os.makedirs(os.path.dirname(it["src"]), exist_ok=True)
shutil.copy2(it["bak"], it["src"])
print(" [restore] %s" % it["rel"])
print("恢复完成 <- %s" % bak_dir)
return 0
def list_bak():
if not os.path.isdir(BAK):
print("还没有任何备份: %s" % BAK)
return 1
rows = []
for name in sorted(os.listdir(BAK), reverse=True):
mp = os.path.join(BAK, name, "_manifest.json")
if not os.path.isfile(mp):
continue
with open(mp, encoding="utf-8") as f:
m = json.load(f)
rows.append((name, len(m.get("items", [])), m.get("note", "")))
if not rows:
print("备份目录为空: %s" % BAK)
return 1
for name, n, note in rows:
print(" %s %2d 个 %s" % (name, n, note))
return 0
def _expand(root, patterns):
out = []
for pat in patterns:
full = os.path.join(root, pat.replace("/", os.sep))
if os.path.isdir(full):
for dirpath, _, files in os.walk(full):
for fn in files:
if fn.endswith(".pyc"):
continue
out.append(os.path.join(dirpath, fn))
else:
out.append(full)
return out
def main(argv):
if not argv:
print(__doc__)
return 1
if argv[0] in ("-h", "--help"):
print(__doc__)
return 0
if argv[0] == "--restore":
if len(argv) < 2:
print(__doc__)
return 1
return restore(argv[1])
if argv[0] == "--list":
return list_bak()
note = ""
root = None
while argv and argv[0].startswith("--"):
opt = argv[0]
if opt == "--note" and len(argv) >= 2:
note = argv[1]
argv = argv[2:]
elif opt == "--from-root" and len(argv) >= 2:
root = os.path.abspath(argv[1])
argv = argv[2:]
else:
print("未知参数: %s" % opt)
print(__doc__)
return 1
if not argv:
print(__doc__)
return 1
backup(_expand(root, argv) if root else argv, note)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+88
View File
@@ -0,0 +1,88 @@
# -*- coding: utf-8 -*-
"""从历史脚本 remake_v5.py 抽出 8 首已认可老歌的基线资料。
用途:QC 需要"歌词正文"才能算召回率。没有歌词,coverage() 恒等于 0,
老歌基线就退化成"召回 >= 0%",等于没有基线——这种假放行比不放行更危险。
同时抽出 bpm / duration / key,让 QC 能按真实 8 小节算理论前奏秒数。
不重新生成音频,只读源码里的 BODY / META。
输出:config/baseline/qc_baseline_old.json
源脚本路径可用环境变量 SONGFORGE_REMAKE_V5 覆盖。
"""
import importlib.util
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
_PKG = os.path.dirname(HERE)
OUT = os.path.join(_PKG, "config", "baseline", "qc_baseline_old.json")
_DEFAULT_SRC = os.path.join(
os.environ.get("USERPROFILE", os.environ.get("HOME", "")),
r".trae-cn\work\6ab523de391489c168050edc\remake_v5.py")
SRC = os.environ.get("SONGFORGE_REMAKE_V5") or _DEFAULT_SRC
BRACKET = re.compile(r"^\[[^\]]*\]")
CJK = re.compile(r"[\u4e00-\u9fff]")
def _load_remake():
if not os.path.isfile(SRC):
print("[错误] 找不到 remake_v5.py: %s" % SRC)
print(" 设置 SONGFORGE_REMAKE_V5=完整路径 后重试")
return None
spec = importlib.util.spec_from_file_location("remake_v5", SRC)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m) # __main__ 有守卫,不会提交任何任务
return m
def body_text(m, title):
"""把 BODY[title] 折成纯歌词正文。"""
seen, keep = set(), []
for _tag, text in m.BODY[title]:
if "Instrumental" in text:
continue
for line in text.split("\n"):
line = BRACKET.sub("", line).strip()
if not line or not CJK.search(line):
continue
if line in seen:
continue
seen.add(line)
keep.append(line)
return "\n".join(keep)
def main():
m = _load_remake()
if m is None:
return 2
items = []
for title, seed, bpm, key, dur, style in m.META:
items.append(dict(
title=title,
file="v5_%s_swl_00001.flac" % title,
bpm=bpm, key=key, duration=dur,
group="old",
lyrics=body_text(m, title),
))
os.makedirs(os.path.dirname(OUT), exist_ok=True)
with open(OUT, "w", encoding="utf-8") as f:
json.dump(dict(note="8 首用户已认可老歌的基线资料,"
"由 tools/make_baseline.py 从 remake_v5.py 抽取",
items=items), f,
ensure_ascii=False, indent=1)
for it in items:
n = len(CJK.findall(it["lyrics"]))
print("%-8s bpm=%-4s dur=%-4s 汉字=%d" % (it["title"], it["bpm"],
it["duration"], n))
print("\nwrote %s" % OUT)
return 0
if __name__ == "__main__":
sys.exit(main() or 0)
+183
View File
@@ -0,0 +1,183 @@
# -*- coding: utf-8 -*-
"""用历史已认可作品建风格质心语料 -> config/baseline/style_ref.json
跑法(必须在 ComfyUI venv 的 Python 下):
C:\\comfyui-venv\\Scripts\\python.exe tools\\make_style_ref.py
音乐目录 / 输出路径读 config/default.json + local.json(勿写死盘符)。
"""
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
# 坑位:songforge.py(CLI 入口)和 songforge/(包)同名,
# tools/ 内部互相引用一律走文件路径加载。
sys.path.insert(0, HERE)
import qc_style # noqa: E402
_PKG = os.path.dirname(HERE)
def _paths_from_config():
paths = {}
for name in ("default.json", "local.json"):
p = os.path.join(_PKG, "config", name)
if not os.path.isfile(p):
continue
with open(p, encoding="utf-8") as f:
blob = json.load(f)
paths.update(blob.get("paths") or {})
music = paths.get("music_dir") or os.environ.get("SONGFORGE_MUSIC_DIR")
if not music:
cro = paths.get("comfy_root") or os.environ.get("SONGFORGE_COMFY_ROOT")
if cro:
music = os.path.join(
cro, "output", paths.get("output_prefix") or "MyMusic")
if not music:
music = os.path.join(
os.path.dirname(os.path.dirname(_PKG)), "output", "MyMusic")
out = os.path.join(_PKG, "config", "baseline", "style_ref.json")
cache = os.path.join(_PKG, "cache", "style")
return os.path.abspath(music), out, cache
MUSIC, OUT, CACHE = _paths_from_config()
# 前缀白名单:确认过的直接给 family,避免子串规则误伤
EXACT = {
"smile13": "pop",
"hit10": "pop",
"dy10": "pop",
"col2": "pop",
"punk4": "punk",
"niaopunk": "punk",
"urbanhiphop": "hiphop",
"chillhiphop": "hiphop",
"chillhiphopen": "hiphop",
"chillhiphopja": "hiphop",
"upbeathiphop": "hiphop",
"funkyhiphop": "hiphop",
"discofunk": "hiphop",
"partytrap": "hiphop",
"smoothhiphop": "hiphop",
"喜剧hiphop": "hiphop",
"欧式hiphop": "hiphop",
}
# 出现在前缀里就归某家族(前面已排除精确表未命中的)
SUBSTR = (
("punk", "punk"),
("hiphop", "hiphop"),
("trap", "hiphop"),
)
SEED = re.compile(r"_\d{5}\.flac$", re.I)
# 只收每个 seed 序列的第一首。同源的 _00002/_00003 全收进来,语料就被
# 少数几首歌按 seed 数投票,质心被拉偏(踩过:172 个文件其实只有 30 来首歌)。
FIRST_SEED = re.compile(r"_00001\.flac$", re.I)
def family_of(name):
"""从文件名解析风格家族,解析不出来返回 None(直接排除)。"""
stem = SEED.sub("", name)
head = stem.split("_")[0]
if head in EXACT:
return EXACT[head]
low = head.lower()
for key, fam in SUBSTR:
if key in low:
return fam
return None
def main():
if not os.path.isdir(MUSIC):
print("[错误] 找不到音频目录 %s" % MUSIC)
return 2
files = sorted(f for f in os.listdir(MUSIC) if f.lower().endswith(".flac"))
picked = []
for f in files:
fam = family_of(f)
if not fam:
continue
if not FIRST_SEED.search(f): # 只收每首歌的第一个 seed
continue
p = os.path.join(MUSIC, f)
if not os.path.isfile(p):
continue
picked.append((f, fam, p))
if not picked:
print("[错误] 一首都没匹配上,检查 EXACT / SUBSTR 是否还匹配文件名")
return 2
print("语料候选 %d 首,开始算特征(每首几秒)..." % len(picked))
os.makedirs(CACHE, exist_ok=True)
items = []
for i, (f, fam, p) in enumerate(picked, 1):
cp = os.path.join(CACHE, f + ".json")
# 缓存 key 带上音频 mtime + 特征列表,音频换了或特征改了都会自动失效
stamp = "%s|%s" % (os.path.getmtime(p), ",".join(qc_style.FEATURES))
vec = None
if os.path.isfile(cp):
try:
with open(cp, encoding="utf-8") as fh:
blob = json.load(fh)
if blob.get("key") == stamp:
vec = blob["vec"]
except Exception:
vec = None
if vec is None:
try:
# expect_bpm=None:历史文件没有可靠的 BPM 记录,靠自身中位数定折叠锚点,
# 保证语料里的 tempo 尺度自洽。新歌的 BPM 对齐由 qc_worker 单独判。
vec, _raw = qc_style.features(p, expect_bpm=None)
except Exception as exc:
print(" [%d/%d] 跳过 %s -> %s: %s"
% (i, len(picked), f, type(exc).__name__, exc))
continue
with open(cp, "w", encoding="utf-8") as fh:
json.dump(dict(key=stamp, vec=vec), fh)
items.append(dict(file=f, family=fam, vec=vec))
print(" [%d/%d] %-44s %-6s tempo=%5.1f flat=%.4f"
% (i, len(picked), f[:44], fam, vec["tempo"], vec["flatness"]))
counts = {}
for it in items:
counts[it["family"]] = counts.get(it["family"], 0) + 1
print("按家族统计:%s" % counts)
for fam in qc_style.FAMILIES:
if counts.get(fam, 0) < 3:
print("[错误] %s 只有 %d 首,建不出可信质心(至少 3)"
% (fam, counts.get(fam, 0)))
return 2
ref = qc_style.build(items)
with open(OUT, "w", encoding="utf-8") as f:
json.dump(ref, f, ensure_ascii=False, indent=1)
loo = ref["loo"]
print("")
print("已写出 %s" % OUT)
print("样本 %d(%d 首不同的歌),分组留一准确率 %.1f%%,trusted=%s"
% (len(items), loo["n_songs"], loo["acc"] * 100, ref["trusted"]))
print("分家族:%s" % json.dumps(loo["per_family"], ensure_ascii=False))
print("混淆矩阵(行=真实,列=判成):")
for fam, row in sorted(loo["confusion"].items()):
print(" %-7s %s" % (fam, json.dumps(row, ensure_ascii=False)))
if not ref["trusted"]:
print("")
print("[结论] 风格判定不可信,只写进报告当参考,不当放行闸门。")
print(" 风格的第一物理保证是实测 BPM 与设定 BPM 对齐(QC 的 bpm_rel_tol)。")
print(" 注意:语料里 pop 的 chill/disco/funk 变体和 hiphop 制作手法本就连续,")
print(" 分组 LOO 总体约 60~67%、单家族最低约 43%,"
"这是语料重叠,不是分类器没调好。")
return 0
if __name__ == "__main__":
sys.exit(main())
+416
View File
@@ -0,0 +1,416 @@
# -*- coding: utf-8 -*-
"""风格特征与风格分类 —— 只吃 librosa,纯数值,不碰 demucs/whisper。
为什么单独一个文件:
songforge 主链路是零重依赖的,风格判定属于"生成后验收"的一部分,
必须在 venv 侧跑。把它独立出来,`qc_worker.py` 和
`tools/make_style_ref.py` 共用同一套取特征逻辑——否则"建语料"和
"验收"各写一份,特征对不上,分类结果就是自欺欺人。
风格怎么判(重要,不要改成拍脑袋的阈值):
这里不做"频谱质心 > X 就是朋克"这种单指标硬判。做法是拿历史里
已经按风格命名、并且用户听过没否掉的歌当语料,逐首算同一套特征,
按稳健标准化后建三个风格质心(pop / punk / hiphop),用最近质心
分类,并做留一验证(LOO)把准确率一起存下来。
准确率不够高时,报告里如实写"风格判定不可信",只当参考不当闸门。
坑位记录:
1. 速度必须做八度折叠。实测 `晚风不加班`(设定 86 BPM)会被判成
170.5 BPM,正好是 2 倍——librosa 的 onset 包络在半速拍子上会
锁到二倍拍。直接比设定值会把这个风格判死。
2. 频谱类特征跨度极大(质心 1400~6000 Hz),必须取 log 再标准化,
否则质心一项就主导了整段欧氏距离。
3. perc_ratio 用 HPSS 的打击成分占比。朋克的军鼓+失真吉他、
hiphop 的 kick+hi-hat 都会偏高,流行的人声+弦乐偏低。
单看这个不如 BPM 有区分度,但作为辅助项能压掉误判。
4. 特征里绝对不能有"人声轨 / 混音轨 能量比"。带标签的历史语料有 30~50 首,
每一首都跑 demucs 要花几十分钟,而且 demucs 对不同混音的分离程度
本身就不一致,这个比值混进去是纯噪声。风格只看混音轨。
"""
import os
import re
import numpy as np
FAMILY = {
"pop": "pop",
"punk": "punk",
"emopunk": "punk",
"urbanhiphop": "hiphop",
"chillhiphop": "hiphop",
"partyrap": "hiphop",
"funkhiphop": "hiphop",
"discofunk": "hiphop",
"jazzhiphop": "hiphop",
"guofeng": "hiphop",
}
FAMILIES = ("pop", "punk", "hiphop")
# 特征顺序即向量顺序,改这里必须重建 style_ref.json,否则老语料错位。
FEATURES = (
"tempo", # 八度折叠后的实测速度
"tempo_drift", # 速度稳定度(越小越稳)
"centroid", # log 频谱质心 -> 亮/暗
"rolloff", # log 85% rolloff -> 高频能量
"hf_ratio", # >6kHz 能量占比 -> 亮泽/嘶叫
"lf_ratio", # <150Hz 能量占比 -> 低频厚度/sub
"dynamic", # 动态范围 dB
"onset_density", # 每秒击打数
"perc_ratio", # HPSS 打击成分占比
"flatness", # 谱平坦度 -> 噪声/失真成分(朋克嘶叫会抬高)
"crest", # 峰值因子,越小越被压得平
)
_LOG_IDX = (FEATURES.index("centroid"), FEATURES.index("rolloff"))
# ------------------------------------------------------------------ 工具
def fold_bpm(value, ref):
"""把 value 折叠到离 ref 最近的八度。
坑位:librosa.beat 在慢速律动上会锁到 2 倍拍,不折叠会把 86 BPM 的歌
判成 170 BPM,然后"实测速度与设定偏差 98%",一个完全正常的歌被判死。
"""
if value is None or ref is None:
return value
try:
v = float(value)
r = float(ref)
except (TypeError, ValueError):
return value
# 坑位:非有限值和非正数会一路穿到 log2 里,log2(inf) 再喂给 round()
# 直接抛 OverflowError,把整首 QC 打断。下游只想要"折不动就原样返回"。
if not (np.isfinite(v) and np.isfinite(r)) or v <= 0 or r <= 0:
return v
ratio = r / v
if not np.isfinite(ratio) or ratio <= 0:
return v
return v * (2.0 ** round(np.log2(ratio)))
def fold_track(track, ref):
return np.array([fold_bpm(x, ref) for x in track], dtype=np.float32)
def _band_ratio(y, sr, lo, hi):
"""指定频带能量占比。用 rfft 直接算,比 mel 滤波器组省事也够稳。"""
if y.size < 256:
return 0.0
n = 1 << int(np.ceil(np.log2(y.size)))
sp = np.abs(np.fft.rfft(y, n)) ** 2
freqs = np.fft.rfftfreq(n, 1.0 / sr)
band = sp[(freqs >= lo) & (freqs < hi)].sum()
tot = sp.sum()
return float(band / tot) if tot > 0 else 0.0
# ------------------------------------------------------------------ 取特征
def tempo_of(y, sr, expect_bpm=None):
"""返回 (折叠后中位速度, 折叠后速度漂移)。expect_bpm 用来定折叠方向。"""
import librosa
y16 = y if sr == 16000 else librosa.resample(
np.asarray(y, dtype=np.float32), orig_sr=sr, target_sr=16000)
sr16 = 16000 if sr != 16000 else sr
oe = librosa.onset.onset_strength(y=y16, sr=sr16)
# librosa 0.11 起 beat.tempo 全是 keyword-only,位置传参直接 TypeError
tr = librosa.beat.tempo(onset_envelope=oe, sr=sr16, hop_length=512,
aggregate=None)
tr = np.asarray(tr, dtype=np.float32)
tr = tr[np.isfinite(tr) & (tr > 0)]
if not tr.size:
return 0.0, 0.0
raw_med = float(np.median(tr))
anchor = fold_bpm(raw_med, expect_bpm) if expect_bpm else raw_med
ft = fold_track(tr, anchor)
ft = ft[(ft > 0) & (ft < 400)]
if not ft.size:
return 0.0, 0.0
med = float(np.median(ft))
# 坑位:原来用 (p90 - p10) / median 算漂移,但 librosa 逐帧 tempo 的首尾
# 各有一拍宽的边界伪影,180s 的歌能攒出十几秒伪影区,被 p90/p10 一夹
# 就放大成 25%+ 的"漂移",而同一首歌按 10s 分块的中位全是设定值
# (实测 104.2/104.2,IQR=0)。改用中位绝对偏差,只对整体性的加速/
# 减速敏感,对边界伪影和偶发跳拍免疫。
drift = _mad_rel(ft, med)
return med, drift
def _mad_rel(track, med):
"""相对中位绝对偏差。返回 0.0 表示测不出整体漂移。"""
if track.size == 0 or med <= 0:
return 0.0
mad = float(np.median(np.abs(track - med)))
return (mad / med) if med > 0 else 0.0
def features(path, expect_bpm=None, cache_dir=None):
"""算一首歌的完整风格特征向量。
坑位:这个函数只允许吃混音轨(path)。不要往里塞 demucs 人声轨——
建历史语料时要对几十首老歌跑,塞进去就等于把风格判定绑死在分离质量上,
而 demucs 的分离程度本身随混音变化。声线由 qc_worker 单独负责。
"""
import librosa
import soundfile as sf
x, sr = sf.read(path, always_2d=True)
x = np.asarray(x, dtype=np.float32)
y = x.mean(axis=1)
dur = y.size / float(sr)
tempo, tempo_drift = tempo_of(y, sr, expect_bpm)
y16 = librosa.resample(y, orig_sr=sr, target_sr=16000)
sr16 = 16000
S = np.abs(librosa.stft(y16, n_fft=2048, hop_length=512)) + 1e-12
centroid = float(np.mean(librosa.feature.spectral_centroid(S=S, sr=sr16)))
rolloff = float(np.mean(librosa.feature.spectral_rolloff(
S=S, sr=sr16, roll_percent=0.85)))
# 谱平坦度:几何均值/算术均值。噪声化(失真、嘶叫、lo-fi)会把它抬高,
# 干净的钢琴/弦乐 pad 会压得很低。比 "高频能量占比" 更能区分失真音色。
gm = np.exp(np.mean(np.log(S), axis=0))
am = np.mean(S, axis=0)
flatness = float(np.mean(gm / am))
bs = 3 * sr
n = max(1, y.size // bs)
rmss = np.array([np.sqrt(np.mean(np.square(y[i * bs:(i + 1) * bs])) + 1e-20)
for i in range(n)], dtype=np.float32)
dyn = float(20 * np.log10(max(rmss.max(), 1e-9) / max(rmss.min(), 1e-9)))
oe = librosa.onset.onset_strength(y=y16, sr=sr16)
hop = 512
onset_density = float(len(librosa.onset.onset_detect(
onset_envelope=oe, sr=sr16, hop_length=hop)) / max(dur, 1e-6))
h, p = librosa.effects.hpss(y16)
perc_ratio = float(np.mean(np.abs(p)) /
max(np.mean(np.abs(h)) + np.mean(np.abs(p)), 1e-9))
peak = float(np.max(np.abs(y))) if y.size else 0.0
rms_all = float(np.sqrt(np.mean(np.square(y)) + 1e-20))
crest = float(20 * np.log10(max(peak, 1e-9) / max(rms_all, 1e-9)))
vec = {
"tempo": tempo,
"tempo_drift": tempo_drift,
"centroid": float(np.log10(max(centroid, 1.0))),
"rolloff": float(np.log10(max(rolloff, 1.0))),
"hf_ratio": _band_ratio(y16, sr16, 6000, sr16 / 2),
"lf_ratio": _band_ratio(y16, sr16, 20, 150),
"dynamic": dyn,
"onset_density": onset_density,
"perc_ratio": perc_ratio,
"flatness": flatness,
"crest": crest,
}
return vec, dict(centroid_hz=centroid, rolloff_hz=rolloff,
flatness=flatness,
onset_density=onset_density, perc_ratio=perc_ratio,
crest=crest, peak=peak)
def vector(vec):
return np.array([float(vec[k]) for k in FEATURES], dtype=np.float64)
# ------------------------------------------------------------------ 分类器
def _robust_scale(X):
"""中位数 + IQR 标准化。IQR 比 std 抗离群值。"""
med = np.median(X, axis=0)
q1 = np.percentile(X, 25, axis=0)
q3 = np.percentile(X, 75, axis=0)
iqr = np.maximum(q3 - q1, 1e-6)
return med, iqr
class StyleRef(object):
"""风格质心分类器。语料不足或 LOO 太低时 self.trusted=False。"""
def __init__(self, data):
self.note = data.get("note", "")
self.loo = data.get("loo", {})
self.items = data.get("items", [])
self.med = np.array(data["med"], dtype=np.float64)
self.iqr = np.array(data["iqr"], dtype=np.float64)
self.centroids = {k: np.array(v, dtype=np.float64)
for k, v in data["centroids"].items()}
self.counts = data.get("counts", {})
self.trusted = bool(data.get("trusted", False))
def _z(self, vec):
return (vector(vec) - self.med) / self.iqr
def classify(self, vec):
"""返回 (top_family, conf, dists)。conf 是 softmax 后的置信度。"""
z = self._z(vec)
dists = {}
for fam, c in self.centroids.items():
dists[fam] = float(np.sqrt(np.mean((z - c) ** 2)))
order = sorted(dists, key=lambda k: dists[k])
if not order:
return "", 0.0, dists
top = order[0]
e = {k: np.exp(-dists[k]) for k in order}
s = sum(e.values())
return top, float(e[top] / s if s > 0 else 0.0), dists
def nn(self, vec):
"""最近邻:返回 (最像的文件名, 与它的标准化距离, 该文件所属风格)。
这是声线之外第二个'像不像已认可作品'的信号,且自带人耳可解释性:
报告里能直接说出"最像 身体先听懂(urbanhiphop)"。
"""
z = self._z(vec)
best = ("", 1e9, "")
for it in self.items:
d = float(np.sqrt(np.mean((z - np.array(it["z"], dtype=np.float64)) ** 2)))
if d < best[1]:
best = (it["file"], d, it.get("family", ""))
return best
def load(path):
import json
if not path or not os.path.isfile(path):
return None
with open(path, encoding="utf-8") as f:
return StyleRef(json.load(f))
def _loo_groups(items):
"""按"歌"分组,而不是按文件。
坑位(踩过):最初按文件留一,得到 100% 准确率,一度以为分类器完美。
实际上同一首歌的 _00001/_00002/_00003 是同一首曲子的不同 seed,
音频高度同源。留一时只拿掉一个 seed,剩下 5 个"同款"还留在质心里,
等于让样本给自己作证,准确率必然虚高。
真正的留一必须整首拿掉——验证的是"没听过这首歌时能不能认出风格"。
"""
g = {}
for i, it in enumerate(items):
key = it.get("group") or _group_key(it.get("file", ""))
g.setdefault(key, []).append(i)
return g
def _group_key(file):
"""从文件名还原"这是哪一首歌"。dy10_城市晚安_swl_00001 -> dy10_城市晚安。
只用于分组,不是标签。
坑位:这里曾经把第一个下划线之前的前缀当"批次号"砍掉,只留后面的歌名。
结果 chillhiphop_慢慢来 和 hit10_慢慢来 被并成同一组,58 个文件只出
57 个组。留一验证时同一首歌的另一版本还留在质心里,样本等于给自己作证。
所以只剥 seed 号和模型后缀,风格前缀必须留着——它本来就是区分同名歌的
唯一信息。命名不规范时退回整条文件名也不会错。
"""
stem = file.rsplit(".flac", 1)[0]
stem = re.sub(r"_\d{5}$", "", stem) # 去掉 seed 号
stem = re.sub(r"_swl$", "", stem, flags=re.I) # 去掉模型后缀
return stem
def build(items, loo_min=0.65, fam_min=0.50):
"""由带标签的语料建质心,并做按歌分组的留一验证。
items: [{"file","family","bpm","vec"}]
返回可直接 json.dump 的字典。
关于阈值为什么这么严(实测数据,别拍脑袋改):
语料是 58 首歌(pop 35 / hiphop 16 / punk 7)。按歌分组留一后,
最好的组合也只到 ~65%:pop 有 4 成被判成 hiphop,hiphop 也有近
1 成被判成 pop。逐个特征看下来没有救——tempo 单项 49%、centroid
单项 39%,加特征、加权、改标准化都只在 60~67% 之间晃。
根因是语料本身重叠:pop 语料里的 chill/disco/funk 变体和 hiphop
语料在制作手法上就是连续的,不是分类器没调好。
所以这里刻意把门槛设高(loo_min=0.65 且每个家族都要 >=0.50),
让 trusted 大概率为 False —— 风格判定只写进报告当参考,不当放行闸门。
宁可报告里写"风格不可信",也不要一个 60% 准确率的分类器
拿去做"风格不符就判 FAIL"的闸门,那是在用假精度杀人。
风格的第一物理保证是实测 BPM 与设定 BPM 对齐(见 HARD.bpm_rel_tol)。
"""
import json
X = np.array([vector(it["vec"]) for it in items], dtype=np.float64)
med, iqr = _robust_scale(X)
Z = (X - med) / iqr
cent = {}
counts = {}
for fam in FAMILIES:
idx = [i for i, it in enumerate(items) if it["family"] == fam]
if not idx:
continue
counts[fam] = len(idx)
cent[fam] = np.mean(Z[idx], axis=0)
# ---- 按歌分组留一:整首拿掉,重算标准化和质心,再看它能不能被认对
groups = _loo_groups(items)
correct = 0
total = 0
per = {}
confusion = {}
for key, idxs in groups.items():
fam = items[idxs[0]]["family"]
keep = [i for i in range(len(items)) if i not in set(idxs)]
Xk = np.array([vector(items[i]["vec"]) for i in keep],
dtype=np.float64)
mk, ik = _robust_scale(Xk)
Zk = (Xk - mk) / ik
ck = {}
for f in FAMILIES:
j = [n for n, i in enumerate(keep) if items[i]["family"] == f]
if j:
ck[f] = np.mean(Zk[j], axis=0)
if len(ck) < 2:
continue
z = np.mean([(vector(items[i]["vec"]) - mk) / ik for i in idxs], axis=0)
d = {f: float(np.sqrt(np.mean((z - c) ** 2))) for f, c in ck.items()}
top = min(d, key=lambda k: d[k])
total += 1
good = top == fam
correct += 1 if good else 0
a = per.setdefault(fam, [0, 0])
a[1] += 1
a[0] += 1 if good else 0
cell = confusion.setdefault(fam, {})
cell[top] = cell.get(top, 0) + 1
acc = float(correct / total) if total else 0.0
fam_acc = {k: (v[0] / float(v[1]) if v[1] else 0.0) for k, v in per.items()}
# 总体准确率高也可能被某一个大类撑起来,所以每个家族都要单独过线。
# 三个家族里只要有一个基本认不出来(比如 punk 全被判成 pop),
# 这个分类器就不能拿去做风格闸门。
fam_ok = bool(fam_acc) and min(fam_acc.values()) >= fam_min
ref = dict(
features=list(FEATURES),
med=[float(x) for x in med],
iqr=[float(x) for x in iqr],
centroids={k: [float(x) for x in v] for k, v in cent.items()},
counts=counts,
items=[dict(file=it["file"], family=it["family"],
group=it.get("group") or _group_key(it["file"]),
bpm=it.get("bpm"), vec=it["vec"],
z=[float(x) for x in Z[i]])
for i, it in enumerate(items)],
loo=dict(acc=round(acc, 4), n=total, n_songs=len(groups),
mode="group-by-song",
per_family={k: dict(acc=round(v[0] / max(v[1], 1), 3), n=v[1])
for k, v in per.items()},
confusion=confusion,
fam_min=round(min(fam_acc.values()) if fam_acc else 0.0, 3)),
trusted=bool(total >= 9 and acc >= loo_min and fam_ok),
note=("由 tools/make_style_ref.py 在历史已认可歌上生成,不要手改。"
"trusted 只有在按歌分组 LOO >= %.0f%% 且每个家族都 >= %.0f%% 时为真;"
"实测语料 pop/hiphop 制作手法重叠,多轮尝试后总体约 60~67%%、"
"单家族最低约 43%%,"
"所以本文件通常 trusted=false —— 风格判定只当参考,"
"风格的第一物理保证是实测 BPM 与设定 BPM 对齐。"
% (loo_min * 100, fam_min * 100)),
)
return ref
+1216
View File
File diff suppressed because it is too large Load Diff
+220
View File
@@ -0,0 +1,220 @@
{
"id": "songforge-template-2026-10-09",
"revision": 6,
"last_node_id": 11,
"last_link_id": 30,
"nodes": [
{
"id": 0,
"type": "CheckpointLoaderSimple",
"pos": [50, -200],
"size": [300, 200],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{"name": "ckpt_name", "type": "STRING", "widget": {"name": "ckpt_name"}, "link": null}
],
"outputs": [
{"name": "MODEL", "type": "MODEL", "links": [0]},
{"name": "CLIP", "type": "CLIP", "links": [1, 2]},
{"name": "VAE", "type": "VAE", "links": [3]}
],
"widgets_values": ["ace_step_1.5_turbo_swl_fused.safetensors"]
},
{
"id": 1,
"type": "LoraLoader",
"pos": [300, -200],
"size": [300, 200],
"flags": {},
"order": 1,
"mode": 0,
"inputs": [
{"name": "lora_name", "type": "STRING", "widget": {"name": "lora_name"}, "link": null},
{"name": "strength_model", "type": "FLOAT", "widget": {"name": "strength_model"}, "link": null},
{"name": "strength_clip", "type": "FLOAT", "widget": {"name": "strength_clip"}, "link": null}
],
"outputs": [
{"name": "MODEL", "type": "MODEL", "links": [4]},
{"name": "CLIP", "type": "CLIP", "links": [5, 6]}
],
"widgets_values": ["swl_voice_best_ep257.safetensors", 0.5, 0.5]
},
{
"id": 2,
"type": "ModelSamplingAuraFlow",
"pos": [450, -200],
"size": [300, 200],
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{"name": "model", "type": "MODEL", "link": 0},
{"name": "shift", "type": "FLOAT", "widget": {"name": "shift"}, "link": null},
{"name": "sampling", "type": "COMBO", "widget": {"name": "sampling"}, "link": null}
],
"outputs": [
{"name": "MODEL", "type": "MODEL", "links": [7]}
],
"widgets_values": [1.73, "flow"]
},
{
"id": 3,
"type": "EmptyAceStep1.5LatentAudio",
"pos": [50, 100],
"size": [300, 200],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{"name": "seconds", "type": "FLOAT", "widget": {"name": "seconds"}, "link": null},
{"name": "batch_size", "type": "INT", "widget": {"name": "batch_size"}, "link": null}
],
"outputs": [
{"name": "LATENT", "type": "LATENT", "links": [8]}
],
"widgets_values": [150, 1]
},
{
"id": 4,
"type": "TextEncodeAceStepAudio1.5",
"pos": [450, 50],
"size": [500, 250],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{"name": "clip", "type": "CLIP", "link": 1},
{"name": "tags", "type": "STRING", "widget": {"name": "tags"}, "link": null},
{"name": "lyrics", "type": "STRING", "widget": {"name": "lyrics"}, "link": null},
{"name": "seed", "type": "INT", "widget": {"name": "seed"}, "link": null},
{"name": "bpm", "type": "INT", "widget": {"name": "bpm"}, "link": null},
{"name": "duration", "type": "FLOAT", "widget": {"name": "duration"}, "link": null},
{"name": "timesignature", "type": "COMBO", "widget": {"name": "timesignature"}, "link": null},
{"name": "language", "type": "COMBO", "widget": {"name": "language"}, "link": null},
{"name": "keyscale", "type": "COMBO", "widget": {"name": "keyscale"}, "link": null},
{"name": "generate_audio_codes", "type": "BOOLEAN", "widget": {"name": "generate_audio_codes"}, "link": null},
{"name": "cfg_scale", "type": "FLOAT", "widget": {"name": "cfg_scale"}, "link": null},
{"name": "temperature", "type": "FLOAT", "widget": {"name": "temperature"}, "link": null},
{"name": "top_p", "type": "FLOAT", "widget": {"name": "top_p"}, "link": null},
{"name": "top_k", "type": "INT", "widget": {"name": "top_k"}, "link": null},
{"name": "min_p", "type": "FLOAT", "widget": {"name": "min_p"}, "link": null}
],
"outputs": [
{"name": "CONDITIONING", "type": "CONDITIONING", "links": [9]}
],
"widgets_values": ["", "", 42, 120, 150, "4", "zh", "C major", true, 3.0, 0.68, 0.88, 50, 0.02]
},
{
"id": 5,
"type": "TextEncodeAceStepAudio1.5",
"pos": [450, 400],
"size": [500, 250],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{"name": "clip", "type": "CLIP", "link": 2},
{"name": "tags", "type": "STRING", "widget": {"name": "tags"}, "link": null},
{"name": "lyrics", "type": "STRING", "widget": {"name": "lyrics"}, "link": null},
{"name": "seed", "type": "INT", "widget": {"name": "seed"}, "link": null},
{"name": "bpm", "type": "INT", "widget": {"name": "bpm"}, "link": null},
{"name": "duration", "type": "FLOAT", "widget": {"name": "duration"}, "link": null},
{"name": "timesignature", "type": "COMBO", "widget": {"name": "timesignature"}, "link": null},
{"name": "language", "type": "COMBO", "widget": {"name": "language"}, "link": null},
{"name": "keyscale", "type": "COMBO", "widget": {"name": "keyscale"}, "link": null},
{"name": "generate_audio_codes", "type": "BOOLEAN", "widget": {"name": "generate_audio_codes"}, "link": null},
{"name": "cfg_scale", "type": "FLOAT", "widget": {"name": "cfg_scale"}, "link": null},
{"name": "temperature", "type": "FLOAT", "widget": {"name": "temperature"}, "link": null},
{"name": "top_p", "type": "FLOAT", "widget": {"name": "top_p"}, "link": null},
{"name": "top_k", "type": "INT", "widget": {"name": "top_k"}, "link": null},
{"name": "min_p", "type": "FLOAT", "widget": {"name": "min_p"}, "link": null}
],
"outputs": [
{"name": "CONDITIONING", "type": "CONDITIONING", "links": [10]}
],
"widgets_values": ["", "", 42, 120, 150, "4", "zh", "C major", true, 3.0, 0.68, 0.88, 50, 0.0],
"title": "negative"
},
{
"id": 6,
"type": "KSampler",
"pos": [1050, 100],
"size": [300, 250],
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{"name": "model", "type": "MODEL", "link": 3},
{"name": "seed", "type": "INT", "widget": {"name": "seed"}, "link": null},
{"name": "steps", "type": "INT", "widget": {"name": "steps"}, "link": null},
{"name": "cfg", "type": "FLOAT", "widget": {"name": "cfg"}, "link": null},
{"name": "sampler_name", "type": "COMBO", "widget": {"name": "sampler_name"}, "link": null},
{"name": "scheduler", "type": "COMBO", "widget": {"name": "scheduler"}, "link": null},
{"name": "positive", "type": "CONDITIONING", "link": 9},
{"name": "negative", "type": "CONDITIONING", "link": 10},
{"name": "latent_image", "type": "LATENT", "link": 8},
{"name": "denoise", "type": "FLOAT", "widget": {"name": "denoise"}, "link": null}
],
"outputs": [
{"name": "LATENT", "type": "LATENT", "links": [11]}
],
"widgets_values": [42, "fixed", 28, 2.0, "euler", "simple", 1.0]
},
{
"id": 7,
"type": "VAEDecodeAudio",
"pos": [1450, 100],
"size": [300, 200],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{"name": "samples", "type": "LATENT", "link": 11},
{"name": "vae", "type": "VAE", "link": 3}
],
"outputs": [
{"name": "AUDIO", "type": "AUDIO", "links": [12]}
],
"widgets_values": []
},
{
"id": 8,
"type": "SaveAudioAdvanced",
"pos": [1850, 100],
"size": [300, 200],
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{"name": "audio", "type": "AUDIO", "link": 12},
{"name": "filename_prefix", "type": "STRING", "widget": {"name": "filename_prefix"}, "link": null},
{"name": "format", "type": "COMBO", "widget": {"name": "format"}, "link": null}
],
"outputs": [
{"name": "AUDIO", "type": "AUDIO", "links": []}
],
"widgets_values": ["songforge/output", "wav"]
}
],
"links": [
{"id": 0, "origin_id": 0, "origin_slot": 0, "target_id": 1, "target_slot": 0, "type": "MODEL"},
{"id": 1, "origin_id": 0, "origin_slot": 1, "target_id": 4, "target_slot": 0, "type": "CLIP"},
{"id": 2, "origin_id": 0, "origin_slot": 1, "target_id": 5, "target_slot": 0, "type": "CLIP"},
{"id": 3, "origin_id": 1, "origin_slot": 0, "target_id": 2, "target_slot": 0, "type": "MODEL"},
{"id": 4, "origin_id": 2, "origin_slot": 0, "target_id": 6, "target_slot": 0, "type": "MODEL"},
{"id": 5, "origin_id": 2, "origin_slot": 1, "target_id": 5, "target_slot": 0, "type": "CLIP"},
{"id": 6, "origin_id": 2, "origin_slot": 2, "target_id": 5, "target_slot": 1, "type": "CLIP"},
{"id": 7, "origin_id": 3, "origin_slot": 0, "target_id": 7, "target_slot": 0, "type": "LATENT"},
{"id": 8, "origin_id": 4, "origin_slot": 0, "target_id": 8, "target_slot": 0, "type": "LATENT"},
{"id": 9, "origin_id": 8, "origin_slot": 0, "target_id": 9, "target_slot": 0, "type": "CONDITIONING"},
{"id": 10, "origin_id": 9, "origin_slot": 0, "target_id": 6, "target_slot": 0, "type": "CONDITIONING"},
{"id": 11, "origin_id": 5, "origin_slot": 0, "target_id": 6, "target_slot": 1, "type": "CONDITIONING"},
{"id": 12, "origin_id": 6, "origin_slot": 0, "target_id": 7, "target_slot": 0, "type": "CONDITIONING"},
{"id": 13, "origin_id": 7, "origin_slot": 0, "target_id": 8, "target_slot": 0, "type": "AUDIO"},
{"id": 14, "origin_id": 8, "origin_slot": 2, "target_id": 8, "target_slot": 1, "type": "AUDIO"}
],
"groups": [],
"definitions": {}
}