Add Home Pulse App API and verified device-command workflow
Browse files- app.py +28 -6
- integration/openapi.json +0 -0
- web/server-bundle.mjs +0 -0
app.py
CHANGED
|
@@ -12,6 +12,7 @@ import threading
|
|
| 12 |
import base64
|
| 13 |
import io
|
| 14 |
import time
|
|
|
|
| 15 |
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 16 |
|
| 17 |
import gradio as gr
|
|
@@ -29,6 +30,7 @@ NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','8791'))
|
|
| 29 |
PORT=int(os.getenv('PORT','7860'))
|
| 30 |
WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
|
| 31 |
VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
|
|
|
|
| 32 |
os.environ.setdefault('TOKENIZERS_PARALLELISM','false')
|
| 33 |
os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
|
| 34 |
os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
|
|
@@ -74,8 +76,11 @@ def visual(route:str,body:str,workspace:str,request:gr.Request)->dict:
|
|
| 74 |
if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace):
|
| 75 |
return {'status':400,'body':{'error':'观察请求无效'}}
|
| 76 |
if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}}
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
| 79 |
print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)
|
| 80 |
remote=Client(REMOTE_SPACE,headers={'x-ip-token':token} if token else {},verbose=False)
|
| 81 |
class VisitorBridge(ModelBridge):
|
|
@@ -86,7 +91,8 @@ def visual(route:str,body:str,workspace:str,request:gr.Request)->dict:
|
|
| 86 |
with httpx.Client(trust_env=False,timeout=210) as client:
|
| 87 |
response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={
|
| 88 |
'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY,
|
| 89 |
-
'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port)
|
|
|
|
| 90 |
return {'status':response.status_code,'body':response.json()}
|
| 91 |
finally:
|
| 92 |
bridge.shutdown();bridge.server_close()
|
|
@@ -105,11 +111,27 @@ model_health=(0,False)
|
|
| 105 |
|
| 106 |
@app.api_route('/api/{path:path}',methods=['GET','POST'])
|
| 107 |
async def api_proxy(path:str,request:Request):
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
if request.method=='POST' and VISUAL.fullmatch('/api/'+path):
|
| 111 |
return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)
|
| 112 |
-
headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host')}
|
| 113 |
headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace})
|
| 114 |
client=httpx.AsyncClient(trust_env=False,timeout=220)
|
| 115 |
try:
|
|
|
|
| 12 |
import base64
|
| 13 |
import io
|
| 14 |
import time
|
| 15 |
+
import asyncio
|
| 16 |
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 17 |
|
| 18 |
import gradio as gr
|
|
|
|
| 30 |
PORT=int(os.getenv('PORT','7860'))
|
| 31 |
WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
|
| 32 |
VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
|
| 33 |
+
APP_VISUAL=re.compile(r'^/api/v1/(?:setups/[a-zA-Z0-9_-]+/trial|watches/[a-zA-Z0-9_-]+/observe)$')
|
| 34 |
os.environ.setdefault('TOKENIZERS_PARALLELISM','false')
|
| 35 |
os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
|
| 36 |
os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
|
|
|
|
| 76 |
if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace):
|
| 77 |
return {'status':400,'body':{'error':'观察请求无效'}}
|
| 78 |
if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}}
|
| 79 |
+
return run_visual(route,body,workspace,dict(request.headers) if request else {})
|
| 80 |
+
|
| 81 |
+
def run_visual(route:str,body:str,workspace:str,request_headers:dict)->dict:
|
| 82 |
+
# The browser and native REST adapter share the visitor-quota protocol.
|
| 83 |
+
token=request_headers.get('x-ip-token','')
|
| 84 |
print('Visual gateway: visitor quota forwarded =',bool(token),flush=True)
|
| 85 |
remote=Client(REMOTE_SPACE,headers={'x-ip-token':token} if token else {},verbose=False)
|
| 86 |
class VisitorBridge(ModelBridge):
|
|
|
|
| 91 |
with httpx.Client(trust_env=False,timeout=210) as client:
|
| 92 |
response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={
|
| 93 |
'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY,
|
| 94 |
+
'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port),
|
| 95 |
+
'Idempotency-Key':request_headers.get('idempotency-key','')})
|
| 96 |
return {'status':response.status_code,'body':response.json()}
|
| 97 |
finally:
|
| 98 |
bridge.shutdown();bridge.server_close()
|
|
|
|
| 111 |
|
| 112 |
@app.api_route('/api/{path:path}',methods=['GET','POST'])
|
| 113 |
async def api_proxy(path:str,request:Request):
|
| 114 |
+
native=path.startswith('v1/')
|
| 115 |
+
public=(request.method=='POST' and path=='v1/sessions') or (request.method=='GET' and path=='v1/openapi.json')
|
| 116 |
+
authorization=request.headers.get('authorization','')
|
| 117 |
+
workspace=(authorization[7:] if native and authorization.startswith('Bearer ') else '') or request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')
|
| 118 |
+
if not public and not WORKSPACE.fullmatch(workspace):
|
| 119 |
+
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':'请刷新页面,重新连接你的空间'}
|
| 120 |
+
return JSONResponse(error,status_code=401)
|
| 121 |
+
if request.method=='POST' and APP_VISUAL.fullmatch('/api/'+path):
|
| 122 |
+
chunks=[];size=0
|
| 123 |
+
async for chunk in request.stream():
|
| 124 |
+
size+=len(chunk)
|
| 125 |
+
if size>6*1024*1024:return JSONResponse({'error':{'code':'BODY_TOO_LARGE','message':'单次请求不能超过 6 MB','retryable':False}},status_code=413)
|
| 126 |
+
chunks.append(chunk)
|
| 127 |
+
try:
|
| 128 |
+
result=await asyncio.to_thread(run_visual,'/api/'+path,b''.join(chunks).decode('utf-8'),workspace,dict(request.headers))
|
| 129 |
+
return JSONResponse(result['body'],status_code=result['status'])
|
| 130 |
+
except Exception:
|
| 131 |
+
return JSONResponse({'error':{'code':'VISUAL_GATEWAY_UNAVAILABLE','message':'视觉服务暂时未返回结果,请稍后重试','retryable':True}},status_code=503)
|
| 132 |
if request.method=='POST' and VISUAL.fullmatch('/api/'+path):
|
| 133 |
return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)
|
| 134 |
+
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')}
|
| 135 |
headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace})
|
| 136 |
client=httpx.AsyncClient(trust_env=False,timeout=220)
|
| 137 |
try:
|
integration/openapi.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
web/server-bundle.mjs
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|