Files
swlandCursor 6d79ab93a2
selftest / selftest (push) Canceled after 0s
Add align/recheck/compare, plugins, and refresh Agent docs.
Wire deliver_report/listen_pack/retry hooks; gen --auto-retry and intro light check; make AGENTS_MIN the up-to-date agent entry with full command map.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-10 13:03:44 +08:00

93 lines
3.1 KiB
Python

# -*- coding: utf-8 -*-
"""把歌词正文音节对齐到 meter 放行窗口(一键凑密度)。"""
import re
from . import meter
_TAG = re.compile(r"^\[.+\]\s*$")
def _body_lines(text):
"""保留结构:返回 [(is_tag, line)]。"""
rows = []
for ln in text.split("\n"):
s = ln.rstrip("\r")
if _TAG.match(s.strip()):
rows.append((True, s))
else:
rows.append((False, s))
return rows
def _syllables_of_rows(rows):
body = "\n".join(ln for is_tag, ln in rows if not is_tag and ln.strip())
return meter.syllable(body)
def align_lyrics(lyrics, duration, bpm, cfg_lyrics, target=None):
"""调整正文行数使音节落在放行窗;返回 (新歌词, 诊断 dict)。
过少:循环复用已有可唱行(不造新词)。
过多:从末尾删可唱行(保留至少每段一行若可能)。
结构标记与空行尽量保留。
"""
cfg_lyrics = meter.pick(cfg_lyrics, None)
mid, wlo, whi = meter.target_words(duration, bpm, cfg_lyrics)
want = int(target) if target is not None else mid
want = max(wlo, min(want, whi))
rows = _body_lines(lyrics)
before = _syllables_of_rows(rows)
singable = [ln for is_tag, ln in rows if (not is_tag) and ln.strip()]
if not singable:
return lyrics, dict(before=before, after=before, want=want,
win_lo=wlo, win_hi=whi, changed=False,
note="无可唱行")
# 过少:在最后一个非空可唱行后插入副本
guard = 0
while _syllables_of_rows(rows) < wlo and guard < 500:
guard += 1
# 找最后一个可唱行位置
idx = None
for i in range(len(rows) - 1, -1, -1):
if (not rows[i][0]) and rows[i][1].strip():
idx = i
break
if idx is None:
break
donor = singable[guard % len(singable)]
rows.insert(idx + 1, (False, donor))
# 过多:从末尾删可唱行,但至少留 4 行
guard = 0
while _syllables_of_rows(rows) > whi and guard < 500:
guard += 1
n_sing = sum(1 for is_tag, ln in rows if (not is_tag) and ln.strip())
if n_sing <= 4:
break
for i in range(len(rows) - 1, -1, -1):
if (not rows[i][0]) and rows[i][1].strip():
rows.pop(i)
break
# 微调到 want 附近(仍夹在窗口内)
guard = 0
while _syllables_of_rows(rows) < want and _syllables_of_rows(rows) < whi \
and guard < 200:
guard += 1
idx = next((i for i in range(len(rows) - 1, -1, -1)
if (not rows[i][0]) and rows[i][1].strip()), None)
if idx is None:
break
rows.insert(idx + 1, (False, singable[guard % len(singable)]))
after = _syllables_of_rows(rows)
out = "\n".join(ln for _, ln in rows)
if not out.endswith("\n"):
out += "\n"
ok = wlo <= after <= whi
return out, dict(before=before, after=after, want=want,
win_lo=wlo, win_hi=whi, changed=(out != lyrics),
ok=ok, note=("ok" if ok else "仍未落入窗口"))