585 lines
23 KiB
Python
585 lines
23 KiB
Python
"""原声逐词ASR边界;禁止用句子长度推算时间或回填期望台词。"""
|
||
|
||
import hashlib
|
||
import json
|
||
import math
|
||
import re
|
||
import sqlite3
|
||
import subprocess
|
||
import sys
|
||
|
||
POLICY = "native_av_v1"
|
||
TIMESTAMP_SOURCE = "whisper-word-timestamps"
|
||
ASR_REVISION = "41f01f3fe87f28c78e2fbf8b568835947dd65ed9"
|
||
CONTENT_VERIFICATION_POLICY = "whisper-sensevoice-consensus-v1"
|
||
WHISPER_DECODING_POLICY = "whisper-standard-no-speech-v1"
|
||
NO_SPEECH_THRESHOLD = 0.6
|
||
LOGPROB_THRESHOLD = -1.0
|
||
|
||
|
||
def validate_content_verification(report):
|
||
from .audio_quality import SENSEVOICE_REVISION, SENSEVOICE_RUNTIME, normalized_text
|
||
from .native_silence import POLICY as SILENCE_POLICY
|
||
from .native_silence import validate_evidence
|
||
|
||
if (
|
||
report.get("secondary_status") != "completed"
|
||
or report.get("secondary_asr_revision") != SENSEVOICE_REVISION
|
||
or report.get("secondary_runtime_revision") != SENSEVOICE_RUNTIME
|
||
or any(
|
||
not isinstance(report.get(k), str)
|
||
for k in ("expected_text", "transcript", "secondary_transcript")
|
||
)
|
||
or type(report.get("secondary_content_error_rate")) not in (int, float)
|
||
or report["secondary_content_error_rate"] != 0
|
||
or report.get("normalized_secondary_transcript")
|
||
!= normalized_text(report["secondary_transcript"])
|
||
):
|
||
raise ValueError("Missing independently measured native content consensus")
|
||
if not report["expected_text"].strip():
|
||
if (
|
||
report.get("content_verification_policy") != SILENCE_POLICY
|
||
or report.get("content_decision_source") != "verified_silence"
|
||
or report["secondary_transcript"].strip()
|
||
or report.get("normalized_expected_text") != ""
|
||
or report.get("normalized_transcript")
|
||
!= normalized_text(report["transcript"])
|
||
or type(report.get("content_error_rate")) not in (int, float)
|
||
or report["content_error_rate"]
|
||
!= content_error_rate("", report["transcript"])
|
||
or type(report.get("clipped_fraction")) not in (int, float)
|
||
or report["clipped_fraction"] != 0
|
||
):
|
||
raise ValueError("Missing verified silence measurement")
|
||
vad = validate_evidence(
|
||
report.get("silence_verification"),
|
||
report.get("audio_sha256"),
|
||
report.get("source_start_sample"),
|
||
report.get("source_end_sample"),
|
||
)
|
||
if vad["decision"] != "no_speech" or vad["channels"] != 2:
|
||
raise ValueError("VAD did not verify silence")
|
||
elif (
|
||
report.get("content_verification_policy") != CONTENT_VERIFICATION_POLICY
|
||
or report.get("content_decision_source") != "whisper_sensevoice_consensus"
|
||
or not normalized_text(report["expected_text"])
|
||
or normalized_text(report["expected_text"])
|
||
!= normalized_text(report["transcript"])
|
||
or normalized_text(report["transcript"])
|
||
!= normalized_text(report["secondary_transcript"])
|
||
):
|
||
raise ValueError("Missing independently measured native content consensus")
|
||
|
||
|
||
def content_error_rate(expected, actual):
|
||
from .audio_quality import error_rate, normalized_text
|
||
|
||
if not normalized_text(expected):
|
||
return 0.0 if not normalized_text(actual) else 1.0
|
||
return error_rate(expected, actual)
|
||
|
||
|
||
def validate_words(words, start_sample, end_sample, transcript, *, allow_silence=False):
|
||
from .audio_quality import normalized_text
|
||
|
||
if (
|
||
not isinstance(words, list)
|
||
or not words
|
||
and not (allow_silence and not normalized_text(transcript))
|
||
or not isinstance(transcript, str)
|
||
or type(start_sample) is not int
|
||
or type(end_sample) is not int
|
||
or not 0 <= start_sample < end_sample
|
||
):
|
||
raise ValueError("Missing genuine word timestamp alignment")
|
||
previous = start_sample
|
||
for word in words:
|
||
if (
|
||
not isinstance(word, dict)
|
||
or not isinstance(word.get("text"), str)
|
||
or not word["text"].strip()
|
||
or type(word.get("start_sample")) is not int
|
||
or type(word.get("end_sample")) is not int
|
||
or not previous <= word["start_sample"] < word["end_sample"] <= end_sample
|
||
):
|
||
raise ValueError("Invalid real word alignment boundaries")
|
||
previous = word["end_sample"]
|
||
if normalized_text("".join(w["text"] for w in words)) != normalized_text(
|
||
transcript
|
||
):
|
||
raise ValueError("Word alignment does not cover the actual transcript")
|
||
return words
|
||
|
||
|
||
def word_timestamps(result, start_sample, end_sample):
|
||
from .audio_quality import normalized_text
|
||
|
||
if (
|
||
isinstance(result, dict)
|
||
and isinstance(result.get("text"), str)
|
||
and not normalized_text(result["text"])
|
||
and result.get("chunks") == []
|
||
):
|
||
return validate_words(
|
||
[], start_sample, end_sample, result["text"], allow_silence=True
|
||
)
|
||
if (
|
||
not isinstance(result, dict)
|
||
or not isinstance(result.get("text"), str)
|
||
or not isinstance(result.get("chunks"), list)
|
||
or not result["chunks"]
|
||
or type(start_sample) is not int
|
||
or type(end_sample) is not int
|
||
or not 0 <= start_sample < end_sample
|
||
):
|
||
raise ValueError("Missing genuine word timestamp alignment")
|
||
words, previous = [], start_sample
|
||
for chunk in result["chunks"]:
|
||
if (
|
||
not isinstance(chunk, dict)
|
||
or not isinstance(chunk.get("text"), str)
|
||
or not chunk["text"].strip()
|
||
):
|
||
raise ValueError("Invalid word text in timestamp alignment")
|
||
stamp = chunk.get("timestamp")
|
||
if (
|
||
not isinstance(stamp, (list, tuple))
|
||
or len(stamp) != 2
|
||
or any(type(t) not in (int, float) or not math.isfinite(t) for t in stamp)
|
||
):
|
||
raise ValueError("Missing real word start/end timestamp")
|
||
left, right = (start_sample + round(t * 48000) for t in stamp)
|
||
if not previous <= left < right <= end_sample:
|
||
raise ValueError("Nonmonotonic or out-of-audio word timestamps")
|
||
words.append({"text": chunk["text"], "start_sample": left, "end_sample": right})
|
||
previous = right
|
||
return validate_words(words, start_sample, end_sample, result["text"])
|
||
|
||
|
||
def capability(settings):
|
||
from ..store import open_confined_file
|
||
from . import REVISIONS, SPEECH_INSPECT, profile
|
||
from .audio_quality import SENSEVOICE_REVISION, SENSEVOICE_RUNTIME
|
||
from .native_silence import (
|
||
MODEL_SHA256,
|
||
validate_evidence,
|
||
)
|
||
from .native_silence import (
|
||
POLICY as SILENCE_POLICY,
|
||
)
|
||
from .native_silence import (
|
||
REVISION as VAD_REVISION,
|
||
)
|
||
from .profiles import measured_job
|
||
|
||
cap = {
|
||
"available": False,
|
||
"profile": profile(SPEECH_INSPECT),
|
||
"revision": REVISIONS[SPEECH_INSPECT],
|
||
"asr_revision": ASR_REVISION,
|
||
"content_verification_policy": CONTENT_VERIFICATION_POLICY,
|
||
"secondary_asr_revision": SENSEVOICE_REVISION,
|
||
"secondary_runtime_revision": SENSEVOICE_RUNTIME,
|
||
"silence_verification_policy": SILENCE_POLICY,
|
||
"silence_vad_revision": VAD_REVISION,
|
||
"silence_vad_sha256": MODEL_SHA256,
|
||
"policy": POLICY,
|
||
"timestamp_source": TIMESTAMP_SOURCE,
|
||
"sample_rate": 48000,
|
||
"report_sha256": None,
|
||
"decision": None,
|
||
"audited": False,
|
||
}
|
||
try:
|
||
path = (
|
||
settings.app_root
|
||
/ "config"
|
||
/ "dialogue-validation"
|
||
/ "speech_inspect-native_av_v1.json"
|
||
)
|
||
with open_confined_file(path, settings.workspace_root) as stream:
|
||
raw = stream.read(65537)
|
||
if len(raw) > 65536:
|
||
raise ValueError("Oversized native alignment certificate")
|
||
report = json.loads(raw)
|
||
if (
|
||
any(
|
||
report.get(k) != cap[k]
|
||
for k in (
|
||
"profile",
|
||
"revision",
|
||
"asr_revision",
|
||
"content_verification_policy",
|
||
"secondary_asr_revision",
|
||
"secondary_runtime_revision",
|
||
"silence_verification_policy",
|
||
"silence_vad_revision",
|
||
"silence_vad_sha256",
|
||
"policy",
|
||
"timestamp_source",
|
||
"sample_rate",
|
||
)
|
||
)
|
||
or report.get("decision") != "pass"
|
||
or report.get("audited") is not True
|
||
or report.get("task_type") != SPEECH_INSPECT
|
||
or report.get("adapter_contract_version") != "native-av-alignment-v1"
|
||
or any(
|
||
not isinstance(report.get(field), str)
|
||
or re.fullmatch("[0-9a-f]{32}", report[field]) is None
|
||
for field in ("validation_job_id", "silence_validation_job_id")
|
||
)
|
||
or report["validation_job_id"] == report["silence_validation_job_id"]
|
||
):
|
||
raise ValueError("Invalid native alignment certificate identity")
|
||
for field, silence in (
|
||
("validation_job_id", False),
|
||
("silence_validation_job_id", True),
|
||
):
|
||
meta, _, params = measured_job(settings, report[field], SPEECH_INSPECT)
|
||
validate_content_verification(meta)
|
||
if (
|
||
params.get("native_av_policy") != POLICY
|
||
or meta.get("native_av_policy") != POLICY
|
||
or meta.get("decision") != "pass"
|
||
or (not meta["expected_text"].strip()) != silence
|
||
or meta.get("timestamp_source") != TIMESTAMP_SOURCE
|
||
or meta.get("timestamp_origin") != "audio_asset"
|
||
or meta.get("asr_revision") != ASR_REVISION
|
||
or meta.get("sample_rate") != 48000
|
||
):
|
||
raise ValueError(
|
||
"Missing successful native speech/silence alignment measurement"
|
||
)
|
||
if not silence:
|
||
if meta.get("content_error_rate") != 0:
|
||
raise ValueError("Missing exact spoken content measurement")
|
||
validate_words(
|
||
meta["words"],
|
||
meta["source_start_sample"],
|
||
meta["source_end_sample"],
|
||
meta["transcript"],
|
||
)
|
||
positive = validate_evidence(
|
||
meta.get("silence_verification"),
|
||
meta.get("audio_sha256"),
|
||
meta["source_start_sample"],
|
||
meta["source_end_sample"],
|
||
)
|
||
if positive["decision"] != "speech" or positive["channels"] != 2:
|
||
raise ValueError("Missing independent VAD speech positive control")
|
||
cap.update(
|
||
available=True,
|
||
decision="pass",
|
||
audited=True,
|
||
report_sha256=hashlib.sha256(raw).hexdigest(),
|
||
)
|
||
except (OSError, ValueError, KeyError, TypeError, AttributeError, sqlite3.Error):
|
||
pass
|
||
return cap
|
||
|
||
|
||
def measured_whisper_model(base):
|
||
"""观察固定transformers 5.19的标准决定,不替代其解码或静默判决。"""
|
||
|
||
class MeasuredWhisper(base):
|
||
def _need_fallback(
|
||
self,
|
||
seek_sequence,
|
||
seek_outputs,
|
||
index,
|
||
logits_processor,
|
||
generation_config,
|
||
vocab_size,
|
||
temperature,
|
||
):
|
||
outcome = super()._need_fallback(
|
||
seek_sequence,
|
||
seek_outputs,
|
||
index,
|
||
logits_processor,
|
||
generation_config,
|
||
vocab_size,
|
||
temperature,
|
||
)
|
||
# 与官方_need_fallback取同一输出的相同统计量,只记录,不改其返回值。
|
||
if hasattr(seek_outputs[0], "sequences_scores"):
|
||
logprob = seek_outputs[index]["sequences_scores"]
|
||
else:
|
||
logprob = self._retrieve_avg_logprobs(
|
||
seek_outputs[index]["scores"],
|
||
seek_sequence,
|
||
temperature,
|
||
)
|
||
no_speech = next(
|
||
item.no_speech_prob[index]
|
||
for item in logits_processor
|
||
if hasattr(item, "no_speech_prob")
|
||
)
|
||
self.native_decode_evidence.append(
|
||
{
|
||
"no_speech_probability": float(no_speech),
|
||
"average_log_probability": float(logprob),
|
||
"no_speech_threshold": generation_config.no_speech_threshold,
|
||
"logprob_threshold": generation_config.logprob_threshold,
|
||
"needs_fallback": bool(outcome[0]),
|
||
"should_skip": bool(outcome[1]),
|
||
}
|
||
)
|
||
return outcome
|
||
|
||
def generate(self, *args, **kwargs):
|
||
self.native_decode_evidence = []
|
||
self.native_empty_segments_removed = False
|
||
result = super().generate(*args, **kwargs)
|
||
if isinstance(result, dict) and result.get("segments") == [[]]:
|
||
# 5.19 pipeline对空segments执行torch.cat([]);保留模型真实空token张量,
|
||
# 仅移除可选segments,让其走官方已有token_timestamps分支。
|
||
if (
|
||
not self.native_decode_evidence
|
||
or not all(
|
||
item["should_skip"] for item in self.native_decode_evidence
|
||
)
|
||
or any(
|
||
result.get(key) is None
|
||
or tuple(result[key].shape) != (1, 0)
|
||
or result[key].numel() != 0
|
||
for key in ("sequences", "token_timestamps")
|
||
)
|
||
):
|
||
raise ValueError(
|
||
"Unmeasured or inconsistent empty Whisper segments"
|
||
)
|
||
result = {
|
||
key: value for key, value in result.items() if key != "segments"
|
||
}
|
||
self.native_empty_segments_removed = True
|
||
return result
|
||
|
||
return MeasuredWhisper
|
||
|
||
|
||
def transcribe_words(wav):
|
||
import torch
|
||
from transformers import WhisperForConditionalGeneration, WhisperProcessor, pipeline
|
||
|
||
model_dir = "/workspace/models/whisper-large-v3-turbo"
|
||
processor = WhisperProcessor.from_pretrained(model_dir, local_files_only=True)
|
||
# Whisper词时间依赖交叉注意力,显式使用eager,不能拿分块边界假冒逐词对齐。
|
||
model = (
|
||
measured_whisper_model(WhisperForConditionalGeneration)
|
||
.from_pretrained(
|
||
model_dir,
|
||
local_files_only=True,
|
||
dtype=torch.float16,
|
||
attn_implementation="eager",
|
||
)
|
||
.eval()
|
||
)
|
||
asr = pipeline(
|
||
"automatic-speech-recognition",
|
||
model=model,
|
||
tokenizer=processor.tokenizer,
|
||
feature_extractor=processor.feature_extractor,
|
||
device=0,
|
||
)
|
||
with torch.inference_mode():
|
||
result = asr(
|
||
{"array": wav, "sampling_rate": 16000},
|
||
return_timestamps="word",
|
||
generate_kwargs={
|
||
"language": "zh",
|
||
"task": "transcribe",
|
||
"do_sample": False,
|
||
# 5.19的平均logprob计算比较temperature>0,必须显式给确定性0.0。
|
||
"temperature": 0.0,
|
||
# OpenAI Whisper官方默认成对配置;全native一致,不按稿件或能量选用。
|
||
"no_speech_threshold": NO_SPEECH_THRESHOLD,
|
||
"logprob_threshold": LOGPROB_THRESHOLD,
|
||
},
|
||
)
|
||
result["whisper_decoding"] = {
|
||
"policy": WHISPER_DECODING_POLICY,
|
||
"no_speech_threshold": NO_SPEECH_THRESHOLD,
|
||
"logprob_threshold": LOGPROB_THRESHOLD,
|
||
"temperature": 0.0,
|
||
"segments": getattr(model, "native_decode_evidence", []),
|
||
"empty_segments_removed": getattr(
|
||
model, "native_empty_segments_removed", False
|
||
),
|
||
}
|
||
return result
|
||
|
||
|
||
def inspect_native_speech(inp, p, root, out):
|
||
from . import native_silence
|
||
from .audio_quality import (
|
||
SENSEVOICE_REVISION,
|
||
SENSEVOICE_RUNTIME,
|
||
digest,
|
||
normalized_text,
|
||
selected_speech,
|
||
sensevoice_transcribe,
|
||
voiced_signal,
|
||
)
|
||
|
||
wav, clipped, start, end = selected_speech(inp["audio_path"], p)
|
||
_, voiced = voiced_signal(wav)
|
||
# 静默反应镜头也必须实际识别,不能用能量阈值跳过ASR并假定没有额外台词。
|
||
result = transcribe_words(wav)
|
||
# 保留解码器原始证据,便于定位真实静默或词时间异常;不能用稿件修补识别结果。
|
||
raw_result = json.dumps(result, ensure_ascii=False, default=str)
|
||
(out / "native-whisper-raw.json").write_text(raw_result, encoding="utf-8")
|
||
print("NATIVE_WHISPER_RAW=" + raw_result, file=sys.stderr, flush=True)
|
||
transcript = result.get("text", "")
|
||
reasons = []
|
||
alignment_error = None
|
||
try:
|
||
words = word_timestamps(result, start, end)
|
||
except ValueError as exc:
|
||
# 无效词时间必须拒绝,但不能提前丢掉独立识别证据;None不冒充空词静默。
|
||
words = None
|
||
alignment_error = str(exc)
|
||
reasons.append("invalid_word_timestamps")
|
||
cer = content_error_rate(inp["expected_text"], transcript)
|
||
expects_speech = bool(normalized_text(inp["expected_text"]))
|
||
if inp["expected_text"].strip() and not expects_speech:
|
||
reasons.append("empty_spoken_content")
|
||
if expects_speech and voiced < 0.15:
|
||
reasons.append("silent")
|
||
if clipped > 0.015:
|
||
reasons.append("clipped")
|
||
if cer != 0:
|
||
reasons.append("spoken_content_mismatch")
|
||
if expects_speech and not words:
|
||
reasons.append("missing_word_timestamps")
|
||
evidence = {
|
||
"content_verification_policy": CONTENT_VERIFICATION_POLICY,
|
||
"secondary_status": "unavailable",
|
||
"secondary_transcript": None,
|
||
"normalized_secondary_transcript": None,
|
||
"secondary_content_error_rate": None,
|
||
"secondary_asr_revision": SENSEVOICE_REVISION,
|
||
"secondary_runtime_revision": SENSEVOICE_RUNTIME,
|
||
}
|
||
# 两路只接收同一原音频选段,绝不给识别器期望稿;静默也不能跳过独立识别。
|
||
# 独立内容确认不得修改Whisper真实词边界或回填稿中文字。
|
||
try:
|
||
secondary = sensevoice_transcribe(wav, root, out, allow_empty=True)
|
||
if not isinstance(secondary, str):
|
||
raise TypeError("Missing independent transcript")
|
||
except (
|
||
OSError,
|
||
ValueError,
|
||
TypeError,
|
||
RuntimeError,
|
||
ImportError,
|
||
AttributeError,
|
||
subprocess.SubprocessError,
|
||
) as exc:
|
||
evidence["secondary_error"] = type(exc).__name__
|
||
unavailable = True
|
||
else:
|
||
unavailable = False
|
||
secondary_cer = content_error_rate(inp["expected_text"], secondary)
|
||
evidence.update(
|
||
secondary_status="completed",
|
||
secondary_transcript=secondary,
|
||
normalized_secondary_transcript=normalized_text(secondary),
|
||
secondary_content_error_rate=secondary_cer,
|
||
)
|
||
if normalized_text(transcript) != normalized_text(secondary):
|
||
reasons.append("independent_content_disagreement")
|
||
if secondary_cer != 0:
|
||
reasons.append("independent_spoken_content_mismatch")
|
||
decision = "reject" if reasons else "indeterminate" if unavailable else "pass"
|
||
if unavailable:
|
||
reasons.append("independent_content_unavailable")
|
||
primary_reasons = list(reasons)
|
||
source_hash = digest(inp["audio_path"])
|
||
try:
|
||
vad = native_silence.inspect_silence(
|
||
inp["audio_path"],
|
||
root,
|
||
audio_sha256=source_hash,
|
||
start_sample=start,
|
||
end_sample=end,
|
||
)
|
||
native_silence.validate_evidence(vad, source_hash, start, end)
|
||
except Exception as exc: # noqa: BLE001 -- 外部ORT错误必须变为缺证据,不能冒充静默。
|
||
vad = {
|
||
"policy": native_silence.POLICY,
|
||
"source": native_silence.SOURCE,
|
||
"revision": native_silence.REVISION,
|
||
"model_sha256": native_silence.MODEL_SHA256,
|
||
"runtime": native_silence.RUNTIME,
|
||
"runtime_version": native_silence.RUNTIME_VERSION,
|
||
"status": "unavailable",
|
||
"error": type(exc).__name__,
|
||
"source_audio_sha256": source_hash,
|
||
"source_start_sample": start,
|
||
"source_end_sample": end,
|
||
}
|
||
evidence["content_decision_source"] = (
|
||
"whisper_sensevoice_consensus" if decision == "pass" else "unconfirmed"
|
||
)
|
||
if not inp["expected_text"].strip():
|
||
# 无对白走独立VAD+真实空的SenseVoice;原Whisper幻觉、CER和失败词时间完整保留。
|
||
evidence["content_verification_policy"] = native_silence.POLICY
|
||
reasons = []
|
||
rejected = False
|
||
if clipped != 0:
|
||
reasons.append("clipped")
|
||
rejected = True
|
||
if not unavailable and evidence["secondary_transcript"].strip():
|
||
reasons.append("independent_spoken_content_mismatch")
|
||
rejected = True
|
||
if vad.get("status") != "completed":
|
||
reasons.append("independent_vad_unavailable")
|
||
elif vad["channels"] != 2:
|
||
reasons.append("independent_vad_incomplete_channels")
|
||
elif vad["decision"] == "speech":
|
||
reasons.append("independent_vad_detected_speech")
|
||
rejected = True
|
||
elif vad["decision"] != "no_speech":
|
||
reasons.append("independent_vad_uncertain")
|
||
if unavailable:
|
||
reasons.append("independent_content_unavailable")
|
||
decision = "reject" if rejected else "indeterminate" if reasons else "pass"
|
||
evidence["content_decision_source"] = (
|
||
"verified_silence" if decision == "pass" else "unconfirmed"
|
||
)
|
||
# 原生角色声线由画面模型生成,无需克隆声纹;内容须经双路逐字共识验收。
|
||
report = {
|
||
**evidence,
|
||
"decision": decision,
|
||
"reasons": reasons,
|
||
"primary_reasons": primary_reasons,
|
||
"silence_verification": vad,
|
||
"speaker_id": inp["speaker_id"],
|
||
"expected_text": inp["expected_text"],
|
||
"transcript": transcript,
|
||
"normalized_expected_text": normalized_text(inp["expected_text"]),
|
||
"normalized_transcript": normalized_text(transcript),
|
||
"content_error_rate": cer,
|
||
"audio_sha256": source_hash,
|
||
"source_start_sample": start,
|
||
"source_end_sample": end,
|
||
"sample_rate": 48000,
|
||
"timestamp_origin": "audio_asset",
|
||
"timestamp_source": TIMESTAMP_SOURCE,
|
||
"native_av_policy": POLICY,
|
||
"words": words,
|
||
"word_alignment_status": "invalid" if alignment_error else "completed",
|
||
"word_alignment_error": alignment_error,
|
||
"whisper_decoding": result.get("whisper_decoding"),
|
||
"asr_revision": ASR_REVISION,
|
||
"voiced_seconds": voiced,
|
||
"clipped_fraction": clipped,
|
||
}
|
||
path = out / "speech-quality.json"
|
||
path.write_text(
|
||
json.dumps(report, ensure_ascii=False, allow_nan=False), encoding="utf-8"
|
||
)
|
||
return [path], report
|