File size: 15,740 Bytes
3380376
63ed3a7
3380376
63ed3a7
 
 
 
 
1120045
63ed3a7
1120045
63ed3a7
 
 
 
 
 
 
 
 
3380376
 
 
63ed3a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3380376
6e558c0
3380376
63ed3a7
 
 
1120045
63ed3a7
 
 
 
 
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63ed3a7
 
3380376
63ed3a7
3380376
63ed3a7
3380376
1120045
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120045
3380376
 
 
 
 
 
 
 
 
 
 
1120045
 
3380376
 
63ed3a7
3380376
1120045
 
3380376
 
63ed3a7
3380376
1120045
 
3380376
 
63ed3a7
 
3380376
 
 
 
 
63ed3a7
3380376
 
 
 
 
 
 
 
 
 
 
 
 
63ed3a7
3380376
 
 
63ed3a7
3380376
 
 
 
 
 
 
 
 
 
1120045
3380376
63ed3a7
3380376
 
 
 
 
 
63ed3a7
1120045
3380376
 
 
 
 
63ed3a7
1120045
3380376
 
63ed3a7
 
 
1120045
 
3380376
63ed3a7
1120045
63ed3a7
1120045
 
3380376
63ed3a7
1120045
63ed3a7
1120045
 
3380376
63ed3a7
 
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120045
63ed3a7
 
3380376
 
1120045
3380376
 
1120045
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120045
 
3380376
 
1120045
 
3380376
 
 
 
 
 
 
 
 
 
 
1120045
3380376
 
 
 
1120045
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120045
 
 
3380376
 
1120045
 
 
3380376
 
 
1120045
 
3380376
 
 
1120045
 
3380376
 
1120045
 
 
3380376
 
 
1120045
 
3380376
 
 
1120045
 
3380376
 
1120045
 
 
3380376
 
 
1120045
 
3380376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1120045
 
 
 
3380376
 
 
63ed3a7
 
 
6e558c0
3380376
 
 
63ed3a7
3380376
 
63ed3a7
 
 
3380376
 
63ed3a7
3380376
 
f1df768
1120045
 
3380376
 
1120045
 
63ed3a7
f1df768
 
 
 
 
 
 
 
 
3380376
f1df768
 
3380376
1120045
 
3380376
1120045
f9fa7dd
1120045
 
 
 
 
 
 
 
63ed3a7
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import asyncio
import logging
import os
import threading
import time

import gradio as gr
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse

# Import our existing components
from inference_server.main import app as fastapi_app
from inference_server.main import session_manager

logger = logging.getLogger(__name__)

# Configuration
DEFAULT_PORT = 7860
DEFAULT_TRANSPORT_SERVER_URL = os.getenv(
    "TRANSPORT_SERVER_URL", "http://localhost:8000"
)

# Global server thread
server_thread = None
server_started = False


def start_api_server_thread(port: int = 8001):
    """Start the API server in a background thread."""
    global server_thread, server_started

    if server_thread and server_thread.is_alive():
        return

    def run_server():
        global server_started
        logger.info(f"Starting AI server on port {port}")
        uvicorn.run(fastapi_app, host="0.0.0.0", port=port, log_level="warning")
        server_started = False

    server_thread = threading.Thread(target=run_server, daemon=True)
    server_thread.start()
    server_started = True

    # Wait a moment for server to start
    time.sleep(2)


