""" 语音:朗读(TTS)和语音识别(STT)。 对应 Node 版 server/src/speech.mjs,两份实现的请求体/返回字段逐字段一致。 为什么放在内核里而不是安卓端直接调: 1. API Key 只存一份(跟对话的 Key 放一起),安卓端拿不到也不该拿; 2. 电脑端的 Web/exe 版能白捡同一个能力(浏览器用 MediaRecorder 录音就行); 3. 厂商鉴权差异只在这一个文件里,界面侧只管"给我一段文字 / 给我一段音频"。 支持的引擎: TTS - 'volc' 火山语音合成(豆包同款音色)https://openspeech.bytedance.com/api/v1/tts - 'openai' OpenAI 兼容的 /audio/speech(返回原始音频字节) - 'system' 不调云端,交给设备自带的 TTS(安卓 TextToSpeech / 浏览器 speechSynthesis) STT - 'openai' OpenAI 兼容的 /audio/transcriptions(multipart) - 'system' 交给设备自带的识别(安卓 SpeechRecognizer) 只用标准库:urllib 发请求;multipart 手拼(标准库没有现成的编码器)。 """ import base64 import json import os import urllib.error import urllib.request import uuid DEFAULT_TIMEOUT_TTS = 60 DEFAULT_TIMEOUT_STT = 120 # 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么" # (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数) VOLC_TTS_URL = os.environ.get('DOUBAO_VOLC_TTS_URL') or 'https://openspeech.bytedance.com/api/v1/tts' # 火山的 encoding -> MIME。文档里 mp3/wav/ogg_opus/pcm 是常用的几个 VOLC_MIME = { 'mp3': 'audio/mpeg', 'wav': 'audio/wav', 'ogg_opus': 'audio/ogg', 'pcm': 'audio/L16', } class SpeechError(Exception): """带用户可读原因的失败。界面直接把它显示出来,不用再猜。""" def _settings_speech(settings: dict) -> dict: speech = (settings or {}).get('speech') return speech if isinstance(speech, dict) else {} def _post_json(url: str, body: dict, headers: dict, timeout: int) -> dict: data = json.dumps(body, ensure_ascii=False).encode('utf-8') req = urllib.request.Request(url, data=data, method='POST') req.add_header('Content-Type', 'application/json') for k, v in headers.items(): req.add_header(k, v) try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read() except urllib.error.HTTPError as exc: detail = '' try: detail = exc.read().decode('utf-8', 'replace')[:400] except Exception: # noqa: BLE001 pass raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc except urllib.error.URLError as exc: raise SpeechError(f'连不上:{exc.reason}') from exc try: return json.loads(raw.decode('utf-8')) except Exception as exc: # noqa: BLE001 raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc # --------------------------------------------------------------------------- # # 朗读 # --------------------------------------------------------------------------- # def synthesize(text: str, settings: dict) -> dict: """ 把文字合成为音频。 返回: {'engine': 'system'} → 让设备自己念(没配云端时) {'engine': 'volc'|'openai', 'mime': ..., 'audio': ''} """ content = (text or '').strip() if not content: raise SpeechError('没有要朗读的内容') speech = _settings_speech(settings) engine = (speech.get('ttsEngine') or 'system').lower() speed = float(speech.get('ttsSpeed') or 1.0) speed = min(max(speed, 0.2), 3.0) if engine == 'volc': return _synthesize_volc(content, speech, speed) if engine == 'openai': return _synthesize_openai(content, settings, speech, speed) return {'engine': 'system'} def _synthesize_volc(text: str, speech: dict, speed: float) -> dict: """ 火山语音合成。 两个容易踩的点(都对着官方文档和第三方实现核对过): 1. 鉴权头是 `Bearer;{token}` —— **分号,不是空格**。写成空格会被判鉴权失败; 2. 成功判定看 body 里的 `code == 3000`,HTTP 状态码是 200 也可能带错误码。 返回的 `data` 是**纯 base64**(不是 data URL),直接解出来就是音频字节。 """ app_id = (speech.get('volcAppId') or '').strip() token = (speech.get('volcToken') or '').strip() cluster = (speech.get('volcCluster') or 'volcano_tts').strip() or 'volcano_tts' voice = (speech.get('ttsVoice') or '').strip() or 'BV700_streaming' encoding = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3' if not app_id or not token: raise SpeechError('火山语音需要 App ID 和 Access Token(在火山控制台「语音技术」里创建应用后拿到)') body = { 'app': {'appid': app_id, 'token': token, 'cluster': cluster}, 'user': {'uid': 'doubao'}, 'audio': { 'voice_type': voice, 'encoding': encoding, 'speed_ratio': speed, 'volume_ratio': 1.0, 'pitch_ratio': 1.0, }, 'request': { 'reqid': str(uuid.uuid4()), 'text': text, 'text_type': 'plain', 'operation': 'query', }, } result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS) code = result.get('code') if code != 3000: raise SpeechError(f'火山返回 code={code} message={result.get("message") or result.get("Message") or "?"}') data = result.get('data') if not data: raise SpeechError('火山没返回音频数据') return {'engine': 'volc', 'mime': VOLC_MIME.get(encoding, 'audio/mpeg'), 'audio': data} def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) -> dict: """OpenAI 兼容的 /audio/speech:POST 进去,直接吐音频字节(不是 JSON)。""" api_key, base_url = _resolve_openai(settings, speech) voice = (speech.get('ttsVoice') or '').strip() or 'alloy' model = (speech.get('ttsModel') or '').strip() or 'tts-1' fmt = (speech.get('openaiFormat') or 'mp3').strip() or 'mp3' body = json.dumps({ 'model': model, 'input': text, 'voice': voice, 'response_format': fmt, 'speed': speed, }, ensure_ascii=False).encode('utf-8') req = urllib.request.Request(f'{base_url}/audio/speech', data=body, method='POST') req.add_header('Content-Type', 'application/json') req.add_header('Authorization', f'Bearer {api_key}') try: with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp: raw = resp.read() ctype = resp.headers.get('Content-Type') or 'audio/mpeg' except urllib.error.HTTPError as exc: detail = '' try: detail = exc.read().decode('utf-8', 'replace')[:400] except Exception: # noqa: BLE001 pass raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc except urllib.error.URLError as exc: raise SpeechError(f'连不上:{exc.reason}') from exc if not raw: raise SpeechError('返回了空音频') return { 'engine': 'openai', 'mime': ctype.split(';')[0].strip() or 'audio/mpeg', 'audio': base64.b64encode(raw).decode('ascii'), } # --------------------------------------------------------------------------- # # 语音识别 # --------------------------------------------------------------------------- # def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -> dict: """ 把一段音频转成文字。 返回 {'engine': 'system'} 表示"交给设备自己的识别", 否则 {'engine': 'openai', 'text': '...'}。 """ if not audio: raise SpeechError('没有录到音频') speech = _settings_speech(settings) engine = (speech.get('sttEngine') or 'system').lower() if engine != 'openai': return {'engine': 'system'} api_key, base_url = _resolve_openai(settings, speech) model = (speech.get('sttModel') or '').strip() or 'whisper-1' lang = (speech.get('sttLanguage') or '').strip() fields = {'model': model} if lang: fields['language'] = lang body, boundary = _multipart(fields, 'file', filename or 'audio.wav', content_type or 'audio/wav', audio) req = urllib.request.Request(f'{base_url}/audio/transcriptions', data=body, method='POST') req.add_header('Content-Type', f'multipart/form-data; boundary={boundary}') req.add_header('Authorization', f'Bearer {api_key}') try: with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp: raw = resp.read() except urllib.error.HTTPError as exc: detail = '' try: detail = exc.read().decode('utf-8', 'replace')[:400] except Exception: # noqa: BLE001 pass raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc except urllib.error.URLError as exc: raise SpeechError(f'连不上:{exc.reason}') from exc try: result = json.loads(raw.decode('utf-8')) except Exception as exc: # noqa: BLE001 raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc text = (result.get('text') or '').strip() if not text: raise SpeechError('识别结果为空(可能是没人说话,或音频格式不对)') return {'engine': 'openai', 'text': text} def _multipart(fields: dict, file_field: str, filename: str, content_type: str, content: bytes): """ 手拼 multipart/form-data。 为什么不用 requests:Chaquopy 里第三方库要额外打包,而标准库没有 multipart 编码器 —— 这个格式本身很简单,拼一遍就够了。 """ boundary = f'----doubao{uuid.uuid4().hex}' out = bytearray() for key, value in fields.items(): out += f'--{boundary}\r\n'.encode() out += f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode() out += f'{value}\r\n'.encode() out += f'--{boundary}\r\n'.encode() out += f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'.encode() out += f'Content-Type: {content_type}\r\n\r\n'.encode() out += content out += f'\r\n--{boundary}--\r\n'.encode() return bytes(out), boundary def _resolve_openai(settings: dict, speech: dict): """ 取 OpenAI 兼容那套的 Key 和地址。 默认复用主对话的设置(同一个 Key 通常也能用语音接口); 也可以在 speech 里单独填,方便"对话用方舟、语音用 OpenAI"这种组合。 """ api_key = (speech.get('openaiApiKey') or '').strip() or (settings or {}).get('apiKey') or '' base_url = (speech.get('openaiBaseUrl') or '').strip() or (settings or {}).get('baseUrl') or '' base_url = base_url.rstrip('/') if not api_key: raise SpeechError('没有 API Key(在设置里填,或在「语音」里单独指定)') if not base_url: raise SpeechError('没有 Base URL') return api_key, base_url def speech_state(settings: dict) -> dict: """给界面看的当前语音配置(脱敏)。""" speech = _settings_speech(settings) return { 'ttsEngine': speech.get('ttsEngine') or 'system', 'ttsVoice': speech.get('ttsVoice') or '', 'ttsSpeed': speech.get('ttsSpeed') or 1.0, 'autoRead': bool(speech.get('autoRead')), 'sttEngine': speech.get('sttEngine') or 'system', 'sttModel': speech.get('sttModel') or 'whisper-1', 'sttLanguage': speech.get('sttLanguage') or '', 'volcAppId': speech.get('volcAppId') or '', 'volcCluster': speech.get('volcCluster') or 'volcano_tts', 'volcEncoding': speech.get('volcEncoding') or 'mp3', 'hasVolcToken': bool(speech.get('volcToken')), 'hasOpenaiKey': bool(speech.get('openaiApiKey') or (settings or {}).get('apiKey')), 'openaiBaseUrl': speech.get('openaiBaseUrl') or '', 'ttsModel': speech.get('ttsModel') or 'tts-1', } # 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致 DEFAULT_SPEECH = { 'ttsEngine': 'system', 'ttsVoice': '', 'ttsSpeed': 1.0, 'autoRead': False, 'sttEngine': 'system', 'sttModel': 'whisper-1', 'sttLanguage': '', 'volcAppId': '', 'volcToken': '', 'volcCluster': 'volcano_tts', 'volcEncoding': 'mp3', 'openaiApiKey': '', 'openaiBaseUrl': '', 'ttsModel': 'tts-1', } # 常用音色,给界面做下拉。火山那几个是文档里的常见 voice_type。 VOLC_VOICES = [ {'value': 'BV700_streaming', 'label': '通用女声(BV700)'}, {'value': 'BV001_streaming', 'label': '通用女声 2(BV001)'}, {'value': 'BV002_streaming', 'label': '通用男声(BV002)'}, {'value': 'BV701_streaming', 'label': '通用男声 2(BV701)'}, {'value': 'BV064_streaming', 'label': '甜美女声(BV064)'}, {'value': 'BV138_streaming', 'label': '沉稳男声(BV138)'}, ] OPENAI_VOICES = [ {'value': 'alloy', 'label': 'alloy(中性)'}, {'value': 'nova', 'label': 'nova(女声,推荐)'}, {'value': 'shimmer', 'label': 'shimmer(女声,柔和)'}, {'value': 'echo', 'label': 'echo(男声)'}, {'value': 'onyx', 'label': 'onyx(男声,低沉)'}, {'value': 'fable', 'label': 'fable(叙述)'}, {'value': 'coral', 'label': 'coral(女声,明快)'}, {'value': 'sage', 'label': 'sage(女声,沉稳)'}, ] def voice_options(engine: str): if engine == 'volc': return VOLC_VOICES if engine == 'openai': return OPENAI_VOICES return [] def debug_env() -> dict: """给 /api/speech/state 用的环境信息(判断能不能用云端语音)。""" return { 'isAndroid': bool(os.environ.get('ANDROID_ROOT')), 'hasStdlib': True, }