HAND DESIGN COLLECTION 02
+选择你的灵巧手。
+两款方案,一个入口。进入模型后,可随时通过顶部菜单切换。
+
+ 实际 CAD 模型
+
+
+ diff --git a/examples/hand_gallery/.gitignore b/examples/hand_gallery/.gitignore new file mode 100644 index 00000000..1da3bddd --- /dev/null +++ b/examples/hand_gallery/.gitignore @@ -0,0 +1,2 @@ +.runtime/ +__pycache__/ diff --git a/examples/hand_gallery/README.md b/examples/hand_gallery/README.md new file mode 100644 index 00000000..2961f232 --- /dev/null +++ b/examples/hand_gallery/README.md @@ -0,0 +1,17 @@ +# 两款灵巧手的本地选择菜单 + +从仓库根目录启动: + +```sh +python3 examples/hand_gallery/launch.py +``` + +- `http://127.0.0.1:8764/`:选择菜单。 +- `http://127.0.0.1:8764/hands/codex`:Codex 的 LH20。 +- `http://127.0.0.1:8764/hands/claude`:Claude 的 20 自由度灵巧手。 + +顶部菜单可随时切换;浏览器前进、后退和直接刷新路由均支持。已经打开的编辑器保留在各自 iframe 中,切换不会触发整手重新构建。右上角可将当前编辑器放到独立窗口。 + +启动器检查现有服务的工作区,复用匹配的 8765 / 8771 编辑器;未启动时使用 `.venv/bin/sca` / `.venv-hand/bin/sca` 启动相应 `hand.py`。遇到无关服务占用端口会报错,不终止其他进程。菜单只绑定本机地址;预览图直接读取两个项目已有的 CAD 渲染结果。 + +`models.py` 管理模型路径与端口,`server.py` 提供只读状态与固定资源路由,`web/` 实现页面;无需新增依赖。日志和 PID 位于忽略提交的 `.runtime/`。本菜单不修改任一 CAD 模型或 SDK 源码。 diff --git a/examples/hand_gallery/launch.py b/examples/hand_gallery/launch.py new file mode 100644 index 00000000..e04966e0 --- /dev/null +++ b/examples/hand_gallery/launch.py @@ -0,0 +1,61 @@ +"""Start missing editors and the menu; reuse already running matching services.""" + +import json +import socket +import subprocess +import sys +from urllib.request import urlopen + +from models import HERE, HOST, MODELS, PORT, ROOT, editor_url +from server import status + + +def port_available(port): + with socket.socket() as sock: + try: + sock.bind((HOST, port)) + except OSError: + return False + return True + + +def spawn(name, args): + runtime = HERE / ".runtime" + runtime.mkdir(exist_ok=True) + with (runtime / f"{name}.log").open("a") as log: + process = subprocess.Popen( + args, cwd=ROOT, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True, + ) + (runtime / f"{name}.pid").write_text(str(process.pid)) + print(f"Started {name}: PID {process.pid}") + + +def main(): + for key, model in MODELS.items(): + state = status(key, model)["state"] + if state in ("online", "loading"): + print(f"Reusing {model['name']}: {editor_url(model)}") + continue + if state == "mismatch" or not port_available(model["port"]): + raise SystemExit(f"Port {model['port']} belongs to another service; left unchanged.") + if not model["executable"].is_file() or not (model["workspace"] / "hand.py").is_file(): + raise SystemExit(f"Missing editor or hand.py for {model['name']}.") + spawn(key, [str(model["executable"]), "edit", str(model["workspace"] / "hand.py"), + "--host", HOST, "--port", str(model["port"]), "--no-browser"]) + if port_available(PORT): + spawn("menu", [sys.executable, str(HERE / "server.py")]) + else: + try: + with urlopen(f"http://{HOST}:{PORT}/api/health", timeout=2) as response: + health = json.load(response) + if health.get("service") != "simplecad-hand-gallery": + raise ValueError("Different service") + except (OSError, ValueError) as error: + raise SystemExit(f"Port {PORT} is occupied; left unchanged: {error}") from error + print("Reusing hand selector") + print(f"Open http://{HOST}:{PORT}/") + + +if __name__ == "__main__": + main() diff --git a/examples/hand_gallery/models.py b/examples/hand_gallery/models.py new file mode 100644 index 00000000..4433ac0a --- /dev/null +++ b/examples/hand_gallery/models.py @@ -0,0 +1,28 @@ +"""The two existing hand workspaces; no CAD source is copied or modified.""" + +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +HOST = "127.0.0.1" +PORT = 8764 +MODELS = { + "codex": { + "name": "LH20 · Codex", + "workspace": ROOT / "examples/lh20_hand", + "executable": ROOT / ".venv/bin/sca", + "port": 8765, + "preview": ROOT / "examples/lh20_hand/out/lh20_right_hand_overview.png", + }, + "claude": { + "name": "20 自由度灵巧手 · Claude", + "workspace": ROOT / "examples/dexterous_hand_20dof", + "executable": ROOT / ".venv-hand/bin/sca", + "port": 8771, + "preview": ROOT / "examples/dexterous_hand_20dof/out/renders/hand_open_iso.png", + }, +} + + +def editor_url(model): + return f"http://{HOST}:{model['port']}" diff --git a/examples/hand_gallery/server.py b/examples/hand_gallery/server.py new file mode 100644 index 00000000..5beb20c0 --- /dev/null +++ b/examples/hand_gallery/server.py @@ -0,0 +1,77 @@ +"""Loopback-only hand selector, with independent editors kept in iframes.""" + +from concurrent.futures import ThreadPoolExecutor +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.error import URLError +from urllib.parse import urlsplit +from urllib.request import urlopen +import json +import mimetypes + +from models import HERE, HOST, MODELS, PORT, editor_url + + +def status(key, model): + row = {"id": key, "name": model["name"], "url": editor_url(model)} + try: + with urlopen(row["url"] + "/api/health", timeout=2) as response: + health = json.load(response) + correct = ( + health.get("ok") is True + and Path(health.get("workspace", "")).resolve() == model["workspace"].resolve() + ) + row.update( + state=("online" if health.get("kernel") else "loading") if correct else "mismatch", + notebook=health.get("notebook") if correct else None, + ) + except (OSError, URLError, ValueError, TypeError): + row["state"] = "offline" + return row + + +class Handler(BaseHTTPRequestHandler): + def send(self, code, data, content_type, head=False): + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.end_headers() + if not head: + self.wfile.write(data) + + def do_HEAD(self): + self.do_GET(head=True) + + def do_GET(self, head=False): + path = urlsplit(self.path).path.rstrip("/") or "/" + if path == "/api/health": + payload = {"ok": True, "service": "simplecad-hand-gallery"} + elif path == "/api/models": + with ThreadPoolExecutor(max_workers=2) as pool: + rows = list(pool.map(lambda item: status(*item), MODELS.items())) + payload = {"models": rows} + else: + payload = None + if payload is not None: + self.send(200, json.dumps(payload, ensure_ascii=False).encode(), "application/json; charset=utf-8", head) + return + routes = { + "/": HERE / "web/index.html", + **{f"/hands/{key}": HERE / "web/index.html" for key in MODELS}, + "/assets/app.js": HERE / "web/app.js", + "/assets/style.css": HERE / "web/style.css", + **{f"/previews/{key}.png": model["preview"] for key, model in MODELS.items()}, + } + file = routes.get(path) + if file is None or not file.is_file(): + self.send(404, b"Not found", "text/plain; charset=utf-8", head) + return + mime = mimetypes.guess_type(file.name)[0] or "application/octet-stream" + self.send(200, file.read_bytes(), mime + ("; charset=utf-8" if mime.startswith("text/") else ""), head) + + +if __name__ == "__main__": + print(f"Hand selector: http://{HOST}:{PORT}", flush=True) + ThreadingHTTPServer((HOST, PORT), Handler).serve_forever() diff --git a/examples/hand_gallery/web/app.js b/examples/hand_gallery/web/app.js new file mode 100644 index 00000000..b065b3f1 --- /dev/null +++ b/examples/hand_gallery/web/app.js @@ -0,0 +1,84 @@ +const models = { + codex: { name: "LH20 · Codex", url: "http://127.0.0.1:8765", state: "checking" }, + claude: { name: "20 自由度灵巧手 · Claude", url: "http://127.0.0.1:8771", state: "checking" }, +}; +const labels = { online: "编辑器已连接", loading: "编辑器启动中", offline: "编辑器未启动", mismatch: "端口对应其他项目", checking: "检查连接中", unavailable: "暂时无法检查连接" }; +const frames = new Map(); +let active = null; + +function updateStatus() { + document.querySelectorAll("[data-status]").forEach((badge) => { + const state = models[badge.dataset.status].state; + badge.textContent = labels[state]; + badge.className = `status ${state}`; + }); + if (!active) return; + const model = models[active]; + const badge = document.querySelector("#workspace-status"); + badge.textContent = labels[model.state]; + badge.className = `status ${model.state}`; + const notice = document.querySelector("#connection-notice"); + notice.hidden = ["online", "checking"].includes(model.state); + notice.textContent = model.state === "mismatch" + ? "这个端口当前对应其他项目,请先检查编辑器服务。" + : model.state === "loading" + ? "编辑器正在启动,首次构建可能需要一些时间。" + : "暂时无法连接此编辑器。重新启动工作台后会自动连接,也可以使用右侧的独立窗口链接。"; + // Create each editor only after verifying its workspace. Keep existing frames + // mounted so switching does not discard camera or in-progress editor state. + if (model.state === "online" && !frames.has(active)) { + const frame = document.createElement("iframe"); + frame.title = `${model.name} 模型编辑器`; + frame.src = model.url; + frame.dataset.model = active; + document.querySelector("#editors").append(frame); + frames.set(active, frame); + } + frames.forEach((frame, id) => { frame.hidden = id !== active; }); +} + +function route() { + const path = location.pathname.replace(/\/$/, "") || "/"; + const key = path.startsWith("/hands/") ? path.slice(7) : null; + active = Object.hasOwn(models, key) ? key : null; + document.querySelector("#gallery").hidden = Boolean(active); + document.querySelector("#workspace").hidden = !active; + document.body.classList.toggle("editing", Boolean(active)); + document.querySelectorAll("nav [data-route]").forEach((link) => { + if (link.dataset.route === path) link.setAttribute("aria-current", "page"); + else link.removeAttribute("aria-current"); + }); + if (active) { + document.querySelector("#workspace-title").textContent = models[active].name; + document.querySelector("#direct-link").href = models[active].url; + } + document.title = active ? `${models[active].name} · 灵巧手工作台` : "灵巧手工作台 · SimpleCAD"; + updateStatus(); +} + +document.addEventListener("click", (event) => { + const link = event.target.closest("a[data-route]"); + if (!link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + if (location.pathname !== link.dataset.route) history.pushState({}, "", link.dataset.route); + route(); + window.scrollTo(0, 0); +}); +window.addEventListener("popstate", route); + +async function refreshStatus() { + try { + const response = await fetch("/api/models", { signal: AbortSignal.timeout(6000) }); + if (!response.ok) throw new Error("Status unavailable"); + const data = await response.json(); + data.models.forEach((row) => { + if (Object.hasOwn(models, row.id)) models[row.id].state = row.state; + }); + } catch { + Object.values(models).forEach((model) => { model.state = "unavailable"; }); + } + updateStatus(); + window.setTimeout(refreshStatus, 5000); +} +route(); +refreshStatus(); diff --git a/examples/hand_gallery/web/index.html b/examples/hand_gallery/web/index.html new file mode 100644 index 00000000..24033f97 --- /dev/null +++ b/examples/hand_gallery/web/index.html @@ -0,0 +1,65 @@ + + +
+ + +HAND DESIGN COLLECTION 02
+两款方案,一个入口。进入模型后,可随时通过顶部菜单切换。
+
+ 实际 CAD 模型
+
+
+