docs: restructure markdown docs and publish the bridge

This commit is contained in:
xiaoan
2026-11-14 22:50:21 +08:00
commit 38dccd9a9f
45 changed files with 4353 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
"""Standalone STT entry point for dsh-onebot-qq.
Called by the plugin as its "custom" engine:
python stt.py --file <wav> --out <workdir>/out --model <model>
The plugin hands over a 16 kHz mono WAV (already converted with ffmpeg) and
reads the first *.txt in the work dir, so this script writes <out>.txt.
Two backends:
* SenseVoice (sherpa-onnx) — used when --model points at a *.onnx file.
Fast on CPU and strong on short Chinese utterances.
* faster-whisper — used when --model is a whisper size or a local
CTranslate2 model directory.
"""
from __future__ import annotations
import argparse
import os
import re
import sys
import time
import wave
from pathlib import Path
MODEL_ROOT = os.environ.get("STT_MODEL_ROOT") or str(Path.home() / ".dsh" / "stt-models")
TAG_RE = re.compile(r"<\|[^|]*\|>")
def log(msg: str) -> None:
sys.stderr.write(f"[stt] {msg}\n")
sys.stderr.flush()
def read_wav(path: Path) -> tuple["object", int]:
import numpy as np
with wave.open(str(path), "rb") as wf:
channels = wf.getnchannels()
rate = wf.getframerate()
width = wf.getsampwidth()
frames = wf.readframes(wf.getnframes())
if width != 2:
raise SystemExit(f"expected 16-bit PCM, got sample width {width}")
samples = np.frombuffer(frames, dtype=np.int16).astype("float32") / 32768.0
if channels > 1:
samples = samples.reshape(-1, channels).mean(axis=1)
return samples, rate
def transcribe_sense_voice(wav: Path, model: Path, tokens: Path, language: str) -> str:
import sherpa_onnx
if not tokens.is_file():
raise SystemExit(f"missing sense-voice tokens file: {tokens}")
recognizer = sherpa_onnx.OfflineRecognizer.from_sense_voice(
model=str(model),
tokens=str(tokens),
num_threads=int(os.environ.get("STT_THREADS") or 1),
use_itn=True,
language=language or "zh",
debug=False,
)
samples, rate = read_wav(wav)
stream = recognizer.create_stream()
stream.accept_waveform(rate, samples)
recognizer.decode_stream(stream)
return TAG_RE.sub("", stream.result.text or "").strip()
def transcribe_whisper(wav: Path, model: str, language: str, prompt: str) -> str:
# huggingface.co is unreachable here; hf-mirror serves the same repos.
os.environ["HF_ENDPOINT"] = os.environ.get("STT_HF_ENDPOINT") or "https://hf-mirror.com"
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
from faster_whisper import WhisperModel
root = Path(model)
asr = WhisperModel(
str(root) if root.exists() else model,
device="cpu",
compute_type="int8",
download_root=MODEL_ROOT,
cpu_threads=int(os.environ.get("STT_THREADS") or 0),
)
segments, _info = asr.transcribe(
str(wav),
language=language or None,
beam_size=1,
vad_filter=True,
condition_on_previous_text=False,
initial_prompt=prompt or None,
)
return "".join(seg.text for seg in segments).strip()
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--file", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--model", default="small")
ap.add_argument("--tokens", default="")
ap.add_argument("--lang", default="")
ap.add_argument("--prompt", default="以下是普通话的句子,请用简体中文转写。")
args = ap.parse_args()
wav = Path(args.file)
if not wav.is_file():
log(f"missing input: {wav}")
return 2
started = time.time()
if args.model.lower().endswith(".onnx"):
tokens = Path(args.tokens) if args.tokens else Path(args.model).with_name("tokens.txt")
text = transcribe_sense_voice(wav, Path(args.model), tokens, args.lang)
backend = "sense-voice"
else:
text = transcribe_whisper(wav, args.model, args.lang, args.prompt)
backend = "whisper"
out = Path(args.out + ".txt")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text, encoding="utf-8")
log(f"ok backend={backend} chars={len(text)} elapsed={time.time() - started:.1f}s")
return 0
if __name__ == "__main__":
sys.exit(main())