Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,60 +1,52 @@
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
from tensorflow.keras.models import load_model
|
|
|
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
import io
|
| 6 |
|
| 7 |
-
|
| 8 |
-
app = FastAPI(
|
| 9 |
-
title="MNIST Digit Classifier API",
|
| 10 |
-
version="1.0"
|
| 11 |
-
)
|
| 12 |
|
| 13 |
-
# Global model variable
|
| 14 |
model = None
|
| 15 |
|
| 16 |
-
|
| 17 |
-
# Load model at startup (SAFE WAY)
|
| 18 |
@app.on_event("startup")
|
| 19 |
def load_model_on_startup():
|
| 20 |
global model
|
| 21 |
try:
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
except Exception as e:
|
| 25 |
-
|
| 26 |
-
|
| 27 |
|
| 28 |
-
# Health check
|
| 29 |
@app.get("/")
|
| 30 |
def read_root():
|
| 31 |
-
return {
|
| 32 |
-
"message": "MNIST Classification API is running. Send POST requests to /predict/"
|
| 33 |
-
}
|
| 34 |
|
| 35 |
-
|
| 36 |
-
# Prediction endpoint
|
| 37 |
@app.post("/predict/")
|
| 38 |
async def predict_digit(file: UploadFile = File(...)):
|
| 39 |
-
|
| 40 |
if not file.content_type.startswith("image/"):
|
| 41 |
-
raise HTTPException(
|
| 42 |
|
| 43 |
try:
|
| 44 |
-
# Read image
|
| 45 |
contents = await file.read()
|
| 46 |
image = Image.open(io.BytesIO(contents)).convert("L")
|
| 47 |
-
|
| 48 |
-
# Resize to MNIST format
|
| 49 |
image = image.resize((28, 28))
|
| 50 |
-
|
| 51 |
-
# Convert to numpy
|
| 52 |
image_array = np.array(image).astype("float32") / 255.0
|
| 53 |
-
|
| 54 |
-
# Flatten for Dense model
|
| 55 |
image_array = image_array.reshape(1, 784)
|
| 56 |
|
| 57 |
-
# Predict
|
| 58 |
prediction_probs = model.predict(image_array, verbose=0)
|
| 59 |
predicted_class = int(np.argmax(prediction_probs))
|
| 60 |
confidence = float(np.max(prediction_probs))
|
|
@@ -64,6 +56,5 @@ async def predict_digit(file: UploadFile = File(...)):
|
|
| 64 |
"predicted_digit": predicted_class,
|
| 65 |
"confidence": round(confidence, 4)
|
| 66 |
}
|
| 67 |
-
|
| 68 |
except Exception as e:
|
| 69 |
-
raise HTTPException(
|
|
|
|
| 1 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
from tensorflow.keras.models import load_model
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import os
|
| 5 |
from PIL import Image
|
| 6 |
import numpy as np
|
| 7 |
import io
|
| 8 |
|
| 9 |
+
app = FastAPI(title="MNIST Digit Classifier API", version="1.0")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
|
|
|
| 11 |
model = None
|
| 12 |
|
|
|
|
|
|
|
| 13 |
@app.on_event("startup")
|
| 14 |
def load_model_on_startup():
|
| 15 |
global model
|
| 16 |
try:
|
| 17 |
+
# Try .keras first, fallback to .h5
|
| 18 |
+
model_path = "mnist_model.keras"
|
| 19 |
+
if not os.path.exists(model_path):
|
| 20 |
+
model_path = "mnist_model.h5"
|
| 21 |
+
|
| 22 |
+
print(f"Loading model from: {model_path}")
|
| 23 |
+
model = load_model(model_path, compile=False)
|
| 24 |
+
model.compile(optimizer='adam',
|
| 25 |
+
loss='sparse_categorical_crossentropy',
|
| 26 |
+
metrics=['accuracy'])
|
| 27 |
+
print("✅ Model loaded successfully!")
|
| 28 |
+
print(f"Input shape: {model.input_shape}")
|
| 29 |
except Exception as e:
|
| 30 |
+
print(f"❌ Failed to load model: {e}")
|
| 31 |
+
raise RuntimeError(f"Model loading error: {e}")
|
| 32 |
|
|
|
|
| 33 |
@app.get("/")
|
| 34 |
def read_root():
|
| 35 |
+
return {"message": "MNIST API is running. POST to /predict/"}
|
|
|
|
|
|
|
| 36 |
|
|
|
|
|
|
|
| 37 |
@app.post("/predict/")
|
| 38 |
async def predict_digit(file: UploadFile = File(...)):
|
|
|
|
| 39 |
if not file.content_type.startswith("image/"):
|
| 40 |
+
raise HTTPException(400, "File must be an image")
|
| 41 |
|
| 42 |
try:
|
|
|
|
| 43 |
contents = await file.read()
|
| 44 |
image = Image.open(io.BytesIO(contents)).convert("L")
|
|
|
|
|
|
|
| 45 |
image = image.resize((28, 28))
|
| 46 |
+
|
|
|
|
| 47 |
image_array = np.array(image).astype("float32") / 255.0
|
|
|
|
|
|
|
| 48 |
image_array = image_array.reshape(1, 784)
|
| 49 |
|
|
|
|
| 50 |
prediction_probs = model.predict(image_array, verbose=0)
|
| 51 |
predicted_class = int(np.argmax(prediction_probs))
|
| 52 |
confidence = float(np.max(prediction_probs))
|
|
|
|
| 56 |
"predicted_digit": predicted_class,
|
| 57 |
"confidence": round(confidence, 4)
|
| 58 |
}
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
+
raise HTTPException(500, f"Processing error: {str(e)}")
|