adffedccasfe commited on
Commit
223e14e
·
verified ·
1 Parent(s): 2791744

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. main.py +145 -52
main.py CHANGED
@@ -25,11 +25,6 @@ from huggingface_hub import hf_hub_download
25
  # Import your orchestration pipeline
26
  from orchestration import WBCClassificationPipeline
27
 
28
- # Configure logging
29
- logging.basicConfig(level=logging.INFO)
30
- logger = logging.getLogger(__name__)
31
-
32
- # Create FastAPI app instance
33
  app = FastAPI(
34
  title="WBC Classification API",
35
  description="AI-Powered White Blood Cell Classification System",
@@ -37,6 +32,11 @@ app = FastAPI(
37
  docs_url="/docs",
38
  redoc_url="/redoc"
39
  )
 
 
 
 
 
40
 
41
  # Add CORS middleware
42
  app.add_middleware(
@@ -47,8 +47,32 @@ app.add_middleware(
47
  allow_headers=["*"],
48
  )
49
 
50
- # Configuration - FIXED PATHS
51
- MODEL_PATH = "./Models/at_batch_size=32.D24E.keras" # Fixed path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  STATIC_DIR = "static"
53
  UPLOADS_DIR = "uploads"
54
  MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
@@ -71,13 +95,25 @@ async def startup_event():
71
  global pipeline
72
 
73
  logger.info("Starting WBC Classification API...")
 
74
  logger.info(f"Model path: {MODEL_PATH}")
 
 
 
 
 
75
 
76
  try:
77
  # Check if model file exists
78
  if not os.path.exists(MODEL_PATH):
79
  logger.error(f"Model file not found at: {MODEL_PATH}")
80
- logger.error("Please ensure your model file is in the Models folder")
 
 
 
 
 
 
81
  return
82
 
83
  # Initialize pipeline
@@ -101,21 +137,109 @@ async def startup_event():
101
  async def read_root():
102
  """Serve the main HTML page"""
103
  try:
104
- html_path = os.path.join(STATIC_DIR, "index.html")
105
- if os.path.exists(html_path):
106
- with open(html_path, 'r', encoding='utf-8') as f:
107
- html_content = f.read()
 
 
 
 
 
 
 
 
 
 
 
 
108
  return HTMLResponse(content=html_content)
109
  else:
 
110
  return HTMLResponse(
111
  content="""
112
- <h1>🩸 WBC Classifier API</h1>
113
- <p>Frontend HTML file not found in static folder.</p>
114
- <p>Please move your index.html to the 'static' folder.</p>
115
- <p><a href="/docs">View API Documentation</a></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  """,
117
  status_code=200
118
  )
 
119
  except Exception as e:
120
  logger.error(f"Error serving root page: {str(e)}")
121
  return HTMLResponse(
@@ -135,7 +259,9 @@ async def health_check():
135
  "status": "healthy" if model_loaded else "unhealthy",
136
  "model_loaded": model_loaded,
137
  "model_info": model_info,
138
- "api_version": "1.0.0"
 
 
139
  }
140
  except Exception as e:
141
  logger.error(f"Health check failed: {str(e)}")
@@ -334,6 +460,8 @@ async def test_endpoint():
334
  "message": "WBC Classification API is working!",
335
  "status": "ok",
336
  "model_loaded": pipeline is not None and pipeline.is_loaded if pipeline else False,
 
 
337
  "endpoints": [
338
  "/ - Main page",
339
  "/api/health - Health check",
@@ -345,38 +473,3 @@ async def test_endpoint():
345
  }
346
 
347
  # Main function to run the server
348
- def main():
349
- """Main function to run the FastAPI server"""
350
-
351
- print("🚀 Starting WBC Classification FastAPI Server")
352
- print("=" * 50)
353
- print(f"📁 Model path: {MODEL_PATH}")
354
- print(f"📁 Static files: {STATIC_DIR}")
355
- print("📋 Available endpoints:")
356
- print(" 🏠 Main page: http://localhost:8000/")
357
- print(" 🔍 Health check: http://localhost:8000/api/health")
358
- print(" 📤 Single prediction: POST http://localhost:8000/api/predict")
359
- print(" 📤 Batch prediction: POST http://localhost:8000/api/predict_batch")
360
- print(" 📚 API docs: http://localhost:8000/docs")
361
- print("=" * 50)
362
-
363
- # Check if model exists before starting
364
- if not os.path.exists(MODEL_PATH):
365
- print(f"⚠️ WARNING: Model file not found at {MODEL_PATH}")
366
- print(" Please ensure your model file is in the Models folder")
367
-
368
- # Check if HTML file exists
369
- html_path = os.path.join(STATIC_DIR, "index.html")
370
- if not os.path.exists(html_path):
371
- print(f"⚠️ WARNING: HTML file not found at {html_path}")
372
- print(" Please move your index.html to the static folder")
373
-
374
- # Run the server
375
- uvicorn.run(
376
- "main:app",
377
- host="0.0.0.0",
378
- port=8000,
379
- reload=True,
380
- log_level="info"
381
- )
382
-
 
25
  # Import your orchestration pipeline
26
  from orchestration import WBCClassificationPipeline
27
 
 
 
 
 
 
28
  app = FastAPI(
29
  title="WBC Classification API",
30
  description="AI-Powered White Blood Cell Classification System",
 
32
  docs_url="/docs",
33
  redoc_url="/redoc"
34
  )
35
+ # Configure logging
36
+ logging.basicConfig(level=logging.INFO)
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
 
41
  # Add CORS middleware
42
  app.add_middleware(
 
47
  allow_headers=["*"],
48
  )
49
 
50
+ # Configuration - DYNAMIC PATHS FOR HUGGING FACE SPACES
51
+ def get_model_path():
52
+ """Get model path dynamically based on environment"""
53
+ # For local development
54
+ local_path = "./Models/at_batch_size=32.D24E.keras"
55
+ if os.path.exists(local_path):
56
+ return local_path
57
+
58
+ # For Hugging Face Spaces - model should be in root
59
+ hf_path = "at_batch_size=32.D24E.keras"
60
+ if os.path.exists(hf_path):
61
+ return hf_path
62
+
63
+ # Alternative path in Models folder
64
+ models_path = "Models/at_batch_size=32.D24E.keras"
65
+ if os.path.exists(models_path):
66
+ return models_path
67
+
68
+ # Last resort - current directory
69
+ current_dir_path = os.path.join(os.getcwd(), "at_batch_size=32.D24E.keras")
70
+ if os.path.exists(current_dir_path):
71
+ return current_dir_path
72
+
73
+ return local_path # Return default for error handling
74
+
75
+ MODEL_PATH = get_model_path()
76
  STATIC_DIR = "static"
77
  UPLOADS_DIR = "uploads"
78
  MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
 
95
  global pipeline
96
 
97
  logger.info("Starting WBC Classification API...")
98
+ logger.info(f"Current working directory: {os.getcwd()}")
99
  logger.info(f"Model path: {MODEL_PATH}")
100
+ logger.info(f"Files in current directory: {os.listdir('.')}")
101
+
102
+ # List files in Models directory if it exists
103
+ if os.path.exists("Models"):
104
+ logger.info(f"Files in Models directory: {os.listdir('Models')}")
105
 
106
  try:
107
  # Check if model file exists
108
  if not os.path.exists(MODEL_PATH):
109
  logger.error(f"Model file not found at: {MODEL_PATH}")
110
+ logger.error("Please ensure your model file is accessible")
111
+
112
+ # Try to find the model file
113
+ for root, dirs, files in os.walk("."):
114
+ for file in files:
115
+ if file.endswith(".keras"):
116
+ logger.info(f"Found keras file: {os.path.join(root, file)}")
117
  return
118
 
119
  # Initialize pipeline
 
137
  async def read_root():
138
  """Serve the main HTML page"""
139
  try:
140
+ # Try multiple possible locations for the HTML file
141
+ possible_paths = [
142
+ os.path.join(STATIC_DIR, "index.html"),
143
+ "index.html",
144
+ os.path.join(".", "index.html")
145
+ ]
146
+
147
+ html_content = None
148
+ for html_path in possible_paths:
149
+ if os.path.exists(html_path):
150
+ with open(html_path, 'r', encoding='utf-8') as f:
151
+ html_content = f.read()
152
+ logger.info(f"Serving HTML from: {html_path}")
153
+ break
154
+
155
+ if html_content:
156
  return HTMLResponse(content=html_content)
157
  else:
158
+ # Return a basic HTML page if index.html is not found
159
  return HTMLResponse(
160
  content="""
161
+ <!DOCTYPE html>
162
+ <html>
163
+ <head>
164
+ <title>WBC Classification API</title>
165
+ <style>
166
+ body { font-family: Arial, sans-serif; margin: 40px; }
167
+ .container { max-width: 800px; margin: 0 auto; }
168
+ .upload-area { border: 2px dashed #ccc; padding: 40px; text-align: center; margin: 20px 0; }
169
+ .btn { background: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }
170
+ .results { margin-top: 20px; padding: 20px; background: #f8f9fa; }
171
+ </style>
172
+ </head>
173
+ <body>
174
+ <div class="container">
175
+ <h1>🩸 WBC Classification API</h1>
176
+ <p>Upload white blood cell images for classification</p>
177
+
178
+ <div class="upload-area">
179
+ <input type="file" id="fileInput" accept="image/*" style="display: none;">
180
+ <button class="btn" onclick="document.getElementById('fileInput').click()">
181
+ Select Image
182
+ </button>
183
+ <p>Supported formats: JPG, PNG, BMP, TIFF, GIF</p>
184
+ </div>
185
+
186
+ <div id="results" class="results" style="display: none;"></div>
187
+
188
+ <div>
189
+ <h3>API Endpoints:</h3>
190
+ <ul>
191
+ <li><a href="/docs">API Documentation</a></li>
192
+ <li><a href="/api/health">Health Check</a></li>
193
+ <li><a href="/api/model_info">Model Information</a></li>
194
+ </ul>
195
+ </div>
196
+ </div>
197
+
198
+ <script>
199
+ document.getElementById('fileInput').addEventListener('change', function(event) {
200
+ const file = event.target.files[0];
201
+ if (file) {
202
+ const formData = new FormData();
203
+ formData.append('file', file);
204
+
205
+ fetch('/api/predict', {
206
+ method: 'POST',
207
+ body: formData
208
+ })
209
+ .then(response => response.json())
210
+ .then(data => {
211
+ const resultsDiv = document.getElementById('results');
212
+ if (data.success) {
213
+ resultsDiv.innerHTML = `
214
+ <h3>Classification Results:</h3>
215
+ <p><strong>Predicted Class:</strong> ${data.results.predicted_class}</p>
216
+ <p><strong>Confidence:</strong> ${(data.results.confidence * 100).toFixed(2)}%</p>
217
+ <h4>All Probabilities:</h4>
218
+ <ul>
219
+ ${Object.entries(data.results.all_probabilities).map(([className, prob]) =>
220
+ `<li>${className}: ${(prob * 100).toFixed(2)}%</li>`
221
+ ).join('')}
222
+ </ul>
223
+ `;
224
+ } else {
225
+ resultsDiv.innerHTML = `<p style="color: red;">Error: ${data.detail || 'Unknown error'}</p>`;
226
+ }
227
+ resultsDiv.style.display = 'block';
228
+ })
229
+ .catch(error => {
230
+ const resultsDiv = document.getElementById('results');
231
+ resultsDiv.innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
232
+ resultsDiv.style.display = 'block';
233
+ });
234
+ }
235
+ });
236
+ </script>
237
+ </body>
238
+ </html>
239
  """,
240
  status_code=200
241
  )
242
+
243
  except Exception as e:
244
  logger.error(f"Error serving root page: {str(e)}")
245
  return HTMLResponse(
 
259
  "status": "healthy" if model_loaded else "unhealthy",
260
  "model_loaded": model_loaded,
261
  "model_info": model_info,
262
+ "api_version": "1.0.0",
263
+ "model_path": MODEL_PATH,
264
+ "model_exists": os.path.exists(MODEL_PATH)
265
  }
266
  except Exception as e:
267
  logger.error(f"Health check failed: {str(e)}")
 
460
  "message": "WBC Classification API is working!",
461
  "status": "ok",
462
  "model_loaded": pipeline is not None and pipeline.is_loaded if pipeline else False,
463
+ "model_path": MODEL_PATH,
464
+ "model_exists": os.path.exists(MODEL_PATH),
465
  "endpoints": [
466
  "/ - Main page",
467
  "/api/health - Health check",
 
473
  }
474
 
475
  # Main function to run the server