File size: 1,907 Bytes
ef500f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from fastapi import FastAPI, UploadFile, File, HTTPException
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
import io

# Initialize FastAPI app
app = FastAPI(title="MNIST Digit Classifier API by Muhammad Taha Sattar Arain", version="1.0")

# Load the trained model globally so it only loads once on startup
try:
    model = load_model("mnist_model.keras")
except Exception as e:
    raise RuntimeError(f"Error loading model: {e}")

@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 the uploaded file into memory
        contents = await file.read()
        image = Image.open(io.BytesIO(contents))
        
        # Preprocessing: Match the notebook's logic
        # 1. Convert to grayscale
        image = image.convert('L')
        # 2. Resize to 28x28 (MNIST standard)
        image = image.resize((28, 28))
        # 3. Convert to numpy array and normalize
        image_array = np.array(image).astype('float32') / 255.0
        # 4. Reshape to match the Dense layer input (1, 784)
        image_array = image_array.reshape(1, 784)
        
        # Make prediction
        prediction_probs = model.predict(image_array)
        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)}")

# Health check endpoint
@app.get("/")
def read_root():
    return {"message": "MNIST Classification API is running. Send POST requests to /predict/"}