def create_gradio(
    transport_server_url: str = DEFAULT_TRANSPORT_SERVER_URL,
) -> gr.Blocks:
    """Create an enhanced Gradio interface with step-by-step workflow."""
    server_manager = ServerManagement()

    custom_css = """
    .gradio-container {
        max-width: 1200px !important;
        margin: 0 auto !important;
        padding: 20px !important;
    }

    .main-header {
        text-align: center;
        margin-bottom: 30px;
        padding: 20px;
        border-radius: 10px;
    }

    .main-header h1 {
        margin: 0;
        font-size: 2.5em;
        font-weight: bold;
    }

    .main-header p {
        margin: 10px 0 0 0;
        font-size: 1.1em;
        opacity: 0.8;
    }

    .status-display {
        font-family: monospace;
        font-size: 0.9em;
    }
    """

    with gr.Blocks(
        title="๐Ÿค– RobotHub AI Control Center",
        theme=gr.themes.Soft(),
        css=custom_css,
    ) as demo:
        # Main header
        with gr.Row():
            with gr.Column():
                gr.HTML("""
                <div class="main-header">
                    <h1>๐Ÿค– RobotHub AI Control Center</h1>
                    <p>Control your robot with AI using ACT (Action Chunking Transformer) models</p>
                </div>
                """)

        # Step 1: Server Status
        with gr.Group():
            gr.Markdown("## ๐Ÿ“ก Step 1: AI Server Status")

            with gr.Row():
                with gr.Column(scale=3):
                    server_status_display = gr.Textbox(
                        label="Server Status",
                        value="โœ… Integrated server ready",
                        interactive=False,
                        lines=2,
                        elem_classes="status-display",
                    )

                with gr.Column(scale=1, min_width=200):
                    check_status_btn = gr.Button(
                        "๐Ÿ” Check Status", variant="secondary", size="lg"
                    )

        # Step 2: Robot Setup
        with gr.Group():
            gr.Markdown("## ๐Ÿค– Step 2: Set Up Robot AI")

            with gr.Row():
                with gr.Column(scale=2):
                    session_name = gr.Textbox(
                        label="Session Name",
                        placeholder="my-robot-session",
                        value="my-robot-01",
                    )

                    model_path = gr.Textbox(
                        label="AI Model Path",
                        placeholder="LaetusH/act_so101_beyond",
                        value="LaetusH/act_so101_beyond",
                    )

                    camera_names = gr.Textbox(
                        label="Camera Names (comma-separated)",
                        placeholder="front, wrist, overhead",
                        value="front",
                    )

                    transport_server_url = gr.Textbox(
                        label="Transport Server URL",
                        placeholder="http://localhost:8000",
                        value=transport_server_url,
                    )

                    with gr.Row():
                        create_btn = gr.Button(
                            "๐ŸŽฏ Create & Start AI Control", variant="primary", size="lg"
                        )

                with gr.Column(scale=2):
                    setup_result = gr.Textbox(
                        label="Setup Result",
                        lines=12,
                        interactive=False,
                        placeholder="Click 'Create & Start AI Control' to begin...",
                        elem_classes="status-display",
                    )

        # Step 3: Control Session
        with gr.Group():
            gr.Markdown("## ๐ŸŽฎ Step 3: Control Session")

            with gr.Row():
                with gr.Column(scale=2):
                    session_id_input = gr.Textbox(
                        label="Session ID",
                        placeholder="Will be auto-filled",
                        interactive=True,
                    )

                with gr.Column(scale=2), gr.Row():
                    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.Textbox(
                label="Session Status",
                lines=10,
                interactive=False,
                elem_classes="status-display",
            )

        # Event handlers
        check_status_btn.click(
            fn=server_manager.check_server_status,
            outputs=[server_status_display],
        )

        create_btn.click(
            fn=server_manager.create_and_start_session,
            inputs=[session_name, model_path, camera_names, transport_server_url],
            outputs=[session_id_input, setup_result],
        )

        start_btn.click(
            fn=server_manager.start_session,
            inputs=[session_id_input],
            outputs=[session_status_display],
        )

        stop_btn.click(
            fn=server_manager.stop_session,
            inputs=[session_id_input],
            outputs=[session_status_display],
        )

        status_btn.click(
            fn=server_manager.get_session_status,
            inputs=[session_id_input],
            outputs=[session_status_display],
        )

        # Auto-refresh on load
        demo.load(server_manager.check_server_status, outputs=[server_status_display])

        # Add helpful instructions
        with gr.Group():
            gr.Markdown("""
            ---
            ### ๐Ÿ“– Quick Guide:
            1. **Server Status**: The integrated server is ready by default
            2. **Configure Your Robot**: Enter your model path and camera setup (Step 2)
            3. **Create Session**: Click "Create & Start AI Control" to begin
            4. **Monitor & Control**: Use Step 3 to start/stop and monitor your session

            ๐Ÿ’ก **Tips**:
            - Make sure your ACT model path exists before creating a session
            - Camera names should match your robot's camera configuration
            - Session will automatically start after creation
            - All components run in a single integrated process for simplicity
            """)

    return demo


