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85d8
b615834
d1a85d8
 
b615834
 
 
d1a85d8
 
b615834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1a85d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b615834
 
 
 
 
 
 
 
 
 
d1a85d8
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
"""
FastAPI server for Sumobot with Milvus Vector Search
Real-time action retrieval using similarity search
"""

import re
import platform
import time
from typing import Dict, Optional, List
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import numpy as np
from pymilvus import connections, Collection

# ==================== Configuration ====================
MILVUS_HOST = "127.0.0.1"
MILVUS_PORT = "19530"
COLLECTION_NAME = "sumobot_states"
TOP_K = 1  # Number of similar states to retrieve
NPROBE = 16  # Search parameter for IVF_FLAT index

print("="*70)
print("🤖 Sumobot Milvus Vector Search API Server")
print("="*70)
print(f"Platform: {platform.system()} {platform.machine()}")
print(f"Milvus: {MILVUS_HOST}:{MILVUS_PORT}")
print(f"Collection: {COLLECTION_NAME}")
print("="*70)

# ==================== Connect to Milvus ====================
print("\n⏳ Connecting to Milvus...")
start_time = time.time()

try:
    connections.connect("default", host=MILVUS_HOST, port=MILVUS_PORT)
    col = Collection(COLLECTION_NAME)
    col.load()
    
    load_time = time.time() - start_time
    num_entities = col.num_entities
    
    print(f"✅ Connected to Milvus in {load_time:.2f}s")
    print(f"📊 Collection has {num_entities} entities\n")
    
except Exception as e:
    print(f"❌ Failed to connect to Milvus: {e}")
    print("\nMake sure:")
    print(f"  1. Milvus is running at {MILVUS_HOST}:{MILVUS_PORT}")
    print(f"  2. Collection '{COLLECTION_NAME}' exists")
    print("  3. pymilvus is installed: pip install pymilvus")
    exit(1)

# ==================== State Encoding ====================
def encode_state(angle: float, angle_score: float, dist_score: float, 
                 near_score: float, facing: float) -> np.ndarray:
    """
    Encode game state into 5D vector
    
    Args:
        angle: AngleToEnemy (degrees, normalized to [-1, 1])
        angle_score: AngleToEnemyScore [0, 1]
        dist_score: DistanceToEnemyScore [0, 1]
        near_score: NearBorderArenaScore [0, 1]
        facing: FacingToArena [-1, 1]
    
    Returns:
        5D numpy array [angle_normalized, angle_score, dist_score, near_score, facing]
    """
    # Normalize angle from [-180, 180] to [-1, 1]
    angle_normalized = angle / 180.0
    
    return np.array([
        angle_normalized,
        angle_score,
        dist_score,
        near_score,
        facing
    ], dtype=np.float32)

def parse_state_string(state_str: str) -> Dict[str, float]:
    """
    Parse state string into dictionary
    
    Example input: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
    Returns: {"AngleToEnemy": 7.77, "AngleToEnemyScore": 0.99, ...}
    """
    state_dict = {}
    
    # Remove trailing punctuation from entire string
    state_str = state_str.rstrip('.,;')
    
    for part in state_str.split(","):
        part = part.strip()
        if "=" in part:
            key, value = part.split("=", 1)  # Split only on first '='
            # Clean up value: remove trailing periods, spaces, etc.
            value_clean = value.strip().rstrip('.')
            try:
                state_dict[key.strip()] = float(value_clean)
            except ValueError as e:
                raise ValueError(f"Cannot parse '{key.strip()}={value}' - invalid float value: {e}")
    
    return state_dict

