| from fastapi import FastAPI |
| from pydantic import BaseModel |
| import numpy as np |
| from tensorflow import keras |
| import os |
| from fastapi.middleware.cors import CORSMiddleware |
| app = FastAPI() |
|
|
|
|
|
|
| origins = [ |
| "https://namanrajput-git.github.io/RT_Digit_Recognizer-Frontend/", |
| |
| ] |
|
|
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_credentials=False, |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
|
|
| print("Current working directory:", os.getcwd()) |
| print("Files in app folder:", os.listdir(".")) |
|
|
|
|
| model_path = "best_model.h5" |
| model = keras.models.load_model(model_path) |
| class InputData(BaseModel): |
| pixels: list |
|
|
| @app.get("/") |
| def root(): |
| return {"message": "MNIST API running"} |
|
|
| @app.post("/predict") |
| def predict(data: InputData): |
| X = np.array(data.pixels).reshape(1, 28, 28, 1) / 255.0 |
| y_pred = model.predict(X) |
| predicted_class = int(np.argmax(y_pred, axis=1)[0]) |
| return {"prediction": predicted_class} |
|
|