Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from tensorflow.keras.models import load_model
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
app = FastAPI(title="OralScan Model API")
|
| 11 |
+
|
| 12 |
+
# Load the model when the app starts
|
| 13 |
+
model = None
|
| 14 |
+
|
| 15 |
+
@app.on_event("startup")
|
| 16 |
+
async def load_model_on_startup():
|
| 17 |
+
global model
|
| 18 |
+
try:
|
| 19 |
+
model = load_model("model.keras")
|
| 20 |
+
print("✅ MobileNetV2 model loaded successfully!")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"❌ Error loading model: {e}")
|
| 23 |
+
|
| 24 |
+
@app.get("/")
|
| 25 |
+
def home():
|
| 26 |
+
return {"message": "OralScan Model API is running! Upload image to /predict"}
|
| 27 |
+
|
| 28 |
+
@app.post("/predict")
|
| 29 |
+
async def predict(file: UploadFile = File(...)):
|
| 30 |
+
if model is None:
|
| 31 |
+
raise HTTPException(status_code=500, detail="Model not loaded yet")
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
# Read uploaded image
|
| 35 |
+
contents = await file.read()
|
| 36 |
+
img = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 37 |
+
|
| 38 |
+
# Resize to 224x224 (what MobileNetV2 expects)
|
| 39 |
+
img = img.resize((224, 224))
|
| 40 |
+
|
| 41 |
+
# Preprocess
|
| 42 |
+
img_array = image.img_to_array(img)
|
| 43 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 44 |
+
img_array = img_array / 255.0
|
| 45 |
+
|
| 46 |
+
# Predict
|
| 47 |
+
predictions = model.predict(img_array)
|
| 48 |
+
predicted_class = int(np.argmax(predictions[0]))
|
| 49 |
+
confidence = float(np.max(predictions[0]) * 100)
|
| 50 |
+
|
| 51 |
+
# Change these class names to match your actual 3 classes
|
| 52 |
+
class_names = ["Healthy", "Mild Condition", "Severe Condition"]
|
| 53 |
+
|
| 54 |
+
return {
|
| 55 |
+
"predicted_class": predicted_class,
|
| 56 |
+
"class_name": class_names[predicted_class],
|
| 57 |
+
"confidence": round(confidence, 2),
|
| 58 |
+
"message": "Prediction successful"
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
raise HTTPException(status_code=400, detail=f"Error processing image: {str(e)}")
|