Spaces:
Sleeping
Sleeping
Update main.py
Browse files5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051523 unmodified lines56575859605 unmodified linesimport numpy as npimport ioapp = FastAPI(title="MNIST Digit Classifier API", version="1.0")model = None@app.on_event("startup")def load_model_on_startup():global modeltry:# Try .keras first, fallback to .h5model_path = "mnist_model.keras"if not os.path.exists(model_path):model_path = "mnist_model.h5"print(f"Loading model from: {model_path}")model = load_model(model_path, compile=False)model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])print("✅ Model loaded successfully!")print(f"Input shape: {model.input_shape}")except Exception as e:print(f"❌ Failed to load model: {e}")raise RuntimeError(f"Model loading error: {e}")@app.get("/")def read_root():return {"message": "MNIST API is running. POST to /predict/"}@app.post("/predict/")async def predict_digit(file: UploadFile = File(...)):if not file.content_type.startswith("image/"):raise HTTPException(400, "File must be 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.0image_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))3 unmodified lines"predicted_digit": predicted_class,"confidence": round(confidence, 4)}except Exception as e:raise HTTPException(500, f"Processing error: {str(e)}")5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879803 unmodified lines8485868788895 unmodified linesimport numpy as npimport io# Initialize FastAPI appapp = FastAPI(title="MNIST Digit Classifier API",version="1.0")# Global model variablemodel = None# Load model at startup@app.on_event("startup")def load_model_on_startup():global modeltry:# Prefer .keras (native Keras 3 format), fallback to .h5if os.path.exists("mnist_model.keras"):model_path = "mnist_model.keras"else:model_path = "mnist_model.h5"print(f"Loading model from: {model_path}")model = load_model(model_path, compile=False)# Recompile the modelmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])print("✅ Model loaded successfully!")print(f"Model input shape: {model.input_shape}")except Exception as e:print(f"❌ Failed to load model: {e}")raise RuntimeError(f"Error loading model: {e}")# Health check@app.get("/")def read_root():return {"message": "MNIST Classification API is running. Send POST requests to /predict/"}# Prediction endpoint@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:# Read imagecontents = await file.read()image = Image.open(io.BytesIO(contents)).convert("L")# Resize to MNIST format (28x28)image = image.resize((28, 28))# Convert to numpy array and normalizeimage_array = np.array(image).astype("float32") / 255.0# Flatten for the Dense modelimage_array = image_array.reshape(1, 784)# Predictprediction_probs = model.predict(image_array, verbose=0)predicted_class = int(np.argmax(prediction_probs))confidence = float(np.max(prediction_probs))3 unmodified lines"predicted_digit": predicted_class,"confidence": round(confidence, 4)}except Exception as e:raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
main.py+42-13