# Web Interface and Dashboard

Casino of Life provides a powerful web interface for monitoring, controlling, and visualizing your AI training processes. This guide explains how to set up and use the web dashboard effectively.

### Getting Started with the Web Interface

The web interface allows you to monitor training progress, manage multiple agents, and control training parameters through an intuitive dashboard.

#### Starting the Training Server

To use the web interface, you need to start the training server:

```python
from casino_of_life.web import TrainingServer

# Start training server on default port (8080)
server = TrainingServer()
server.start()

# Or specify a custom port
server = TrainingServer(port=9000)
server.start()
```

Once started, you can access the dashboard at `http://localhost:8080` (or your custom port).

### Dashboard Features

#### Training Monitoring

The dashboard provides real-time monitoring of your training sessions:

* **Performance Metrics**: Win rate, average rewards, episode length
* **Learning Graphs**: Visualize reward trends, action distributions, and more
* **State Visualization**: See what the agent sees during training
* **Memory Usage**: Monitor resource utilization

#### Agent Management

Manage multiple agents from a single interface:

* **Create New Agents**: Configure and launch new training sessions
* **Load Saved Agents**: Resume training from checkpoints
* **Compare Agents**: Run A/B testing between different models
* **Export Models**: Save trained agents for deployment

#### Interactive Chat Interface

Communicate with CaballoLoko directly from the web interface:

* **Natural Language Commands**: Send training instructions
* **Training Feedback**: Get real-time updates on training progress
* **Strategy Adjustment**: Modify training parameters on the fly
* **Chat History**: Review previous instructions and responses

### API Integration

The web interface exposes a RESTful API for programmatic control:

#### Starting a Training Session

```python
import requests
import json

# Start a new training session
response = requests.post(
    "http://localhost:8080/api/training/start",
    json={
        "game": "MortalKombatII-Genesis",
        "character": "LiuKang",
        "policy": "PPO",
        "timesteps": 100000
    }
)

training_id = response.json()["training_id"]
```

#### Checking Training Status

```python
# Get training status
status = requests.get(
    f"http://localhost:8080/api/training/{training_id}/status"
).json()

print(f"Training progress: {status['progress']}%")
print(f"Current win rate: {status['metrics']['win_rate']}%")
```

#### WebSocket for Real-time Updates

For real-time updates, you can connect to the WebSocket endpoint:

```python
import asyncio
import websockets
import json

async def monitor_training(training_id):
    uri = f"ws://localhost:8080/api/training/{training_id}/live"
    
    async with websockets.connect(uri) as websocket:
        while True:
            message = await websocket.recv()
            data = json.loads(message)
            
            print(f"Step: {data['step']}")
            print(f"Reward: {data['reward']}")
            print(f"Action: {data['action']}")

# Run the monitoring function
asyncio.run(monitor_training(training_id))
```

### Customizing the Dashboard

The dashboard can be customized using configuration files:

```python
from casino_of_life.web import TrainingServer, DashboardConfig

# Create custom dashboard configuration
config = DashboardConfig(
    theme="dark",
    default_view="performance",
    refresh_rate=2,  # seconds
    custom_metrics=["combo_count", "special_move_frequency"]
)

# Start server with custom configuration
server = TrainingServer(dashboard_config=config)
server.start()
```

### Deployment Options

The web interface can be deployed in several ways:

#### Local Development

```bash
python -m casino_of_life.web.server
```

#### Docker Container

```bash
docker run -p 8080:8080 cimai/casino-of-life
```

#### Production Deployment

For production environments, we recommend using a reverse proxy:

```bash
# Example with nginx
server {
    listen 80;
    server_name casino.yourdomain.com;

    location / {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
    }
}
```

### Security Considerations

The web interface includes several security features:

* **Authentication**: Optional user authentication system
* **API Keys**: Secure API access using token-based authentication
* **Rate Limiting**: Protection against excessive requests
* **CORS Configuration**: Control which domains can access the API

To enable authentication:

```python
from casino_of_life.web import TrainingServer, SecurityConfig

security = SecurityConfig(
    enable_auth=True,
    admin_username="admin",
    admin_password="secure_password"
)

server = TrainingServer(security_config=security)
server.start()
```

### Troubleshooting

Common issues and their solutions:

* **Server won't start**: Check for port conflicts or missing dependencies
* **Slow dashboard updates**: Reduce refresh rate or limit monitored metrics
* **High memory usage**: Decrease the number of parallel training sessions
* **Connection issues**: Verify network settings and firewall configurations

The web interface provides a powerful way to control and monitor your Casino of Life training sessions, making complex reinforcement learning accessible and visual.

####
