cmvr-visual/inference/llm_services/dialogue/native_silence.py

226 lines
8.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""独立CPU Silero VAD;不读取稿件,也不修改任何ASR转写或词时间。"""
import hashlib
import math
import re
POLICY = "silero-sensevoice-verified-silence-v1"
SOURCE = "silero-vad-onnx-cpu"
REVISION = "be95df9152c0d7618fa1edfeb296fc3dae32376f"
MODEL_SHA256 = "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3"
MODEL_BYTES = 2327524
MODEL_URL = f"https://raw.githubusercontent.com/snakers4/silero-vad/{REVISION}/src/silero_vad/data/silero_vad.onnx"
RUNTIME = "onnxruntime-cpu"
RUNTIME_VERSION = "1.31.1"
WINDOW = 512
THRESHOLD = 0.5
NEGATIVE_THRESHOLD = 0.35
CHANNEL_POLICY = "all_channels_no_speech"
def _decision(maximum):
if maximum >= THRESHOLD:
return "speech"
return "indeterminate" if maximum >= NEGATIVE_THRESHOLD else "no_speech"
def validate_evidence(evidence, audio_sha256, start_sample, end_sample):
if (
not isinstance(evidence, dict)
or not isinstance(audio_sha256, str)
or not re.fullmatch("[0-9a-f]{64}", audio_sha256)
or type(start_sample) is not int
or type(end_sample) is not int
or not 0 <= start_sample < end_sample
):
raise ValueError("Invalid VAD source evidence")
count = (end_sample - start_sample + 2) // 3
expected = {
"policy": POLICY,
"source": SOURCE,
"revision": REVISION,
"model_sha256": MODEL_SHA256,
"runtime": RUNTIME,
"runtime_version": RUNTIME_VERSION,
"status": "completed",
"source_audio_sha256": audio_sha256,
"source_start_sample": start_sample,
"source_end_sample": end_sample,
"sample_rate": 16000,
"sample_count": count,
"window_size_samples": WINDOW,
"window_count": (count + WINDOW - 1) // WINDOW,
"threshold": THRESHOLD,
"negative_threshold": NEGATIVE_THRESHOLD,
}
probabilities = evidence.get("probabilities")
channel_probabilities = evidence.get("channel_probabilities")
channels = evidence.get("channels")
if (
count < WINDOW
or not 1 <= expected["window_count"] <= 10000
or any(evidence.get(k) != v for k, v in expected.items())
or any(
type(evidence.get(k)) is not int
for k in (
"source_start_sample",
"source_end_sample",
"sample_rate",
"sample_count",
"window_size_samples",
"window_count",
)
)
or not isinstance(probabilities, list)
or len(probabilities) != expected["window_count"]
or any(
type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1
for p in probabilities
)
or type(evidence.get("max_speech_probability")) not in (int, float)
or evidence["max_speech_probability"] != max(probabilities)
or evidence.get("decision") != _decision(max(probabilities))
or evidence.get("channel_policy") != CHANNEL_POLICY
or type(channels) is not int
or channels not in (1, 2)
or not isinstance(channel_probabilities, list)
or len(channel_probabilities) != channels
or any(
not isinstance(values, list) or len(values) != expected["window_count"]
for values in channel_probabilities
)
or any(
type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1
for values in channel_probabilities
for p in values
)
or probabilities
!= [max(values) for values in zip(*channel_probabilities, strict=True)]
):
raise ValueError("Missing complete bounded VAD measurement")
return evidence
def inspect_silence(source_path, root, *, audio_sha256, start_sample, end_sample):
import numpy as np
import soundfile as sf
from scipy.signal import resample_poly
if (
type(start_sample) is not int
or type(end_sample) is not int
or not 0 <= start_sample < end_sample
or (end_sample - start_sample + 2) // 3 < WINDOW
):
raise ValueError("Incomplete VAD audio selection")
# 必须从同一原文件读取每一轨,不能复用ASR的mean下混;反相语音会在下混中相消。
# 哈希与解码共享同一打开流,避免把另一文件或单轨摘要冒充原双声道证据。
with open(source_path, "rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != audio_sha256:
raise ValueError("VAD source audio hash mismatch")
stream.seek(0)
with sf.SoundFile(stream) as source:
channels = source.channels
if (
source.samplerate != 48000
or channels not in (1, 2)
or end_sample > source.frames
):
raise ValueError("Invalid original VAD source channels or sample range")
source.seek(start_sample)
values = source.read(
end_sample - start_sample, dtype="float32", always_2d=True
)
if (
values.shape != (end_sample - start_sample, channels)
or not np.isfinite(values).all()
):
raise ValueError("Incomplete original VAD channel samples")
selected = np.column_stack(
[
resample_poly(values[:, channel], 1, 3, axis=0).astype(np.float32)
for channel in range(channels)
]
)
if (
selected.shape != ((end_sample - start_sample + 2) // 3, channels)
or not np.isfinite(selected).all()
):
raise ValueError("Incomplete resampled VAD channels")
path = root / "silero-vad" / "silero_vad.onnx"
with path.open("rb") as stream:
weights = stream.read(MODEL_BYTES + 1)
if (
len(weights) != MODEL_BYTES
or hashlib.sha256(weights).hexdigest() != MODEL_SHA256
):
raise ValueError("Silero model weight hash mismatch")
import onnxruntime as ort
if ort.__version__ != RUNTIME_VERSION:
raise ValueError("Unverified VAD runtime version")
options = ort.SessionOptions()
options.inter_op_num_threads = options.intra_op_num_threads = 1
session = ort.InferenceSession(
weights, providers=["CPUExecutionProvider"], sess_options=options
)
if session.get_providers() != ["CPUExecutionProvider"]:
raise ValueError("VAD must execute independently on CPU")
channel_probabilities = []
for channel in range(channels):
# 循环状态和64样本上下文必须逐轨重新初始化,不把上一轨状态传给下一轨。
state = np.zeros((2, 1, 128), dtype=np.float32)
context = np.zeros((1, 64), dtype=np.float32)
probabilities = []
for position in range(0, len(selected), WINDOW):
chunk = np.zeros((1, WINDOW), dtype=np.float32)
values = selected[position : position + WINDOW, channel]
chunk[0, : len(values)] = values
combined = np.concatenate((context, chunk), axis=1)
output, state = session.run(
None,
{
"input": combined,
"state": state,
"sr": np.array(16000, dtype=np.int64),
},
)
output, state = np.asarray(output), np.asarray(state)
if (
output.shape != (1, 1)
or state.shape != (2, 1, 128)
or not np.isfinite(output).all()
or not np.isfinite(state).all()
or not 0 <= float(output.item()) <= 1
):
raise ValueError("Invalid independent VAD model output")
probabilities.append(float(output.item()))
context = combined[:, -64:]
channel_probabilities.append(probabilities)
probabilities = [max(values) for values in zip(*channel_probabilities, strict=True)]
evidence = {
"policy": POLICY,
"source": SOURCE,
"revision": REVISION,
"model_sha256": MODEL_SHA256,
"runtime": RUNTIME,
"runtime_version": ort.__version__,
"status": "completed",
"decision": _decision(max(probabilities)),
"source_audio_sha256": audio_sha256,
"source_start_sample": start_sample,
"source_end_sample": end_sample,
"sample_rate": 16000,
"sample_count": len(selected),
"channel_policy": CHANNEL_POLICY,
"channels": channels,
"channel_probabilities": channel_probabilities,
"window_size_samples": WINDOW,
"window_count": len(probabilities),
"threshold": THRESHOLD,
"negative_threshold": NEGATIVE_THRESHOLD,
"max_speech_probability": max(probabilities),
"probabilities": probabilities,
}
return validate_evidence(evidence, audio_sha256, start_sample, end_sample)