Files
doubao-clone/android/kernel/uploads.py
l f056bcf45a 豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、
不需要另外装 Termux。

安卓端
- 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的
- 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹
- 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端;
  pty 不可用的 ROM 上自动降级成命令控制台
- APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上
- 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板
- 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎

AI 能力
- 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 /
  通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义
- 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发),
  认不出来的一律不发,避免给不支持的厂商发字段直接 400
- MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式

跨端
- 安卓走原生 Compose,Web / Windows 走 Lynx
- Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本

自检脚本(都不需要真 Key)
- verify-phone.mjs          设备端 24 项验收
- verify-speech.mjs         语音链路 31 项,两份内核各跑一遍
- parity-thinking.mjs       思考强度映射对拍
- probe-settings-wipe.mjs   设置防清空攻击测试
- mock-llm.mjs              假的 OpenAI + 火山语音服务

许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron)
的授权见 LICENSE。
2026-10-09 14:09:36 +08:00

179 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
附件:上传落盘、拖拽文件待取队列、以及"附件 → 模型输入"的转换。
对应 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 的上限;再大就只登记路径,不复制
COPY_LIMIT = 25 * 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