406 lines
13 KiB
Python
406 lines
13 KiB
Python
"""Verify the actual normalized utterance against its script and independent voice reference."""
|
|
|
|
import json
|
|
import math
|
|
import re
|
|
import subprocess
|
|
import unicodedata
|
|
|
|
from .media import digest
|
|
|
|
THIRD_PERSON_PRONOUNS = str.maketrans({"她": "他", "它": "他"})
|
|
|
|
|
|
def normalized_text(text):
|
|
value = unicodedata.normalize("NFKC", text).casefold()
|
|
# Whisper 可用阿拉伯数字表示同一个普通话数词,例如“五号楼”。
|
|
value = re.sub(
|
|
r"(?<![0-9])[0-9](?![0-9])", lambda m: "零一二三四五六七八九"[int(m[0])], value
|
|
)
|
|
return "".join(c for c in value.translate(THIRD_PERSON_PRONOUNS) if c.isalnum())
|
|
|
|
|
|
def error_rate(expected, observed):
|
|
a, b = normalized_text(expected), normalized_text(observed)
|
|
if not a:
|
|
return 1.0
|
|
prev = list(range(len(b) + 1))
|
|
for i, left in enumerate(a, 1):
|
|
curr = [i]
|
|
for j, right in enumerate(b, 1):
|
|
curr.append(
|
|
min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (left != right))
|
|
)
|
|
prev = curr
|
|
return prev[-1] / len(a)
|
|
|
|
|
|
def verdict(expected, transcript, voiced, clipped, ref_voiced, similarity):
|
|
cer = error_rate(expected, transcript)
|
|
reasons = []
|
|
if voiced < 0.15:
|
|
reasons.append("silent")
|
|
if clipped > 0.015:
|
|
reasons.append("clipped")
|
|
if cer >= 0.20:
|
|
reasons.append("spoken_content_mismatch")
|
|
if similarity is not None and similarity < 0.25:
|
|
reasons.append("different_voice")
|
|
if reasons:
|
|
return "reject", reasons, cer
|
|
if voiced < 1.0:
|
|
reasons.append("short_speech")
|
|
if cer:
|
|
reasons.append("uncertain_transcript")
|
|
if ref_voiced < 1.0 or similarity is None:
|
|
reasons.append("missing_independent_voice_evidence")
|
|
elif similarity < 0.50:
|
|
reasons.append("uncertain_voice")
|
|
return "indeterminate" if reasons else "pass", reasons, cer
|
|
|
|
|
|
CONTENT_REVIEW_POLICY = "whisper-sensevoice-exact-v1"
|
|
SENSEVOICE_REVISION = "90c1c61912018b70ada0fcc024ea24aca62f2e63"
|
|
SENSEVOICE_RUNTIME = "6991744856587fa44379e8b5dcc432debffeb1be"
|
|
|
|
|
|
def review_content(
|
|
expected, primary, voiced, clipped, ref_voiced, similarity, blind, simplify
|
|
):
|
|
script = simplify(expected)
|
|
decision, reasons, cer = verdict(
|
|
script, simplify(primary), voiced, clipped, ref_voiced, similarity
|
|
)
|
|
evidence = {
|
|
"content_review_policy": CONTENT_REVIEW_POLICY,
|
|
"primary_content_error_rate": cer,
|
|
"content_decision_source": "whisper" if not cer else "unconfirmed",
|
|
"secondary_status": "not_requested",
|
|
"secondary_transcript": None,
|
|
"secondary_content_error_rate": None,
|
|
"secondary_asr_revision": None,
|
|
"secondary_runtime_revision": None,
|
|
}
|
|
if (
|
|
decision != "indeterminate"
|
|
or reasons != ["uncertain_transcript"]
|
|
or not 0 < cer < 0.20
|
|
):
|
|
return decision, reasons, cer, evidence
|
|
evidence.update(
|
|
secondary_asr_revision=SENSEVOICE_REVISION,
|
|
secondary_runtime_revision=SENSEVOICE_RUNTIME,
|
|
)
|
|
try:
|
|
secondary = blind()
|
|
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
|
evidence.update(
|
|
secondary_status="unavailable", secondary_error=type(exc).__name__
|
|
)
|
|
return decision, reasons, cer, evidence
|
|
secondary_cer = error_rate(script, simplify(secondary))
|
|
evidence.update(
|
|
secondary_status="completed",
|
|
secondary_transcript=secondary,
|
|
secondary_content_error_rate=secondary_cer,
|
|
)
|
|
if secondary_cer == 0:
|
|
evidence["content_decision_source"] = "sensevoice"
|
|
return "pass", [], 0.0, evidence
|
|
return decision, reasons, cer, evidence
|
|
|
|
|
|
def sensevoice_transcribe(wav, root, out, *, allow_empty=False):
|
|
import os
|
|
import tempfile
|
|
|
|
import numpy as np
|
|
import soundfile as sf
|
|
|
|
# The decoder only receives 16 kHz audio and local weights within the current lease.
|
|
model = root / "sensevoice" / "sensevoice-small-f16.gguf"
|
|
binary = "/workspace/envs/dialogue-v1/bin/llama-funasr-sensevoice"
|
|
cpus = ",".join(str(c) for c in sorted(os.sched_getaffinity(0))[:2])
|
|
env = {
|
|
**os.environ,
|
|
"OMP_NUM_THREADS": "2",
|
|
"OMP_THREAD_LIMIT": "2",
|
|
"OPENBLAS_NUM_THREADS": "2",
|
|
}
|
|
chunks = []
|
|
start = 0
|
|
with tempfile.TemporaryDirectory(dir=out) as tmp:
|
|
from pathlib import Path
|
|
|
|
path = Path(tmp) / "segment.wav"
|
|
while start < len(wav):
|
|
end = min(start + 28 * 16000, len(wav))
|
|
if end < len(wav):
|
|
window = wav[end - 3 * 16000 : end].reshape(-1, 320)
|
|
end -= (
|
|
3 * 16000 - int(np.square(window).mean(axis=1).argmin()) * 320 - 160
|
|
)
|
|
sf.write(path, wav[start:end], 16000, subtype="PCM_16")
|
|
result = subprocess.run(
|
|
["taskset", "-c", cpus, binary, "-m", str(model), "-a", str(path)],
|
|
env=env,
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
timeout=90,
|
|
check=True,
|
|
)
|
|
# 原生静默验收可保留空转写,但仍须成功退出并具备解码完成标记。
|
|
if (
|
|
not allow_empty and not result.stdout.strip()
|
|
or "[sensevoice] done" not in result.stderr
|
|
or "compute failed" in result.stderr
|
|
):
|
|
raise ValueError("Incomplete SenseVoice decoding")
|
|
chunks.append(result.stdout.strip())
|
|
start = end
|
|
return "".join(chunks)
|
|
|
|
|
|
def load_audio(path, limit, *, required_rate=None):
|
|
import numpy as np
|
|
from scipy.signal import resample_poly
|
|
|
|
info = json.loads(
|
|
subprocess.check_output(
|
|
[
|
|
"ffprobe",
|
|
"-v",
|
|
"error",
|
|
"-select_streams",
|
|
"a:0",
|
|
"-show_entries",
|
|
"stream=sample_rate:format=duration",
|
|
"-of",
|
|
"json",
|
|
str(path),
|
|
],
|
|
timeout=30,
|
|
)
|
|
)
|
|
rate = int(info["streams"][0]["sample_rate"])
|
|
if required_rate and rate != required_rate:
|
|
raise ValueError("Utterance must be normalized at 48 kHz")
|
|
if not (0 < float(info["format"]["duration"]) <= limit and 8000 <= rate <= 192000):
|
|
raise ValueError("Unsupported audio duration or sampling rate")
|
|
raw = subprocess.check_output(
|
|
[
|
|
"ffmpeg",
|
|
"-nostdin",
|
|
"-v",
|
|
"error",
|
|
"-threads",
|
|
"2",
|
|
"-i",
|
|
str(path),
|
|
"-t",
|
|
str(limit),
|
|
"-vn",
|
|
"-map",
|
|
"0:a:0",
|
|
"-ac",
|
|
"1",
|
|
"-ar",
|
|
str(rate),
|
|
"-f",
|
|
"f32le",
|
|
"pipe:1",
|
|
],
|
|
timeout=max(60, limit * 2),
|
|
)
|
|
wav = np.frombuffer(raw, dtype="<f4")
|
|
if not len(wav) or not np.isfinite(wav).all():
|
|
raise ValueError("Invalid speech signal")
|
|
clipped = float(np.mean(np.abs(wav) >= 0.999))
|
|
divisor = math.gcd(rate, 16000)
|
|
wav = resample_poly(wav, 16000 // divisor, rate // divisor).astype(np.float32)
|
|
return wav, clipped
|
|
|
|
|
|
def voiced_signal(wav):
|
|
import numpy as np
|
|
|
|
chunks = wav[: len(wav) // 320 * 320].reshape(-1, 320)
|
|
if not chunks.size:
|
|
return wav[:0], 0.0
|
|
rms = np.sqrt(np.mean(chunks**2, axis=1))
|
|
mask = rms >= max(0.003, float(np.percentile(rms, 90)) * 0.04)
|
|
return chunks[mask].reshape(-1), float(mask.sum() * 0.02)
|
|
|
|
|
|
def embedding(model, wav):
|
|
import numpy as np
|
|
import torch
|
|
from torchaudio.compliance.kaldi import fbank
|
|
|
|
features = fbank(
|
|
torch.from_numpy(wav).unsqueeze(0) * 32768,
|
|
num_mel_bins=80,
|
|
frame_length=25,
|
|
frame_shift=10,
|
|
dither=0,
|
|
sample_frequency=16000,
|
|
window_type="hamming",
|
|
use_energy=False,
|
|
)
|
|
features -= features.mean(dim=0, keepdim=True)
|
|
vec = model.run(None, {model.get_inputs()[0].name: features.numpy()[None]})[
|
|
0
|
|
].ravel()
|
|
norm = np.linalg.norm(vec)
|
|
if not np.isfinite(norm) or norm <= 0:
|
|
raise ValueError("Invalid speaker embedding")
|
|
return vec / norm
|
|
|
|
|
|
def transcribe(wav):
|
|
import numpy as np
|
|
import torch
|
|
from transformers import WhisperForConditionalGeneration, WhisperProcessor
|
|
|
|
model_dir = "/workspace/models/whisper-large-v3-turbo"
|
|
proc = WhisperProcessor.from_pretrained(model_dir, local_files_only=True)
|
|
model = (
|
|
WhisperForConditionalGeneration.from_pretrained(
|
|
model_dir, local_files_only=True, dtype=torch.float16
|
|
)
|
|
.cuda()
|
|
.eval()
|
|
)
|
|
chunks = []
|
|
start = 0
|
|
with torch.inference_mode():
|
|
while start < len(wav):
|
|
end = min(start + 28 * 16000, len(wav))
|
|
if end < len(wav):
|
|
window = wav[end - 3 * 16000 : end].reshape(-1, 320)
|
|
end = (
|
|
end
|
|
- 3 * 16000
|
|
+ int(np.square(window).mean(axis=1).argmin()) * 320
|
|
+ 160
|
|
)
|
|
features = proc.feature_extractor(
|
|
wav[start:end], sampling_rate=16000, return_tensors="pt"
|
|
).input_features
|
|
ids = model.generate(
|
|
features.half().cuda(),
|
|
language="zh",
|
|
task="transcribe",
|
|
max_new_tokens=440,
|
|
do_sample=False,
|
|
)
|
|
chunks.append(proc.batch_decode(ids, skip_special_tokens=True)[0])
|
|
start = end
|
|
return "".join(chunks).strip()
|
|
|
|
|
|
def selected_speech(source, p):
|
|
import numpy as np
|
|
import soundfile as sf
|
|
from scipy.signal import resample_poly
|
|
|
|
with sf.SoundFile(source) as f:
|
|
start = p.get("source_start_sample", 0)
|
|
end = (
|
|
p.get("source_end_sample")
|
|
if p.get("source_end_sample") is not None
|
|
else f.frames
|
|
)
|
|
if (
|
|
f.samplerate != 48000
|
|
or not 0 <= start < end <= f.frames
|
|
or end - start > 600 * 48000
|
|
):
|
|
raise ValueError("Invalid normalized speech selection")
|
|
f.seek(start)
|
|
values = f.read(end - start, dtype="float32", always_2d=True)
|
|
if len(values) != end - start or not np.isfinite(values).all():
|
|
raise ValueError("Invalid normalized speech samples")
|
|
clipped = float(np.mean(np.abs(values) >= 0.999))
|
|
return (
|
|
resample_poly(values.mean(axis=1), 1, 3).astype(np.float32),
|
|
clipped,
|
|
start,
|
|
end,
|
|
)
|
|
|
|
|
|
def inspect_speech(inp, p, root, out):
|
|
if p.get('native_av_policy') == 'native_av_v1':
|
|
from .native_alignment import inspect_native_speech
|
|
return inspect_native_speech(inp, p, root, out)
|
|
import numpy as np
|
|
import onnxruntime as ort
|
|
from zhconv import convert
|
|
|
|
source = inp["audio_path"]
|
|
wav, clipped, start, end = selected_speech(source, p)
|
|
voice, voiced = voiced_signal(wav)
|
|
transcript = transcribe(wav) if voiced >= 0.15 else ""
|
|
similarity = None
|
|
ref_voiced = 0.0
|
|
ref_hash = None
|
|
source_hash = digest(source)
|
|
if inp.get("reference_path"):
|
|
ref_hash = digest(inp["reference_path"])
|
|
if ref_hash != source_hash:
|
|
ref, _ = load_audio(inp["reference_path"], 30)
|
|
ref, ref_voiced = voiced_signal(ref)
|
|
if min(ref_voiced, voiced) >= 1:
|
|
options = ort.SessionOptions()
|
|
options.intra_op_num_threads = 2
|
|
options.inter_op_num_threads = 1
|
|
model = ort.InferenceSession(
|
|
str(root / "wespeaker" / "voxceleb_resnet34_LM.onnx"),
|
|
options,
|
|
providers=["CPUExecutionProvider"],
|
|
)
|
|
similarity = float(
|
|
np.clip(embedding(model, voice) @ embedding(model, ref), -1, 1)
|
|
)
|
|
simplified_expected = convert(inp["expected_text"], "zh-cn")
|
|
simplified_transcript = convert(transcript, "zh-cn")
|
|
decision, reasons, cer, content_evidence = review_content(
|
|
inp["expected_text"],
|
|
transcript,
|
|
voiced,
|
|
clipped,
|
|
ref_voiced,
|
|
similarity,
|
|
lambda: sensevoice_transcribe(wav, root, out),
|
|
lambda s: convert(s, "zh-cn"),
|
|
)
|
|
report = {
|
|
**content_evidence,
|
|
"decision": decision,
|
|
"speaker_id": inp["speaker_id"],
|
|
"expected_text": inp["expected_text"],
|
|
"transcript": transcript,
|
|
"normalization_policy": "zh-cn-spoken-v2-third-person-他她它",
|
|
"normalized_expected_text": normalized_text(simplified_expected),
|
|
"normalized_transcript": normalized_text(simplified_transcript),
|
|
"content_error_rate": cer,
|
|
"identity_similarity": similarity,
|
|
"reference_sha256": ref_hash,
|
|
"audio_sha256": source_hash,
|
|
"source_start_sample": start,
|
|
"source_end_sample": end,
|
|
"voiced_seconds": voiced,
|
|
"reference_voiced_seconds": ref_voiced,
|
|
"clipped_fraction": clipped,
|
|
"reasons": reasons,
|
|
"asr_revision": "41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
|
|
"speaker_revision": "f0c48c298fd835726c27956a5d617bad7115627e",
|
|
}
|
|
path = out / "speech-quality.json"
|
|
path.write_text(
|
|
json.dumps(report, ensure_ascii=False, allow_nan=False), encoding="utf-8"
|
|
)
|
|
return [path], report
|