funterpie's picture
Update main.py
c128a33 verified
Raw History Blame Contribute Delete
2.61 kB
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import numpy as np
import io
app = FastAPI(title="MNIST Digit Classifier API", version="1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
model = None
def build_model():
"""Rebuild model architecture and load weights only β€” avoids Keras version issues."""
import tensorflow as tf
m = tf.keras.Sequential([
tf.keras.layers.Input(shape=(784,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax'),
])
m.load_weights("mnist_model_fixed.h5", by_name=False, skip_mismatch=False)
return m
@app.on_event("startup")
def load_model_on_startup():
global model
try:
model = build_model()
print("βœ… Model loaded via weights-only approach!")
except Exception as e:
print(f"❌ Weights load failed, trying full load: {e}")
try:
import tensorflow as tf
model = tf.keras.models.load_model("mnist_model_fixed.h5", compile=False)
print("βœ… Model loaded via full load!")
except Exception as e2:
print(f"❌ Both methods failed: {e2}")
raise RuntimeError(f"Model loading failed: {e2}")
@app.get("/")
def read_root():
return {
"message": "MNIST Classification API is running. Send POST requests to /predict/",
"author": "Muhammad Taha Sattar Arain β€” Alpha Orbit"
}
@app.post("/predict/")
async def predict_digit(file: UploadFile = File(...)):
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File provided is not an image.")
try:
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert("L")
image = image.resize((28, 28))
image_array = np.array(image).astype("float32") / 255.0
image_array = image_array.reshape(1, 784)
prediction_probs = model.predict(image_array, verbose=0)
predicted_class = int(np.argmax(prediction_probs))
confidence = float(np.max(prediction_probs))
return {
"filename": file.filename,
"predicted_digit": predicted_class,
"confidence": round(confidence, 4),
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")