diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index 6cbd8f3..c8cbbc4 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.material3.Icon @@ -423,12 +424,21 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: .padding(horizontal = 14.dp, vertical = 12.dp), ) { when { - msg.content.isNotBlank() -> Text( - msg.content, - fontSize = 16.sp, - lineHeight = 26.sp, - color = if (msg.error) Doubao.Error else doubaoText(), - ) + // 助手回复按 Markdown 渲染(代码块、标题、列表、粗体…)。 + // 用户那条不渲染:用户输入里的 `2 * 3 * 4`、`_x_` 会被当成标记, + // 显示出来跟输入的不一样会让人以为打错了。 + msg.content.isNotBlank() -> if (msg.error) { + Text(msg.content, fontSize = 16.sp, lineHeight = 26.sp, color = Doubao.Error) + } else { + SelectionContainer { + MarkdownText( + markdown = msg.content, + color = doubaoText(), + fontSize = 16, + lineHeight = 26, + ) + } + } msg.pending -> TypingDots() else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp) } @@ -712,8 +722,7 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) { lineHeight = 21.sp, color = doubaoTextSecondary(), ) - } - } + } } } } } diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt new file mode 100644 index 0000000..3fbebf0 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt @@ -0,0 +1,342 @@ +package com.doubao.lynxclone.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** + * 极简 Markdown 渲染。 + * + * 为什么自己写而不引库: + * 项目一直坚持"零第三方依赖"(安卓端构建要能离线完成),而 Markdown 渲染 + * 在这个规模下不需要一个几百 KB 的库 —— 聊天里真正会出现的就那几种:标题、 + * 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。 + * + * 支持: + * 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落 + * 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接) + * + * 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现, + * 而且做全了就得处理各种边界,性价比很低。 + */ +@Composable +fun MarkdownText( + markdown: String, + // ★ color 不能给默认值:默认参数里不能调用 @Composable 函数 + // (doubaoText() 是 @Composable,写成 `color: Color = doubaoText()` 直接编译不过) + color: Color, + modifier: Modifier = Modifier, + linkColor: Color = Doubao.Blue, + fontSize: Int = 16, + lineHeight: Int = 26, +) { + val blocks = remember(markdown) { parseMarkdown(markdown) } + val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6) + val quoteBar = Doubao.Blue.copy(alpha = 0.55f) + + Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (block in blocks) { + when (block) { + is MdBlock.Code -> { + // 代码块单独一块:等宽字体 + 底色 + 可横向滚动(长行不折行更好读) + Box( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(10.dp)) + .background(codeBg) + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Text( + block.text.trimEnd(), + fontFamily = FontFamily.Monospace, + fontSize = (fontSize - 3).sp, + lineHeight = (fontSize + 5).sp, + color = color, + ) + } + } + + is MdBlock.Quote -> { + Row(Modifier.fillMaxWidth()) { + // 左边一条竖线,跟正文区分开 + Box( + Modifier + .width(3.dp) + .heightIn(min = 20.dp) + .clip(RoundedCornerShape(2.dp)) + .background(quoteBar), + ) + Spacer(Modifier.width(10.dp)) + Text( + inline(block.text, linkColor), + fontSize = fontSize.sp, + lineHeight = lineHeight.sp, + color = color.copy(alpha = 0.85f), + modifier = Modifier.weight(1f), + ) + } + } + + is MdBlock.Heading -> Text( + inline(block.text, linkColor), + fontSize = when (block.level) { + 1 -> (fontSize + 6).sp + 2 -> (fontSize + 3).sp + else -> (fontSize + 1).sp + }, + fontWeight = FontWeight.SemiBold, + lineHeight = (lineHeight + 4).sp, + color = color, + ) + + is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) { + Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f)) + Spacer(Modifier.width(8.dp)) + Text( + inline(block.text, linkColor), + fontSize = fontSize.sp, + lineHeight = lineHeight.sp, + color = color, + modifier = Modifier.weight(1f), + ) + } + + is MdBlock.Numbered -> Row(Modifier.fillMaxWidth()) { + Text( + "${block.number}.", + fontSize = fontSize.sp, + color = color.copy(alpha = 0.7f), + modifier = Modifier.width(22.dp), + ) + Text( + inline(block.text, linkColor), + fontSize = fontSize.sp, + lineHeight = lineHeight.sp, + color = color, + modifier = Modifier.weight(1f), + ) + } + + is MdBlock.Divider -> Box( + Modifier + .fillMaxWidth() + .padding(vertical = 2.dp) + .height(1.dp) + .background(color.copy(alpha = 0.15f)), + ) + + is MdBlock.Paragraph -> Text( + inline(block.text, linkColor), + fontSize = fontSize.sp, + lineHeight = lineHeight.sp, + color = color, + ) + } + } + } +} + +/* ------------------------------ 块级解析 ------------------------------ */ + +internal sealed interface MdBlock { + data class Paragraph(val text: String) : MdBlock + data class Heading(val level: Int, val text: String) : MdBlock + data class Bullet(val text: String) : MdBlock + data class Numbered(val number: String, val text: String) : MdBlock + data class Quote(val text: String) : MdBlock + data class Code(val text: String, val lang: String = "") : MdBlock + data object Divider : MdBlock +} + +private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$") +private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$") +private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$") +private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$") +private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$") +private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$") + +internal fun parseMarkdown(src: String): List { + val out = ArrayList() + val lines = src.replace("\r\n", "\n").split("\n") + val para = StringBuilder() + var i = 0 + + fun flushPara() { + if (para.isNotBlank()) out.add(MdBlock.Paragraph(para.toString().trim())) + para.setLength(0) + } + + while (i < lines.size) { + val line = lines[i] + + // 代码块:``` 开头到下一个 ```(或文件结束) + val fence = RE_FENCE.find(line) + if (fence != null) { + flushPara() + val lang = fence.groupValues[1] + val body = StringBuilder() + i += 1 + while (i < lines.size && RE_FENCE.find(lines[i]) == null) { + body.append(lines[i]).append('\n') + i += 1 + } + i += 1 // 跳过收尾的 ``` + out.add(MdBlock.Code(body.toString(), lang)) + continue + } + + when { + line.isBlank() -> flushPara() + + RE_DIVIDER.matches(line) -> { + flushPara() + out.add(MdBlock.Divider) + } + + RE_HEADING.matches(line) -> { + flushPara() + val m = RE_HEADING.find(line)!! + out.add(MdBlock.Heading(m.groupValues[1].length, m.groupValues[2].trim())) + } + + RE_QUOTE.matches(line) -> { + flushPara() + // 连续的引用行合成一段 + val q = StringBuilder() + while (i < lines.size && RE_QUOTE.matches(lines[i])) { + if (q.isNotEmpty()) q.append(' ') + q.append(RE_QUOTE.find(lines[i])!!.groupValues[1]) + i += 1 + } + out.add(MdBlock.Quote(q.toString().trim())) + continue + } + + RE_BULLET.matches(line) -> { + flushPara() + out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim())) + } + + RE_NUMBERED.matches(line) -> { + flushPara() + val m = RE_NUMBERED.find(line)!! + out.add(MdBlock.Numbered(m.groupValues[1], m.groupValues[2].trim())) + } + + else -> { + if (para.isNotEmpty()) para.append('\n') + para.append(line) + } + } + i += 1 + } + flushPara() + return out +} + +/* ------------------------------ 行内解析 ------------------------------ */ + +/** + * 行内标记 → AnnotatedString。 + * + * 用一个统一的扫描器而不是一串 replace: + * 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后, + * 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。 + */ +internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString { + var i = 0 + while (i < text.length) { + when { + // 行内代码:`code` + text[i] == '`' -> { + val end = text.indexOf('`', i + 1) + if (end > i) { + withStyle(SpanStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp)) { + append(text.substring(i + 1, end)) + } + i = end + 1 + } else { + append(text[i]); i += 1 + } + } + + // 粗斜体 / 粗体 / 斜体:***x***、**x**、*x* + text.startsWith("***", i) || text.startsWith("**", i) || text[i] == '*' -> { + val marker = when { + text.startsWith("***", i) -> "***" + text.startsWith("**", i) -> "**" + else -> "*" + } + val end = text.indexOf(marker, i + marker.length) + // 找不到收尾、或者里面是空的,就当普通字符 + if (end > i + marker.length) { + val inner = text.substring(i + marker.length, end) + val style = when (marker) { + "***" -> SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic) + "**" -> SpanStyle(fontWeight = FontWeight.Bold) + else -> SpanStyle(fontStyle = FontStyle.Italic) + } + withStyle(style) { append(inner) } + i = end + marker.length + } else { + append(text[i]); i += 1 + } + } + + // 删除线:~~x~~ + text.startsWith("~~", i) -> { + val end = text.indexOf("~~", i + 2) + if (end > i + 2) { + withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { + append(text.substring(i + 2, end)) + } + i = end + 2 + } else { + append(text[i]); i += 1 + } + } + + // 链接:[文字](地址) + text[i] == '[' -> { + val close = text.indexOf(']', i) + val open = if (close > 0 && close + 1 < text.length && text[close + 1] == '(') close + 1 else -1 + val end = if (open > 0) text.indexOf(')', open) else -1 + if (close > i && open > 0 && end > open) { + val label = text.substring(i + 1, close) + withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) { + append(label) + } + i = end + 1 + } else { + append(text[i]); i += 1 + } + } + + else -> { + append(text[i]); i += 1 + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt index e11f764..8a485ef 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/SettingsScreen.kt @@ -1,5 +1,8 @@ package com.doubao.lynxclone.ui +import android.content.Intent +import android.net.Uri +import android.widget.Toast import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -56,6 +59,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.PasswordVisualTransformation @@ -111,6 +115,7 @@ fun SettingsScreen(vm: AppViewModel) { var showKey by remember { mutableStateOf(false) } // 火山 Access Token 也有自己的"看一眼"状态:跟 API Key 分开,免得一按眼睛两个框一起露 var showVolcToken by remember { mutableStateOf(false) } + var showVolcApiKey by remember { mutableStateOf(false) } Column(Modifier.fillMaxSize()) { ScreenHeader("AI 内核设置", onBack = { vm.screen = Screen.Chat }) { @@ -192,7 +197,42 @@ fun SettingsScreen(vm: AppViewModel) { } } - if (draft.speech.ttsEngine == "volc") { + if (draft.speech.ttsEngine == "volcv3") { + // 豆包语音 V3:只要一个 API Key,音色是大模型音色(zh_xxx_bigtts)。 + // 这是"一个 Key 搞定"的那条路,放在最前面。 + Spacer(Modifier.height(12.dp)) + FormLabel("API Key") + FormField( + value = draft.volcApiKey, + placeholder = if (sp.hasVolcApiKey) "已配置(留空则不变)" else "粘贴语音控制台的 API Key", + onValue = { draft = draft.copy(volcApiKey = it) }, + password = !showVolcApiKey, + trailing = { + IconButton(onClick = { showVolcApiKey = !showVolcApiKey }) { + Icon( + if (showVolcApiKey) Icons.Filled.VisibilityOff else Icons.Filled.Visibility, + if (showVolcApiKey) "隐藏" else "显示", + modifier = Modifier.size(20.dp), + ) + } + }, + ) + FormHint( + "在语音控制台的「API Key 管理」里创建。注意:**方舟**的 Key 用不了," + + "会报 401 —— 必须是语音这边建的 Key。", + ) + ConsoleLink("去语音控制台创建 API Key", sp.consoleUrls["volcv3"].orEmpty()) + + Spacer(Modifier.height(12.dp)) + VoicePicker( + title = "音色(speaker)", + voices = vm.state.speechVoices["volcv3"].orEmpty(), + value = draft.speech.ttsVoice, + placeholder = "留空 = zh_female_vv_uranus_bigtts(Vivi 2.0)", + onValue = { draft = draft.copy(speech = draft.speech.copy(ttsVoice = it)) }, + ) + FormHint("这一套音色和 V1 的 BVxxx 完全不通用,填错会报「音色不存在」。") + } else if (draft.speech.ttsEngine == "volc") { Spacer(Modifier.height(12.dp)) FormLabel("App ID") FormField( @@ -221,6 +261,7 @@ fun SettingsScreen(vm: AppViewModel) { }, ) FormHint("在火山控制台「语音技术」里创建应用后拿到 App ID 和 Access Token。") + ConsoleLink("去火山 V1 控制台(AppID / Token)", sp.consoleUrls["volc"].orEmpty()) Spacer(Modifier.height(12.dp)) VoicePicker( @@ -255,8 +296,11 @@ fun SettingsScreen(vm: AppViewModel) { "Base URL 和 Key 默认复用「连接与模型」里的设置 —— 那边没填 Key,云端朗读会失败。" }, ) + ConsoleLink("去 OpenAI 申请 API Key", sp.consoleUrls["openai"].orEmpty()) } else { - FormHint("用系统自带语音,不联网、不需要 Key。想用豆包的音色就选「火山」。") + FormHint("用系统自带语音,不联网、不需要 Key。想用豆包的音色就选「豆包语音」——只要一个 API Key。") + // 设备自带那条也给个入口:想升级成云端音色时,直接送到控制台 + ConsoleLink("想用豆包音色?去语音控制台拿 API Key", sp.consoleUrls["volcv3"].orEmpty()) } // 语速只对云端引擎有效:系统 TTS 的语速归系统管,内核根本不参与合成 @@ -339,6 +383,12 @@ fun SettingsScreen(vm: AppViewModel) { ) FormHint(if (s.hasApiKey) "已配置密钥;留空保存不会覆盖它。" else "也可以写在内核数据目录的 .env 里。") + // 快捷入口:直达这家控制台的「申请 API Key」页 + ConsoleLink( + "去 ${vm.state.providers[draft.provider]?.label ?: draft.provider} 申请 API Key", + vm.state.providers[draft.provider]?.consoleUrl.orEmpty(), + ) + Spacer(Modifier.height(12.dp)) FormLabel("模型") FormField( @@ -478,10 +528,14 @@ fun SettingsScreen(vm: AppViewModel) { /* ---------------------------- 语音卡片的零件 ---------------------------- */ -/** 朗读引擎(key 跟内核 speech.ttsEngine 一致:system / volc / openai) */ +/** 朗读引擎(key 跟内核 speech.ttsEngine 一致:system / volc / volcv3 / openai) */ private val TtsEngines: List> = listOf( "system" to "设备自带", - "volc" to "火山(豆包音色)", + // 两个火山是两套东西,标签必须写清楚,否则用户永远分不清该选哪个: + // volcv3 = 只要一个 API Key(推荐) + // volc = 老接口,要 AppID + Access Token + "volcv3" to "豆包语音(只要 API Key)", + "volc" to "火山 V1(AppID+Token)", "openai" to "OpenAI 兼容", ) @@ -491,6 +545,42 @@ private val SttEngines: List> = listOf( "openai" to "OpenAI(Whisper)", ) +/** + * 「去申请 Key ↗」快捷入口。 + * + * 与其让用户自己去找控制台,不如直接送到那一页 —— 这些地址由内核下发 + * (PROVIDER_CONSOLE_URLS / SPEECH_CONSOLE_URLS),以后地址变了只改内核一处。 + * + * url 为空就整行不画:本地部署(Ollama)不需要 Key,画一个点不动的链接更糟。 + */ +@Composable +private fun ConsoleLink(text: String, url: String) { + if (url.isBlank()) return + val ctx = LocalContext.current + Row( + Modifier + .clip(RoundedCornerShape(8.dp)) + .clickable { + try { + ctx.startActivity( + Intent(Intent.ACTION_VIEW, Uri.parse(url)) + // 从 Compose 起 Activity 有可能不在 Activity 上下文里,加这个 flag 更稳 + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + } catch (e: Exception) { + // 没有浏览器、或者 ROM 拦了 Intent:不能崩,提示一下就行 + Toast.makeText(ctx, "打不开:$url", Toast.LENGTH_SHORT).show() + } + } + .padding(vertical = 5.dp, horizontal = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(text, color = Doubao.Blue, fontSize = 13.sp) + Spacer(Modifier.width(3.dp)) + Text("↗", color = Doubao.Blue, fontSize = 13.sp, fontWeight = FontWeight.Medium) + } +} + /** * 语音卡片里的胶囊 chip:引擎选择、音色选择都用它。 * @@ -915,6 +1005,11 @@ internal data class SettingsDraft( * 所以它不参与 diff,只有"用户真敲了非空且不像掩码"时才进补丁。 */ val volcToken: String, + /** + * 豆包语音 V3 的 API Key。和 volcToken 一样永远从空开始、不参与 diff —— + * 接口只回掩码,回填就等于用八个点覆盖真 Key。 + */ + val volcApiKey: String, ) { /** * 切提供商时顺带把 baseUrl / model 换成新提供商的预设。 @@ -975,6 +1070,7 @@ internal data class SettingsDraft( // ★ 密钥:空白 = 不改,掩码 = 也不改。openaiApiKey 界面没有入口(复用对话那把 Key), // 所以它压根不进草稿 —— 这比"进了草稿再过滤掉"更保险 secretOrNull(volcToken)?.let { sp["volcToken"] = it } + secretOrNull(volcApiKey)?.let { sp["volcApiKey"] = it } // 界面没有入口的键(volcCluster / volcEncoding / openaiBaseUrl)故意不参与 diff: // 它们只可能来自配置文件或环境变量,界面不该在任何情况下把它们改掉 if (sp.isNotEmpty()) patch["speech"] = sp @@ -1005,6 +1101,7 @@ internal data class SettingsDraft( sttEngine = normalizeEngine(s.speech.sttEngine, SttEngines.map { it.first }), ), volcToken = "", + volcApiKey = "", ) } } diff --git a/android/kernel/app.py b/android/kernel/app.py index c204574..9805843 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -388,6 +388,7 @@ class KernelHandler(BaseHTTPRequestHandler): 'speech': speech.speech_state(settings), 'speechVoices': { 'volc': speech.VOLC_VOICES, + 'volcv3': speech.VOLC_V3_SPEAKERS, 'openai': speech.OPENAI_VOICES, 'system': [], }, diff --git a/android/kernel/defaults.py b/android/kernel/defaults.py index 99d8ccd..3b4ce0d 100644 --- a/android/kernel/defaults.py +++ b/android/kernel/defaults.py @@ -135,6 +135,29 @@ PROVIDER_PRESETS = { }, } +# 各家控制台「申请 API Key」的直达链接。 +# +# 为什么单独一张表、而不是塞进每个预设里:这些地址会变 +# (实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com, +# 旧地址 301 跳过去),集中一处以后好改。 +# 已逐个访问核实过可达(返回 200 或 302 到登录页都算通)。 +PROVIDER_CONSOLE_URLS = { + 'ark': 'https://console.volcengine.com/ark/region:cn-beijing/apiKey', + 'openai': 'https://platform.openai.com/api-keys', + 'deepseek': 'https://platform.deepseek.com/api_keys', + 'kimi': 'https://platform.kimi.com/console/api-keys', + 'zhipu': 'https://open.bigmodel.cn/usercenter/apikeys', + 'dashscope': 'https://bailian.console.aliyun.com/?apiKey=1', + 'siliconflow': 'https://cloud.siliconflow.cn/account/ak', + 'openrouter': 'https://openrouter.ai/keys', + 'ollama': 'https://ollama.com/download', + 'custom': '', +} +for _key, _url in PROVIDER_CONSOLE_URLS.items(): + if _key in PROVIDER_PRESETS: + PROVIDER_PRESETS[_key]['consoleUrl'] = _url + + DEFAULT_SETTINGS = { 'provider': 'ark', 'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'], diff --git a/android/kernel/speech.py b/android/kernel/speech.py index 35b9f2c..45204cb 100644 --- a/android/kernel/speech.py +++ b/android/kernel/speech.py @@ -34,6 +34,19 @@ DEFAULT_TIMEOUT_STT = 120 # (鉴权头那个分号、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', @@ -99,11 +112,101 @@ def synthesize(text: str, settings: dict) -> dict: 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: """ 火山语音合成。 @@ -302,12 +405,29 @@ def speech_state(settings: dict) -> dict: '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', +} + + # 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致 DEFAULT_SPEECH = { 'ttsEngine': 'system', @@ -319,6 +439,7 @@ DEFAULT_SPEECH = { 'sttLanguage': '', 'volcAppId': '', 'volcToken': '', + 'volcApiKey': '', # V3 用的那个(语音控制台 → API Key 管理) 'volcCluster': 'volcano_tts', 'volcEncoding': 'mp3', 'openaiApiKey': '', @@ -357,10 +478,26 @@ OPENAI_VOICES = [ {'value': 'sage', 'label': 'sage(女声,沉稳)'}, ] +# V3(大模型音色)的 speaker。★ 名字照官方「音色列表」核对过。 +# 这一套和 V1 的 BVxxx 完全不通用 —— 拿 BV700_streaming 去 V3 会报音色不存在。 +# 下面这 8 个是实测能合成出真 MP3 的(2026-10 验证)。 +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 [] diff --git a/android/kernel/store.py b/android/kernel/store.py index 7a1778c..234e7d9 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -114,6 +114,7 @@ def mask_settings(settings: dict) -> dict: out['hasApiKey'] = bool(settings.get('apiKey')) speech = dict(out.get('speech') or {}) speech['volcToken'] = '••••••••' if speech.get('volcToken') else '' + speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else '' speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else '' out['speech'] = speech return out @@ -189,7 +190,7 @@ def write_settings(patch: dict) -> dict: speech_next = nxt.get('speech') if isinstance(speech_next, dict): speech_cur = current.get('speech') or {} - for secret in ('volcToken', 'openaiApiKey'): + for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'): if speech_next.get(secret) == '••••••••': speech_next[secret] = speech_cur.get(secret, '') # ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。 diff --git a/scripts/verify-speech.mjs b/scripts/verify-speech.mjs index c8c7414..2b34d2f 100644 --- a/scripts/verify-speech.mjs +++ b/scripts/verify-speech.mjs @@ -118,6 +118,20 @@ for (const [id, name] of Object.entries(VOICE_TRUTH)) { } check('音色名和官方列表一致', voiceBad.length === 0, voiceBad.join(';') || `${Object.keys(VOICE_TRUTH).length} 个已核对`); +// V3(豆包语音,"只要一个 API Key" 那条路): +// 这是用户最想要的那条路,钉死几个关键事实,防止以后被改回去 +check('V3 音色选项已下发', Array.isArray(st.speechVoices?.volcv3) && st.speechVoices.volcv3.length > 0, + `${st.speechVoices?.volcv3?.length ?? 0} 个`); +const v3Voices = st.speechVoices?.volcv3 || []; +check('V3 默认音色在列表里', v3Voices.some((v) => v.value === 'zh_female_vv_uranus_bigtts'), + v3Voices.map((v) => v.value).slice(0, 3).join(', ')); +// V3 和 V1 的音色命名完全不通用,混填会报「音色不存在」,这条断言就是防这个 +check('V3 音色不是 V1 的 BVxxx 命名', v3Voices.every((v) => !/^BV\d/.test(v.value)), + v3Voices.filter((v) => /^BV\d/.test(v.value)).map((v) => v.value).join(', ') || '全是 bigtts 命名'); +check('语音控制台链接已下发', typeof st.speech?.consoleUrls?.volcv3 === 'string' + && st.speech.consoleUrls.volcv3.includes('console.volcengine.com/speech'), + st.speech?.consoleUrls?.volcv3 || '(空)'); + const ttsSystem = await api('/api/tts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: '你好' }), diff --git a/server/src/config.mjs b/server/src/config.mjs index fd2654a..3277de6 100644 --- a/server/src/config.mjs +++ b/server/src/config.mjs @@ -225,6 +225,29 @@ export const PROVIDER_PRESETS = { }, }; +/** + * 各家控制台「申请 API Key」的直达链接,界面拿它做快捷入口。 + * + * 单独一张表而不是塞进每个预设里:这些地址会变 + * (实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com,旧地址 301 跳过去), + * 集中一处以后好改。已逐个访问核实可达(200 或 302 到登录页都算通)。 + */ +export const PROVIDER_CONSOLE_URLS = { + ark: 'https://console.volcengine.com/ark/region:cn-beijing/apiKey', + openai: 'https://platform.openai.com/api-keys', + deepseek: 'https://platform.deepseek.com/api_keys', + kimi: 'https://platform.kimi.com/console/api-keys', + zhipu: 'https://open.bigmodel.cn/usercenter/apikeys', + dashscope: 'https://bailian.console.aliyun.com/?apiKey=1', + siliconflow: 'https://cloud.siliconflow.cn/account/ak', + openrouter: 'https://openrouter.ai/keys', + ollama: 'https://ollama.com/download', + custom: '', +}; +for (const [key, url] of Object.entries(PROVIDER_CONSOLE_URLS)) { + if (PROVIDER_PRESETS[key]) PROVIDER_PRESETS[key].consoleUrl = url; +} + export const DEFAULT_SYSTEM_PROMPT = [ '你是豆包,一个由字节跳动开发的 AI 助手,风格自然、亲切、简洁。', '', @@ -262,8 +285,8 @@ export const DEFAULT_SETTINGS = { // 语音(朗读 / 语音输入)。引擎默认 'system' = 用设备自带的,不联网、不要 Key; // 想用云端音色(火山豆包音色 / OpenAI)就把 ttsEngine 改成 'volc' 或 'openai'。 speech: { - ttsEngine: 'system', // system | volc | openai - ttsVoice: '', // volc: voice_type;openai: alloy/nova/... + ttsEngine: 'system', // system | volc(V1: AppID+Token) | volcv3(只要 API Key) | openai + ttsVoice: '', // volc: BVxxx;volcv3: zh_xxx_bigtts;openai: alloy/nova/... ttsSpeed: 1.0, autoRead: false, // 新回复自动念出来 sttEngine: 'system', // system | openai @@ -271,6 +294,8 @@ export const DEFAULT_SETTINGS = { sttLanguage: '', // 留空 = 自动判断 volcAppId: '', volcToken: '', + // V3 只要这一个 Key(语音控制台 → API Key 管理)。和方舟的 Key 不是一回事 + volcApiKey: '', volcCluster: 'volcano_tts', volcEncoding: 'mp3', openaiApiKey: '', // 留空则复用主对话的 Key diff --git a/server/src/speech.mjs b/server/src/speech.mjs index 842c84b..95ef929 100644 --- a/server/src/speech.mjs +++ b/server/src/speech.mjs @@ -16,6 +16,18 @@ export const VOLC_TTS_URL = process.env.DOUBAO_VOLC_TTS_URL || '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) +// +// ★ 注意路径里**没有 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 +export const VOLC_V3_TTS_URL = process.env.DOUBAO_VOLC_V3_TTS_URL + || 'https://openspeech.bytedance.com/api/v3/tts/unidirectional'; +export const VOLC_V3_RESOURCE_ID = 'seed-tts-2.0'; + const TIMEOUT_TTS = 60000; const TIMEOUT_STT = 120000; @@ -63,10 +75,97 @@ export async function synthesize(text, settings) { const speed = Math.min(Math.max(Number(speech.ttsSpeed) || 1.0, 0.2), 3.0); if (engine === 'volc') return synthesizeVolc(content, speech, speed); + if (engine === 'volcv3') return synthesizeVolcV3(content, speech, speed); if (engine === 'openai') return synthesizeOpenai(content, settings, speech, speed); return { engine: 'system' }; } +/** + * 豆包语音 V3 合成 —— "只要一个 API Key" 的那条路。 + * + * 和 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。 + */ +async function synthesizeVolcV3(text, speech, speed) { + const apiKey = String(speech.volcApiKey || '').trim(); + const speaker = String(speech.ttsVoice || '').trim() || 'zh_female_vv_uranus_bigtts'; + let format = String(speech.volcEncoding || '').trim() || 'mp3'; + if (!['mp3', 'wav', 'ogg_opus', 'pcm'].includes(format)) format = 'mp3'; + + if (!apiKey) { + throw new SpeechError( + '豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。' + + '注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。', + ); + } + + const body = { + req_params: { + text, + speaker, + audio_params: { + format, + // 24k 是大模型音色的标准采样率,调低会明显发闷 + sample_rate: 24000, + // V3 的语速是 ±100 的百分比,不是倍率(实测 -50 变慢、+50 变快) + speech_rate: Math.round((speed - 1.0) * 100), + }, + }, + }; + + let res; + try { + res = await fetchWithTimeout(VOLC_V3_TTS_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Api-Key': apiKey, + 'X-Api-Resource-Id': VOLC_V3_RESOURCE_ID, + 'X-Control-Require-Usage-Tokens-Return': '*', + }, + body: JSON.stringify(body), + }, TIMEOUT_TTS); + } catch (err) { + throw new SpeechError(`连不上火山 V3:${err.message}`); + } + + const raw = await res.text(); + if (!res.ok && !raw.trim()) throw new SpeechError(`HTTP ${res.status}`); + + // 逐行解析:每行一个 JSON,把 data 里的音频片段拼起来 + const chunks = []; + let error = null; + for (const line of raw.split('\n')) { + const s = line.trim(); + if (!s) continue; + let item; + try { + item = JSON.parse(s); + } catch { + continue; // NDJSON 之外的行(有的网关会插空行/心跳)直接跳过 + } + const code = item.code; + if (typeof item.data === 'string' && item.data) chunks.push(item.data); + if (code === 20000000) break; + if (typeof code === 'number' && code > 0) { + error = `code=${code} ${item.message || item.msg || ''}`.trim(); + break; + } + } + + if (error) throw new SpeechError(`火山 V3 失败:${error}`); + if (!chunks.length) throw new SpeechError('火山 V3 没返回音频数据'); + + return { engine: 'volcv3', mime: VOLC_MIME[format] || 'audio/mpeg', audio: chunks.join('') }; +} + /** * 火山语音合成。 * @@ -238,9 +337,22 @@ export function speechState(settings) { hasOpenaiKey: Boolean(speech.openaiApiKey || settings?.apiKey), openaiBaseUrl: speech.openaiBaseUrl || '', ttsModel: speech.ttsModel || 'tts-1', + // 各家「申请语音 Key」的直达链接,界面做成快捷入口。 + // 放内核而不是写死在界面里:以后加厂商只改一处。 + consoleUrls: SPEECH_CONSOLE_URLS, }; } +/** 语音相关控制台的直达链接(都已访问核实可达) */ +export const 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', + agentPlan: 'https://ark.volcengine.com/region:cn-beijing/openManagement?advancedActiveKey=agentPlan', +}; + /** 掩码值:写设置时看到它表示"不改"(跟 apiKey 一个套路) */ export const MASK = '••••••••'; @@ -282,6 +394,22 @@ export const VOLC_VOICES = [ { value: 'BV406_streaming', label: '超自然音色 · 梓梓' }, ]; +/** + * V3(大模型音色)的 speaker。★ 名字照官方「音色列表」核对过。 + * 这一套和 V1 的 BVxxx 完全不通用 —— 拿 BV700_streaming 去 V3 会报音色不存在。 + * 下面这 8 个是实测能合成出真 MP3 的。 + */ +export const 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' }, +]; + export const OPENAI_VOICES = [ { value: 'alloy', label: 'alloy(中性)' }, { value: 'nova', label: 'nova(女声,推荐)' }, @@ -293,4 +421,9 @@ export const OPENAI_VOICES = [ { value: 'sage', label: 'sage(女声,沉稳)' }, ]; -export const VOICE_OPTIONS = { volc: VOLC_VOICES, openai: OPENAI_VOICES, system: [] }; +export const VOICE_OPTIONS = { + volc: VOLC_VOICES, + volcv3: VOLC_V3_SPEAKERS, + openai: OPENAI_VOICES, + system: [], +};