Rafs-an09002 commited on
Commit
d249d53
·
verified ·
1 Parent(s): 826638c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -32
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
- Nexus-Core Inference API (Fixed)
3
- Fast and efficient chess engine with proper error handling
4
  """
5
 
6
  from fastapi import FastAPI, HTTPException
@@ -62,36 +62,39 @@ async def startup_event():
62
  global engine
63
  logger.info("🚀 Starting Nexus-Core API...")
64
 
65
- # Check model file
66
- model_path = "/app/models/nexus_core.onnx"
 
 
 
67
 
68
- # Debug: List files in models directory
69
  if os.path.exists("/app/models"):
70
- logger.info(f"📂 Files in /app/models/:")
71
  for f in os.listdir("/app/models"):
72
  full_path = os.path.join("/app/models", f)
73
- size = os.path.getsize(full_path) / (1024*1024)
74
- logger.info(f" - {f} ({size:.2f} MB)")
 
75
  else:
76
  logger.error("❌ /app/models/ directory does not exist!")
77
  raise FileNotFoundError("/app/models/ not found")
78
 
79
- # Check if model exists
80
  if not os.path.exists(model_path):
81
- logger.error(f"❌ Model not found at {model_path}")
82
- logger.error("Available files:", os.listdir("/app/models") if os.path.exists("/app/models") else "No models dir")
83
- raise FileNotFoundError(f"Model file not found: {model_path}")
84
 
85
- logger.info(f"✅ Model found: {model_path} ({os.path.getsize(model_path)/(1024*1024):.2f} MB)")
86
 
87
  try:
88
  engine = NexusCoreEngine(
89
  model_path=model_path,
90
  num_threads=2
91
  )
92
- logger.info("✅ Nexus-Core engine loaded successfully")
 
93
  except Exception as e:
94
- logger.error(f"❌ Failed to load engine: {e}", exc_info=True)
95
  raise
96
 
97
 
@@ -101,29 +104,29 @@ async def health_check():
101
  "status": "healthy" if engine else "unhealthy",
102
  "model_loaded": engine is not None,
103
  "version": "2.0.0",
104
- "model_path": "/app/models/nexus_core.onnx" if engine else None
105
  }
106
 
107
 
108
  @app.post("/get-move", response_model=MoveResponse)
109
  async def get_move(request: MoveRequest):
110
  if not engine:
111
- raise HTTPException(503, "Engine not loaded")
112
 
113
  if not engine.validate_fen(request.fen):
114
- raise HTTPException(400, "Invalid FEN")
115
 
116
  start = time.time()
117
 
118
  try:
119
  result = engine.get_best_move(
120
- request.fen,
121
- request.depth,
122
- request.time_limit
123
  )
124
 
125
  logger.info(
126
- f"Move: {result['best_move']} | "
127
  f"Eval: {result['evaluation']:+.2f} | "
128
  f"Depth: {result['depth_searched']} | "
129
  f"Nodes: {result['nodes_evaluated']} | "
@@ -131,28 +134,35 @@ async def get_move(request: MoveRequest):
131
  )
132
 
133
  return MoveResponse(**result)
134
-
135
  except Exception as e:
136
- logger.error(f"Error during search: {e}", exc_info=True)
137
- raise HTTPException(500, str(e))
138
 
139
 
140
  @app.get("/")
141
  async def root():
142
  return {
143
- "name": "Nexus-Core API",
144
  "version": "2.0.0",
145
  "model": "13M parameters",
146
- "speed": "Ultra-fast (0.5-1s per move)",
147
- "status": "healthy" if engine else "loading",
 
148
  "endpoints": {
149
- "POST /get-move": "Get best move",
150
- "GET /health": "Health check",
151
- "GET /docs": "API documentation"
152
  }
153
  }
154
 
155
 
156
  if __name__ == "__main__":
157
  import uvicorn
158
- uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
 
 
 
 
 
 
 
1
  """
