Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -4,50 +4,76 @@ from PIL import Image
|
|
| 4 |
import numpy as np
|
| 5 |
import io
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# Load the trained model globally so it only loads once on startup
|
| 11 |
-
try:
|
| 12 |
-
model = load_model("mnist_model.keras")
|
| 13 |
-
except Exception as e:
|
| 14 |
-
raise RuntimeError(f"Error loading model: {e}")
|
| 15 |
|
| 16 |
@app.post("/predict/")
|
| 17 |
async def predict_digit(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
| 18 |
if not file.content_type.startswith("image/"):
|
| 19 |
-
raise HTTPException(status_code=400, detail="
|
| 20 |
|
| 21 |
try:
|
| 22 |
-
# Read the uploaded file into memory
|
| 23 |
contents = await file.read()
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
image = image.resize((28, 28))
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
predicted_class = int(np.argmax(prediction_probs))
|
| 39 |
confidence = float(np.max(prediction_probs))
|
| 40 |
-
|
| 41 |
return {
|
| 42 |
"filename": file.filename,
|
| 43 |
"predicted_digit": predicted_class,
|
| 44 |
"confidence": round(confidence, 4)
|
| 45 |
}
|
| 46 |
|
| 47 |
-
except
|
| 48 |
-
raise
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import io
|
| 6 |
|
| 7 |
+
app = FastAPI(
|
| 8 |
+
title="MNIST Digit Classifier API",
|
| 9 |
+
version="1.0"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
# Global model holder
|
| 13 |
+
model = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@app.on_event("startup")
|
| 17 |
+
def load_model_on_startup():
|
| 18 |
+
global model
|
| 19 |
+
try:
|
| 20 |
+
model = load_model("mnist_model.keras")
|
| 21 |
+
print("Model loaded successfully")
|
| 22 |
+
except Exception as e:
|
| 23 |
+
raise RuntimeError(f"Failed to load model: {e}")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@app.get("/")
|
| 27 |
+
def health_check():
|
| 28 |
+
return {"message": "MNIST API running"}
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
@app.post("/predict/")
|
| 32 |
async def predict_digit(file: UploadFile = File(...)):
|
| 33 |
+
global model
|
| 34 |
+
|
| 35 |
+
# Basic validation
|
| 36 |
if not file.content_type.startswith("image/"):
|
| 37 |
+
raise HTTPException(status_code=400, detail="Only image files are allowed")
|
| 38 |
|
| 39 |
try:
|
|
|
|
| 40 |
contents = await file.read()
|
| 41 |
+
|
| 42 |
+
if len(contents) == 0:
|
| 43 |
+
raise HTTPException(status_code=400, detail="Empty file")
|
| 44 |
+
|
| 45 |
+
# Load image safely
|
| 46 |
+
try:
|
| 47 |
+
image = Image.open(io.BytesIO(contents)).convert("L")
|
| 48 |
+
except Exception:
|
| 49 |
+
raise HTTPException(status_code=400, detail="Invalid image file")
|
| 50 |
+
|
| 51 |
+
# Resize to MNIST format
|
| 52 |
image = image.resize((28, 28))
|
| 53 |
+
|
| 54 |
+
# Convert to numpy
|
| 55 |
+
image_array = np.array(image).astype("float32") / 255.0
|
| 56 |
+
|
| 57 |
+
# CNN format: (1, 28, 28, 1)
|
| 58 |
+
image_array = np.expand_dims(image_array, axis=-1)
|
| 59 |
+
image_array = np.expand_dims(image_array, axis=0)
|
| 60 |
+
|
| 61 |
+
# Prediction
|
| 62 |
+
prediction_probs = model.predict(image_array, verbose=0)
|
| 63 |
predicted_class = int(np.argmax(prediction_probs))
|
| 64 |
confidence = float(np.max(prediction_probs))
|
| 65 |
+
|
| 66 |
return {
|
| 67 |
"filename": file.filename,
|
| 68 |
"predicted_digit": predicted_class,
|
| 69 |
"confidence": round(confidence, 4)
|
| 70 |
}
|
| 71 |
|
| 72 |
+
except HTTPException as he:
|
| 73 |
+
raise he
|
| 74 |
|
| 75 |
+
except Exception as e:
|
| 76 |
+
raise HTTPException(
|
| 77 |
+
status_code=500,
|
| 78 |
+
detail=f"Prediction error: {str(e)}"
|
| 79 |
+
)
|