1717from .schemas import HealthResponse , PredictionResponse , ErrorResponse
1818
1919# Configure logging
20- logging .basicConfig (
21- level = logging .INFO ,
22- format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
23- )
20+ logging .basicConfig (level = logging .INFO , format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" )
2421logger = logging .getLogger (__name__ )
2522
2623
@@ -33,10 +30,7 @@ async def lifespan(app: FastAPI):
3330 # Startup: Load the MONAI model
3431 logger .info ("Starting up: Loading MONAI model..." )
3532 try :
36- model_loader .load_model (
37- model_name = "spleen_ct_segmentation" ,
38- bundle_dir = "./models"
39- )
33+ model_loader .load_model (model_name = "spleen_ct_segmentation" , bundle_dir = "./models" )
4034 logger .info ("Model loaded successfully!" )
4135 except Exception as e :
4236 logger .error (f"Failed to load model: { e } " )
@@ -77,8 +71,8 @@ async def global_exception_handler(request, exc):
7771 content = {
7872 "error" : "InternalServerError" ,
7973 "detail" : "An unexpected error occurred. Please try again." ,
80- "status_code" : 500
81- }
74+ "status_code" : 500 ,
75+ },
8276 )
8377
8478
@@ -97,7 +91,7 @@ async def root():
9791 "health" : "/health" ,
9892 "predict" : "/predict" ,
9993 "docs" : "/docs" ,
100- }
94+ },
10195 }
10296
10397
@@ -132,14 +126,9 @@ async def health_check():
132126 200 : {"description" : "Successful prediction" },
133127 400 : {"model" : ErrorResponse , "description" : "Bad request" },
134128 500 : {"model" : ErrorResponse , "description" : "Internal server error" },
135- }
129+ },
136130)
137- async def predict (
138- file : UploadFile = File (
139- ...,
140- description = "Medical image file (NIfTI format: .nii or .nii.gz)"
141- )
142- ):
131+ async def predict (file : UploadFile = File (..., description = "Medical image file (NIfTI format: .nii or .nii.gz)" )):
143132 """
144133 Run inference on uploaded medical image.
145134
@@ -153,64 +142,46 @@ async def predict(
153142 HTTPException: If file format is invalid or inference fails
154143 """
155144 # Validate file format
156- if not file .filename .endswith ((' .nii' , ' .nii.gz' )):
145+ if not file .filename .endswith ((" .nii" , " .nii.gz" )):
157146 raise HTTPException (
158- status_code = status .HTTP_400_BAD_REQUEST ,
159- detail = "Invalid file format. Supported formats: .nii, .nii.gz"
147+ status_code = status .HTTP_400_BAD_REQUEST , detail = "Invalid file format. Supported formats: .nii, .nii.gz"
160148 )
161149
162150 # Check if model is loaded
163151 if not model_loader .is_loaded ():
164152 raise HTTPException (
165- status_code = status .HTTP_503_SERVICE_UNAVAILABLE ,
166- detail = "Model not loaded. Please try again later."
153+ status_code = status .HTTP_503_SERVICE_UNAVAILABLE , detail = "Model not loaded. Please try again later."
167154 )
168155
169156 try :
170157 # Read file content
171158 contents = await file .read ()
172159
173160 # Run inference
174- result = await inference_engine .process_image (
175- image_bytes = contents ,
176- filename = file .filename
177- )
161+ result = await inference_engine .process_image (image_bytes = contents , filename = file .filename )
178162
179163 return PredictionResponse (** result )
180164
181165 except ValueError as e :
182166 # Client error (bad input)
183167 logger .warning (f"Bad request: { str (e )} " )
184- raise HTTPException (
185- status_code = status .HTTP_400_BAD_REQUEST ,
186- detail = str (e )
187- )
168+ raise HTTPException (status_code = status .HTTP_400_BAD_REQUEST , detail = str (e ))
188169
189170 except RuntimeError as e :
190171 # Server error (inference failed)
191172 logger .error (f"Inference error: { str (e )} " )
192- raise HTTPException (
193- status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
194- detail = f"Inference failed: { str (e )} "
195- )
173+ raise HTTPException (status_code = status .HTTP_500_INTERNAL_SERVER_ERROR , detail = f"Inference failed: { str (e )} " )
196174
197175 except Exception as e :
198176 # Unexpected error
199177 logger .error (f"Unexpected error during prediction: { str (e )} " )
200178 raise HTTPException (
201- status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
202- detail = "An unexpected error occurred during prediction"
179+ status_code = status .HTTP_500_INTERNAL_SERVER_ERROR , detail = "An unexpected error occurred during prediction"
203180 )
204181
205182
206183if __name__ == "__main__" :
207184 import uvicorn
208185
209186 # For development only - use proper ASGI server in production
210- uvicorn .run (
211- "main:app" ,
212- host = "0.0.0.0" ,
213- port = 8000 ,
214- reload = True ,
215- log_level = "info"
216- )
187+ uvicorn .run ("main:app" , host = "0.0.0.0" , port = 8000 , reload = True , log_level = "info" )
0 commit comments