class ServerManagement:
    """Enhanced session management with better error handling and status display."""

    def check_server_status(self):
        """Check the status of the integrated server."""
        try:
            # Since we're running integrated, we can check session_manager directly
            if hasattr(session_manager, "sessions"):
                active_count = len([
                    s
                    for s in session_manager.sessions.values()
                    if s.status == "running"
                ])
                total_count = len(session_manager.sessions)
                return f"โœ… Integrated server running - {active_count}/{total_count} sessions active"
            return "โœ… Integrated server ready - No active sessions"
        except Exception as e:
            return f"โš ๏ธ Server check failed: {e!s}"

    def create_and_start_session(
        self, session_name: str, model_path: str, camera_names: str, transport_url: str
    ):
        """Create and start a new session with enhanced error handling."""
        try:
            # Input validation
            if not session_name.strip():
                return "", "โŒ Session name cannot be empty"

            if not model_path.strip():
                return "", "โŒ Model path cannot be empty"

            # Parse camera names
            cameras = [c.strip() for c in camera_names.split(",") if c.strip()]
            if not cameras:
                cameras = ["front"]

            # Create session directly using session_manager
            # Use asyncio.run to handle the async function

            try:
                room_info = asyncio.run(
                    session_manager.create_session(
                        session_id=session_name.strip(),
                        policy_path=model_path.strip(),
                        camera_names=cameras,
                        transport_server_url=transport_url.strip(),
                    )
                )

                # Start the session
                asyncio.run(session_manager.start_inference(session_name.strip()))

                success_msg = f"""โœ… Session '{session_name}' created and started!

๐Ÿ“ก Configuration:
โ€ข Model: {model_path}
โ€ข Cameras: {", ".join(cameras)}
โ€ข Transport: {transport_url}
โ€ข Workspace: {room_info["workspace_id"]}

๐Ÿ  Rooms Created:
โ€ข Camera rooms: {", ".join(f"{k}:{v}" for k, v in room_info["camera_room_ids"].items())}
โ€ข Joint input: {room_info["joint_input_room_id"]}
โ€ข Joint output: {room_info["joint_output_room_id"]}

๐Ÿค– Ready for robot control!"""

                return session_name.strip(), success_msg

            except Exception as e:
                error_msg = f"โŒ Error creating/starting session: {e!s}"
                logger.exception(error_msg)
                return "", error_msg

        except Exception as e:
            error_msg = f"โŒ Error creating session: {e!s}"
            logger.exception(error_msg)
            return "", error_msg

    def start_session(self, session_id: str):
        """Start an existing session with better error handling."""
        if not session_id.strip():
            return "โš ๏ธ Please provide a session ID"

        try:
            import asyncio

            asyncio.run(session_manager.start_inference(session_id.strip()))
            return f"โœ… Session `{session_id}` started successfully!"
        except Exception as e:
            error_msg = f"โŒ Failed to start session: {e!s}"
            logger.exception(error_msg)
            return error_msg

    def stop_session(self, session_id: str):
        """Stop an existing session with better error handling."""
        if not session_id.strip():
            return "โš ๏ธ Please provide a session ID"

        try:
            import asyncio

            asyncio.run(session_manager.stop_inference(session_id.strip()))
            return f"โน๏ธ Session `{session_id}` stopped successfully!"
        except Exception as e:
            error_msg = f"โŒ Failed to stop session: {e!s}"
            logger.exception(error_msg)
            return error_msg

    def get_session_status(self, session_id: str):
        """Get detailed session status with enhanced display."""
        if not session_id.strip():
            return "โš ๏ธ Please provide a session ID"

        try:
            # Access the session directly from session_manager.sessions
            session_id_clean = session_id.strip()
            if session_id_clean not in session_manager.sessions:
                return f"โŒ Session `{session_id}` not found"

            # Get session and call its get_status method
            session = session_manager.sessions[session_id_clean]
            status = session.get_status()

            # Enhanced status display with emojis
            status_emoji = {
                "running": "๐ŸŸข",
                "ready": "๐ŸŸก",
                "stopped": "๐Ÿ”ด",
                "initializing": "๐ŸŸ ",
                "error": "โŒ",
                "timeout": "โฐ",
            }.get(status.get("status", "unknown"), "โšช")

            status_msg = f"""{status_emoji} Session: `{session_id}`

**Status:** {status.get("status", "Unknown").upper()}
**Model:** {status.get("policy_path", "N/A")}
**Policy Type:** {status.get("policy_type", "N/A")}
**Cameras:** {", ".join(status.get("camera_names", []))}
**Workspace:** {status.get("workspace_id", "N/A")}

๐Ÿ“Š **Performance:**
โ€ข Inferences: {status.get("stats", {}).get("inference_count", 0)}
โ€ข Commands sent: {status.get("stats", {}).get("commands_sent", 0)}
โ€ข Queue length: {status.get("stats", {}).get("actions_in_queue", 0)}
โ€ข Errors: {status.get("stats", {}).get("errors", 0)}

๐Ÿ”ง **Data Flow:**
โ€ข Images received: {status.get("stats", {}).get("images_received", {})}
โ€ข Joint states received: {status.get("stats", {}).get("joints_received", 0)}

๐Ÿ  **Rooms:**
โ€ข Camera rooms: {", ".join(f"{k}:{v}" for k, v in status.get("rooms", {}).get("camera_room_ids", {}).items())}
โ€ข Joint input: {status.get("rooms", {}).get("joint_input_room_id", "N/A")}
โ€ข Joint output: {status.get("rooms", {}).get("joint_output_room_id", "N/A")}"""

            return status_msg

        except Exception as e:
            error_msg = f"โŒ Error getting status: {e!s}"
            logger.exception(error_msg)
            return error_msg