# ==================== Action Parser ====================
def parse_action(output: str) -> Dict[str, Optional[float]]:
    """
    Parse action string into dictionary
    
    Expected format: "FWD 1.5, TR 0.8" or "SK, DS 2.0"
    Returns: {"Accelerate": 1.5, "TurnRight": 0.8} or {"Skill": None, "Dash": 2.0}
    """
    action_map = {
        "SK": "Skill",
        "DS": "Dash",
        "FWD": "Accelerate",
        "TL": "TurnLeft",
        "TR": "TurnRight",
    }
    
    actions: Dict[str, Optional[float]] = {}
    
    # Split by comma and process each action
    for part in [p.strip() for p in output.split(",")]:
        if not part:
            continue
            
        name = part
        duration = None
        
        # Try to extract duration (e.g., "FWD 1.5" -> name="FWD", duration=1.5)
        direct_match = re.match(r"^([A-Za-z]+)\s*([\d.]+)$", part)
        if direct_match:
            name = direct_match.group(1).strip()
            duration = float(direct_match.group(2))
        
        # Normalize shorthand to full action name
        for short, full in action_map.items():
            if name.upper().startswith(short):
                name = full
                break
        
        actions[name] = duration
    
    return actions

# ==================== Vector Search Function ====================
def query_action(angle: float, angle_score: float, dist_score: float, 
                 near_score: float, facing: float, top_k: int = TOP_K) -> dict:
    """
    Query action from Milvus using vector similarity search
    
    Args:
        angle: AngleToEnemy (degrees)
        angle_score: AngleToEnemyScore [0, 1]
        dist_score: DistanceToEnemyScore [0, 1]
        near_score: NearBorderArenaScore [0, 1]
        facing: FacingToArena [-1, 1]
        top_k: Number of similar states to retrieve
    
    Returns:
        {
            "raw_output": "FWD 1.5, TR 0.8",
            "action": {"Accelerate": 1.5, "TurnRight": 0.8},
            "search_time_ms": 2.5,
            "distance": 0.123,
            "top_k_results": [...]  # Only if top_k > 1
        }
    """
    # Encode state into vector
    vec = encode_state(angle, angle_score, dist_score, near_score, facing)
    
    # Perform vector search
    start = time.time()
    
    result = col.search(
        data=[vec.tolist()],
        anns_field="state_vec",
        param={"nprobe": NPROBE},
        limit=top_k,
        output_fields=["action"],
    )
    
    search_time = (time.time() - start) * 1000  # Convert to ms
    
    # Extract results
    if len(result[0]) == 0:
        raise ValueError("No similar states found in database")
    
    top_hit = result[0][0]
    action_str = top_hit.entity.get("action")
    distance = top_hit.distance
    
    # Parse action
    parsed_actions = parse_action(action_str)
    
    response = {
        "raw_output": action_str,
        "action": parsed_actions,
        "search_time_ms": round(search_time, 2),
        "distance": round(distance, 4)
    }
    
    # Include all results if top_k > 1
    if top_k > 1:
        response["top_k_results"] = [
            {
                "action": hit.entity.get("action"),
                "distance": round(hit.distance, 4)
            }
            for hit in result[0]
        ]
    
    return response

def query_action_from_string(state_str: str, top_k: int = TOP_K) -> dict:
    """
    Query action from state string
    
    Args:
        state_str: "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
        top_k: Number of similar states to retrieve
    
    Returns:
        Same as query_action()
    """
    # Parse state string
    state_dict = parse_state_string(state_str)
    
    # Extract required fields
    required_fields = [
        "AngleToEnemy",
        "AngleToEnemyScore",
        "DistanceToEnemyScore",
        "NearBorderArenaScore",
        "FacingToArena"
    ]
    
    missing_fields = [f for f in required_fields if f not in state_dict]
    if missing_fields:
        raise ValueError(f"Missing required fields: {missing_fields}")
    
    # Query action
    return query_action(
        angle=state_dict["AngleToEnemy"],
        angle_score=state_dict["AngleToEnemyScore"],
        dist_score=state_dict["DistanceToEnemyScore"],
        near_score=state_dict["NearBorderArenaScore"],
        facing=state_dict["FacingToArena"],
        top_k=top_k
    )

# ==================== FastAPI Setup ====================
app = FastAPI(
    title="Sumobot Milvus Vector Search API",
    description="Real-time Sumobot action retrieval using vector similarity search",
    version="1.0.0"
)

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

