797 lines
31 KiB
Python
797 lines
31 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Official vLLM adapter for CUDA Qwen3-ASR."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
import importlib.util
|
|
import logging
|
|
import os
|
|
import queue
|
|
import re
|
|
import threading
|
|
import time
|
|
import unicodedata
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Optional
|
|
|
|
import librosa
|
|
import numpy as np
|
|
|
|
from app.core.hotword_resolver import strip_hotword_prompt_leakage
|
|
from app.utils.text_processing import normalize_asr_text
|
|
|
|
from .engines import ASRRawResult, ASRSegmentResult, WordToken
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_DEFAULT_SAMPLE_RATE = 16000
|
|
_LANGUAGE_ALIASES = {
|
|
"zh": "Chinese",
|
|
"zh-cn": "Chinese",
|
|
"zh-hans": "Chinese",
|
|
"zh-hant": "Chinese",
|
|
"cn": "Chinese",
|
|
"en": "English",
|
|
"en-us": "English",
|
|
"en-gb": "English",
|
|
"ja": "Japanese",
|
|
"jp": "Japanese",
|
|
"ko": "Korean",
|
|
"yue": "Cantonese",
|
|
"fr": "French",
|
|
"de": "German",
|
|
"es": "Spanish",
|
|
"ru": "Russian",
|
|
}
|
|
_PROMPT_LEAK_PATTERNS = (
|
|
re.compile(r"^\s*Transcribe the speech accurately\.\s*", re.IGNORECASE),
|
|
re.compile(r"^\s*Transcribe the speech in [A-Za-z\s-]+\.\s*", re.IGNORECASE),
|
|
)
|
|
|
|
|
|
def is_vllm_available() -> bool:
|
|
"""Return True when the official vLLM runtime is installed."""
|
|
return importlib.util.find_spec("vllm") is not None
|
|
|
|
|
|
def _normalize_language_name(language: Optional[str]) -> Optional[str]:
|
|
if not language:
|
|
return None
|
|
normalized = language.strip()
|
|
if not normalized:
|
|
return None
|
|
alias = _LANGUAGE_ALIASES.get(normalized.lower())
|
|
if alias:
|
|
return alias
|
|
if " " in normalized:
|
|
return " ".join(part.capitalize() for part in normalized.split())
|
|
return normalized.capitalize()
|
|
|
|
|
|
def _load_audio(audio_path: str) -> np.ndarray:
|
|
audio, _sample_rate = librosa.load(audio_path, sr=_DEFAULT_SAMPLE_RATE, mono=True)
|
|
return audio.astype(np.float32)
|
|
|
|
|
|
def _build_chat_prompt(context: str = "", language: Optional[str] = None) -> str:
|
|
instructions: list[str] = []
|
|
if language:
|
|
instructions.append(f"Transcribe the speech in {language}.")
|
|
else:
|
|
instructions.append("Transcribe the speech accurately.")
|
|
if context.strip():
|
|
instructions.append(context.strip())
|
|
system_text = " ".join(instructions).strip()
|
|
return (
|
|
f"<|im_start|>system\n{system_text}<|im_end|>\n"
|
|
"<|im_start|>user\n<|audio_start|><|audio_pad|><|audio_end|><|im_end|>\n"
|
|
"<|im_start|>assistant\n"
|
|
)
|
|
|
|
|
|
def _build_alignment_prompt(tokens: list[str]) -> str:
|
|
body = "<timestamp><timestamp>".join(tokens) + "<timestamp><timestamp>"
|
|
return f"<|audio_start|><|audio_pad|><|audio_end|>{body}"
|
|
|
|
|
|
def _strip_prompt_leakage(text: str) -> str:
|
|
cleaned = text or ""
|
|
changed = True
|
|
while changed and cleaned:
|
|
changed = False
|
|
for pattern in _PROMPT_LEAK_PATTERNS:
|
|
updated, count = pattern.subn("", cleaned, count=1)
|
|
if count:
|
|
cleaned = updated
|
|
changed = True
|
|
return strip_hotword_prompt_leakage(cleaned)
|
|
|
|
|
|
def _sanitize_detected_language(detected: str, fallback: Optional[str]) -> str:
|
|
candidate = (detected or "").strip()
|
|
if not candidate:
|
|
return fallback or ""
|
|
|
|
candidate = re.sub(r"^[^\w]+", "", candidate)
|
|
match = re.search(r"language\s+([A-Za-z][A-Za-z\s-]*)$", candidate, re.IGNORECASE)
|
|
if match:
|
|
candidate = match.group(1).strip()
|
|
|
|
normalized = _normalize_language_name(candidate)
|
|
return normalized or (fallback or "")
|
|
|
|
|
|
def _parse_asr_output(raw_text: str, language: Optional[str]) -> tuple[str, str]:
|
|
text = (raw_text or "").strip()
|
|
if "<asr_text>" in text:
|
|
left, right = text.split("<asr_text>", 1)
|
|
detected = _sanitize_detected_language(left.strip(), language)
|
|
return detected, _strip_prompt_leakage(right.strip())
|
|
return (language or ""), _strip_prompt_leakage(text)
|
|
|
|
|
|
def _split_alignment_units(text: str) -> list[str]:
|
|
if not text:
|
|
return []
|
|
|
|
# Mixed Chinese/English transcripts should not fall back to whitespace-only
|
|
# tokenization, otherwise a long CJK sentence with a single embedded English
|
|
# word can collapse into one giant alignment unit.
|
|
token_pattern = re.compile(
|
|
r"[\u4e00-\u9fff]" # CJK ideographs, align per character
|
|
r"|[A-Za-z0-9]+(?:['._+-][A-Za-z0-9]+)*" # Latin / alnum words
|
|
r"|[^\w\s]", # punctuation and symbols
|
|
re.UNICODE,
|
|
)
|
|
return token_pattern.findall(text)
|
|
|
|
|
|
def _resolve_forced_aligner_gpu_memory_utilization(primary_utilization: float) -> float:
|
|
override = (os.getenv("QWEN_FORCE_ALIGNER_GPU_MEMORY_UTILIZATION") or "").strip()
|
|
if override:
|
|
try:
|
|
value = float(override)
|
|
if 0.0 < value <= 1.0:
|
|
return value
|
|
except ValueError:
|
|
logger.warning(
|
|
"Invalid QWEN_FORCE_ALIGNER_GPU_MEMORY_UTILIZATION=%s, ignoring override",
|
|
override,
|
|
)
|
|
|
|
return primary_utilization
|
|
|
|
|
|
@dataclass
|
|
class _GeneratedTranscript:
|
|
text: str
|
|
language: str
|
|
|
|
|
|
@dataclass
|
|
class _GenerateRequest:
|
|
prompts: list[dict[str, Any]]
|
|
sampling_params: Any
|
|
batch_key: tuple[Any, ...]
|
|
operation: str = "transcribe"
|
|
trace_id: str = ""
|
|
queued_at: float = field(default_factory=time.monotonic)
|
|
done: threading.Event = field(default_factory=threading.Event)
|
|
outputs: Optional[list[Any]] = None
|
|
error: Optional[Exception] = None
|
|
|
|
|
|
class _VLLMGenerateBatcher:
|
|
"""Collect concurrent session requests into small compatible vLLM batches."""
|
|
|
|
def __init__(
|
|
self,
|
|
llm: Any,
|
|
engine_lock: threading.RLock,
|
|
*,
|
|
batch_wait_ms: int,
|
|
max_batch_size: int,
|
|
) -> None:
|
|
self._llm = llm
|
|
self._engine_lock = engine_lock
|
|
self._batch_wait_sec = max(0, batch_wait_ms) / 1000.0
|
|
self._max_batch_size = max(1, max_batch_size)
|
|
self._requests: queue.Queue[_GenerateRequest] = queue.Queue()
|
|
self._pending: Optional[_GenerateRequest] = None
|
|
self._worker = threading.Thread(
|
|
target=self._run,
|
|
name="qwen-vllm-realtime-batcher",
|
|
daemon=True,
|
|
)
|
|
self._worker.start()
|
|
|
|
def generate(
|
|
self,
|
|
prompts: list[dict[str, Any]],
|
|
*,
|
|
sampling_params: Any,
|
|
batch_key: tuple[Any, ...],
|
|
operation: str = "transcribe",
|
|
trace_id: str = "",
|
|
) -> list[Any]:
|
|
request = _GenerateRequest(
|
|
prompts=prompts,
|
|
sampling_params=sampling_params,
|
|
batch_key=batch_key,
|
|
operation=operation,
|
|
trace_id=trace_id,
|
|
)
|
|
self._requests.put(request)
|
|
request.done.wait()
|
|
if request.error is not None:
|
|
raise request.error
|
|
return request.outputs or []
|
|
|
|
def _take_request(self, timeout: Optional[float] = None) -> _GenerateRequest:
|
|
if self._pending is not None:
|
|
request, self._pending = self._pending, None
|
|
return request
|
|
return self._requests.get(timeout=timeout)
|
|
|
|
def _run(self) -> None:
|
|
while True:
|
|
first = self._take_request()
|
|
collected = [first]
|
|
prompt_count = len(first.prompts)
|
|
deadline = time.monotonic() + self._batch_wait_sec
|
|
|
|
# A short collection window lets independently scheduled WebSocket
|
|
# sessions share one GPU launch, as FunASR's realtime batcher does.
|
|
while prompt_count < self._max_batch_size and self._batch_wait_sec > 0:
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
break
|
|
try:
|
|
request = self._requests.get(timeout=remaining)
|
|
except queue.Empty:
|
|
break
|
|
if prompt_count + len(request.prompts) > self._max_batch_size:
|
|
self._pending = request
|
|
break
|
|
collected.append(request)
|
|
prompt_count += len(request.prompts)
|
|
|
|
compatible: dict[tuple[Any, ...], list[_GenerateRequest]] = {}
|
|
for request in collected:
|
|
compatible.setdefault(request.batch_key, []).append(request)
|
|
|
|
for group in compatible.values():
|
|
self._generate_group(group)
|
|
|
|
def _generate_group(self, requests: list[_GenerateRequest]) -> None:
|
|
prompts = [prompt for request in requests for prompt in request.prompts]
|
|
queued_at = min(request.queued_at for request in requests)
|
|
lock_wait_started = time.monotonic()
|
|
try:
|
|
with self._engine_lock:
|
|
generate_started = time.monotonic()
|
|
outputs = self._llm.generate(
|
|
prompts,
|
|
sampling_params=requests[0].sampling_params,
|
|
use_tqdm=False,
|
|
)
|
|
if len(outputs) != len(prompts):
|
|
raise RuntimeError(
|
|
f"vLLM returned {len(outputs)} outputs for {len(prompts)} prompts"
|
|
)
|
|
generate_ms = (time.monotonic() - generate_started) * 1000.0
|
|
lock_wait_ms = (generate_started - lock_wait_started) * 1000.0
|
|
operations = ",".join(sorted({request.operation for request in requests}))
|
|
trace_ids = ",".join(sorted({request.trace_id for request in requests if request.trace_id})) or "-"
|
|
# Log every realtime decode so partial inference latency can be
|
|
# separated from final/offline transcription and queue contention.
|
|
if (
|
|
"realtime_partial" in operations
|
|
or len(requests) > 1
|
|
or generate_ms >= 500.0
|
|
or lock_wait_ms >= 100.0
|
|
):
|
|
logger.info(
|
|
"vLLM decode batch completed: operation=%s sessions=%s requests=%d prompts=%d max_tokens=%s "
|
|
"queue_wait_ms=%.1f engine_lock_wait_ms=%.1f generate_ms=%.1f",
|
|
operations,
|
|
trace_ids,
|
|
len(requests),
|
|
len(prompts),
|
|
getattr(requests[0].sampling_params, "max_tokens", None),
|
|
(lock_wait_started - queued_at) * 1000.0,
|
|
lock_wait_ms,
|
|
generate_ms,
|
|
)
|
|
cursor = 0
|
|
for request in requests:
|
|
request.outputs = list(outputs[cursor:cursor + len(request.prompts)])
|
|
cursor += len(request.prompts)
|
|
request.done.set()
|
|
except Exception as exc:
|
|
# A backend may reject a combined call for shape or memory reasons.
|
|
# Retry each request separately so one session cannot fail its peers.
|
|
memory_error = any(
|
|
marker in str(exc).lower()
|
|
for marker in ("out of memory", "no_memory", "cuda out of memory")
|
|
)
|
|
if len(requests) > 1 and not memory_error:
|
|
logger.warning("Combined vLLM request failed; retrying requests separately: %s", exc)
|
|
for request in requests:
|
|
try:
|
|
with self._engine_lock:
|
|
request.outputs = list(
|
|
self._llm.generate(
|
|
request.prompts,
|
|
sampling_params=request.sampling_params,
|
|
use_tqdm=False,
|
|
)
|
|
)
|
|
except Exception as request_exc:
|
|
request.error = request_exc
|
|
finally:
|
|
request.done.set()
|
|
return
|
|
for request in requests:
|
|
request.error = exc
|
|
request.done.set()
|
|
|
|
|
|
@dataclass
|
|
class VLLMRealtimeState:
|
|
prompt_raw: str
|
|
language: str
|
|
chunk_size_sec: float
|
|
unfixed_chunk_num: int
|
|
unfixed_token_num: int
|
|
max_new_tokens: int
|
|
trace_id: str = ""
|
|
max_audio_window_sec: float = 8.0
|
|
chunk_id: int = 0
|
|
text: str = ""
|
|
raw_decoded: str = ""
|
|
window_rolled: bool = False
|
|
audio_buffer: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.float32))
|
|
audio_accum: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.float32))
|
|
|
|
|
|
def _normalize_transcript_with_positions(text: str) -> tuple[str, list[int]]:
|
|
"""忽略标点比较窗口重叠,同时保留回到原文的位置映射。"""
|
|
normalized: list[str] = []
|
|
source_positions: list[int] = []
|
|
for index, char in enumerate(text):
|
|
category = unicodedata.category(char)
|
|
if char.isspace() or category.startswith(("P", "S")):
|
|
continue
|
|
folded = char.casefold()
|
|
normalized.extend(folded)
|
|
source_positions.extend([index] * len(folded))
|
|
return "".join(normalized), source_positions
|
|
|
|
|
|
def _merge_overlapping_transcripts(existing: str, incoming: str) -> Optional[str]:
|
|
"""Port FunASR's conservative suffix-to-prefix rolling-window merge."""
|
|
existing_norm, existing_positions = _normalize_transcript_with_positions(existing)
|
|
incoming_norm, incoming_positions = _normalize_transcript_with_positions(incoming)
|
|
if not existing_norm or not incoming_norm:
|
|
return None
|
|
|
|
minimum_overlap = max(4, min(len(existing_norm), len(incoming_norm)) // 4)
|
|
for overlap in range(min(len(existing_norm), len(incoming_norm)), minimum_overlap - 1, -1):
|
|
if existing_norm[-overlap:] != incoming_norm[:overlap]:
|
|
continue
|
|
existing_start = len(existing_norm) - overlap
|
|
if (
|
|
existing_start > 0
|
|
and existing_positions[existing_start - 1] == existing_positions[existing_start]
|
|
):
|
|
continue
|
|
if (
|
|
overlap < len(incoming_positions)
|
|
and incoming_positions[overlap - 1] == incoming_positions[overlap]
|
|
):
|
|
continue
|
|
|
|
suffix_start = incoming_positions[overlap - 1] + 1
|
|
# Keep punctuation from the incoming tail, but avoid duplicating a mark
|
|
# already present at the exact join boundary.
|
|
while suffix_start < len(incoming):
|
|
category = unicodedata.category(incoming[suffix_start])
|
|
if not category.startswith(("P", "S")) or not existing.endswith(incoming[suffix_start]):
|
|
break
|
|
suffix_start += 1
|
|
return existing + incoming[suffix_start:]
|
|
return None
|
|
|
|
|
|
class Qwen3VLLMBackend:
|
|
"""Thin adapter over official vLLM APIs for Qwen3-ASR."""
|
|
|
|
def __init__(
|
|
self,
|
|
model_path: str,
|
|
forced_aligner_path: Optional[str],
|
|
gpu_memory_utilization: float,
|
|
max_inference_batch_size: int,
|
|
max_new_tokens: int,
|
|
enforce_eager: bool = True,
|
|
max_model_len: Optional[int] = None,
|
|
tensor_parallel_size: int = 1,
|
|
decode_batch_wait_ms: int = 10,
|
|
decode_max_batch_size: int = 8,
|
|
) -> None:
|
|
try:
|
|
vllm_module = importlib.import_module("vllm")
|
|
transformers_module = importlib.import_module("transformers")
|
|
except ImportError as exc:
|
|
raise RuntimeError(
|
|
"CUDA Qwen3-ASR now requires official vLLM with Qwen3 forced aligner support. "
|
|
"Install it with: pip install 'vllm[audio]==0.19.0'"
|
|
) from exc
|
|
|
|
self._llm_cls = getattr(vllm_module, "LLM")
|
|
self._sampling_params_cls = getattr(vllm_module, "SamplingParams")
|
|
self._tokenizer = getattr(transformers_module, "AutoTokenizer").from_pretrained(
|
|
model_path,
|
|
trust_remote_code=True,
|
|
)
|
|
|
|
llm_kwargs: dict[str, Any] = {
|
|
"model": model_path,
|
|
"gpu_memory_utilization": gpu_memory_utilization,
|
|
"enforce_eager": enforce_eager,
|
|
"trust_remote_code": True,
|
|
}
|
|
if max_model_len is not None:
|
|
llm_kwargs["max_model_len"] = max_model_len
|
|
if tensor_parallel_size > 1:
|
|
llm_kwargs["tensor_parallel_size"] = tensor_parallel_size
|
|
|
|
self._llm = self._llm_cls(**llm_kwargs)
|
|
self._sampling_params = self._sampling_params_cls(
|
|
temperature=0.01,
|
|
max_tokens=max_new_tokens,
|
|
)
|
|
self._max_inference_batch_size = max(1, max_inference_batch_size)
|
|
self._decode_max_batch_size = max(1, decode_max_batch_size)
|
|
self._gpu_memory_utilization = gpu_memory_utilization
|
|
self._enforce_eager = enforce_eager
|
|
self._tensor_parallel_size = tensor_parallel_size
|
|
self._forced_aligner_path = forced_aligner_path
|
|
self._forced_aligner: Any | None = None
|
|
self._timestamp_token_id: int | None = None
|
|
self._timestamp_segment_time: float | None = None
|
|
# Keep generation and forced alignment mutually exclusive on this engine.
|
|
self._engine_lock = threading.RLock()
|
|
self._generate_batcher = _VLLMGenerateBatcher(
|
|
self._llm,
|
|
self._engine_lock,
|
|
batch_wait_ms=decode_batch_wait_ms,
|
|
max_batch_size=self._decode_max_batch_size,
|
|
)
|
|
logger.info(
|
|
"Enabled vLLM decode micro-batching: wait_ms=%s, max_batch_size=%s",
|
|
max(0, decode_batch_wait_ms),
|
|
self._decode_max_batch_size,
|
|
)
|
|
|
|
def _get_forced_aligner_gpu_memory_utilization(self) -> float:
|
|
configured = _resolve_forced_aligner_gpu_memory_utilization(self._gpu_memory_utilization)
|
|
logger.info(
|
|
"Resolved forced aligner gpu_memory_utilization=%s (primary=%s)",
|
|
configured,
|
|
self._gpu_memory_utilization,
|
|
)
|
|
return configured
|
|
|
|
def _get_forced_aligner(self) -> Any:
|
|
if not self._forced_aligner_path:
|
|
raise RuntimeError("word_timestamps requires a configured forced aligner model")
|
|
|
|
if self._forced_aligner is None:
|
|
forced_aligner_gpu_memory_utilization = self._get_forced_aligner_gpu_memory_utilization()
|
|
logger.info(
|
|
"Loading Qwen3 forced aligner via official vLLM: %s (gpu_memory_utilization=%s)",
|
|
self._forced_aligner_path,
|
|
forced_aligner_gpu_memory_utilization,
|
|
)
|
|
self._forced_aligner = self._llm_cls(
|
|
model=self._forced_aligner_path,
|
|
runner="pooling",
|
|
enforce_eager=self._enforce_eager,
|
|
gpu_memory_utilization=forced_aligner_gpu_memory_utilization,
|
|
tensor_parallel_size=self._tensor_parallel_size,
|
|
trust_remote_code=True,
|
|
hf_overrides={
|
|
"architectures": ["Qwen3ASRForcedAlignerForTokenClassification"],
|
|
},
|
|
)
|
|
llm_engine = getattr(self._forced_aligner, "llm_engine", None)
|
|
if llm_engine is None:
|
|
raise RuntimeError("Forced aligner did not expose a vLLM engine instance")
|
|
config = llm_engine.vllm_config.model_config.hf_config
|
|
self._timestamp_token_id = int(config.timestamp_token_id)
|
|
self._timestamp_segment_time = float(config.timestamp_segment_time)
|
|
|
|
return self._forced_aligner
|
|
|
|
def ensure_forced_aligner_loaded(self) -> None:
|
|
if self._forced_aligner_path:
|
|
self._get_forced_aligner()
|
|
|
|
def _run_generate(
|
|
self,
|
|
audio_items: list[tuple[np.ndarray, str, Optional[str]]],
|
|
) -> list[_GeneratedTranscript]:
|
|
prompts: list[dict[str, Any]] = []
|
|
for audio, context, language in audio_items:
|
|
prompts.append(
|
|
{
|
|
"prompt": _build_chat_prompt(context=context, language=_normalize_language_name(language)),
|
|
"multi_modal_data": {"audio": [audio]},
|
|
}
|
|
)
|
|
|
|
outputs: list[Any] = []
|
|
# Keep one offline request within the same hard batch cap used for
|
|
# combining concurrent realtime sessions.
|
|
for start in range(0, len(prompts), self._decode_max_batch_size):
|
|
outputs.extend(
|
|
self._generate_batcher.generate(
|
|
prompts[start:start + self._decode_max_batch_size],
|
|
sampling_params=self._sampling_params,
|
|
batch_key=(self._sampling_params.max_tokens, self._sampling_params.temperature),
|
|
operation="transcribe",
|
|
)
|
|
)
|
|
|
|
transcripts: list[_GeneratedTranscript] = []
|
|
for output, (_audio, _context, language) in zip(outputs, audio_items):
|
|
raw_text = str(output.outputs[0].text if output.outputs else "")
|
|
parsed_language, parsed_text = _parse_asr_output(raw_text, _normalize_language_name(language))
|
|
transcripts.append(_GeneratedTranscript(text=parsed_text, language=parsed_language))
|
|
return transcripts
|
|
|
|
def transcribe_text(
|
|
self,
|
|
audio_path: str,
|
|
context: str = "",
|
|
language: Optional[str] = None,
|
|
enable_itn: bool = False,
|
|
) -> str:
|
|
transcript = self._run_generate([(_load_audio(audio_path), context, language)])[0]
|
|
return normalize_asr_text(transcript.text, enable_itn=enable_itn)
|
|
|
|
def transcribe_raw(
|
|
self,
|
|
audio_path: str,
|
|
context: str = "",
|
|
language: Optional[str] = None,
|
|
word_timestamps: bool = False,
|
|
enable_itn: bool = False,
|
|
) -> ASRRawResult:
|
|
audio = _load_audio(audio_path)
|
|
transcript = self._run_generate([(audio, context, language)])[0]
|
|
text = normalize_asr_text(transcript.text, enable_itn=enable_itn)
|
|
if not word_timestamps:
|
|
return ASRRawResult(
|
|
text=text,
|
|
segments=[ASRSegmentResult(text=text, start_time=0.0, end_time=0.0)] if text else [],
|
|
)
|
|
|
|
aligned = self.align_transcript(audio_path=audio_path, text=text, language=language, audio=audio)
|
|
word_tokens = [
|
|
WordToken(
|
|
text=str(item["text"]),
|
|
start_time=round(float(item["start_ms"]) / 1000.0, 3),
|
|
end_time=round(float(item["end_ms"]) / 1000.0, 3),
|
|
)
|
|
for item in aligned
|
|
]
|
|
if not word_tokens:
|
|
return ASRRawResult(
|
|
text=text,
|
|
segments=[ASRSegmentResult(text=text, start_time=0.0, end_time=0.0)] if text else [],
|
|
)
|
|
return ASRRawResult(
|
|
text=text,
|
|
segments=[
|
|
ASRSegmentResult(
|
|
text=text,
|
|
start_time=word_tokens[0].start_time,
|
|
end_time=word_tokens[-1].end_time,
|
|
word_tokens=word_tokens,
|
|
)
|
|
],
|
|
)
|
|
|
|
def transcribe_batch(
|
|
self,
|
|
audio_paths: list[str],
|
|
context: str = "",
|
|
language: Optional[str] = None,
|
|
word_timestamps: bool = False,
|
|
enable_itn: bool = False,
|
|
) -> list[ASRSegmentResult]:
|
|
audios = [_load_audio(path) for path in audio_paths]
|
|
results: list[ASRSegmentResult] = []
|
|
for start in range(0, len(audios), self._max_inference_batch_size):
|
|
chunk = audios[start:start + self._max_inference_batch_size]
|
|
transcripts = self._run_generate([(audio, context, language) for audio in chunk])
|
|
for audio_path, audio, transcript in zip(audio_paths[start:start + len(chunk)], chunk, transcripts):
|
|
text = normalize_asr_text(transcript.text, enable_itn=enable_itn)
|
|
if not word_timestamps:
|
|
results.append(ASRSegmentResult(text=text, start_time=0.0, end_time=0.0))
|
|
continue
|
|
aligned = self.align_transcript(
|
|
audio_path=audio_path,
|
|
text=text,
|
|
language=language,
|
|
audio=audio,
|
|
)
|
|
word_tokens = [
|
|
WordToken(
|
|
text=str(item["text"]),
|
|
start_time=round(float(item["start_ms"]) / 1000.0, 3),
|
|
end_time=round(float(item["end_ms"]) / 1000.0, 3),
|
|
)
|
|
for item in aligned
|
|
]
|
|
results.append(
|
|
ASRSegmentResult(
|
|
text=text,
|
|
start_time=word_tokens[0].start_time if word_tokens else 0.0,
|
|
end_time=word_tokens[-1].end_time if word_tokens else 0.0,
|
|
word_tokens=word_tokens or None,
|
|
)
|
|
)
|
|
return results
|
|
|
|
def align_transcript(
|
|
self,
|
|
audio_path: str,
|
|
text: str,
|
|
language: Optional[str] = None,
|
|
audio: Optional[np.ndarray] = None,
|
|
) -> list[dict[str, float | str]]:
|
|
tokens = _split_alignment_units(text)
|
|
if not tokens:
|
|
return []
|
|
|
|
aligner = self._get_forced_aligner()
|
|
prompt = _build_alignment_prompt(tokens)
|
|
audio_array = audio if audio is not None else _load_audio(audio_path)
|
|
with self._engine_lock:
|
|
outputs = aligner.encode(
|
|
[{"prompt": prompt, "multi_modal_data": {"audio": audio_array}}],
|
|
pooling_task="token_classify",
|
|
)
|
|
output = outputs[0]
|
|
logits = output.outputs.data
|
|
predictions = logits.argmax(dim=-1) if hasattr(logits, "argmax") else np.argmax(logits, axis=-1)
|
|
ts_predictions = [
|
|
float(pred.item() if hasattr(pred, "item") else pred) * float(self._timestamp_segment_time or 0.0)
|
|
for tid, pred in zip(output.prompt_token_ids, predictions)
|
|
if int(tid) == int(self._timestamp_token_id or -1)
|
|
]
|
|
|
|
expected_timestamps = len(tokens) * 2
|
|
if len(ts_predictions) < expected_timestamps:
|
|
raise RuntimeError(
|
|
"Forced aligner returned fewer timestamp predictions than expected: "
|
|
f"expected={expected_timestamps}, got={len(ts_predictions)}, tokens={len(tokens)}"
|
|
)
|
|
|
|
aligned: list[dict[str, float | str]] = []
|
|
for index, token in enumerate(tokens):
|
|
start_ms = ts_predictions[index * 2]
|
|
end_ms = ts_predictions[index * 2 + 1]
|
|
if end_ms < start_ms:
|
|
logger.warning(
|
|
"Forced aligner produced reversed timestamps for token=%r: start_ms=%s end_ms=%s",
|
|
token,
|
|
start_ms,
|
|
end_ms,
|
|
)
|
|
start_ms, end_ms = end_ms, start_ms
|
|
aligned.append({"text": token, "start_ms": start_ms, "end_ms": end_ms})
|
|
return aligned
|
|
|
|
def init_streaming_state(
|
|
self,
|
|
*,
|
|
context: str = "",
|
|
language: Optional[str] = None,
|
|
chunk_size_sec: float = 1.2,
|
|
unfixed_chunk_num: int = 2,
|
|
unfixed_token_num: int = 5,
|
|
max_new_tokens: int = 32,
|
|
max_audio_window_sec: float = 8.0,
|
|
trace_id: str = "",
|
|
) -> VLLMRealtimeState:
|
|
normalized_language = _normalize_language_name(language) or ""
|
|
return VLLMRealtimeState(
|
|
prompt_raw=_build_chat_prompt(context=context, language=normalized_language or None),
|
|
language=normalized_language,
|
|
chunk_size_sec=chunk_size_sec,
|
|
unfixed_chunk_num=unfixed_chunk_num,
|
|
unfixed_token_num=unfixed_token_num,
|
|
max_new_tokens=max_new_tokens,
|
|
trace_id=trace_id,
|
|
max_audio_window_sec=max(1.0, max_audio_window_sec),
|
|
audio_buffer=np.array([], dtype=np.float32),
|
|
audio_accum=np.array([], dtype=np.float32),
|
|
)
|
|
|
|
def _decode_stream(self, state: VLLMRealtimeState) -> VLLMRealtimeState:
|
|
prefix = ""
|
|
# After the audio window rolls, decode a fresh window snapshot and stitch
|
|
# its text overlap; old token prefixes would pin the model to stale audio.
|
|
if not state.window_rolled and state.chunk_id >= state.unfixed_chunk_num and state.raw_decoded:
|
|
token_ids = self._tokenizer.encode(state.raw_decoded, add_special_tokens=False)
|
|
rollback = token_ids[-state.unfixed_token_num:] if state.unfixed_token_num > 0 else []
|
|
if rollback:
|
|
prefix = self._tokenizer.decode(rollback, skip_special_tokens=False).replace("\ufffd", "")
|
|
|
|
sampling_params = self._sampling_params_cls(
|
|
temperature=0.01,
|
|
max_tokens=state.max_new_tokens,
|
|
)
|
|
output = self._generate_batcher.generate(
|
|
[
|
|
{
|
|
"prompt": state.prompt_raw + prefix,
|
|
"multi_modal_data": {"audio": [state.audio_accum]},
|
|
}
|
|
],
|
|
sampling_params=sampling_params,
|
|
batch_key=(state.max_new_tokens, 0.01),
|
|
operation="realtime_partial",
|
|
trace_id=state.trace_id,
|
|
)[0]
|
|
generated = str(output.outputs[0].text if output.outputs else "")
|
|
parsed_language, parsed_text = _parse_asr_output(prefix + generated, state.language or None)
|
|
state.raw_decoded = prefix + generated
|
|
if state.window_rolled and parsed_text:
|
|
merged_text = _merge_overlapping_transcripts(state.text, parsed_text)
|
|
# FunASR only joins a confirmed suffix-prefix overlap; on mismatch it
|
|
# starts a fresh partial snapshot instead of guessing an interior match.
|
|
state.text = merged_text if merged_text is not None else parsed_text
|
|
elif not state.window_rolled:
|
|
state.text = parsed_text
|
|
state.language = parsed_language or state.language
|
|
state.chunk_id += 1
|
|
return state
|
|
|
|
def feed_stream(self, pcm: np.ndarray, state: VLLMRealtimeState) -> VLLMRealtimeState:
|
|
state.audio_buffer = np.concatenate([state.audio_buffer, pcm.astype(np.float32)])
|
|
segment_size = int(max(state.chunk_size_sec, 0.1) * _DEFAULT_SAMPLE_RATE)
|
|
while len(state.audio_buffer) >= segment_size:
|
|
segment = state.audio_buffer[:segment_size].copy()
|
|
state.audio_buffer = state.audio_buffer[segment_size:]
|
|
state.audio_accum = np.concatenate([state.audio_accum, segment])
|
|
max_window_samples = int(state.max_audio_window_sec * _DEFAULT_SAMPLE_RATE)
|
|
if len(state.audio_accum) > max_window_samples:
|
|
samples_to_drop = len(state.audio_accum) - max_window_samples
|
|
# Partial 只保留最近窗口,完整音频仍由 WebSocket 侧保留用于定稿。
|
|
state.audio_accum = state.audio_accum[samples_to_drop:]
|
|
state.window_rolled = True
|
|
state = self._decode_stream(state)
|
|
return state
|
|
|
|
def finish_stream(self, state: VLLMRealtimeState) -> VLLMRealtimeState:
|
|
if len(state.audio_buffer) > 0:
|
|
state.audio_accum = np.concatenate([state.audio_accum, state.audio_buffer])
|
|
state.audio_buffer = np.array([], dtype=np.float32)
|
|
max_window_samples = int(state.max_audio_window_sec * _DEFAULT_SAMPLE_RATE)
|
|
if len(state.audio_accum) > max_window_samples:
|
|
samples_to_drop = len(state.audio_accum) - max_window_samples
|
|
# 收尾 partial 仍按窗口处理;最终整段转写使用外层保留的完整音频。
|
|
state.audio_accum = state.audio_accum[samples_to_drop:]
|
|
state.window_rolled = True
|
|
state = self._decode_stream(state)
|
|
elif state.chunk_id == 0 and len(state.audio_accum) > 0:
|
|
state = self._decode_stream(state)
|
|
return state
|