funterpie commited on
Commit
2a2e48b
·
verified ·
1 Parent(s): db86a1b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +55 -29
main.py CHANGED
@@ -4,50 +4,76 @@ from PIL import Image
4
  import numpy as np
5
  import io
6
 
7
- # Initialize FastAPI app
8
- app = FastAPI(title="MNIST Digit Classifier API by Muhammad Taha Sattar Arain", version="1.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="File provided is not an image.")
20
 
21
  try:
22
- # Read the uploaded file into memory
23
  contents = await file.read()
24
- image = Image.open(io.BytesIO(contents))
25
-
26
- # Preprocessing: Match the notebook's logic
27
- # 1. Convert to grayscale
28
- image = image.convert('L')
29
- # 2. Resize to 28x28 (MNIST standard)
 
 
 
 
 
30
  image = image.resize((28, 28))
31
- # 3. Convert to numpy array and normalize
32
- image_array = np.array(image).astype('float32') / 255.0
33
- # 4. Reshape to match the Dense layer input (1, 784)
34
- image_array = image_array.reshape(1, 784)
35
-
36
- # Make prediction
37
- prediction_probs = model.predict(image_array)
 
 
 
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 Exception as e:
48
- raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
49
 
50
- # Health check endpoint
51
- @app.get("/")
52
- def read_root():
53
- return {"message": "MNIST Classification API is running. Send POST requests to /predict/"}
 
 
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
+ )