2
+ Nexus-Core Inference API - Path Fixed
3
+ Model: /app/models/nexus-core.onnx
4
  """
5
 
6
  from fastapi import FastAPI, HTTPException
 
62
  global engine
63
  logger.info("🚀 Starting Nexus-Core API...")
64
 
65
+ # FIXED: Correct model path with hyphen
66
+ model_path = "/app/models/nexus-core.onnx"
67
+
68
+ # Debug logging
69
+ logger.info(f"Looking for model at: {model_path}")
70
 
 
71
  if os.path.exists("/app/models"):
72
+ logger.info("📂 Files in /app/models/:")
73
  for f in os.listdir("/app/models"):
74
  full_path = os.path.join("/app/models", f)
75
+ if os.path.isfile(full_path):
76
+ size = os.path.getsize(full_path) / (1024*1024)
77
+ logger.info(f" ✓ {f} ({size:.2f} MB)")
78
  else:
79
  logger.error("❌ /app/models/ directory does not exist!")
80
  raise FileNotFoundError("/app/models/ not found")
81
 
 
82
  if not os.path.exists(model_path):
83
+ logger.error(f"❌ Model not found at: {model_path}")
84
+ logger.error("💡 Available files:", os.listdir("/app/models"))
85
+ raise FileNotFoundError(f"Model file missing: {model_path}")
86
 
87
+ logger.info(f"✅ Model found: {os.path.getsize(model_path)/(1024*1024):.2f} MB")
88
 
89
  try:
90
  engine = NexusCoreEngine(
91
  model_path=model_path,
92
  num_threads=2
93
  )
94
+ logger.info("✅ Nexus-Core engine loaded successfully!")
95
+
96
  except Exception as e:
97
+ logger.error(f"❌ Engine load failed: {e}", exc_info=True)
98
  raise
99
 
100
 
 
104
  "status": "healthy" if engine else "unhealthy",
105
  "model_loaded": engine is not None,
106
  "version": "2.0.0",
107
+ "model_path": "/app/models/nexus-core.onnx"
108
  }
109
 
110
 
111
  @app.post("/get-move", response_model=MoveResponse)
112
  async def get_move(request: MoveRequest):
113
  if not engine:
114
+ raise HTTPException(status_code=503, detail="Engine not loaded")
115
 
116
  if not engine.validate_fen(request.fen):
117
+ raise HTTPException(status_code=400, detail="Invalid FEN string")
118
 
119
  start = time.time()
120
 
121
  try:
122
  result = engine.get_best_move(
123
+ fen=request.fen,
124
+ depth=request.depth,
125
+ time_limit=request.time_limit
126
  )
127
 
128
  logger.info(
129
+ f"Move: {result['best_move']} | "
130
  f"Eval: {result['evaluation']:+.2f} | "
131
  f"Depth: {result['depth_searched']} | "
132
  f"Nodes: {result['nodes_evaluated']} | "
 
134
  )
135
 
136
  return MoveResponse(**result)
137
+
138
  except Exception as e:
139
+ logger.error(f" Search error: {e}", exc_info=True)
140
+ raise HTTPException(status_code=500, detail=str(e))
141
 
142
 
143
  @app.get("/")
144
  async def root():
145
  return {
146
+ "name": "Nexus-Core Inference API",
147
  "version": "2.0.0",
148
  "model": "13M parameters",
149
+ "architecture": "ResNet CNN",
150
+ "speed": "0.5-1s per move @ depth 4",
151
+ "status": "online" if engine else "starting",
152
  "endpoints": {
153
+ "POST /get-move": "Get best chess move",
154
+ "GET /health": "API health check",
155
+ "GET /docs": "Interactive API documentation"
156
  }
157
  }
158
 
159
 
160
  if __name__ == "__main__":
161
  import uvicorn
162
+ uvicorn.run(
163
+ app,
164
+ host="0.0.0.0",
165
+ port=7860,
166
+ log_level="info",
167
+ access_log=True
168
+ )