Update
Browse files3 unmodified lines4567891019 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931946 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293306 unmodified lines3373383393403413423433443453463474 unmodified lines3523533543553563573583593603613623633643653663673683693 unmodified linesimport gradio as grimport uvicornfrom fastapi.middleware.cors import CORSMiddleware# Import our existing componentsfrom inference_server.main import app as fastapi_app19 unmodified linesdef run_server():global server_startedfrom inference_server.main import apptry:uvicorn.run(app, host="localhost", port=port, log_level="warning")except Exception as e:logger.exception(f"API server error: {e}")finally:server_started = Falseserver_thread = threading.Thread(target=run_server, daemon=True)server_thread.start()# Wait a moment for server to starttime.sleep(2)server_started = Trueclass SimpleServerManager:"""Direct access to session manager without HTTP calls."""def __init__(self):self.session_manager = session_managerasync def create_and_start_session(self,session_id: str,policy_path: str,camera_names: str,arena_server_url: str,) -> str:"""Create and start a session directly."""try:cameras = [name.strip() for name in camera_names.split(",") if name.strip()]if not cameras:cameras = ["front"]# Create session directlyroom_info = await self.session_manager.create_session(session_id=session_id,policy_path=policy_path,camera_names=cameras,arena_server_url=arena_server_url,)# Start the sessionawait self.session_manager.start_inference(session_id)# Format camera rooms more clearlycamera_info = []for camera_name, room_id in room_info["camera_room_ids"].items():camera_info.append(f" ๐น **{camera_name.title()}**: `{room_id}`")return f"""## โ Session Created Successfully!**Session ID**: `{session_id}`**Status**: ๐ข **RUNNING** (inference active)### ๐ก Arena Connection Details:**Workspace ID**: `{room_info["workspace_id"]}`**Camera Rooms**:{chr(10).join(camera_info)}**Joint Communication**:๐ฅ **Input**: `{room_info["joint_input_room_id"]}`๐ค **Output**: `{room_info["joint_output_room_id"]}`---## ๐ค Ready for Robot Control!Your robot can now connect to these rooms to start AI-powered control."""except Exception as e:return f"โ Error: {e!s}"async def control_session(self, session_id: str, action: str) -> str:"""Control a session directly."""if not session_id.strip():return "โ ๏ธ No session ID provided"try:# Check current statusif session_id not in self.session_manager.sessions:return f"โ Session '{session_id}' not found"session = self.session_manager.sessions[session_id]current_status = session.status# Smart action handlingif action == "start" and current_status == "running":return f"โน๏ธ Session '{session_id}' is already running"if action == "stop" and current_status in {"stopped", "ready"}:return f"โน๏ธ Session '{session_id}' is already stopped"# Perform actionif action == "start":await self.session_manager.start_inference(session_id)return f"โ Inference started for session {session_id}"if action == "stop":await self.session_manager.stop_inference(session_id)return f"โ Inference stopped for session {session_id}"if action == "restart":await self.session_manager.restart_inference(session_id)return f"โ Inference restarted for session {session_id}"return f"โ Unknown action: {action}"except Exception as e:return f"โ Error: {e!s}"async def get_session_status(self, session_id: str) -> str:"""Get session status directly."""if not session_id.strip():return "โ ๏ธ No session ID provided"try:if session_id not in self.session_manager.sessions:return f"โ Session '{session_id}' not found"session_data = await self.session_manager.get_session_status(session_id)session = session_datastatus_emoji = {"running": "๐ข","ready": "๐ก","stopped": "๐ด","initializing": "๐ ",}.get(session["status"], "โช")# Smart suggestionssuggestions = ""if session["status"] == "running":suggestions = "\n\n### ๐ก Smart Suggestion:\n**Session is active!** Use the 'โธ๏ธ Stop' button to pause inference."elif session["status"] in {"ready", "stopped"}:suggestions = "\n\n### ๐ก Smart Suggestion:\n**Session is ready!** Use the 'โถ๏ธ Start' button to begin inference."# Format camera names nicelycamera_list = [f"**{cam.title()}**" for cam in session["camera_names"]]return f"""## {status_emoji} Session Status**Session ID**: `{session_id}`**Status**: {status_emoji} **{session["status"].upper()}****Model**: `{session["policy_path"]}`**Cameras**: {", ".join(camera_list)}### ๐ Performance Metrics:| Metric | Value ||--------|-------|| ๐ง **Inferences** | {session["stats"]["inference_count"]} || ๐ค **Commands Sent** | {session["stats"]["commands_sent"]} || ๐ **Queue Length** | {session["stats"]["actions_in_queue"]} actions || โ **Errors** | {session["stats"]["errors"]} |### ๐ง Data Flow:- ๐น **Images Received**: {session["stats"]["images_received"]}- ๐ค **Joint States Received**: {session["stats"]["joints_received"]}{suggestions}"""except Exception as e:return f"โ Error: {e!s}"def create_simple_gradio_interface() -> gr.Blocks:6 unmodified linescss=".gradio-container { max-width: 1200px !important; }",fill_height=True,) as demo:gr.Markdown("""# ๐ค Robot AI Control Center**Control your robot with AI using ACT models***Integrated mode - FastAPI available at `/api/docs` for direct API access*""")# Server statuswith gr.Group():gr.Markdown("## ๐ก API Status")gr.Markdown(value="""โ **FastAPI Server**: Available at `/api`๐ **API Documentation**: Available at `/api/docs`๐ **Health Check**: Available at `/api/health`""",show_copy_button=True,)# Setupwith gr.Group():gr.Markdown("## ๐ค Set Up Robot AI")with gr.Row():with gr.Column():session_id_input = gr.Textbox(label="Session Name", value="my-robot-01")policy_path_input = gr.Textbox(label="AI Model Path", value="./checkpoints/act_so101_beyond")camera_names_input = gr.Textbox(label="Camera Names", value="front")arena_server_url_input = gr.Textbox(label="Arena Server URL",value=DEFAULT_ARENA_SERVER_URL,placeholder="http://localhost:8000",)create_btn = gr.Button("๐ฏ Create & Start AI Control", variant="primary")with gr.Column():setup_result = gr.Markdown(value="Ready to create your robot AI session...",show_copy_button=True,container=True,height=300,)# Controlwith gr.Group():gr.Markdown("## ๐ฎ Control Session")with gr.Row():current_session_input = gr.Textbox(label="Session ID")start_btn = gr.Button("โถ๏ธ Start", variant="primary")stop_btn = gr.Button("โธ๏ธ Stop", variant="secondary")status_btn = gr.Button("๐ Status", variant="secondary")session_status_display = gr.Markdown(value="Click '๐ Status' to check session information...",show_copy_button=True,container=True,height=400,)# Event handlersasync def create_session(session_id, policy_path, camera_names, arena_server_url):result = await server_manager.create_and_start_session(session_id, policy_path, camera_names, arena_server_url)return result, session_idasync def start_session(session_id):return await server_manager.control_session(session_id, "start")async def stop_session(session_id):return await server_manager.control_session(session_id, "stop")async def get_status(session_id):return await server_manager.get_session_status(session_id)# Connect eventscreate_btn.click(create_session,inputs=[session_id_input,policy_path_input,camera_names_input,arena_server_url_input,],outputs=[setup_result, current_session_input],)start_btn.click(start_session,inputs=[current_session_input],outputs=[session_status_display],)stop_btn.click(stop_session,inputs=[current_session_input],outputs=[session_status_display],)status_btn.click(get_status, inputs=[current_session_input], outputs=[session_status_display])gr.Markdown("""### ๐ก Tips:- ๐ข **RUNNING**: Session actively doing inference- ๐ก **READY**: Session created but not started- ๐ด **STOPPED**: Session paused### ๐ API Access:- **FastAPI Docs**: Visit `/api/docs` for interactive API documentation- **Direct API**: Use `/api/sessions` endpoints for programmatic access- **Health Check**: `/api/health` shows server status- **OpenAPI Schema**: Available at `/api/openapi.json`""")return demodef launch_simple_integrated_app(6 unmodified linesprint(f"๐ Health Check: http://{host}:{port}/api/health")print("๐ง Direct session management + API access!")# Create Gradio demodemo = create_simple_gradio_interface()# Create custom FastAPI app from the Gradio demo's built-in appapp = demo.app# Add CORS middlewareapp.add_middleware(4 unmodified linesallow_headers=["*"],)# Mount the FastAPI AI server under /apiapp.mount("/api", fastapi_app)# Launch using Gradio's queue and launch methodsdemo.queue()demo.launch(server_name=host,server_port=port,share=share,show_error=True,show_api=False, # Hide Gradio's default API docs since we have our ownprevent_thread_lock=False,)3 unmodified lines45678910111219 unmodified lines32333435363738394041424344454647484950515253546 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292306 unmodified lines2372382392402412422432442452462472482492502514 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772783 unmodified linesimport gradio as grimport uvicornfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import RedirectResponse# Import our existing componentsfrom inference_server.main import app as fastapi_app19 unmodified linesdef run_server():global server_startedtry:# Import here to avoid circular importsfrom inference_server.main import applogger.info(f"Starting AI server on port {port}")uvicorn.run(app, host="0.0.0.0", port=port, log_level="warning")except Exception as e:logger.exception(f"Failed to start AI server: {e}")finally:server_started = Falseserver_thread = threading.Thread(target=run_server, daemon=True)server_thread.start()server_started = True# Wait a moment for server to starttime.sleep(2)def create_simple_gradio_interface() -> gr.Blocks:6 unmodified linescss=".gradio-container { max-width: 1200px !important; }",fill_height=True,) as demo:gr.Markdown("# ๐ค Robot AI Control Center")gr.Markdown("*Real-time ACT Model Inference for Robot Control*")with gr.Row():with gr.Column(scale=2):gr.Markdown("## ๐ Set Up Robot AI")with gr.Group():session_name = gr.Textbox(label="Session Name",placeholder="my-robot-01",value="default-session",)model_path = gr.Textbox(label="AI Model Path",placeholder="./checkpoints/act_so101_beyond",value="./checkpoints/act_so101_beyond",)camera_names = gr.Textbox(label="Camera Names (comma-separated)",placeholder="front,wrist,overhead",value="front,wrist",)create_btn = gr.Button("๐ฏ Create & Start AI Control", variant="primary")with gr.Column(scale=1):gr.Markdown("## ๐ Control Session")session_id_input = gr.Textbox(label="Session ID",placeholder="Will be auto-filled",interactive=False,)with gr.Row():start_btn = gr.Button("โถ๏ธ Start", variant="secondary")stop_btn = gr.Button("โน๏ธ Stop", variant="secondary")status_btn = gr.Button("๐ Status", variant="secondary")with gr.Row():output_display = gr.Markdown("### Ready to create AI session...")# Event handlerscreate_btn.click(fn=server_manager.create_and_start_session,inputs=[session_name, model_path, camera_names],outputs=[session_id_input, output_display],)start_btn.click(fn=server_manager.start_session,inputs=[session_id_input],outputs=[output_display],)stop_btn.click(fn=server_manager.stop_session,inputs=[session_id_input],outputs=[output_display],)status_btn.click(fn=server_manager.get_session_status,inputs=[session_id_input],outputs=[output_display],)return democlass SimpleServerManager:"""Direct session management without HTTP API calls."""def create_and_start_session(self, name: str, model_path: str, camera_names: str):"""Create and start a new session directly."""try:# Parse camera namescameras = [c.strip() for c in camera_names.split(",") if c.strip()]# Create session directly using session_managersession_data = {"name": name,"model_path": model_path,"arena_server_url": DEFAULT_ARENA_SERVER_URL,"workspace_id": "default_workspace","room_id": f"room_{name}","camera_names": cameras,}session_id = session_manager.create_session(session_data)session_manager.start_session(session_id)success_msg = f"""### โ Success!**Session ID:** `{session_id}`**Status:** Running**Model:** {model_path}**Cameras:** {", ".join(cameras)}๐ AI control is now active!"""return session_id, success_msgexcept Exception as e:error_msg = f"""### โ ErrorFailed to create session: {e!s}Please check your model path and try again."""return "", error_msgdef start_session(self, session_id: str):"""Start an existing session."""if not session_id:return "โ ๏ธ Please provide a session ID"try:session_manager.start_session(session_id)return f"โ Session `{session_id}` started successfully!"except Exception as e:return f"โ Failed to start session: {e!s}"def stop_session(self, session_id: str):"""Stop an existing session."""if not session_id:return "โ ๏ธ Please provide a session ID"try:session_manager.stop_session(session_id)return f"โน๏ธ Session `{session_id}` stopped successfully!"except Exception as e:return f"โ Failed to stop session: {e!s}"def get_session_status(self, session_id: str):"""Get detailed session status."""if not session_id:return "โ ๏ธ Please provide a session ID"try:status = session_manager.get_session_status(session_id)if not status:return f"โ Session `{session_id}` not found"status_msg = f"""### ๐ Session Status: `{session_id}`**State:** {status.get("state", "Unknown")}**Model:** {status.get("model_path", "N/A")}**Inferences:** {status.get("total_inferences", 0)}**Commands Sent:** {status.get("commands_sent", 0)}**Errors:** {status.get("errors", 0)}**Performance:**- Queue Length: {status.get("queue_length", 0)}- Last Update: {status.get("last_update", "Never")}"""return status_msgexcept Exception as e:return f"โ Failed to get status: {e!s}"def launch_simple_integrated_app(6 unmodified linesprint(f"๐ Health Check: http://{host}:{port}/api/health")print("๐ง Direct session management + API access!")# Create Gradio demo firstdemo = create_simple_gradio_interface()# Create main FastAPI appapp = FastAPI(title="๐ค Robot AI Control Center",description="Integrated ACT Model Inference Server with Web Interface",version="1.0.0",)# Add CORS middlewareapp.add_middleware(4 unmodified linesallow_headers=["*"],)# Mount the FastAPI AI server under /api FIRSTapp.mount("/api", fastapi_app)# Mount Gradio at a subpath to avoid the root redirect issueapp = gr.mount_gradio_app(app, demo, path="/gradio")# Add custom root endpoint that redirects to /gradio/ (with trailing slash)@app.get("/")async def root():return RedirectResponse(url="/gradio/", status_code=302)# Launch with uvicornuvicorn.run(app,host=host,port=port,log_level="info",)
src/inference_server/simple_integrated.py+174-265