CoolFace
Apppublic

Danial69749/Digit_recognition

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
main.py59 linesDownload Raw Back to root
1from fastapi import FastAPI, UploadFile, File2from fastapi.responses import HTMLResponse3import numpy as np4from PIL import Image5import io6from tensorflow import keras7 8# Load model9model = keras.models.load_model('mnist_cnn_model.h5')10 11# Class labels (ordered list)12class_labels = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]13 14# Initialize FastAPI app15app = FastAPI()16 17# Preprocess function18from PIL import ImageOps19 20def preprocess_image(image_bytes):21    image = Image.open(io.BytesIO(image_bytes)).convert('L')  # Grayscale22    image = ImageOps.invert(image)  # Invert black/white23    image = image.resize((28, 28))24    img_array = np.array(image) / 255.025    img_array = np.expand_dims(img_array, axis=-1)  # (28, 28, 1)26    img_array = np.expand_dims(img_array, axis=0)   # (1, 28, 28, 1)27    return img_array28 29 30 31# Root endpoint - optional HTML form32@app.get("/", response_class=HTMLResponse)33async def root():34    return """35    <html>36        <head>37            <title>MNIST Predictor</title>38        </head>39        <body>40            <h2>Upload an image to predict</h2>41            <form action="/predict" enctype="multipart/form-data" method="post">42                <input name="file" type="file" accept="image/*">43                <input type="submit" value="Predict">44            </form>45        </body>46    </html>47    """48 49# Prediction endpoint50@app.post("/predict")51async def predict(file: UploadFile = File(...)):52    image_bytes = await file.read()53    img_array = preprocess_image(image_bytes)54    predictions = model.predict(img_array)55    predicted_class = class_labels[np.argmax(predictions)]56    confidence = float(np.max(predictions))57    return {"prediction": predicted_class, "confidence": confidence}58 59