feat: 音频工具 — Piper本地TTS(中英语音+语速调节) + Whisper音频转文字(中英日粤+时间轴) + 声音克隆占位; 服务端全本地模型
This commit is contained in:
1 parent
6bc2120c05
commit
54fba4d97a
11 files changed
+831
-2
No files matched your search
@@ -0,0 +1,104 @@
|
||||
"""Audio tool operations: TTS (edge-tts) and ASR (faster-whisper)."""
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
|
||||
FFMPEG_BIN = "ffmpeg"
|
||||
MAX_TTS_CHARS = 2000
|
||||
MAX_ASR_MB = 30
|
||||
|
||||
VOICE_FILES = {
|
||||
"zh_CN-huayan-medium": "晓妍(女·标准中文)",
|
||||
"en_US-amy-medium": "Amy(女·英语)",
|
||||
}
|
||||
|
||||
_asr_model = None
|
||||
|
||||
|
||||
def _get_asr():
|
||||
global _asr_model
|
||||
if _asr_model is None:
|
||||
from faster_whisper import WhisperModel
|
||||
_asr_model = WhisperModel("small", device="cpu", compute_type="int8")
|
||||
return _asr_model
|
||||
|
||||
|
||||
PIPER_DIR = os.environ.get("PIPER_DIR", "/app/piper-models")
|
||||
_piper_voices = {}
|
||||
|
||||
|
||||
def _load_voice(voice: str):
|
||||
from piper import PiperVoice
|
||||
if voice not in _piper_voices:
|
||||
model = os.path.join(PIPER_DIR, voice + ".onnx")
|
||||
if not os.path.exists(model):
|
||||
raise ValueError("音色不存在: " + voice)
|
||||
_piper_voices[voice] = PiperVoice.load(model)
|
||||
return _piper_voices[voice]
|
||||
|
||||
|
||||
def run_tts(text: str, voice: str, rate_pct: int, pitch_hz: int, out_path: str):
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
raise ValueError("请输入文字内容")
|
||||
if len(text) > MAX_TTS_CHARS:
|
||||
raise ValueError(f"文字过长(最多 {MAX_TTS_CHARS} 字)")
|
||||
if voice not in VOICE_FILES:
|
||||
voice = "zh_CN-huayan-medium"
|
||||
rate_pct = max(-50, min(100, int(rate_pct)))
|
||||
v = _load_voice(voice)
|
||||
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf:
|
||||
wav_path = tf.name
|
||||
try:
|
||||
with open(wav_path, "wb") as f:
|
||||
with wave.open(f, "wb") as wf:
|
||||
v.synthesize_wav(text, wf)
|
||||
# post-process: speed (atempo) + pitch-free, output mp3
|
||||
tempo = 1 + rate_pct / 100.0
|
||||
tempo = max(0.5, min(2.0, tempo))
|
||||
argv = [FFMPEG_BIN, "-y", "-i", wav_path, "-filter:a", f"atempo={tempo:.4f}",
|
||||
"-c:a", "libmp3lame", "-b:a", "192k", out_path]
|
||||
env = dict(os.environ)
|
||||
env.pop("HTTPS_PROXY", None)
|
||||
r = subprocess.run(argv, capture_output=True, timeout=120, env=env)
|
||||
if r.returncode != 0:
|
||||
# fallback: plain wav->mp3
|
||||
r = subprocess.run([FFMPEG_BIN, "-y", "-i", wav_path, "-c:a", "libmp3lame",
|
||||
"-b:a", "192k", out_path], capture_output=True, timeout=120, env=env)
|
||||
if r.returncode != 0:
|
||||
raise RuntimeError("音频转码失败")
|
||||
finally:
|
||||
try:
|
||||
os.remove(wav_path)
|
||||
except Exception:
|
||||
pass
|
||||
if not os.path.exists(out_path) or os.path.getsize(out_path) < 100:
|
||||
raise RuntimeError("TTS 生成失败")
|
||||
|
||||
|
||||
def run_asr(audio_path: str, language: str):
|
||||
model = _get_asr()
|
||||
language = language if language in ("zh", "en", "ja", "yue") else None
|
||||
segments, info = model.transcribe(audio_path, language=language, beam_size=2, vad_filter=True)
|
||||
out = []
|
||||
texts = []
|
||||
for s in segments:
|
||||
item = {"start": round(s.start, 1), "end": round(s.end, 1), "text": s.text.strip()}
|
||||
out.append(item)
|
||||
texts.append(s.text.strip())
|
||||
return {
|
||||
"text": "\n".join(texts),
|
||||
"segments": out[:200],
|
||||
"language": info.language,
|
||||
"probability": round(info.language_probability, 2),
|
||||
}
|
||||
|
||||
|
||||
# voices served by local piper models
|
||||
VOICES = [
|
||||
{"value": k, "label": v, "lang": k.split("_")[0]}
|
||||
for k, v in VOICE_FILES.items()
|
||||
]
|
||||
@@ -44,7 +44,7 @@ AUTH_PASS = os.environ.get("AUTH_PASS", "")
|
||||
PROJECT_NAME = os.environ.get("PROJECT_NAME", "IT-Tools")
|
||||
TRIAL_FILE = os.environ.get("TRIAL_FILE", "/app/data/trials.json")
|
||||
TRIAL_MS = int(os.environ.get("TRIAL_MS_MIN", "30")) * 60 * 1000
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools"}
|
||||
PROTECTED_TOOLS = {"translator", "image-ocr", "pdf-ocr", "ai-retouch", "label-designer", "doc-convert", "image-tools", "pdf-tools", "video-tools", "audio-tools"}
|
||||
MACHINE_RE = re.compile(r"^\d{10,16}$")
|
||||
|
||||
# verify() messages that unconditionally block activation
|
||||
@@ -463,6 +463,13 @@ def sites_api(method: str, path: str, payload: dict) -> tuple[int, dict]:
|
||||
return 404, {"code": 404, "message": "not found", "data": None}
|
||||
|
||||
|
||||
def _int_str(v, lo, hi, default=0):
|
||||
try:
|
||||
return max(lo, min(hi, int(float(v))))
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def check(machine: str, tool: str) -> int:
|
||||
if not machine or not MACHINE_RE.match(machine):
|
||||
return 403
|
||||
@@ -950,11 +957,104 @@ class Handler(BaseHTTPRequestHandler):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _handle_tts(self):
|
||||
import audio_ops
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
status = check(machine, "audio-tools")
|
||||
if status != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length) if length else b"{}"
|
||||
payload = json.loads(raw.decode("utf-8") or "{}")
|
||||
import uuid as _uuid
|
||||
out_path = "/tmp/tts-" + _uuid.uuid4().hex[:10] + ".mp3"
|
||||
try:
|
||||
audio_ops.run_tts(
|
||||
str(payload.get("text") or ""),
|
||||
str(payload.get("voice") or ""),
|
||||
_int_str(payload.get("rate"), -50, 100, 0),
|
||||
_int_str(payload.get("pitch"), -50, 50, 0),
|
||||
out_path,
|
||||
)
|
||||
with open(out_path, "rb") as f:
|
||||
out = f.read()
|
||||
finally:
|
||||
try:
|
||||
os.remove(out_path)
|
||||
except Exception:
|
||||
pass
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "audio/mpeg")
|
||||
self.send_header("Content-Length", str(len(out)))
|
||||
self.end_headers()
|
||||
self.wfile.write(out)
|
||||
except ValueError as e:
|
||||
self._reply(400, json.dumps({"code": 400, "message": str(e)}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(500, json.dumps({"code": 500, "message": "合成失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_asr(self):
|
||||
import audio_ops
|
||||
import uuid as _uuid
|
||||
import video_ops
|
||||
machine = self.headers.get("X-Machine-Id", "")
|
||||
status = check(machine, "audio-tools")
|
||||
if status != 200:
|
||||
self._reply(403, json.dumps({"code": 403, "message": "需要授权或免费试用已结束"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
workdir = None
|
||||
try:
|
||||
ctype = self.headers.get("Content-Type", "")
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
if length > audio_ops.MAX_ASR_MB * 1024 * 1024 + 1024 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "音频超过 " + str(audio_ops.MAX_ASR_MB) + "MB 限制"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
raw = self.rfile.read(length) if length else b""
|
||||
env = {"REQUEST_METHOD": "POST", "CONTENT_TYPE": ctype, "CONTENT_LENGTH": str(length)}
|
||||
fs = cgi.FieldStorage(fp=io.BytesIO(raw), environ=env, keep_blank_values=True)
|
||||
fobj = fs["file"] if ("file" in fs.keys()) else None
|
||||
if fobj is None or not fobj.filename:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "缺少音频文件"}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
fname = os.path.basename(fobj.filename or "audio")
|
||||
ext = os.path.splitext(fname)[1].lower()
|
||||
if ext not in (".mp3", ".wav", ".m4a", ".ogg", ".flac", ".aac", ".webm", ".mp4", ".wma", ".opus"):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "不支持的音频格式 " + ext}, ensure_ascii=False).encode(), "application/json")
|
||||
return
|
||||
lang = fs["language"].value if "language" in fs.keys() else ""
|
||||
workdir = "/tmp/asr-" + _uuid.uuid4().hex[:10]
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
fpath = os.path.join(workdir, "in" + ext)
|
||||
with open(fpath, "wb") as f:
|
||||
f.write(fobj.file.read())
|
||||
# normalize to wav mono 16k for whisper (handles mp4/m4a containers too)
|
||||
wav = os.path.join(workdir, "in.wav")
|
||||
argv, _ = video_ops.build_cmd("audio", fpath, None, {"fmt": "wav"})
|
||||
fout = os.path.join(workdir, "tmp.wav")
|
||||
argv[argv.index(fout) if fout in argv else len(argv) - 1] = fout
|
||||
video_ops.run_ffmpeg(argv, timeout=600)
|
||||
result = audio_ops.run_asr(fout, lang)
|
||||
body = json.dumps({"code": 200, "message": "ok", "data": result}, ensure_ascii=False).encode("utf-8")
|
||||
self._reply(200, body, "application/json")
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._reply(500, json.dumps({"code": 500, "message": "识别失败: " + str(e)[:200]}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
finally:
|
||||
if workdir and os.path.isdir(workdir):
|
||||
shutil.rmtree(workdir, ignore_errors=True)
|
||||
|
||||
def do_POST(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
if parsed.path.startswith("/user"):
|
||||
self._handle_user("POST")
|
||||
return
|
||||
if parsed.path == "/tts":
|
||||
self._handle_tts()
|
||||
return
|
||||
if parsed.path == "/asr":
|
||||
self._handle_asr()
|
||||
return
|
||||
if parsed.path == "/video":
|
||||
self._handle_video()
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user