def launch_simple_integrated_app(
    host: str = "0.0.0.0",
    port: int = DEFAULT_PORT,
    share: bool = False,
    transport_server_url: str = DEFAULT_TRANSPORT_SERVER_URL,
):
    """Launch the enhanced integrated application with both FastAPI and Gradio."""
    print(f"๐Ÿš€ Starting enhanced integrated app on {host}:{port}")
    print(f"๐ŸŽจ Gradio UI: http://{host}:{port}/")
    print(f"๐Ÿ“– FastAPI Docs: http://{host}:{port}/api/docs")
    print(f"๐Ÿ”„ Health Check: http://{host}:{port}/api/health")
    print(f"๐ŸšŒ Transport Server: {transport_server_url}")
    print("๐Ÿ”ง Enhanced direct session management + API access!")

    # Create enhanced Gradio demo
    demo = create_gradio(transport_server_url=transport_server_url)

    # Create main FastAPI app
    app = FastAPI(
        title="๐Ÿค– RobotHub AI Control Center",
        description="Enhanced Integrated ACT Model Inference Server with Web Interface",
        version="1.0.0",
    )

    # Add CORS middleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Mount the FastAPI AI server under /api
    app.mount("/api", fastapi_app)

    # Mount Gradio at a subpath
    app = gr.mount_gradio_app(app, demo, path="/gradio")

    # Add custom root endpoint that redirects to /gradio/
    @app.get("/")
    def root_redirect():
        return RedirectResponse(url="/gradio/", status_code=302)

    # Launch with uvicorn
    uvicorn.run(
        app,
        host=host,
        port=port,
        log_level="info",
    )


if __name__ == "__main__":
    launch_simple_integrated_app()