Files
doubao-clone/tools/python_run.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

120 lines
4.1 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.

"""Python 运行工具:直接执行一段 Python 代码或一个 .py 文件,拿回输出。
- 子进程运行,崩溃不影响内核
- 需要联网时可以直接 import requests / httpx / urllib(装了就有)
- `libs` 动作可以列出当前环境装了哪些常用库
"""
import importlib.util
import os
import subprocess
import sys
import tempfile
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _protocol import serve # noqa: E402
TOOL = {
"name": "python_run",
"description": (
"运行一段 Python 代码或指定 .py 文件,返回标准输出/错误。"
"适合做计算、数据处理、调用网络接口(requests/httpx/urllib 可用)。"
"action=libs 可以查看当前环境装了哪些库。"
),
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["run", "libs"],
"description": "run=执行代码/文件(默认);libs=列出可用库",
},
"code": {"type": "string", "description": "要执行的 Python 代码(action=run 时二选一)"},
"file": {"type": "string", "description": "要执行的 .py 文件路径(action=run 时二选一)"},
"stdin": {"type": "string", "description": "传给脚本的标准输入,可留空"},
"timeout": {"type": "number", "description": "超时秒数,默认 60,最大 600"},
},
},
}
WATCHED = [
"requests", "httpx", "aiohttp", "urllib3", "bs4", "lxml", "pandas", "numpy",
"PIL", "openpyxl", "docx", "pptx", "yaml", "dotenv", "mcp", "flask", "fastapi",
]
def python_bin():
"""优先用当前解释器;安卓上没有独立解释器时返回 None(由内核在进程内执行)"""
if sys.executable and os.path.basename(sys.executable).lower().startswith("python"):
return sys.executable
for name in ("python3", "python"):
for folder in os.environ.get("PATH", "").split(os.pathsep):
candidate = os.path.join(folder, name)
if os.path.isfile(candidate):
return candidate
return sys.executable or "python"
def run(args):
action = str(args.get("action") or "run").lower()
if action == "libs":
available = []
missing = []
for name in WATCHED:
(available if importlib.util.find_spec(name) else missing).append(name)
return {
"python": sys.version.split()[0],
"executable": sys.executable,
"available": available,
"missing": missing,
"hint": "缺库时可以用 shell 工具执行 pip install <包名>" if missing else "常用库齐全",
}
code = args.get("code")
file_path = args.get("file")
if not code and not file_path:
raise ValueError("code 和 file 至少要给一个")
timeout = max(1, min(600, int(args.get("timeout", 60) or 60)))
stdin_text = args.get("stdin") or ""
cleanup = None
if file_path:
target = str(file_path)
if not os.path.isfile(target):
raise ValueError(f"文件不存在:{target}")
else:
fd, target = tempfile.mkstemp(suffix=".py", prefix="doubao_run_")
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(str(code))
cleanup = target
try:
proc = subprocess.run(
[python_bin(), target],
input=stdin_text,
capture_output=True,
timeout=timeout,
text=True,
errors="replace",
cwd=os.path.dirname(os.path.abspath(target)),
)
return {
"exit_code": proc.returncode,
"stdout": (proc.stdout or "")[-12000:],
"stderr": (proc.stderr or "")[-6000:],
}
except subprocess.TimeoutExpired:
return {"error": f"执行超时({timeout}s)", "timeout": True}
finally:
if cleanup:
try:
os.unlink(cleanup)
except OSError:
pass
if __name__ == "__main__":
serve(TOOL, run)