用户要"豆包语音支持全"。之前只列了 8 个我们挑出来的,挑剩的虽然也能手填 voice_type,但不列出来用户根本不知道它存在。 【抓取】 新增 scripts/fetch-doubao-voices.mjs,从官方两篇文章抓完整音色表: V1 BVxxx_streaming Tonelist → 73 个 V3 zh_xxx_bigtts Tonelist-1 → 90 个 两套命名**完全不通用**(拿 V1 的 BVxxx 去 V3 会报音色不存在)。 ★ 生成 .py / .mjs 而不是 .json:Chaquopy 的 sourceSets 只保证把 Python 源文件 打进 APK,同目录的 .json 不一定带上(真出过"本地能跑、装到手机上文件不存在")。 塞进 .py 绝对跑不掉;Node 侧同理生成 .mjs,两份内核共用同一份数据, 也就不存在"两边音色表不一致"。 【结构:常用 + 全量两段】 90 个音色铺成胶囊根本没法看,所以: voice_options(engine) 常用 8 个 → 界面快捷胶囊 voice_options_all(engine) 全量 → 界面的"全部音色"(可搜索) 接口上对应 speechVoices 和 speechVoicesAll 两个字段。 【踩的坑】 给 Node 的 /api/state 加 speechVoicesAll 时忘了补 import, 而我的自动检查写反了(文件里已经有 VOICE_OPTIONS_ALL 这个"用法", 所以判定"已存在"就没补)→ 一跑验收就报 ttsEngine=undefined。 **这种"只改一边"的错,对拍脚本一抓一个准** —— 这次也是它抓到的。 回归:两份内核语音验收各 36/36。 【这一轮只做完了 B 的一部分】 用户这一批需求还有: A. 每个智能体独立配模型和语音(留空继承全局) B. 界面上的可搜索音色选择器(内核数据已就位) C. 会议模式(节点+连线编排) 下一轮继续。
742 lines
31 KiB
Python
742 lines
31 KiB
Python
"""
|
||
语音:朗读(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 re
|
||
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'
|
||
|
||
# 火山「豆包语音」V3 接口。★ 和 V1 是两套东西:
|
||
# V1 openspeech/api/v1/tts 鉴权:appid + access_token(Bearer; 分号)
|
||
# V3 openspeech/api/v3/tts/... 鉴权:**只要一个 API Key**(X-Api-Key)
|
||
# 用户问"不是只要 api key 就行了吗"——对,走的就是这条。
|
||
#
|
||
# ★ 注意路径里**没有 plan**:/api/v3/tts/unidirectional 才是语音控制台 API Key 能用的;
|
||
# /api/v3/plan/tts/unidirectional 是方舟 Agent Plan 专用,拿普通 Key 打会 401。
|
||
# 实测:同一个 Key,plan 路径 401、非 plan 路径 200 且返回真 MP3。
|
||
# 文档:https://docs.volcengine.com/docs/DoubaoVoice/APIKeyUsage
|
||
VOLC_V3_TTS_URL = os.environ.get('DOUBAO_VOLC_V3_TTS_URL') or \
|
||
'https://openspeech.bytedance.com/api/v3/tts/unidirectional'
|
||
VOLC_V3_RESOURCE_ID = 'seed-tts-2.0'
|
||
|
||
# 火山的 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 {}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 朗读前把 Markdown 剥掉
|
||
# ---------------------------------------------------------------------------
|
||
# 为什么必须做:回复在界面上是按 Markdown 渲染的,但**语音是照着源码念的**。
|
||
# 不处理的话"**加粗**"会念成"星号星号加粗星号星号",代码块、井号标题、竖线表格
|
||
# 全都会被念出来。这个问题一度只修了系统 TTS 那条路(客户端 splitSentences 里剥),
|
||
# 云端那条路直接把原文发给了厂商。
|
||
#
|
||
# 放在内核而不是客户端:安卓 / Web / exe 三个端都走这里,改一处全好,
|
||
# 而且 Node 和 Python 两份实现对拍得住。
|
||
#
|
||
# 处理范围照着界面那个 MarkdownText 渲染器来 —— 它支持什么,这里就得剥什么,
|
||
# 否则会出现"看得到但念错了"的偏差。
|
||
_MD_FENCE = re.compile(r'```[\s\S]*?```')
|
||
_MD_IMAGE = re.compile(r'!\[[^\]]*\]\([^)]*\)')
|
||
_MD_LINK = re.compile(r'\[([^\]]*)\]\([^)]*\)')
|
||
# ★ 行首缩进一律用 [ \t] 而不是 \s:
|
||
# \s 会匹配换行,于是 "。\n\n- 便宜" 里的空行会被 (?m)^\s{0,3} 吃掉,
|
||
# 两个换行并成一个(该停的地方不停)。这个坑真踩过。
|
||
_MD_HEADING = re.compile(r'(?m)^[ \t]{0,3}#{1,6}[ \t]*')
|
||
_MD_BULLET = re.compile(r'(?m)^[ \t]{0,3}[-*+][ \t]+')
|
||
# 有序列表:编号本身念出来很吵("一、点、内容"),去掉
|
||
_MD_NUMBERED = re.compile(r'(?m)^[ \t]{0,3}\d{1,3}[.)][ \t]+')
|
||
_MD_QUOTE = re.compile(r'(?m)^[ \t]{0,3}>[ \t]?')
|
||
_MD_HR = re.compile(r'(?m)^[ \t]{0,3}(?:-{3,}|\*{3,}|_{3,})[ \t]*$')
|
||
# 表格的分隔行(| --- | --- |)整行连换行一起丢掉 —— 留着会念出一串"减号"
|
||
# ★ 字符类里也只能写 [ \t:|-],不能写 \s:写了 \s 就能跨过换行,
|
||
# 把下一行开头的 "| " 一起吃掉(表格剥完只剩一行半)。这个坑踩了三次了。
|
||
_MD_TABLE_SEP = re.compile(r'(?m)^[ \t]*\|[ \t:|-]+\|[ \t]*\n?')
|
||
# 表格的行内竖线:把 | 换成空格,别让它念成"竖线"
|
||
# ★ 两端也只能用 [ \t]:写成 \s 会把行尾换行吃掉,整个表格挤成一行
|
||
_MD_PIPE = re.compile(r'(?m)^[ \t]*\|(.+)\|[ \t]*$')
|
||
_MD_BOLD_ITALIC = re.compile(r'\*{1,3}([^*\n]+)\*{1,3}')
|
||
_MD_UNDER_BOLD = re.compile(r'_{1,3}([^_\n]+)_{1,3}')
|
||
_MD_STRIKE = re.compile(r'~~([^~\n]+)~~')
|
||
_MD_INLINE_CODE = re.compile(r'`([^`\n]*)`')
|
||
_MD_EMPTY_LINES = re.compile(r'\n{3,}')
|
||
|
||
|
||
def strip_markdown(text: str) -> str:
|
||
"""
|
||
把 Markdown 剥成适合朗读的纯文本。
|
||
|
||
★ 顺序有讲究:**先处理代码围栏**。反引号里的内容不能参与后面的行内替换,
|
||
否则代码里的 `**` `#` `|` 会被当成标记,剥出一堆残缺字符。
|
||
"""
|
||
if not text:
|
||
return ''
|
||
s = text.replace('\r\n', '\n')
|
||
|
||
# 1. 代码块整体替换掉:整段代码念出来毫无意义,而且极长
|
||
s = _MD_FENCE.sub('(代码块)', s)
|
||
# 2. 图片直接删(念 alt 没意义),链接只留文字
|
||
s = _MD_IMAGE.sub('', s)
|
||
s = _MD_LINK.sub(r'\1', s)
|
||
# 3. 行级标记
|
||
s = _MD_TABLE_SEP.sub('', s)
|
||
s = _MD_HR.sub('', s)
|
||
s = _MD_HEADING.sub('', s)
|
||
s = _MD_QUOTE.sub('', s)
|
||
s = _MD_BULLET.sub('', s)
|
||
s = _MD_NUMBERED.sub('', s)
|
||
s = _MD_PIPE.sub(lambda m: ' ' + m.group(1).replace('|', ' ') + ' ', s)
|
||
# 4. 行内标记
|
||
s = _MD_INLINE_CODE.sub(r'\1', s)
|
||
s = _MD_STRIKE.sub(r'\1', s)
|
||
s = _MD_BOLD_ITALIC.sub(r'\1', s)
|
||
s = _MD_UNDER_BOLD.sub(r'\1', s)
|
||
# 5. 收尾:角落里剩下的零散标记、每行两端空白,以及被压出来的空行
|
||
s = s.replace('*', '').replace('`', '')
|
||
s = '\n'.join(line.strip() for line in s.split('\n'))
|
||
# 表格剥完会留下 `名字 值` 这种连续空格,念起来是多余的停顿,压成一个
|
||
s = re.sub(r'[ \t]{2,}', ' ', s)
|
||
s = _MD_EMPTY_LINES.sub('\n\n', s)
|
||
return s.strip()
|
||
|
||
|
||
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': '<base64>'}
|
||
"""
|
||
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 == 'volcv3':
|
||
return _synthesize_volc_v3(content, speech, speed)
|
||
if engine == 'openai':
|
||
return _synthesize_openai(content, settings, speech, speed)
|
||
return {'engine': 'system'}
|
||
|
||
|
||
def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||
"""
|
||
豆包语音 V3 合成。
|
||
|
||
和 V1 的区别(用户最容易搞混的地方):
|
||
- **只要一个 API Key**(语音控制台 → API Key 管理里创建),不需要 AppID / Access Token;
|
||
- 音色是另一套命名:`zh_female_vv_uranus_bigtts`,不是 V1 的 `BV700_streaming`;
|
||
- 返回是**逐行 JSON**(NDJSON),每行一段 base64 音频,`code=20000000` 表示结束。
|
||
|
||
两个实测踩过的坑:
|
||
1. 路径别带 plan。`/api/v3/plan/...` 是方舟 Agent Plan 专用,普通语音 Key 打过去 401;
|
||
2. 普通**方舟** Key 也不行 —— 会回 `acquire failed err:call ark ... 401`。
|
||
必须是**语音控制台**里那个 API Key(console.volcengine.com/speech → API Key 管理)。
|
||
"""
|
||
api_key = (speech.get('volcApiKey') or '').strip()
|
||
speaker = (speech.get('ttsVoice') or '').strip() or 'zh_female_vv_uranus_bigtts'
|
||
fmt = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3'
|
||
if fmt not in ('mp3', 'wav', 'ogg_opus', 'pcm'):
|
||
fmt = 'mp3'
|
||
|
||
if not api_key:
|
||
raise SpeechError(
|
||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||
'注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。'
|
||
)
|
||
|
||
body = {
|
||
'req_params': {
|
||
'text': text,
|
||
'speaker': speaker,
|
||
'audio_params': {
|
||
'format': fmt,
|
||
# 24k 是大模型音色的标准采样率,调低会明显发闷
|
||
'sample_rate': 24000,
|
||
# V3 的语速是 ±100 的百分比,不是倍率(实测 -50 变慢、+50 变快)
|
||
'speech_rate': int(round((speed - 1.0) * 100)),
|
||
},
|
||
},
|
||
}
|
||
|
||
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||
req = urllib.request.Request(VOLC_V3_TTS_URL, data=data, method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
req.add_header('X-Api-Key', api_key)
|
||
req.add_header('X-Api-Resource-Id', VOLC_V3_RESOURCE_ID)
|
||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) 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
|
||
|
||
# 逐行解析:每行一个 JSON,拼 data 里的音频片段
|
||
chunks = []
|
||
error = None
|
||
for line in raw.decode('utf-8', 'replace').splitlines():
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
item = json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
code = item.get('code', 0)
|
||
payload = item.get('data')
|
||
if isinstance(payload, str) and payload:
|
||
chunks.append(payload)
|
||
if code == 20000000:
|
||
break
|
||
if isinstance(code, int) and code > 0 and code != 20000000:
|
||
error = f'code={code} {item.get("message") or item.get("msg") or ""}'.strip()
|
||
break
|
||
|
||
if error:
|
||
raise SpeechError(f'火山 V3 失败:{error}')
|
||
if not chunks:
|
||
raise SpeechError('火山 V3 没返回音频数据')
|
||
return {'engine': 'volcv3', 'mime': VOLC_MIME.get(fmt, 'audio/mpeg'), 'audio': ''.join(chunks)}
|
||
|
||
|
||
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 synthesize_stream(text: str, settings: dict):
|
||
"""
|
||
流式合成:边生成边把音频块吐出来(生成器)。
|
||
|
||
为什么需要它:整段合成完再播,长回复要等好几秒才出声。实测火山 v3 接口
|
||
**本身就是边生成边下发的**(一段 60 字的文本,首块 1.1s 到、末块 6.0s 到,
|
||
跨度 5 秒),所以只要这边不攒、跟着往下传,播放端就能"边生成边读"。
|
||
|
||
★ 不需要 WebSocket。火山确实有 wss://…/tts/bidirection,但那是另一套
|
||
二进制私有协议;HTTP 这条路已经能流式,何必多写一层帧解析。
|
||
|
||
yield 的是 (mime, bytes)。只支持云端引擎 —— system 引擎归系统 TTS 管,
|
||
内核根本不参与合成(调用方自己判断 engine 是不是 system)。
|
||
"""
|
||
engine = (_settings_speech(settings).get('ttsEngine') or 'system').lower()
|
||
speech = _settings_speech(settings)
|
||
# ★ 剥掉 Markdown 再合成:界面上是按 Markdown 渲染的,直接念源码会把
|
||
# ** 念成"星号星号"、井号标题和代码块也照念。详见 strip_markdown 的注释。
|
||
content = strip_markdown(text)
|
||
if not content:
|
||
raise SpeechError('没有要朗读的内容')
|
||
speed = _clamp(speech.get('ttsSpeed', 1.0))
|
||
|
||
if engine == 'volcv3':
|
||
yield from _stream_volc_v3(content, speech, speed)
|
||
return
|
||
# 其他引擎没有流式接口,退回"整段合成再一次给"
|
||
result = synthesize(text, settings)
|
||
audio = result.get('audio')
|
||
if audio:
|
||
yield result.get('mime') or 'audio/mpeg', base64.b64decode(audio)
|
||
|
||
|
||
def _stream_volc_v3(text: str, speech: dict, speed: float):
|
||
"""火山 v3 的流式读取:逐行 NDJSON,每行一段 base64 音频,拿到就 yield。"""
|
||
api_key = (speech.get('volcApiKey') or '').strip()
|
||
speaker = (speech.get('ttsVoice') or '').strip() or 'zh_female_vv_uranus_bigtts'
|
||
if not api_key:
|
||
raise SpeechError(
|
||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||
'注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。'
|
||
)
|
||
|
||
# ★ 流式播放**必须**是 PCM,这里不能跟着 volcEncoding 走。
|
||
#
|
||
# 客户端是把收到的字节直接喂 AudioTrack 的,没有解码器 —— 拿到 MP3 只能
|
||
# 放弃流式、退回"整段收完再播"。而 volcEncoding 的默认值是 mp3,
|
||
# 之前写成 `speech.get('volcEncoding') or 'pcm'`,那个 or 只在 None/空 时生效,
|
||
# 结果永远发 mp3,**"边生成边读"整个失效**,用户感觉就是"根本没实时读"。
|
||
#
|
||
# volcEncoding 仍然管非流式那条路(/api/tts),那条路客户端用 MediaPlayer,MP3 没问题。
|
||
fmt = 'pcm'
|
||
|
||
body = {
|
||
'req_params': {
|
||
'text': text,
|
||
'speaker': speaker,
|
||
'audio_params': {
|
||
'format': fmt,
|
||
'sample_rate': 24000,
|
||
'speech_rate': int(round((speed - 1.0) * 100)),
|
||
},
|
||
},
|
||
}
|
||
req = urllib.request.Request(VOLC_V3_TTS_URL, data=json.dumps(body, ensure_ascii=False).encode('utf-8'), method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
req.add_header('X-Api-Key', api_key)
|
||
req.add_header('X-Api-Resource-Id', VOLC_V3_RESOURCE_ID)
|
||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||
|
||
mime = VOLC_MIME.get(fmt, 'audio/L16')
|
||
try:
|
||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS)
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:300]
|
||
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
|
||
|
||
# ★ 关键就是这里不 read() 全部:用 readline() 一行一行拿,
|
||
# 火山下发一行我们就解一行、yield 一行,播放端立刻能出声。
|
||
error = None
|
||
got_any = False
|
||
try:
|
||
for raw_line in resp:
|
||
line = raw_line.decode('utf-8', 'replace').strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
item = json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
code = item.get('code', 0)
|
||
payload = item.get('data')
|
||
if isinstance(payload, str) and payload:
|
||
got_any = True
|
||
yield mime, base64.b64decode(payload)
|
||
if code == 20000000:
|
||
break
|
||
if isinstance(code, int) and code > 0 and code != 20000000:
|
||
error = f'code={code} {item.get("message") or item.get("msg") or ""}'.strip()
|
||
break
|
||
finally:
|
||
try:
|
||
resp.close()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
if error:
|
||
raise SpeechError(f'火山 V3 失败:{error}')
|
||
if not got_any:
|
||
raise SpeechError('火山 V3 没返回音频数据')
|
||
|
||
|
||
def _clamp(value) -> float:
|
||
try:
|
||
v = float(value)
|
||
except (TypeError, ValueError):
|
||
return 1.0
|
||
return min(max(v, 0.2), 3.0)
|
||
|
||
|
||
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')),
|
||
# V3 只要这一个 Key,所以界面按它判断"配没配"
|
||
'hasVolcApiKey': bool(speech.get('volcApiKey')),
|
||
'hasOpenaiKey': bool(speech.get('openaiApiKey') or (settings or {}).get('apiKey')),
|
||
'openaiBaseUrl': speech.get('openaiBaseUrl') or '',
|
||
'ttsModel': speech.get('ttsModel') or 'tts-1',
|
||
# 各家「申请语音 Key」的直达链接,界面上做成快捷入口。
|
||
# 这里放内核而不是写死在界面里:以后加厂商只改一处。
|
||
'consoleUrls': SPEECH_CONSOLE_URLS,
|
||
}
|
||
|
||
|
||
# 语音相关控制台的直达链接(都已访问核实可达)
|
||
SPEECH_CONSOLE_URLS = {
|
||
# V3:语音控制台 → API Key 管理。**这是"只要一个 API Key"那条路的入口**
|
||
'volcv3': 'https://console.volcengine.com/speech/new/setting/apikeys',
|
||
# V1:同一个控制台,但拿的是 AppID + Access Token(在「语音合成」应用详情里)
|
||
'volc': 'https://console.volcengine.com/speech/app',
|
||
'openai': 'https://platform.openai.com/api-keys',
|
||
# 方舟 Agent Plan:另一条能用 API Key 的路(和语音控制台不是一回事)
|
||
'agentPlan': 'https://ark.volcengine.com/region:cn-beijing/openManagement?advancedActiveKey=agentPlan',
|
||
}
|
||
|
||
# 联网搜索(豆包搜索)相关的地址。
|
||
#
|
||
# activate 那个是**从接口报错里拿到的**:不带 sources 打 /responses 会返回
|
||
# "Your account has not activated web search. You may activate it at
|
||
# https://console.volcengine.com/common-buy/CC_content_plugin"
|
||
# 比让用户自己在控制台里翻要准。manage 那个是「开通管理 → 应用组件库 → 豆包搜索」。
|
||
SEARCH_CONSOLE_URLS = {
|
||
'activate': 'https://console.volcengine.com/common-buy/CC_content_plugin',
|
||
'manage': 'https://console.volcengine.com/ark/region:cn-beijing/openManagement'
|
||
'?advancedActiveKey=component&tab=DoubaoSearch',
|
||
}
|
||
|
||
|
||
# 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致
|
||
DEFAULT_SPEECH = {
|
||
'ttsEngine': 'system',
|
||
'ttsVoice': '',
|
||
'ttsSpeed': 1.0,
|
||
'autoRead': False,
|
||
'sttEngine': 'system',
|
||
'sttModel': 'whisper-1',
|
||
'sttLanguage': '',
|
||
'volcAppId': '',
|
||
'volcToken': '',
|
||
'volcApiKey': '', # V3 用的那个(语音控制台 → API Key 管理)
|
||
'volcCluster': 'volcano_tts',
|
||
'volcEncoding': 'mp3',
|
||
'openaiApiKey': '',
|
||
'openaiBaseUrl': '',
|
||
'ttsModel': 'tts-1',
|
||
}
|
||
|
||
# 全量音色表在 voices_doubao.py 里(由 scripts/fetch-doubao-voices.mjs 抓官方文档生成)。
|
||
# 这里只留一份"常用"精选给界面做快捷胶囊 —— 90 个音色铺成胶囊根本没法看,
|
||
# 所以界面上是"常用几个 + 全部(可搜索)"两段式。
|
||
from voices_doubao import VOLC_VOICES_ALL, VOLC_V3_SPEAKERS_ALL # noqa: E402
|
||
|
||
# 常用的 V1 音色(名字照官方列表核对过)
|
||
VOLC_VOICES = [
|
||
{'value': 'BV700_streaming', 'label': '灿灿 · 通用女声(22 种情感,推荐)'},
|
||
{'value': 'BV700_V2_streaming', 'label': '灿灿 2.0(升级版)'},
|
||
{'value': 'BV001_streaming', 'label': '通用女声'},
|
||
{'value': 'BV002_streaming', 'label': '通用男声'},
|
||
{'value': 'BV701_streaming', 'label': '擎苍 · 有声阅读'},
|
||
{'value': 'BV705_streaming', 'label': '炀炀 · 自然对话'},
|
||
{'value': 'BV009_streaming', 'label': '知性女声'},
|
||
{'value': 'BV123_streaming', 'label': '阳光青年'},
|
||
]
|
||
|
||
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(女声,沉稳)'},
|
||
]
|
||
|
||
# V3(大模型音色)的常用精选。全量在 voices_doubao.py,这里只列界面上的快捷项。
|
||
# ★ 这一套和 V1 的 BVxxx 完全不通用 —— 拿 BV700_streaming 去 V3 会报音色不存在。
|
||
VOLC_V3_SPEAKERS = [
|
||
{'value': 'zh_female_vv_uranus_bigtts', 'label': 'Vivi 2.0(女声,默认)'},
|
||
{'value': 'zh_female_cancan_uranus_bigtts', 'label': '知性灿灿 2.0'},
|
||
{'value': 'zh_female_xiaohe_uranus_bigtts', 'label': '小何 2.0'},
|
||
{'value': 'zh_female_tianmeixiaoyuan_uranus_bigtts', 'label': '甜美小源 2.0'},
|
||
{'value': 'zh_female_shuangkuaisisi_uranus_bigtts', 'label': '爽快思思 2.0'},
|
||
{'value': 'zh_male_qingcang_uranus_bigtts', 'label': '擎苍 2.0(男声)'},
|
||
{'value': 'zh_male_m191_uranus_bigtts', 'label': '云舟 2.0'},
|
||
{'value': 'zh_male_taocheng_uranus_bigtts', 'label': '小天 2.0'},
|
||
]
|
||
|
||
|
||
def voice_options(engine: str):
|
||
"""快捷胶囊用的一小组"""
|
||
if engine == 'volc':
|
||
return VOLC_VOICES
|
||
if engine == 'volcv3':
|
||
return VOLC_V3_SPEAKERS
|
||
if engine == 'openai':
|
||
return OPENAI_VOICES
|
||
return []
|
||
|
||
|
||
def voice_options_all(engine: str):
|
||
"""
|
||
全量音色(界面上"全部音色"那个可搜索的列表用它)。
|
||
|
||
用户要"豆包语音支持全",所以这里给的是官方文档里的完整音色表,
|
||
不是我们挑出来的那几个 —— 挑剩的照样能填 voice_type,但不列出来
|
||
用户根本不知道存在。
|
||
"""
|
||
if engine == 'volc':
|
||
return VOLC_VOICES_ALL
|
||
if engine == 'volcv3':
|
||
return VOLC_V3_SPEAKERS_ALL
|
||
if engine == 'openai':
|
||
return OPENAI_VOICES
|
||
return []
|
||
|
||
|
||
def debug_env() -> dict:
|
||
"""给 /api/speech/state 用的环境信息(判断能不能用云端语音)。"""
|
||
return {
|
||
'isAndroid': bool(os.environ.get('ANDROID_ROOT')),
|
||
'hasStdlib': True,
|
||
}
|