【一、流式朗读为什么没生效】
用户报"语音还是没有实时读"。根因是我自己埋的:
fmt = (speech.get('volcEncoding') or 'pcm').strip() or 'pcm'
volcEncoding 的**默认值是 mp3**,所以 `or 'pcm'` 永远不触发 —— 内核一直
下发 mp3,而播放端是把字节直接喂 AudioTrack 的、没有解码器,
一看不是 PCM 就放弃流式、退回"整段收完再播"。整条链路白做。
更糟的是我在 AudioIo.kt 里写了句"内核那边 volcEncoding 默认给 pcm",
跟事实相反,等于给自己留了个假线索。
修:流式路径**强制 PCM**。这不是用户偏好而是硬要求 ——
AudioTrack 没有解码器。volcEncoding 仍然管非流式那条路(/api/tts),
那条客户端用 MediaPlayer,mp3 没问题。
★ 测试为什么没抓到:verify-tts-route.mjs 里写死了 volcEncoding: 'pcm',
一直是绿的;而真机上是默认的 mp3。**测试跑的不是用户会遇到的那个配置**。
现在改成故意不写 volcEncoding,跑默认配置,并加了一条 Content-Type 必须是
PCM 的断言。新增 verify-tts-device-stream.mjs 直接在实体机上验。
实体机实测(配置里编码还是 mp3):Content-Type=audio/L16、45 块、
首块 1178ms 末块 2002ms —— 确实边生成边下发。
【二、附件上限 25MB → 100MB】
联动改了五处,少改一处就会先被别的限制挡下来:
uploads.py / uploads.mjs COPY_LIMIT 25MB → 100MB
app.py /api/upload 请求体 40MB → 150MB
app.py _read_body_raw(socket 层) 40MB → 150MB
index.mjs /api/upload 请求体 40MB → 150MB
ChatScreen.kt MAX_UPLOAD_BYTES 25MB → 100MB
150MB 是这么算的:100MB 的文件 base64 后约 133MB,再套一层 JSON。
注释里写明了这几个值是联动的,改一个要改另一个。
⚠ 内存:一次上传峰值约 文件大小 × 2.4(原始 JSON 串 + 解码结果),
100MB 要吃 240MB 左右,低端机可能被系统杀掉。真要传超大文件,
正确做法是分片上传而不是继续抬这个数 —— 这条也写进注释了。
188 lines
6.8 KiB
Python
188 lines
6.8 KiB
Python
"""
|
||
附件:上传落盘、拖拽文件待取队列、以及"附件 → 模型输入"的转换。
|
||
|
||
对应 Node 版 server/src/uploads.mjs,字段完全一致:
|
||
{ id, name, size, mime, path, url, at }
|
||
|
||
安卓上的差异:
|
||
* 没有 Electron 的原生选文件钩子,选文件由 Kotlin 侧调用 /api/pick-file 时注入
|
||
(main.py 的 native hooks),默认返回"当前环境不支持原生选文件";
|
||
* 上传仍然走 base64(前端 FileReader → dataUrl),因为 WebView/Lynx 里拿不到真实路径。
|
||
"""
|
||
|
||
import base64
|
||
import binascii
|
||
import os
|
||
import re
|
||
import sys
|
||
import threading
|
||
|
||
import paths
|
||
from store import _rand36, _ts36, now_iso # 复用同一套 id/时间风格
|
||
|
||
_pending = []
|
||
_pending_lock = threading.Lock()
|
||
|
||
IMAGE_EXT = {'.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'}
|
||
TEXT_EXT = {
|
||
'.txt', '.md', '.markdown', '.json', '.csv', '.tsv', '.log', '.ini', '.toml', '.yml', '.yaml',
|
||
'.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.html', '.htm', '.css', '.scss',
|
||
'.xml', '.sql', '.sh', '.bat', '.ps1', '.java', '.c', '.h', '.cpp', '.cs', '.go', '.rs',
|
||
'.rb', '.php', '.swift', '.kt', '.lua', '.r', '.vue', '.svelte',
|
||
}
|
||
|
||
# 复制进 uploads 的上限;再大就只登记路径,不复制
|
||
# 单个文件上限。
|
||
#
|
||
# ★ 这个值和请求体上限是联动的:走 /api/upload 时文件会先 base64 再塞进 JSON,
|
||
# 体积涨 1/3 —— 100MB 的文件对应约 133MB 的请求体,所以 app.py 那边
|
||
# /api/upload 的 read_json_body 得给到 150MB,否则会先被"请求体过大"挡下来。
|
||
#
|
||
# 内存提醒:一次上传的峰值占用大约是 文件大小 × 2.4(原始 JSON 字符串 +
|
||
# base64 解码结果)。100MB 的文件在手机上要吃掉 240MB 左右,低端机有可能
|
||
# 直接被系统杀掉。真要传超大文件,正确做法是分片上传,不是继续抬这个数。
|
||
COPY_LIMIT = 100 * 1024 * 1024
|
||
# 喂给模型的单张图片上限
|
||
VISION_LIMIT = 6 * 1024 * 1024
|
||
|
||
_MIME = {
|
||
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
|
||
'.gif': 'image/gif', '.bmp': 'image/bmp', '.pdf': 'application/pdf',
|
||
'.json': 'application/json', '.md': 'text/markdown',
|
||
}
|
||
|
||
|
||
def _rid() -> str:
|
||
return f'f_{_ts36()}_{_rand36(4)}'
|
||
|
||
|
||
def _safe_name(name: str) -> str:
|
||
"""去掉路径分隔符和 Windows 非法字符,并只保留末尾 60 个字符(和 Node 一致)。"""
|
||
cleaned = re.sub(r'[\\/:*?"<>|]', '_', str(name or 'file'))
|
||
return cleaned[-60:]
|
||
|
||
|
||
def _ext_of(name: str) -> str:
|
||
return os.path.splitext(str(name or ''))[1].lower()
|
||
|
||
|
||
def is_image(name: str) -> bool:
|
||
return _ext_of(name) in IMAGE_EXT
|
||
|
||
|
||
def is_text(name: str) -> bool:
|
||
return _ext_of(name) in TEXT_EXT
|
||
|
||
|
||
def mime_of(name: str) -> str:
|
||
ext = _ext_of(name)
|
||
if ext in _MIME:
|
||
return _MIME[ext]
|
||
return 'text/plain' if is_text(name) else 'application/octet-stream'
|
||
|
||
|
||
def _meta(file_path: str, name: str, copy: bool = True) -> dict:
|
||
size = os.path.getsize(file_path)
|
||
stored_path = file_path
|
||
url = ''
|
||
if copy and size <= COPY_LIMIT:
|
||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||
with open(file_path, 'rb') as src, open(target, 'wb') as dst:
|
||
while True:
|
||
chunk = src.read(256 * 1024)
|
||
if not chunk:
|
||
break
|
||
dst.write(chunk)
|
||
stored_path = target
|
||
url = f'/uploads/{os.path.basename(target)}'
|
||
return {
|
||
'id': _rid(),
|
||
'name': str(name),
|
||
'size': size,
|
||
'mime': mime_of(name),
|
||
'path': stored_path,
|
||
'url': url,
|
||
'at': now_iso(),
|
||
}
|
||
|
||
|
||
def save_upload(name: str, base64_data: str) -> dict:
|
||
"""浏览器上传:base64(dataUrl) → 落盘。"""
|
||
if not name or not base64_data:
|
||
raise ValueError('缺少 name 或 base64')
|
||
raw = re.sub(r'^data:[^,]+,', '', str(base64_data))
|
||
try:
|
||
# validate=False:和 Node 的 Buffer.from(x,'base64') 一样,忽略非法字符
|
||
buffer = base64.b64decode(raw, validate=False)
|
||
except (binascii.Error, ValueError) as exc:
|
||
raise ValueError(f'base64 解码失败:{exc}') from exc
|
||
if len(buffer) > COPY_LIMIT:
|
||
raise ValueError(f'文件超过 {COPY_LIMIT // 1024 // 1024}MB')
|
||
target = os.path.join(paths.get().uploads_dir, f'{_ts36()}_{_safe_name(name)}')
|
||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||
with open(target, 'wb') as fh:
|
||
fh.write(buffer)
|
||
return {
|
||
'id': _rid(),
|
||
'name': str(name),
|
||
'size': len(buffer),
|
||
'mime': mime_of(name),
|
||
'path': target,
|
||
'url': f'/uploads/{os.path.basename(target)}',
|
||
'at': now_iso(),
|
||
}
|
||
|
||
|
||
def register_local_file(file_path: str) -> dict:
|
||
"""安卓/Kotlin 侧选完文件后登记(必要时复制进 uploads)。"""
|
||
if not os.path.isfile(file_path):
|
||
raise ValueError(f'文件不存在:{file_path}')
|
||
return _meta(file_path, os.path.basename(file_path))
|
||
|
||
|
||
def add_pending(items: list) -> None:
|
||
with _pending_lock:
|
||
_pending.extend(items or [])
|
||
|
||
|
||
def take_pending() -> list:
|
||
"""取走待处理附件(取完即清空),Lynx 界面轮询这个接口挂输入框。"""
|
||
global _pending
|
||
with _pending_lock:
|
||
items = _pending
|
||
_pending = []
|
||
return items
|
||
|
||
|
||
def attachment_payload(attachment: dict) -> dict:
|
||
"""
|
||
把附件转成模型能吃的形式:图片走视觉格式(data URL),文本类内联正文。
|
||
返回 {text, images:[{url}]},与 Node 版 attachmentPayload 一致。
|
||
"""
|
||
out = {'text': '', 'images': []}
|
||
item = attachment or {}
|
||
file_path = item.get('path') or ''
|
||
if not file_path or not os.path.isfile(file_path):
|
||
out['text'] = f"【附件 {item.get('name') or '未知'} 已丢失】"
|
||
return out
|
||
size = os.path.getsize(file_path)
|
||
if is_image(item.get('name')) and size <= VISION_LIMIT:
|
||
with open(file_path, 'rb') as fh:
|
||
b64 = base64.b64encode(fh.read()).decode('ascii')
|
||
out['images'].append({'url': f"data:{item.get('mime')};base64,{b64}"})
|
||
out['text'] = f"【图片 {item.get('name')}】"
|
||
return out
|
||
if is_text(item.get('name')) or size < 64 * 1024:
|
||
body = ''
|
||
try:
|
||
with open(file_path, 'r', encoding='utf-8', errors='replace') as fh:
|
||
body = fh.read()
|
||
except OSError as exc:
|
||
print(f'[uploads] 读取 {file_path} 失败:{exc}', file=sys.stderr)
|
||
if body:
|
||
clipped = f'{body[:20000]}\n…(已截断,共 {len(body)} 字符)' if len(body) > 20000 else body
|
||
out['text'] = f"【文件 {item.get('name')}({size} 字节)】\n```\n{clipped}\n```"
|
||
return out
|
||
out['text'] = f"【附件 {item.get('name')}({size} 字节,二进制)本地路径:{file_path}】"
|
||
return out
|