-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
315 lines (282 loc) · 9.31 KB
/
main.py
File metadata and controls
315 lines (282 loc) · 9.31 KB
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
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
import os
import logging
from datetime import datetime
import cv2
import numpy as np
from PIL import Image
import io
import uuid
from typing import Optional, List
import json
# Import custom modules
from app.models.skin_analyzer import SkinAnalyzer
from app.schemas.analysis import AnalysisRequest, AnalysisResponse, ModelInfo
from app.core.config import settings
from app.core.logging import setup_logging
# Setup logging
setup_logging()
logger = logging.getLogger(__name__)
# Initialize FastAPI app
app = FastAPI(
title="SkinMate ML Service",
description="AI-powered skin analysis service for SkinMate platform",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, specify exact origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize skin analyzer
skin_analyzer = SkinAnalyzer()
@app.on_event("startup")
async def startup_event():
"""Initialize ML models on startup"""
logger.info("Starting SkinMate ML Service...")
try:
await skin_analyzer.load_models()
logger.info("ML models loaded successfully")
except Exception as e:
logger.error(f"Failed to load ML models: {e}")
raise e
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup on shutdown"""
logger.info("Shutting down SkinMate ML Service...")
@app.get("/")
async def root():
"""Root endpoint"""
return {
"service": "SkinMate ML Service",
"version": "1.0.0",
"status": "healthy",
"endpoints": {
"health": "/health",
"analyze": "/api/ml/analyze-skin",
"upload": "/api/ml/upload-image",
"model_info": "/api/ml/model-info",
"docs": "/docs"
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"service": "SkinMate ML Service",
"model_status": "loaded" if skin_analyzer.is_loaded else "loading"
}
@app.post("/api/ml/analyze-skin", response_model=AnalysisResponse)
async def analyze_skin(
file: UploadFile = File(...),
user_id: Optional[str] = None
):
"""
Analyze skin type from uploaded image
"""
try:
# Validate file type
if not file.content_type.startswith('image/'):
raise HTTPException(
status_code=400,
detail="Invalid file type. Please upload an image file."
)
# Read and validate image
contents = await file.read()
if len(contents) > settings.MAX_FILE_SIZE:
raise HTTPException(
status_code=400,
detail=f"File too large. Maximum size is {settings.MAX_FILE_SIZE / 1024 / 1024:.1f}MB"
)
# Convert to PIL Image
try:
image = Image.open(io.BytesIO(contents))
if image.mode != 'RGB':
image = image.convert('RGB')
except Exception as e:
raise HTTPException(
status_code=400,
detail="Invalid image format. Please upload a valid image file."
)
# Generate unique analysis ID
analysis_id = str(uuid.uuid4())
# Perform skin analysis
logger.info(f"Starting skin analysis for analysis_id: {analysis_id}")
analysis_result = await skin_analyzer.analyze_skin(image, analysis_id)
# Log analysis completion
logger.info(f"Skin analysis completed for analysis_id: {analysis_id}")
return AnalysisResponse(
analysis_id=analysis_id,
user_id=user_id,
skin_type=analysis_result["skin_type"],
confidence=analysis_result["confidence"],
skin_attributes=analysis_result["attributes"],
recommendations=analysis_result["recommendations"],
processing_time=analysis_result["processing_time"],
timestamp=datetime.utcnow()
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Unexpected error during skin analysis: {e}")
raise HTTPException(
status_code=500,
detail="Internal server error during skin analysis"
)
@app.post("/api/ml/upload-image")
async def upload_image(
file: UploadFile = File(...),
user_id: Optional[str] = None
):
"""
Upload and validate image for analysis
"""
try:
# Validate file
if not file.content_type.startswith('image/'):
raise HTTPException(
status_code=400,
detail="Invalid file type. Please upload an image file."
)
contents = await file.read()
if len(contents) > settings.MAX_FILE_SIZE:
raise HTTPException(
status_code=400,
detail=f"File too large. Maximum size is {settings.MAX_FILE_SIZE / 1024 / 1024:.1f}MB"
)
# Basic image validation
try:
image = Image.open(io.BytesIO(contents))
width, height = image.size
if width < 224 or height < 224:
raise HTTPException(
status_code=400,
detail="Image too small. Minimum size is 224x224 pixels."
)
except Exception as e:
raise HTTPException(
status_code=400,
detail="Invalid image format."
)
# Generate upload ID
upload_id = str(uuid.uuid4())
# In production, save to storage (S3, etc.)
# For now, just return success response
return {
"upload_id": upload_id,
"filename": file.filename,
"size": len(contents),
"dimensions": {"width": width, "height": height},
"status": "uploaded",
"message": "Image uploaded successfully"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error during image upload: {e}")
raise HTTPException(
status_code=500,
detail="Internal server error during image upload"
)
@app.get("/api/ml/analysis/{analysis_id}")
async def get_analysis(analysis_id: str):
"""
Get analysis result by ID
"""
try:
# In production, retrieve from database
# For now, return placeholder
return {
"analysis_id": analysis_id,
"status": "completed",
"message": "Analysis result retrieval endpoint"
}
except Exception as e:
logger.error(f"Error retrieving analysis {analysis_id}: {e}")
raise HTTPException(
status_code=500,
detail="Error retrieving analysis result"
)
@app.get("/api/ml/model-info", response_model=ModelInfo)
async def get_model_info():
"""
Get information about loaded ML models
"""
try:
model_info = await skin_analyzer.get_model_info()
return ModelInfo(**model_info)
except Exception as e:
logger.error(f"Error getting model info: {e}")
raise HTTPException(
status_code=500,
detail="Error retrieving model information"
)
@app.post("/api/ml/train-model")
async def train_model():
"""
Trigger model training (admin only)
"""
# TODO: Implement model training endpoint
return {
"message": "Model training endpoint",
"status": "not_implemented",
"note": "This endpoint will be implemented for model retraining"
}
@app.get("/api/ml/training-status")
async def get_training_status():
"""
Get model training status
"""
# TODO: Implement training status tracking
return {
"training_status": "idle",
"last_training": None,
"next_training": None,
"note": "Training status tracking not implemented yet"
}
@app.post("/api/ml/validate-model")
async def validate_model():
"""
Run model validation tests
"""
try:
validation_result = await skin_analyzer.validate_model()
return {
"validation_status": "completed",
"accuracy": validation_result.get("accuracy", 0.0),
"validation_time": validation_result.get("validation_time", 0.0),
"test_samples": validation_result.get("test_samples", 0),
"details": validation_result
}
except Exception as e:
logger.error(f"Error during model validation: {e}")
raise HTTPException(
status_code=500,
detail="Error during model validation"
)
# Exception handlers
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
logger.error(f"Unhandled exception: {exc}")
return JSONResponse(
status_code=500,
content={"error": "Internal server error", "detail": str(exc)}
)
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8001,
reload=True,
log_level="info"
)