837 lines
34 KiB
Python
837 lines
34 KiB
Python
# coding=utf-8
|
||
# Copyright 2026 The NetEase Youdao team.
|
||
# SPDX-License-Identifier: Apache-2.0
|
||
#
|
||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||
# you may not use this file except in compliance with the License.
|
||
# You may obtain a copy of the License at
|
||
#
|
||
# http://www.apache.org/licenses/LICENSE-2.0
|
||
#
|
||
# Unless required by applicable law or agreed to in writing, software
|
||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
# See the License for the specific language governing permissions and
|
||
# limitations under the License.
|
||
|
||
from dataclasses import dataclass
|
||
from typing import Any, Tuple, List, Optional
|
||
import re
|
||
|
||
import numpy as np
|
||
|
||
from app.services.asr.qwen3_vllm import (
|
||
_build_chat_prompt,
|
||
_normalize_language_name,
|
||
_parse_asr_output,
|
||
)
|
||
|
||
SAMPLE_RATE = 16000
|
||
_ASR_TEXT_TAG = "<asr_text>"
|
||
_LANG_PREFIX = "language "
|
||
normalize_language_name = _normalize_language_name
|
||
|
||
|
||
def parse_asr_output(raw: str, user_language: Optional[str] = None) -> tuple[str, str]:
|
||
"""Adapt the project's parser to the signature expected by the upstream decoder."""
|
||
return _parse_asr_output(raw, user_language)
|
||
|
||
|
||
def validate_language(language: str) -> None:
|
||
"""Reject empty forced-language values; aliases are normalized by Qwen utilities."""
|
||
if not language or not str(language).strip():
|
||
raise ValueError("language must not be empty")
|
||
|
||
|
||
def _build_text_prompt(context: str = "", force_language: Optional[str] = None) -> str:
|
||
"""Build the same Qwen audio prompt used by the project's vLLM adapter."""
|
||
return _build_chat_prompt(context=context, language=force_language)
|
||
|
||
_EN2ZH_PUNCT = {
|
||
",": "?", ".": "?", "!": "?", "?": "?",
|
||
";": "?", ":": "?", "(": "?", ")": "?",
|
||
}
|
||
_ZH2EN_PUNCT = {v: k for k, v in _EN2ZH_PUNCT.items()}
|
||
_ALL_PUNCT_PAT = re.compile(r'[,\.!?;:()\uff0c\u3002\uff01\uff1f\uff1b\uff1a\uff08\uff09]')
|
||
|
||
|
||
def _normalize_punct_by_context(text: str) -> str:
|
||
"""根据每个标点前字符的类型规范化标点:
|
||
- 如果前一个字符是中文,则替换为中文标点。
|
||
- 如果前一个字符是英文字母或数字,则替换为英文标点。
|
||
- 其他情况保留原标点。
|
||
"""
|
||
def _replace(m):
|
||
punct = m.group()
|
||
pos = m.start()
|
||
prev_char = ""
|
||
for i in range(pos - 1, -1, -1):
|
||
if not text[i].isspace():
|
||
prev_char = text[i]
|
||
break
|
||
if not prev_char:
|
||
return punct
|
||
if '\u4e00' <= prev_char <= '\u9fff':
|
||
return _EN2ZH_PUNCT.get(punct, punct)
|
||
elif prev_char.isascii() and (prev_char.isalnum() or prev_char in '"\''):
|
||
return _ZH2EN_PUNCT.get(punct, punct)
|
||
return punct
|
||
return _ALL_PUNCT_PAT.sub(_replace, text)
|
||
|
||
def parse_language_output(
|
||
raw: str,
|
||
user_language: Optional[str] = None,
|
||
) -> Tuple[str, str]:
|
||
"""
|
||
将 Qwen3-ASR 原始输出解析为 (language, text)。
|
||
|
||
情况:
|
||
- 带标签:“language Chinese<asr_text>....”
|
||
- 带换行:“language Chinese\\n...\\n<asr_text>....”
|
||
- 无标签:将整个字符串视为文本。
|
||
- “language None<asr_text>”:视为空音频 -> ("", "")
|
||
|
||
如果提供了 user_language,则强制使用该语言,并将 raw 视为纯文本
|
||
(模型应输出不含元数据的纯转写文本)。
|
||
|
||
参数:
|
||
raw:原始解码字符串。
|
||
user_language:用户强制指定语言时使用的规范语言名称。
|
||
|
||
返回:
|
||
Tuple[str, str]:(language, text)
|
||
"""
|
||
if raw is None:
|
||
return "", ""
|
||
if user_language == "English":
|
||
s = str(raw).rstrip()
|
||
else:
|
||
s = str(raw).strip()
|
||
if not s:
|
||
return "", ""
|
||
|
||
if user_language:
|
||
# 用户显式指定了语言,因此将模型输出视为纯文本
|
||
return user_language, s
|
||
|
||
meta_part = s
|
||
text_part = ""
|
||
has_tag = _ASR_TEXT_TAG in s
|
||
if has_tag:
|
||
meta_part, text_part = s.split(_ASR_TEXT_TAG, 1)
|
||
else:
|
||
# 没有标签,视为纯文本
|
||
return "", s.strip()
|
||
|
||
meta_lower = meta_part.lower()
|
||
|
||
# 空音频启发式判断
|
||
if "language none" in meta_lower:
|
||
t = text_part.strip()
|
||
if not t:
|
||
return "", ""
|
||
# 如果模型仍然返回了内容,则保留内容,但语言设为未知
|
||
return "", t
|
||
|
||
# 从 meta 中提取“language xxx”
|
||
lang = ""
|
||
for line in meta_part.splitlines():
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
low = line.lower()
|
||
if low.startswith(_LANG_PREFIX):
|
||
val = line[len(_LANG_PREFIX):].strip()
|
||
if val:
|
||
lang = normalize_language_name(val)
|
||
break
|
||
|
||
return lang, text_part.strip()
|
||
|
||
@dataclass
|
||
class ASRStreamingState:
|
||
"""
|
||
单个音频流(单句)的流式 ASR 状态。
|
||
|
||
属性:
|
||
unfixed_chunk_num (int):前 N 个分块不使用之前的 ASR 结果作为前缀提示(将前缀重置为 "")。
|
||
unfixed_token_num (int):当 chunk_id >= unfixed_chunk_num 时,使用累积文本作为前缀提示前,
|
||
回退最后 K 个 token,以减少边界抖动。
|
||
chunk_size_sec (float):分块大小(秒)。音频将按此长度递增输入模型。
|
||
chunk_size_samples (int):16kHz 下的分块采样点数(由 chunk_size_sec 推导)。
|
||
chunk_id (int):当前分块索引(从 0 开始)。
|
||
buffer (np.ndarray):尚未消费为完整分块的 PCM 采样点缓冲区。
|
||
audio_accum (np.ndarray):从流开始到当前时刻累积的音频(不填充)。
|
||
prompt_raw (str):由聊天模板生成的基础提示(包含生成提示),不附加前缀文本。
|
||
context (str):上下文字符串。
|
||
force_language (Optional[str]):如果提供,则在 prompt_raw 中追加 "language X<asr_text>",
|
||
强制输出纯文本,与非流式 transcribe() 保持一致。
|
||
language (str):最近一次解析出的语言(每个分块解码后更新)。未知/静音时为空。
|
||
text (str):最近一次解析出的转写文本(每个分块解码后更新)。
|
||
_raw_decoded (str):内部累积的原始解码文本(parse_asr_output 规范化之前)。
|
||
用于回退/token 裁剪,并作为提示前缀。
|
||
"""
|
||
unfixed_chunk_num: int
|
||
unfixed_token_num: int
|
||
chunk_size_sec: float
|
||
chunk_size_samples: int
|
||
|
||
chunk_id: int
|
||
buffer: np.ndarray
|
||
audio_accum: np.ndarray
|
||
|
||
prompt_raw: str
|
||
context: str
|
||
force_language: Optional[str]
|
||
|
||
language: str
|
||
text: str
|
||
_raw_decoded: str
|
||
|
||
chunk_text: List
|
||
last_fixed_text: str
|
||
_first_chunk_discarded: bool
|
||
|
||
class R2T2ASRModel:
|
||
def __init__(
|
||
self,
|
||
backend: str,
|
||
model: Any,
|
||
processor: Any,
|
||
sampling_params: Optional[Any] = None,
|
||
forced_aligner: Optional[Any] = None,
|
||
max_inference_batch_size: int = -1,
|
||
max_new_tokens: int = 512,
|
||
):
|
||
self.backend = backend
|
||
self.model = model
|
||
self.processor = processor
|
||
self.sampling_params = sampling_params
|
||
self.forced_aligner = forced_aligner
|
||
self.max_inference_batch_size = max_inference_batch_size
|
||
self.max_new_tokens = max_new_tokens
|
||
|
||
def _build_text_prompt(self, context: str = "", force_language: Optional[str] = None) -> str:
|
||
return _build_text_prompt(context=context, force_language=force_language)
|
||
|
||
def init_streaming_state(
|
||
self,
|
||
context: str = "",
|
||
language: Optional[str] = None,
|
||
unfixed_chunk_num: int = 2,
|
||
unfixed_token_num: int = 5,
|
||
chunk_size_sec: float = 2.0,
|
||
) -> ASRStreamingState:
|
||
"""
|
||
初始化单个流的 ASR 状态。
|
||
|
||
注意:
|
||
- 流式 ASR 仅支持 vLLM 后端。
|
||
- 流式 ASR 不支持时间戳(不使用强制对齐器)。
|
||
- 不支持批量推理。
|
||
|
||
参数:
|
||
context:上下文字符串。
|
||
language:可选的强制语言。提供时必须属于支持的语言。
|
||
行为与 transcribe() 相同:通过提示后缀强制输出纯文本。
|
||
unfixed_chunk_num:前 N 个分块不使用之前的输出作为前缀提示(将前缀重置为 "")。
|
||
unfixed_token_num:在 unfixed_chunk_num 之后将累积输出作为前缀提示时,回退最后 K 个 token。
|
||
chunk_size_sec:分块大小(秒,音频为 16k PCM)。函数会在内部将其转换为 16kHz 下的采样点数。
|
||
|
||
返回:
|
||
ASRStreamingState:可变状态对象,传递给 streaming_transcribe() 和 finish_streaming_transcribe()。
|
||
|
||
异常:
|
||
ValueError:
|
||
- backend 不是 "vllm"。
|
||
- chunk_size_sec <= 0。
|
||
- 强制语言无效(校验规则与 transcribe() 相同)。
|
||
"""
|
||
if self.backend != "vllm":
|
||
raise ValueError("Streaming ASR is supported only for vLLM backend (backend='vllm').")
|
||
if chunk_size_sec is None or float(chunk_size_sec) <= 0:
|
||
raise ValueError(f"chunk_size_sec must be > 0, got: {chunk_size_sec}")
|
||
|
||
force_language = None
|
||
if language is not None and str(language).strip() != "":
|
||
ln = normalize_language_name(str(language))
|
||
validate_language(ln)
|
||
force_language = ln
|
||
|
||
chunk_size_samples = int(round(float(chunk_size_sec) * SAMPLE_RATE))
|
||
chunk_size_samples = max(1, chunk_size_samples)
|
||
|
||
prompt_raw = self._build_text_prompt(context=context, force_language=force_language)
|
||
|
||
return ASRStreamingState(
|
||
unfixed_chunk_num=int(unfixed_chunk_num),
|
||
unfixed_token_num=int(unfixed_token_num),
|
||
chunk_size_sec=float(chunk_size_sec),
|
||
chunk_size_samples=int(chunk_size_samples),
|
||
chunk_id=0,
|
||
buffer=np.zeros((0,), dtype=np.float32),
|
||
audio_accum=np.zeros((0,), dtype=np.float32),
|
||
prompt_raw=prompt_raw,
|
||
context=context or "",
|
||
force_language=force_language,
|
||
language="",
|
||
text="",
|
||
_raw_decoded="",
|
||
chunk_text=[],
|
||
last_fixed_text="",
|
||
_first_chunk_discarded=False
|
||
)
|
||
|
||
def streaming_transcribe(
|
||
self,
|
||
pcm16k: np.ndarray,
|
||
state: ASRStreamingState,
|
||
max_new_tokens=None,
|
||
rollback_punctuation: bool = False,
|
||
) -> Tuple[str, str]:
|
||
"""
|
||
流式 ASR 解码步骤。
|
||
|
||
此函数接收任意长度的 16k PCM float numpy 数组(单声道)。
|
||
它会缓冲输入采样点;每当累积的采样点足以组成一个完整分块(chunk_size_sec)时,
|
||
就执行一次增量解码并更新:
|
||
|
||
- state.language
|
||
- state.text
|
||
|
||
调用方只需持续向此函数传入音频,并读取 state.language/state.text。
|
||
|
||
实现细节:
|
||
- 每当新分块就绪时,将其追加到 audio_accum,并将截至目前的*全部*音频重新输入模型
|
||
(不进行填充)。
|
||
- 按以下方式更新提示:state.prompt_raw + prefix_text
|
||
- 前缀回退策略:
|
||
* 如果 chunk_id < unfixed_chunk_num:prefix_text = ""
|
||
* 否则:从之前累积的解码文本中回退最后 unfixed_token_num 个 token。
|
||
|
||
注意:
|
||
- 仅支持 vLLM 后端。
|
||
- 不提供时间戳。
|
||
- 仅支持单流(不支持批处理)。
|
||
|
||
参数:
|
||
pcm16k:16kHz 单声道 PCM 波形(np.ndarray)。长度可以是任意非负整数。
|
||
dtype 可以是 float32/float64/int16;将转换为 float32。
|
||
state:init_streaming_state() 返回的流式状态。
|
||
|
||
返回:
|
||
Tuple[str, str]:包含最新转写文本(``state.text``)和当前更新中已固定文本
|
||
(``fixed_text``)的元组。状态对象会原地修改。
|
||
|
||
异常:
|
||
ValueError:backend 不是 "vllm" 或状态无效。
|
||
"""
|
||
if max_new_tokens is not None:
|
||
from vllm import SamplingParams
|
||
if self.backend != "vllm":
|
||
raise ValueError("streaming_transcribe() is supported only for vLLM backend (backend='vllm').")
|
||
if state is None:
|
||
raise ValueError("state must not be None. Call init_streaming_state() first.")
|
||
if pcm16k is None:
|
||
raise ValueError("pcm16k must not be None.")
|
||
|
||
# 确保为一维单声道
|
||
x = np.asarray(pcm16k)
|
||
if x.ndim != 1:
|
||
x = x.reshape(-1)
|
||
|
||
# 如果输入为 int16,则转换为 [-1, 1] 范围内的 float32 PCM
|
||
if x.dtype == np.int16:
|
||
x = (x.astype(np.float32) / 32768.0)
|
||
else:
|
||
x = x.astype(np.float32, copy=False)
|
||
|
||
# 追加到缓冲区
|
||
if x.shape[0] > 0:
|
||
state.buffer = np.concatenate([state.buffer, x], axis=0)
|
||
|
||
# 消费完整分块
|
||
fixed_text = "" # 初始化,避免循环未执行时出现 UnboundLocalError
|
||
while state.buffer.shape[0] >= state.chunk_size_samples:
|
||
chunk = state.buffer[: state.chunk_size_samples]
|
||
state.buffer = state.buffer[state.chunk_size_samples :]
|
||
|
||
# 累积音频(从头重新输入,不进行填充)
|
||
if state.audio_accum.shape[0] == 0:
|
||
state.audio_accum = chunk
|
||
else:
|
||
state.audio_accum = np.concatenate([state.audio_accum, chunk], axis=0)
|
||
|
||
# 使用回退策略构建前缀
|
||
prefix = ""
|
||
if state.chunk_id < state.unfixed_chunk_num:
|
||
prefix = ""
|
||
else:
|
||
state._raw_decoded = state._raw_decoded.split("|")[0]
|
||
cur_ids = self.processor.tokenizer.encode(state._raw_decoded)
|
||
if rollback_punctuation == True:
|
||
_punct = ",。!?、;:.!?;:"
|
||
raw_stripped = state._raw_decoded.strip()
|
||
if raw_stripped and raw_stripped[-1] in _punct:
|
||
k = 0
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
while True:
|
||
end_idx = max(0, len(cur_ids) - k)
|
||
prefix = self.processor.tokenizer.decode(cur_ids[:end_idx]) if end_idx > 0 else ""
|
||
if '\ufffd' not in prefix:
|
||
break
|
||
else:
|
||
if end_idx == 0:
|
||
prefix = ""
|
||
break
|
||
k += 1
|
||
|
||
prefix = prefix.split("|")[0]
|
||
|
||
prompt = state.prompt_raw + prefix
|
||
|
||
# vLLM 输入:单个项目
|
||
inp = {"prompt": prompt, "multi_modal_data": {"audio": [state.audio_accum]}}
|
||
if max_new_tokens is not None:
|
||
sampling_params = SamplingParams(
|
||
temperature=0.0,
|
||
max_tokens=max_new_tokens,
|
||
skip_special_tokens=True,
|
||
)
|
||
outputs = self.model.generate([inp], sampling_params=sampling_params, use_tqdm=False)
|
||
else:
|
||
outputs = self.model.generate([inp], sampling_params=self.sampling_params, use_tqdm=False)
|
||
gen_text = outputs[0].outputs[0].text
|
||
gen_text = _normalize_punct_by_context(gen_text).replace('\ufffd', '')
|
||
#print(f"prefix={prefix}")
|
||
state._raw_decoded = (prefix + gen_text) if prefix is not None else gen_text
|
||
#print(f"state._raw_decoded={state._raw_decoded}")
|
||
|
||
lang = None
|
||
if state.force_language == None:
|
||
lang,_ = parse_language_output(state._raw_decoded, user_language=state.force_language)
|
||
|
||
if state.force_language == "Chinese" or lang == "Chinese":
|
||
# 移除相邻中文字符之间的多余空格;在中英文混合文本中保留英文空格
|
||
state._raw_decoded = re.sub(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])', '', state._raw_decoded)
|
||
lang, txt = parse_asr_output(state._raw_decoded, user_language=state.force_language)
|
||
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if has_tag:
|
||
state._raw_decoded = state._raw_decoded.split("<asr_text>")[0] + "<asr_text>" + txt
|
||
else:
|
||
state._raw_decoded = txt
|
||
|
||
state._raw_decoded = state._raw_decoded.split("|")[0]
|
||
cur_ids = self.processor.tokenizer.encode(state._raw_decoded)
|
||
if rollback_punctuation == True:
|
||
_punct = ",。!?、;:,.!?;:"
|
||
raw_stripped = state._raw_decoded.strip()
|
||
if raw_stripped and raw_stripped[-1] in _punct:
|
||
k = 0
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if has_tag and state._raw_decoded.split('<asr_text>')[1] == "":
|
||
k = 0
|
||
while True:
|
||
end_idx = max(0, len(cur_ids) - k)
|
||
fixed_text = self.processor.tokenizer.decode(cur_ids[:end_idx]) if end_idx > 0 else ""
|
||
if '\ufffd' not in fixed_text:
|
||
break
|
||
else:
|
||
if end_idx == 0:
|
||
fixed_text = ""
|
||
break
|
||
k += 1
|
||
has_tag = "<asr_text>" in fixed_text
|
||
if has_tag:
|
||
meta_part, fixed_text = fixed_text.split("<asr_text>", 1)
|
||
fixed_text = fixed_text.split("|")[0]
|
||
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if not has_tag and state.force_language == None:
|
||
state.text = ""
|
||
fixed_text = ""
|
||
continue
|
||
|
||
state.language = lang
|
||
state.text = txt.split("|")[0]
|
||
|
||
state.chunk_id += 1
|
||
|
||
return state.text,fixed_text
|
||
|
||
def finish_streaming_transcribe(
|
||
self,
|
||
state: ASRStreamingState,
|
||
max_new_tokens=None,
|
||
) -> str:
|
||
"""
|
||
完成流式 ASR。
|
||
|
||
此函数会刷新 state.buffer 中剩余的缓冲音频(尾部音频)。
|
||
即使剩余采样点少于 chunk_size_sec,也会在不填充的情况下发送给模型。
|
||
然后最后一次更新 state.language/state.text。
|
||
|
||
注意:
|
||
- 仅支持 vLLM 后端。
|
||
- 不提供时间戳。
|
||
- 仅支持单流。
|
||
|
||
参数:
|
||
state:init_streaming_state() 返回的流式状态。
|
||
max_new_tokens:最终解码时可选的最大生成 token 数。
|
||
|
||
返回:
|
||
str:最新的转写文本(``state.text``)。状态对象会原地修改,且可复用于后续流式调用。
|
||
|
||
异常:
|
||
ValueError:backend 不是 "vllm" 或状态无效。
|
||
"""
|
||
if max_new_tokens is not None:
|
||
from vllm import SamplingParams
|
||
if self.backend != "vllm":
|
||
raise ValueError("finish_streaming_transcribe() is supported only for vLLM backend (backend='vllm').")
|
||
if state is None:
|
||
raise ValueError("state must not be None.")
|
||
|
||
# 如果没有剩余缓冲区,仍按原样返回状态。
|
||
if state.buffer is None or state.buffer.shape[0] == 0:
|
||
return state.text
|
||
|
||
tail = state.buffer
|
||
state.buffer = np.zeros((0,), dtype=np.float32)
|
||
|
||
# 将尾部追加到累积音频
|
||
if state.audio_accum.shape[0] == 0:
|
||
state.audio_accum = tail
|
||
else:
|
||
state.audio_accum = np.concatenate([state.audio_accum, tail], axis=0)
|
||
|
||
# 前缀回退策略(与逐分块处理相同)
|
||
prefix = ""
|
||
if state.chunk_id < state.unfixed_chunk_num:
|
||
prefix = ""
|
||
else:
|
||
cur_ids = self.processor.tokenizer.encode(state._raw_decoded)
|
||
end_idx = max(1, len(cur_ids) - int(state.unfixed_token_num))
|
||
prefix = self.processor.tokenizer.decode(cur_ids[:end_idx])
|
||
|
||
prefix = prefix.split("|")[0]
|
||
prompt = state.prompt_raw + prefix
|
||
inp = {"prompt": prompt, "multi_modal_data": {"audio": [state.audio_accum]}}
|
||
|
||
if max_new_tokens is not None:
|
||
sampling_params = SamplingParams(
|
||
temperature=0.0,
|
||
max_tokens=max_new_tokens,
|
||
skip_special_tokens=True,
|
||
)
|
||
outputs = self.model.generate([inp], sampling_params=sampling_params, use_tqdm=False)
|
||
else:
|
||
outputs = self.model.generate([inp], sampling_params=self.sampling_params, use_tqdm=False)
|
||
gen_text = outputs[0].outputs[0].text
|
||
gen_text = _normalize_punct_by_context(gen_text).replace('\ufffd', '')
|
||
|
||
state._raw_decoded = (prefix + gen_text) if prefix is not None else gen_text
|
||
state._raw_decoded = state._raw_decoded.split("|")[0]
|
||
lang, txt = parse_asr_output(state._raw_decoded, user_language=state.force_language)
|
||
|
||
state.language = lang
|
||
state.text = txt.split("|")[0]
|
||
state.chunk_id += 1
|
||
return state.text
|
||
|
||
def streaming_transcribe_no_reset(
|
||
self,
|
||
pcm16k: np.ndarray,
|
||
state: ASRStreamingState,
|
||
max_new_tokens=None,
|
||
rollback_punctuation: bool = False,
|
||
) -> Tuple[str, str]:
|
||
"""不重置累积上下文的流式 ASR 解码步骤。
|
||
|
||
此变体维护滚动音频窗口,并将已固定文本累积在 ``state.last_fixed_text`` 中。
|
||
它会缓冲输入采样点,解码每个完整分块,并原地更新流式状态。
|
||
|
||
注意:
|
||
- 仅支持 vLLM 后端。
|
||
- 不提供时间戳。
|
||
- 仅支持单流(不支持批处理)。
|
||
|
||
参数:
|
||
pcm16k:16kHz 单声道 PCM 波形(np.ndarray)。长度可以是任意非负整数,
|
||
函数内部会将其转换为 float32。
|
||
state:init_streaming_state() 返回的流式状态。
|
||
max_new_tokens:每个分块可生成的最大 token 数。
|
||
rollback_punctuation:如果为 True,则当前输出以标点结尾时不回退 token。
|
||
|
||
返回:
|
||
Tuple[str, str]:包含最新转写文本(``state.text``)和累积已固定转写文本
|
||
(``state.last_fixed_text``)的元组。状态对象会原地修改。
|
||
|
||
异常:
|
||
ValueError:backend 不是 "vllm"、状态无效或 pcm16k 为 None。
|
||
"""
|
||
if max_new_tokens is not None:
|
||
from vllm import SamplingParams
|
||
if self.backend != "vllm":
|
||
raise ValueError("streaming_transcribe() is supported only for vLLM backend (backend='vllm').")
|
||
if state is None:
|
||
raise ValueError("state must not be None. Call init_streaming_state() first.")
|
||
if pcm16k is None:
|
||
raise ValueError("pcm16k must not be None.")
|
||
|
||
# 确保为一维单声道
|
||
x = np.asarray(pcm16k)
|
||
if x.ndim != 1:
|
||
x = x.reshape(-1)
|
||
|
||
# 如果输入为 int16,则转换为 [-1, 1] 范围内的 float32 PCM
|
||
if x.dtype == np.int16:
|
||
x = (x.astype(np.float32) / 32768.0)
|
||
else:
|
||
x = x.astype(np.float32, copy=False)
|
||
|
||
# 追加到缓冲区
|
||
if x.shape[0] > 0:
|
||
state.buffer = np.concatenate([state.buffer, x], axis=0)
|
||
|
||
# 消费完整分块
|
||
fixed_text = "" # 初始化,避免循环未执行时出现 UnboundLocalError
|
||
omit_new_asr_text = ""
|
||
while state.buffer.shape[0] >= state.chunk_size_samples:
|
||
chunk = state.buffer[: state.chunk_size_samples]
|
||
state.buffer = state.buffer[state.chunk_size_samples :]
|
||
|
||
# 累积音频(从头重新输入,不进行填充)
|
||
if state.audio_accum.shape[0] == 0:
|
||
state.audio_accum = chunk
|
||
else:
|
||
state.audio_accum = np.concatenate([state.audio_accum, chunk], axis=0)
|
||
# 当累积音频达到 16 秒时,丢弃最早的 8 秒及其对应文本
|
||
max_samples = 16 * SAMPLE_RATE
|
||
discard_samples = 8 * SAMPLE_RATE
|
||
if state.audio_accum.shape[0] > max_samples:
|
||
keep_samples = state.audio_accum.shape[0] - discard_samples
|
||
# 计算要丢弃的准确分块数:第一个分块为 320 毫秒(5,120 个采样点),后续分块为 160 毫秒(2,560 个采样点)
|
||
normal_chunk_samples = 2560 # 160 毫秒
|
||
if not state._first_chunk_discarded:
|
||
# 第一次丢弃:第一个分块为 320 毫秒
|
||
first_chunk_samples = 5120 # 320 毫秒
|
||
discard_chunks = 1 + (discard_samples - first_chunk_samples) // normal_chunk_samples # = 49
|
||
state._first_chunk_discarded = True
|
||
else:
|
||
# 后续丢弃:所有分块均为 160 毫秒
|
||
discard_chunks = discard_samples // normal_chunk_samples # = 50
|
||
state.audio_accum = state.audio_accum[-keep_samples:]
|
||
state.chunk_text = state.chunk_text[discard_chunks:]
|
||
|
||
prefix_text = "".join(state.chunk_text)
|
||
if state.force_language == None and state.language != "":
|
||
prefix = f"language {state.language}<asr_text>" + prefix_text
|
||
else:
|
||
prefix = prefix_text
|
||
prefix = prefix.split("|")[0]
|
||
|
||
prompt = state.prompt_raw + prefix
|
||
|
||
# vLLM 输入:单个项目
|
||
inp = {"prompt": prompt, "multi_modal_data": {"audio": [state.audio_accum]}}
|
||
if max_new_tokens is not None:
|
||
sampling_params = SamplingParams(
|
||
temperature=0.0,
|
||
max_tokens=max_new_tokens,
|
||
skip_special_tokens=True,
|
||
)
|
||
outputs = self.model.generate([inp], sampling_params=sampling_params, use_tqdm=False)
|
||
else:
|
||
outputs = self.model.generate([inp], sampling_params=self.sampling_params, use_tqdm=False)
|
||
gen_text = outputs[0].outputs[0].text
|
||
# gen_text = gen_text.replace("#","|")
|
||
gen_text = _normalize_punct_by_context(gen_text).replace('\ufffd', '')
|
||
|
||
state._raw_decoded = (prefix + gen_text) if prefix is not None else gen_text
|
||
|
||
lang = None
|
||
if state.force_language == None:
|
||
lang,_ = parse_language_output(state._raw_decoded, user_language=state.force_language)
|
||
|
||
if state.force_language == "Chinese" or lang == "Chinese":
|
||
# 移除相邻中文字符之间的多余空格;在中英文混合文本中保留英文空格
|
||
state._raw_decoded = re.sub(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])', '', state._raw_decoded)
|
||
lang, txt = parse_asr_output(state._raw_decoded, user_language=state.force_language)
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if has_tag:
|
||
state._raw_decoded = state._raw_decoded.split("<asr_text>")[0] + "<asr_text>" + txt
|
||
else:
|
||
state._raw_decoded = txt
|
||
|
||
state._raw_decoded = state._raw_decoded.split("|")[0]
|
||
cur_ids = self.processor.tokenizer.encode(state._raw_decoded)
|
||
if rollback_punctuation == True:
|
||
_punct = ",。!?、;:,.!?;:"
|
||
raw_stripped = state._raw_decoded.strip()
|
||
if raw_stripped and raw_stripped[-1] in _punct:
|
||
k = 0
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
else:
|
||
k = int(state.unfixed_token_num)
|
||
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if has_tag and state._raw_decoded.split('<asr_text>')[1] == "":
|
||
k = 0
|
||
while True:
|
||
end_idx = max(0, len(cur_ids) - k)
|
||
fixed_text = self.processor.tokenizer.decode(cur_ids[:end_idx]) if end_idx > 0 else ""
|
||
if '\ufffd' not in fixed_text:
|
||
break
|
||
else:
|
||
if end_idx == 0:
|
||
fixed_text = ""
|
||
break
|
||
k += 1
|
||
has_tag = "<asr_text>" in fixed_text
|
||
if has_tag:
|
||
meta_part, fixed_text = fixed_text.split("<asr_text>", 1)
|
||
|
||
has_tag = "<asr_text>" in state._raw_decoded
|
||
if not has_tag and state.force_language == None:
|
||
state.text = ""
|
||
fixed_text = ""
|
||
continue
|
||
|
||
state.language = lang
|
||
state.text = txt.split("|")[0]
|
||
|
||
state.chunk_id += 1
|
||
prefix_stripped = prefix_text.strip()
|
||
fixed_text_stripped = fixed_text.strip()
|
||
if fixed_text_stripped.startswith(prefix_stripped):
|
||
new_asr_text = fixed_text_stripped[len(prefix_stripped):]
|
||
else:
|
||
new_asr_text = ""
|
||
new_asr_text = new_asr_text.split("|")[0]
|
||
state.chunk_text.append(new_asr_text)
|
||
state.last_fixed_text = state.last_fixed_text + new_asr_text
|
||
|
||
|
||
return state.text, state.last_fixed_text
|
||
|
||
def finish_streaming_transcribe_no_reset(
|
||
self,
|
||
state: ASRStreamingState,
|
||
max_new_tokens=None,
|
||
) -> str:
|
||
"""
|
||
完成流式 ASR,但不重置累积上下文。
|
||
|
||
此函数会刷新 state.buffer 中剩余的缓冲音频(尾部音频)。即使剩余采样点少于
|
||
chunk_size_sec,也会在不填充的情况下发送给模型,并将新固定的文本追加到
|
||
``state.last_fixed_text``。
|
||
|
||
注意:
|
||
- 仅支持 vLLM 后端。
|
||
- 不提供时间戳。
|
||
- 仅支持单流。
|
||
|
||
参数:
|
||
state:init_streaming_state() 返回的流式状态。
|
||
max_new_tokens:最终解码时可选的最大生成 token 数。
|
||
|
||
返回:
|
||
str:累积的已固定转写文本(``state.last_fixed_text``)。状态对象会原地修改。
|
||
如果没有剩余尾部音频,则返回当前已固定文本,不再发起模型请求。
|
||
|
||
异常:
|
||
ValueError:backend 不是 "vllm" 或状态无效。
|
||
"""
|
||
if max_new_tokens is not None:
|
||
from vllm import SamplingParams
|
||
if self.backend != "vllm":
|
||
raise ValueError("finish_streaming_transcribe() is supported only for vLLM backend (backend='vllm').")
|
||
if state is None:
|
||
raise ValueError("state must not be None.")
|
||
|
||
# 如果没有剩余缓冲区,仍按原样返回状态。
|
||
if state.buffer is None or state.buffer.shape[0] == 0:
|
||
# print(f"22text={state.text}")
|
||
return state.last_fixed_text
|
||
|
||
tail = state.buffer
|
||
state.buffer = np.zeros((0,), dtype=np.float32)
|
||
|
||
# 将尾部追加到累积音频
|
||
if state.audio_accum.shape[0] == 0:
|
||
state.audio_accum = tail
|
||
else:
|
||
state.audio_accum = np.concatenate([state.audio_accum, tail], axis=0)
|
||
|
||
# 当累积音频达到 16 秒时,丢弃最早的 8 秒及其对应文本
|
||
max_samples = 16 * SAMPLE_RATE
|
||
discard_samples = 8 * SAMPLE_RATE
|
||
if state.audio_accum.shape[0] > max_samples:
|
||
keep_samples = state.audio_accum.shape[0] - discard_samples
|
||
# 计算要丢弃的准确分块数:第一个分块为 320 毫秒(5,120 个采样点),后续分块为 160 毫秒(2,560 个采样点)
|
||
normal_chunk_samples = 2560 # 160 毫秒
|
||
if not state._first_chunk_discarded:
|
||
# 第一次丢弃:第一个分块为 320 毫秒
|
||
first_chunk_samples = 5120 # 320 毫秒
|
||
discard_chunks = 1 + (discard_samples - first_chunk_samples) // normal_chunk_samples # = 49
|
||
state._first_chunk_discarded = True
|
||
else:
|
||
# 后续丢弃:所有分块均为 160 毫秒
|
||
discard_chunks = discard_samples // normal_chunk_samples # = 50
|
||
state.audio_accum = state.audio_accum[-keep_samples:]
|
||
state.chunk_text = state.chunk_text[discard_chunks:]
|
||
|
||
prefix_text = "".join(state.chunk_text)
|
||
if state.force_language == None and state.language != "":
|
||
prefix = f"language {state.language}<asr_text>" + prefix_text
|
||
else:
|
||
prefix = prefix_text
|
||
|
||
prefix = prefix.split("|")[0]
|
||
prompt = state.prompt_raw + prefix
|
||
|
||
inp = {"prompt": prompt, "multi_modal_data": {"audio": [state.audio_accum]}}
|
||
|
||
if max_new_tokens is not None:
|
||
sampling_params = SamplingParams(
|
||
temperature=0.0,
|
||
max_tokens=max_new_tokens,
|
||
skip_special_tokens=True,
|
||
)
|
||
outputs = self.model.generate([inp], sampling_params=sampling_params, use_tqdm=False)
|
||
else:
|
||
outputs = self.model.generate([inp], sampling_params=self.sampling_params, use_tqdm=False)
|
||
gen_text = outputs[0].outputs[0].text
|
||
|
||
gen_text = _normalize_punct_by_context(gen_text).replace('\ufffd', '')
|
||
|
||
state._raw_decoded = (prefix + gen_text) if prefix is not None else gen_text
|
||
state._raw_decoded = state._raw_decoded.split("|")[0]
|
||
lang, txt = parse_asr_output(state._raw_decoded, user_language=state.force_language)
|
||
txt = txt.split("|")[0]
|
||
state.language = lang
|
||
state.text = txt
|
||
state.chunk_id += 1
|
||
prefix_stripped = prefix_text.strip()
|
||
fixed_text_stripped = txt.strip()
|
||
new_asr_text = fixed_text_stripped[len(prefix_stripped):]
|
||
state.chunk_text.append(new_asr_text)
|
||
state.last_fixed_text = state.last_fixed_text + new_asr_text
|
||
return state.last_fixed_text
|
||
|
||
|
||
|
||
__all__ = ["R2T2ASRModel"]
|