Add Home Pulse App API and verified device-command workflow
Browse filesFiles changed (2)
- app.py+21-5
- web/server-bundle.mjs+7-2
12 unmodified lines13141516171825 unmodified lines44454647484929 unmodified lines79808182838431 unmodified lines1161171181191201211221231241251261271281291301311321331344 unmodified lines13914014114214314414512 unmodified linesimport ioimport timeimport asynciofrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport gradio as gr25 unmodified linesREMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev')app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)class ModelBridge(BaseHTTPRequestHandler):def do_POST(self):29 unmodified linesreturn run_visual(route,body,workspace,dict(request.headers) if request else {})def run_visual(route:str,body:str,workspace:str,request_headers:dict)->dict:# The browser and native REST adapter share the visitor-quota protocol.token=request_headers.get('x-ip-token','')print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)31 unmodified linesauthorization=request.headers.get('authorization','')workspace=(authorization[7:] if native and authorization.startswith('Bearer ') else '') or request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')if not public and not WORKSPACE.fullmatch(workspace):error={'error':{'code':'UNAUTHORIZED','message':'请提供 Home Pulse 空间令牌','retryable':False},'requestId':secrets.token_hex(16),'serverTime':__import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat(),'apiVersion':'1.1.0'} if native else {'error':'请刷新页面,重新连接你的空间'}return JSONResponse(error,status_code=401)if request.method=='POST' and APP_VISUAL.fullmatch('/api/'+path):chunks=[];size=0async for chunk in request.stream():size+=len(chunk)if size>6*1024*1024:return JSONResponse({'error':{'code':'BODY_TOO_LARGE','message':'单次请求不能超过 6 MB','retryable':False}},status_code=413)chunks.append(chunk)try:result=await asyncio.to_thread(run_visual,'/api/'+path,b''.join(chunks).decode('utf-8'),workspace,dict(request.headers))return JSONResponse(result['body'],status_code=result['status'])except Exception:return JSONResponse({'error':{'code':'VISUAL_GATEWAY_UNAVAILABLE','message':'视觉服务暂时未返回结果,请稍后重试','retryable':True}},status_code=503)if request.method=='POST' and VISUAL.fullmatch('/api/'+path):return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host','idempotency-key')}4 unmodified linesoutbound=client.build_request(request.method,target,headers=headers,content=request.stream())response=await client.send(outbound,stream=True)except Exception:await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)async def close(): await response.aclose();await client.aclose()kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))12 unmodified lines1314151617181925 unmodified lines45464748495051525354555629 unmodified lines86878889909192939495969731 unmodified lines1291301311321331341351361371381391401411421431441451461471484 unmodified lines15315415515615715815916016112 unmodified linesimport ioimport timeimport asynciofrom datetime import datetime, timezonefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport gradio as gr25 unmodified linesREMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev')app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)VISUAL_SLOT=threading.BoundedSemaphore(1)def native_error(code,message,status,retryable=False):return JSONResponse({'error':{'code':code,'message':message,'retryable':retryable},'requestId':secrets.token_hex(16),'serverTime':datetime.now(timezone.utc).isoformat(),'apiVersion':'1.1.0'},status_code=status)class ModelBridge(BaseHTTPRequestHandler):def do_POST(self):29 unmodified linesreturn run_visual(route,body,workspace,dict(request.headers) if request else {})def run_visual(route:str,body:str,workspace:str,request_headers:dict)->dict:if not VISUAL_SLOT.acquire(timeout=1):return {'status':429,'body':{'error':'视觉服务正在完成上一轮观察,请稍后重试。'}}try:return run_visual_in_slot(route,body,workspace,request_headers)finally:VISUAL_SLOT.release()def run_visual_in_slot(route:str,body:str,workspace:str,request_headers:dict)->dict:# The browser and native REST adapter share the visitor-quota protocol.token=request_headers.get('x-ip-token','')print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)31 unmodified linesauthorization=request.headers.get('authorization','')workspace=(authorization[7:] if native and authorization.startswith('Bearer ') else '') or request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')if not public and not WORKSPACE.fullmatch(workspace):if native:return native_error('UNAUTHORIZED','请提供 Home Pulse 空间令牌',401)return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401)if request.method=='POST' and APP_VISUAL.fullmatch('/api/'+path):chunks=[];size=0async for chunk in request.stream():size+=len(chunk)if size>6*1024*1024:return native_error('BODY_TOO_LARGE','单次请求不能超过 6 MB',413)chunks.append(chunk)try:result=await asyncio.to_thread(run_visual,'/api/'+path,b''.join(chunks).decode('utf-8'),workspace,dict(request.headers))if isinstance(result['body'].get('error'),str):return native_error('VISUAL_BUSY',result['body']['error'],result['status'],True)return JSONResponse(result['body'],status_code=result['status'])except Exception:return native_error('VISUAL_GATEWAY_UNAVAILABLE','视觉服务暂时未返回结果,请稍后重试',503,True)if request.method=='POST' and VISUAL.fullmatch('/api/'+path):return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host','idempotency-key')}4 unmodified linesoutbound=client.build_request(request.method,target,headers=headers,content=request.stream())response=await client.send(outbound,stream=True)except Exception:await client.aclose()if native:return native_error('GATEWAY_UNAVAILABLE','空间连接暂时中断,请重试',502,True)return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)async def close(): await response.aclose();await client.aclose()kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))
15688 unmodified lines15689156901569115692156931569424 unmodified lines157191572015721157221572315724157251572615727157281572915688 unmodified linesres.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: error48 }));};const limited = (key, max) => {const now = Date.now(), old = rates.get(key), row = old && now - old.start < 36e5 ? old : { start: now, count: 0 };row.count++;24 unmodified linesreq.headers["x-home-pulse-workspace"] = token;if (!url2.pathname.startsWith("/api/")) return send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728");if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan", "/api/v1/setups/draft", "/api/v1/setups/prepare"].includes(url2.pathname)) {if (limited(token, plannerLimit) || limited("all", totalPlannerLimit)) return send(res, 429, "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002");}let entry = workspaces.get(token);if (!entry) {if (workspaces.size >= 2e3) return send(res, 503, "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");let middleware;const root = path6.join(dataDir, "workspaces", token);localApiPlugin(root, { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware = m } });15688 unmodified lines156891569015691156921569315694156951569615697156981569924 unmodified lines157241572515726157271572815729157301573115732157331573415688 unmodified linesres.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: error48 }));};const sendApp = (res, status, code, message) => {const result = appError(new AppError(status, code, message));res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result.body));};const limited = (key, max) => {const now = Date.now(), old = rates.get(key), row = old && now - old.start < 36e5 ? old : { start: now, count: 0 };row.count++;24 unmodified linesreq.headers["x-home-pulse-workspace"] = token;if (!url2.pathname.startsWith("/api/")) return send(res, 404, "\u63A5\u53E3\u4E0D\u5B58\u5728");if (req.method === "POST" && ["/api/setup/draft", "/api/setup/prepare", "/api/plan", "/api/v1/setups/draft", "/api/v1/setups/prepare"].includes(url2.pathname)) {if (limited(token, plannerLimit) || limited("all", totalPlannerLimit)) return native ? sendApp(res, 429, "PLANNER_RATE_LIMITED", "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002") : send(res, 429, "\u672C\u5C0F\u65F6\u7684\u4EFB\u52A1\u8BBE\u7F6E\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002\u5DF2\u6709\u4EFB\u52A1\u4ECD\u53EF\u89C2\u5BDF\u3002");}let entry = workspaces.get(token);if (!entry) {if (workspaces.size >= 2e3) return native ? sendApp(res, 503, "WORKSPACE_LIMIT", "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5") : send(res, 503, "\u5F53\u524D\u4F53\u9A8C\u4EBA\u6570\u8F83\u591A\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");let middleware;const root = path6.join(dataDir, "workspaces", token);localApiPlugin(root, { appScoped: true }).configureServer({ middlewares: { use: (m) => middleware = m } });
app.py+21-5
web/server-bundle.mjs+7-2