""" 附件:上传落盘、拖拽文件待取队列、以及"附件 → 模型输入"的转换。 对应 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