381 lines
18 KiB
Python
381 lines
18 KiB
Python
"""回归用例:平台声线生成必须尊重「性别」,且试听文本不能拿音色描述兜底。
|
||
|
||
现场缺陷(用户在平台资产库生成「李俊杰」男声):
|
||
1. IndexTTS2 是 zero-shot 克隆模型,**只有参考音频能决定音色**,表单里的
|
||
「性别 / 音色描述」对它是纯元数据。旧实现在这条声线没有参考音频时直接回退到
|
||
模型配置里的默认参考(一段女声),于是「男声」被生成成女声(实测中位基频 266.7 Hz),
|
||
界面还全绿不说一句话;
|
||
2. 旧实现拿 ``owner.description`` 当试听文本兜底,用户填的音色描述
|
||
「温和、语速中等,沉稳」被当成台词念了出来。
|
||
|
||
对应修复见 ``app/services/timbre.py``:生成前按性别挑参考(挑不到就明确报错),
|
||
生成后用基频自检并把结论写进素材元数据。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import subprocess
|
||
import tempfile
|
||
import wave
|
||
from pathlib import Path
|
||
|
||
from app.db import SessionLocal
|
||
from app.models import PlatformVoice
|
||
from app.services import timbre
|
||
from tests.conftest import MEDIA_ROOT, _make_image_png # noqa: F401 (png helper 复用)
|
||
|
||
|
||
# ------------------------------------------------------------------ 造音频小工具
|
||
def _sine_wav(frequency: float, seconds: float = 2.0, sample_rate: int = 24000) -> bytes:
|
||
"""用 ffmpeg 合成一段纯净正弦,作为「已知性别」的参考音频。"""
|
||
from app.services import ffmpeg as ff
|
||
|
||
if not ff.available():
|
||
return _fallback_wav(frequency, seconds, sample_rate)
|
||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as handle:
|
||
target = handle.name
|
||
try:
|
||
subprocess.run([ff.FFMPEG, "-hide_banner", "-loglevel", "error", "-y",
|
||
"-f", "lavfi", "-i", f"sine=frequency={frequency}:duration={seconds}",
|
||
"-ar", str(sample_rate), "-ac", "1", target],
|
||
check=True, capture_output=True)
|
||
return Path(target).read_bytes()
|
||
except Exception:
|
||
return _fallback_wav(frequency, seconds, sample_rate)
|
||
finally:
|
||
Path(target).unlink(missing_ok=True)
|
||
|
||
|
||
def _fallback_wav(frequency: float, seconds: float, sample_rate: int) -> bytes:
|
||
"""无 ffmpeg 时自己写 16-bit 单声道正弦 WAV。"""
|
||
import math
|
||
import struct
|
||
|
||
frames = bytearray()
|
||
for index in range(int(seconds * sample_rate)):
|
||
value = int(12000 * math.sin(2 * math.pi * frequency * index / sample_rate))
|
||
frames += struct.pack("<h", value)
|
||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as handle:
|
||
path = handle.name
|
||
with wave.open(path, "wb") as out:
|
||
out.setnchannels(1)
|
||
out.setsampwidth(2)
|
||
out.setframerate(sample_rate)
|
||
out.writeframes(bytes(frames))
|
||
return Path(path).read_bytes()
|
||
|
||
|
||
def _clone_tts(db, *, default: bool = True) -> None:
|
||
"""登记一个「靠参考音频决定音色」的 TTS,让自检链路在 mock 适配下也能真跑。"""
|
||
from app.models import ModelSpec
|
||
|
||
db.query(ModelSpec).filter(ModelSpec.media_type == "tts").delete()
|
||
db.add(ModelSpec(provider="mock", model="mock-clone-tts", display_name="Mock 克隆声",
|
||
media_type="tts", adapter="mock", enabled=True, is_default=default,
|
||
config_json={"clone_reference": True}))
|
||
db.commit()
|
||
|
||
|
||
def _platform_voice(api, *, name: str, gender: str, description: str = "",
|
||
reference_hz: float | None = None) -> int:
|
||
voice_id = api.post("/api/platform/voices",
|
||
json={"name": name, "gender": gender,
|
||
"description": description or f"{name}的音色描述"})["result"]["id"]
|
||
if reference_hz:
|
||
api.post(f"/api/platform/voice/{voice_id}/media",
|
||
files={"file": (f"ref-{reference_hz}.wav", _sine_wav(reference_hz), "audio/wav")},
|
||
data={"kind": "reference", "name": f"{name}参考音频"})
|
||
return voice_id
|
||
|
||
|
||
def _voiced_wav(frequency: float, seconds: float = 1.2, *, noise: float = 0.0) -> bytes:
|
||
"""带泛音的浊音(锯齿近似),比纯正弦更接近真人声带。
|
||
|
||
纯正弦没有高次谐波,测不出「把 3 倍周期当成基频」这类八度错误,
|
||
所以自检的回归用例必须用含泛音的信号来跑。
|
||
"""
|
||
import math
|
||
import random
|
||
import struct
|
||
|
||
sample_rate = 24000
|
||
rnd = random.Random(7)
|
||
phase = 0.0
|
||
frames = bytearray()
|
||
for index in range(int(seconds * sample_rate)):
|
||
phase += 2 * math.pi * frequency / sample_rate
|
||
value = sum(math.sin(harmonic * phase) / harmonic for harmonic in range(1, 11)) * 0.45
|
||
if noise:
|
||
value += noise * (rnd.random() * 2 - 1)
|
||
frames += struct.pack("<h", int(max(-1.0, min(1.0, value)) * 11000))
|
||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as handle:
|
||
path = handle.name
|
||
with wave.open(path, "wb") as out:
|
||
out.setnchannels(1)
|
||
out.setsampwidth(2)
|
||
out.setframerate(sample_rate)
|
||
out.writeframes(bytes(frames))
|
||
return Path(path).read_bytes()
|
||
|
||
|
||
def test_f0_estimator_has_no_octave_error_on_non_integer_periods():
|
||
"""八度错误回归:周期不是整数个采样点时,绝不能把女声低读一个八度。
|
||
|
||
8 kHz 分析采样率下 300 Hz 的周期是 26.67 点,而 3 倍周期恰好落在整数 lag=80 上,
|
||
AMDF 的全局最低谷会跑到 80,音高直接被读成 100 Hz —— 女声判成男声,
|
||
音色自检就此失效(这正是「男声声线生成了女声却全绿」那类问题的镜像)。
|
||
"""
|
||
for hertz in (300.0, 280.0, 247.5, 220.0):
|
||
measured = timbre.estimate_f0(_write_tmp(_voiced_wav(hertz)))
|
||
assert measured, hertz
|
||
assert abs(measured - hertz) / hertz < 0.08, (hertz, measured)
|
||
assert timbre.gender_of(measured) == "female", (hertz, measured)
|
||
# 女声样本绝不能在自检里被读成男声
|
||
assert timbre.check_voice(_write_tmp(_voiced_wav(300)), "male")["matched"] is False
|
||
|
||
|
||
def test_f0_estimator_does_not_fold_male_voices_upward():
|
||
"""折子谐波是单向的:真男声不能因为谐波关系被折成女声。"""
|
||
for hertz in (95.0, 110.0, 125.0, 145.0):
|
||
measured = timbre.estimate_f0(_write_tmp(_voiced_wav(hertz)))
|
||
assert measured, hertz
|
||
assert abs(measured - hertz) / hertz < 0.08, (hertz, measured)
|
||
assert timbre.gender_of(measured) == "male", (hertz, measured)
|
||
|
||
|
||
def test_f0_estimator_survives_background_noise():
|
||
"""试听样本带底噪/气声时仍要测得出来,不能退回「无法判定」。"""
|
||
for hertz, expected in ((115.0, "male"), (250.0, "female")):
|
||
measured = timbre.estimate_f0(_write_tmp(_voiced_wav(hertz, noise=0.25)))
|
||
assert measured and abs(measured - hertz) / hertz < 0.08, (hertz, measured)
|
||
assert timbre.gender_of(measured) == expected, (hertz, measured)
|
||
|
||
|
||
# ------------------------------------------------------------------ 音色自检本体
|
||
def test_f0_estimator_separates_male_and_female():
|
||
"""自检必须能把 110 Hz 的男声参考和 240 Hz 的女声样本分开。"""
|
||
male = timbre.estimate_f0(_write_tmp(_sine_wav(110)))
|
||
female = timbre.estimate_f0(_write_tmp(_sine_wav(240)))
|
||
assert male and 90 <= male <= 135, male
|
||
assert female and 200 <= female <= 280, female
|
||
assert timbre.gender_of(male) == "male"
|
||
assert timbre.gender_of(female) == "female"
|
||
|
||
|
||
def _write_tmp(payload: bytes) -> str:
|
||
MEDIA_ROOT.mkdir(parents=True, exist_ok=True)
|
||
target = MEDIA_ROOT / f"timbre-probe-{abs(hash(payload)) % 10**10}.wav"
|
||
target.write_bytes(payload)
|
||
return str(target)
|
||
|
||
|
||
def test_check_voice_flags_female_sample_declared_male():
|
||
check = timbre.check_voice(_write_tmp(_sine_wav(250)), "male")
|
||
assert check["matched"] is False
|
||
assert "女声" in check["note"] and "男声" in check["note"]
|
||
ok = timbre.check_voice(_write_tmp(_sine_wav(105)), "male")
|
||
assert ok["matched"] is True
|
||
|
||
|
||
# ------------------------------------------------------------------ 参考音频挑选
|
||
def test_male_voice_without_reference_borrows_male_reference(api, db):
|
||
"""男声线自己没有参考音频时,必须借同性别参考,而不是落到模型默认的女声底模。"""
|
||
_clone_tts(db)
|
||
male_master = _platform_voice(api, name="郭靖 · 声线", gender="male", reference_hz=100)
|
||
newcomer = _platform_voice(api, name="俊杰声音", gender="male",
|
||
description="温和、语速中等,沉稳")
|
||
|
||
resolved = timbre.resolve_reference(db, db.get(PlatformVoice, newcomer), clone=True)
|
||
assert resolved["source"] == "gender_sibling"
|
||
assert resolved["voice_name"] == "郭靖 · 声线"
|
||
assert resolved["path"].endswith(".wav")
|
||
assert male_master
|
||
|
||
created = api.post(f"/api/platform/voice/{newcomer}/generate",
|
||
json={"kind": "voice_sample", "sample_text": "我是俊杰,公司的产品专家。"})
|
||
media = created["result"]
|
||
assert media["metadata"]["reference_source"] == "gender_sibling"
|
||
assert media["metadata"]["text"] == "我是俊杰,公司的产品专家。"
|
||
assert "timbre_check" in media["metadata"]
|
||
# 借来的嗓子必须回声线绑定:否则试听是男声、正式配音又落回默认女声
|
||
with SessionLocal() as session:
|
||
assert session.get(PlatformVoice, newcomer).provider_voice_id
|
||
|
||
|
||
def test_male_voice_without_any_male_reference_refuses_to_guess(api, db):
|
||
"""库里只有女声参考时,生成男声必须明确报错,而不是安静地出一个女声。"""
|
||
_clone_tts(db)
|
||
_platform_voice(api, name="小燕子 · 声线", gender="female", reference_hz=240)
|
||
male = _platform_voice(api, name="陈澈 · 声线", gender="male")
|
||
|
||
blocked = api.post(f"/api/platform/voice/{male}/generate",
|
||
json={"kind": "voice_sample", "sample_text": "在下陈澈。"}, expect=409)
|
||
assert "男声" in blocked["detail"] and "参考音频" in blocked["detail"]
|
||
|
||
|
||
def test_reference_status_previews_the_timbre_before_generating(api, db):
|
||
"""界面在用户点「生成」之前就该知道会拿到谁的嗓子。"""
|
||
_clone_tts(db)
|
||
_platform_voice(api, name="阿拉蕾 · 声线", gender="female", reference_hz=250)
|
||
male = _platform_voice(api, name="周砚伯 · 声线", gender="male")
|
||
|
||
status = api.get(f"/api/platform/voice/{male}/reference-status")["result"]
|
||
assert status["gender"] == "male" and status["gender_label"] == "男声"
|
||
assert status["ready"] is False and status["source"] == "none"
|
||
assert "参考音频" in status["note"]
|
||
|
||
|
||
def test_project_side_reference_status_also_reports_the_timbre(api, studio, db):
|
||
"""项目声线也要能在点「生成」前看到会拿到谁的嗓子,不能只有平台侧有。
|
||
|
||
界面那句「绝不会把男声生成成女声」必须是实测结论,
|
||
否则用户看到的是一个保证、实际却没人校验过。
|
||
"""
|
||
from app.models import VoiceAsset
|
||
|
||
_clone_tts(db)
|
||
_platform_voice(api, name="项目里唯一的男声参考", gender="male", reference_hz=110)
|
||
voice_id = studio["voice_id"]
|
||
with SessionLocal() as session:
|
||
voice = session.get(VoiceAsset, voice_id)
|
||
voice.gender = "male"
|
||
voice.provider_voice_id = ""
|
||
session.commit()
|
||
|
||
status = api.get(f"/api/projects/{studio['project_id']}/voices/{voice_id}/reference-status")["result"]
|
||
assert status["gender"] == "male"
|
||
# 项目声线自己没有参考音频 → 借同性别参考:这是「能生成但音色不是自己的」,
|
||
# 界面必须标成 borrowed,提醒用户补一段这个角色专属的参考
|
||
assert status["source"] == "gender_sibling"
|
||
assert status["borrowed"] is True and status["ready"] is True
|
||
assert "参考音频" in status["note"]
|
||
|
||
|
||
# ------------------------------------------------------------------ 试听文本
|
||
def test_sample_text_is_required_and_never_the_description(api, db):
|
||
"""试听文本是台词:留空必须报错,绝不能拿「音色描述」顶上。"""
|
||
_clone_tts(db)
|
||
voice_id = _platform_voice(api, name="紫小慧声音", gender="female",
|
||
description="25岁年轻女性,音色温暖柔和", reference_hz=230)
|
||
|
||
missing = api.post(f"/api/platform/voice/{voice_id}/generate",
|
||
json={"kind": "voice_sample"}, expect=422)
|
||
assert "试听文本" in missing["detail"]
|
||
|
||
blank = api.post(f"/api/platform/voice/{voice_id}/generate",
|
||
json={"kind": "voice_sample", "sample_text": " \n "}, expect=422)
|
||
assert "试听文本" in blank["detail"]
|
||
|
||
produced = api.post(f"/api/platform/voice/{voice_id}/generate",
|
||
json={"kind": "voice_sample", "sample_text": "你好,我是紫小慧。"})["result"]
|
||
assert produced["metadata"]["text"] == "你好,我是紫小慧。"
|
||
assert "音色温暖柔和" not in produced["metadata"]["text"]
|
||
|
||
|
||
def test_project_voice_sample_also_requires_a_spoken_line(api, studio, db):
|
||
"""项目侧生成试听走的是任务链路,同样不能拿音色描述当台词。"""
|
||
_clone_tts(db)
|
||
project_id = studio["project_id"]
|
||
voice_id = studio["voice_id"]
|
||
with SessionLocal() as session:
|
||
from app.models import VoiceAsset
|
||
|
||
voice = session.get(VoiceAsset, voice_id)
|
||
voice.description = "偏低的青年男声,气声多"
|
||
voice.provider_voice_id = ""
|
||
session.commit()
|
||
|
||
result = api.post(f"/api/projects/{project_id}/assets/generate",
|
||
json={"target_type": "voice", "target_id": voice_id,
|
||
"kind": "voice_sample", "provider": "mock", "model": "mock-clone-tts",
|
||
"sample_text": " "})
|
||
assert result["result"]["task"]["status"] in ("failed", "cancelled") or result["result"].get("error")
|
||
|
||
|
||
# ---------------------------------------------------------- AI 样本不得自我克隆
|
||
def _bind_provider_voice(voice_id: int, path: str) -> None:
|
||
with SessionLocal() as session:
|
||
session.get(PlatformVoice, voice_id).provider_voice_id = path
|
||
session.commit()
|
||
|
||
|
||
def test_ai_sample_never_becomes_this_voice_s_own_reference(api, db):
|
||
"""AI 试听样本不能反过来当本声线的克隆参考,否则错音色会自我强化。
|
||
|
||
现场:男声第一次生成时缺参考、借了别人的嗓子(甚至借错了),
|
||
旧实现把生成出来的样本写回 ``provider_voice_id``,此后每次重试都拿
|
||
「上一次 AI 的输出」当输入,女声会一路女声到底,永远翻不出来。
|
||
"""
|
||
_clone_tts(db)
|
||
_platform_voice(api, name="洪七公 · 声线", gender="male", reference_hz=105)
|
||
newcomer = _platform_voice(api, name="李俊杰", gender="male", description="低沉浑厚的男声")
|
||
produced = api.post(f"/api/platform/voice/{newcomer}/generate",
|
||
json={"kind": "voice_sample", "sample_text": "我是李俊杰。"})["result"]
|
||
assert produced["metadata"]["generated"] is True
|
||
|
||
# 模拟旧链路的泄漏现场:声线绑定的其实就是那个 AI 样本
|
||
_bind_provider_voice(newcomer, produced["path"])
|
||
with SessionLocal() as session:
|
||
resolved = timbre.resolve_reference(session, session.get(PlatformVoice, newcomer), clone=True)
|
||
assert resolved["source"] != "self", resolved
|
||
assert resolved["path"] != produced["path"]
|
||
assert resolved["source"] == "gender_sibling"
|
||
|
||
status = api.get(f"/api/platform/voice/{newcomer}/reference-status")["result"]
|
||
assert status["bound_generated"] is True
|
||
assert "AI 生成的试听样本" in status["note"]
|
||
|
||
|
||
def test_a_voice_whose_only_audio_is_an_ai_sample_still_refuses_to_self_clone(api, db):
|
||
"""只有一段 AI 样本、库里又没有同性别真人参考时,必须拦下来而不是自产自销。"""
|
||
_clone_tts(db)
|
||
_platform_voice(api, name="黄蓉 · 声线", gender="female", reference_hz=260)
|
||
male = _platform_voice(api, name="柯镇恶", gender="male")
|
||
_bind_provider_voice(male, "platform/voice-99/voice_sample/voice-99-voice_sample-ai_deadbeef.wav")
|
||
|
||
status = api.get(f"/api/platform/voice/{male}/reference-status")["result"]
|
||
assert status["ready"] is False and status["source"] == "none"
|
||
assert status["bound_generated"] is True
|
||
assert "真人参考音频" in status["note"]
|
||
|
||
|
||
def test_user_uploaded_voice_sample_is_still_a_valid_reference(api, db):
|
||
"""用户上传的音色样本本来就是真人录音,照旧能当参考——不能一刀切。"""
|
||
_clone_tts(db)
|
||
voice_id = _platform_voice(api, name="梅超风 · 声线", gender="female")
|
||
uploaded = api.post(f"/api/platform/voice/{voice_id}/media",
|
||
files={"file": ("梅超风真人样本.wav", _sine_wav(230), "audio/wav")},
|
||
data={"kind": "voice_sample", "name": "梅超风 · 真人音色样本"})["result"]
|
||
_bind_provider_voice(voice_id, uploaded["path"])
|
||
|
||
with SessionLocal() as session:
|
||
own = timbre.own_reference(session, session.get(PlatformVoice, voice_id))
|
||
assert own.endswith(".wav")
|
||
status = api.get(f"/api/platform/voice/{voice_id}/reference-status")["result"]
|
||
assert status["source"] == "self" and status["ready"] is True
|
||
|
||
|
||
def test_importing_a_voice_keeps_the_ai_provenance(api, db, studio):
|
||
"""引入项目时「这段音频是 AI 生成的」必须一起带走。
|
||
|
||
标记一旦在复制中丢失,项目侧就会把它当成真人参考,
|
||
于是同一条错音色从平台一路自我强化到项目里。
|
||
"""
|
||
from app.models import Asset, VoiceAsset
|
||
|
||
_clone_tts(db)
|
||
master = _platform_voice(api, name="周伯通 · 声线", gender="male", reference_hz=118)
|
||
api.post(f"/api/platform/voice/{master}/generate",
|
||
json={"kind": "voice_sample", "sample_text": "老顽童来也。"})
|
||
|
||
api.post("/api/platform/import",
|
||
json={"project_id": studio["project_id"], "asset_type": "voice", "asset_id": master})
|
||
with SessionLocal() as session:
|
||
copy = session.query(VoiceAsset).filter(
|
||
VoiceAsset.project_id == studio["project_id"],
|
||
VoiceAsset.platform_source_id == master).first()
|
||
assert copy is not None
|
||
samples = session.query(Asset).filter(Asset.owner_type == "voice", Asset.owner_id == copy.id,
|
||
Asset.kind == "voice_sample").all()
|
||
assert samples, "平台母版的音色样本应随声线一起引入项目"
|
||
assert all((row.metadata_json or {}).get("generated") for row in samples)
|