Spaces:
Sleeping
Sleeping
Download main.py from funterpie/MNIST_Digit_predictor: direct link, hf CLI and curl.
- Browser
- Download file 2.61 kB
-
https://huggingface.co/spaces/funterpie/MNIST_Digit_predictor/resolve/main/main.py
- Command line
-
hf download hf://spaces/funterpie/MNIST_Digit_predictor/main.py
-
curl -L -o main.py https://huggingface.co/spaces/funterpie/MNIST_Digit_predictor/resolve/main/main.py
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 | |
| 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}") | |
| def read_root(): | |
| return { | |
| "message": "MNIST Classification API is running. Send POST requests to /predict/", | |
| "author": "Muhammad Taha Sattar Arain β Alpha Orbit" | |
| } | |
| 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)}") |