# ==================== Request/Response Models ====================
class QueryInput(BaseModel):
    state: str
    top_k: Optional[int] = 1
    
    class Config:
        json_schema_extra = {
            "example": {
                "state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
                "top_k": 1
            }
        }

class QueryResponse(BaseModel):
    raw_output: str
    action: Dict[str, Optional[float]]
    search_time_ms: float
    distance: float
    top_k_results: Optional[List[Dict]] = None

class BatchQueryInput(BaseModel):
    states: List[str]
    top_k: Optional[int] = 1

class HealthResponse(BaseModel):
    status: str
    milvus_host: str
    collection: str
    num_entities: int
    platform: str

# ==================== API Endpoints ====================

@app.get("/", tags=["Info"])
def root():
    """Root endpoint with API information"""
    return {
        "message": "Sumobot Milvus Vector Search API",
        "endpoints": {
            "health": "/health",
            "query": "/query (POST)",
            "batch": "/batch (POST)",
            "benchmark": "/benchmark (GET)",
            "stats": "/stats (GET)"
        }
    }

@app.get("/health", response_model=HealthResponse, tags=["Info"])
def health_check():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "milvus_host": f"{MILVUS_HOST}:{MILVUS_PORT}",
        "collection": COLLECTION_NAME,
        "num_entities": col.num_entities,
        "platform": f"{platform.system()} {platform.machine()}"
    }

@app.get("/stats", tags=["Info"])
def collection_stats():
    """Get collection statistics"""
    return {
        "collection": COLLECTION_NAME,
        "num_entities": col.num_entities,
        "schema": {
            "fields": [
                {
                    "name": field.name,
                    "type": str(field.dtype),
                    "params": field.params
                }
                for field in col.schema.fields
            ]
        },
        "indexes": [
            {
                "field": index.field_name,
                "type": index.params.get("index_type"),
                "metric": index.params.get("metric_type")
            }
            for index in col.indexes
        ]
    }

@app.post("/query", response_model=QueryResponse, tags=["Search"])
def query(input: QueryInput):
    """
    Get action prediction for a single game state
    
    Example:
    ```json
    {
        "state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
        "top_k": 1
    }
    ```
    """
    
    try:
        result = query_action_from_string(input.state, input.top_k)
        return result
    except Exception as e:
        print(input.state)
        print(f"Error query:\nInput: {input.state}\nDetail: {e.with_traceback()}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/batch", tags=["Search"])
def batch_query(input: BatchQueryInput):
    """
    Get action predictions for multiple game states
    
    Example:
    ```json
    {
        "states": [
            "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
            "AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
        ],
        "top_k": 1
    }
    ```
    """
    try:
        results = []
        total_time = 0
        
        for state in input.states:
            result = query_action_from_string(state, input.top_k)
            results.append(result)
            total_time += result["search_time_ms"]
        
        return {
            "results": results,
            "total_search_time_ms": round(total_time, 2),
            "avg_search_time_ms": round(total_time / len(results), 2)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/benchmark", tags=["Diagnostics"])
def benchmark():
    """
    Benchmark vector search performance
    
    Runs 100 searches and returns statistics
    """
    test_state = "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
    
    print("\n🔥 Running benchmark...")
    
    # Warmup
    query_action_from_string(test_state)
    
    # Benchmark
    times = []
    outputs = []
    
    num_runs = 100
    for i in range(num_runs):
        result = query_action_from_string(test_state)
        times.append(result["search_time_ms"])
        outputs.append(result["raw_output"])
        
        if (i + 1) % 20 == 0:
            print(f"  Run {i+1}/{num_runs}: {result['search_time_ms']:.2f}ms")
    
    times_sorted = sorted(times)
    
    return {
        "runs": num_runs,
        "test_state": test_state,
        "stats": {
            "avg_latency_ms": round(sum(times) / len(times), 2),
            "min_latency_ms": round(min(times), 2),
            "max_latency_ms": round(max(times), 2),
            "p50_latency_ms": round(times_sorted[len(times) // 2], 2),
            "p95_latency_ms": round(times_sorted[int(len(times) * 0.95)], 2),
            "p99_latency_ms": round(times_sorted[int(len(times) * 0.99)], 2),
        },
        "platform": {
            "system": platform.system(),
            "machine": platform.machine(),
            "milvus": f"{MILVUS_HOST}:{MILVUS_PORT}",
            "collection_size": col.num_entities
        },
        "sample_outputs": list(set(outputs[:10]))  # First 10 unique outputs
    }

# ==================== Main ====================
if __name__ == "__main__":
    import sys

    port = 9999
    workers = 20  # Number of worker processes

    # Check if running with multiple workers
    if "--workers" in sys.argv:
        try:
            workers_idx = sys.argv.index("--workers")
            workers = int(sys.argv[workers_idx + 1])
        except (IndexError, ValueError):
            print("⚠️  Invalid --workers argument, using default: 20")

    if "--port" in sys.argv:
        try:
            port_idx = sys.argv.index("--port")
            port = int(sys.argv[port_idx + 1])
        except (IndexError, ValueError):
            print(f"⚠️  Invalid --port argument, using default: {port}")

    print("\n🚀 Starting Sumobot Milvus API server...")
    print(f"📡 Server will be available at: http://0.0.0.0:{port}")
    print(f"👷 Workers: {workers}")
    print(f"📚 API docs: http://0.0.0.0:{port}/docs")
    print(f"🔍 Health check: http://0.0.0.0:{port}/health")
    print(f"📊 Stats: http://0.0.0.0:{port}/stats")
    print("\n" + "="*70 + "\n")

    # For production with multiple workers, use uvicorn with workers parameter
    # Each worker will have its own connection to Milvus
    uvicorn.run(
        "api:app",  # Use string import path for workers to work properly
        host="0.0.0.0",
        port=port,
        workers=workers,
        log_level="info",
        access_log=True
    )

# ==================== Usage Instructions ====================
"""
# ==================== Running the Server ====================

# Run with 20 workers (default)
python vdb/api.py

# Run with custom number of workers
python vdb/api.py --workers 10

# Run with custom port
python vdb/api.py --port 8000 --workers 20

# Alternative: Using Gunicorn for production (install: pip install gunicorn)
gunicorn vdb.api:app \
  --workers 20 \
  --worker-class uvicorn.workers.UvicornWorker \
  --bind 0.0.0.0:9999 \
  --timeout 120 \
  --access-logfile - \
  --error-logfile -

# ==================== Testing the API ====================

# Health check
curl http://localhost:9999/health

# Collection stats
curl http://localhost:9999/stats

# Single query
curl -X POST http://localhost:9999/query \
  -H "Content-Type: application/json" \
  -d '{
    "state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"
  }'

# Query with top-k results
curl -X POST http://localhost:9999/query \
  -H "Content-Type: application/json" \
  -d '{
    "state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
    "top_k": 3
  }'

# Batch query
curl -X POST http://localhost:9999/batch \
  -H "Content-Type: application/json" \
  -d '{
    "states": [
      "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99",
      "AngleToEnemy=2.31, AngleToEnemyScore=0.45, DistanceToEnemyScore=0.92, NearBorderArenaScore=0.12, FacingToArena=0.67"
    ]
  }'

# Benchmark
curl http://localhost:9999/benchmark

# Interactive API docs
# Open in browser: http://localhost:9999/docs

# ==================== Performance Testing ====================

# Load test with Apache Bench (install: brew install httpd or apt-get install apache2-utils)
ab -n 10000 -c 100 -T 'application/json' \
  -p query.json \
  http://localhost:9999/query

# Where query.json contains:
# {"state": "AngleToEnemy=7.77, AngleToEnemyScore=0.99, DistanceToEnemyScore=0.76, NearBorderArenaScore=0.81, FacingToArena=-0.99"}
"""