Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
+
from fastapi.responses import HTMLResponse
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# Load your model once at startup
|
| 12 |
+
model = tf.keras.models.load_model("keras_model.h5")
|
| 13 |
+
labels = ["Good Posture", "Bad Posture"]
|
| 14 |
+
|
| 15 |
+
# Serve frontend files from /static
|
| 16 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 17 |
+
|
| 18 |
+
@app.get("/", response_class=HTMLResponse)
|
| 19 |
+
async def root():
|
| 20 |
+
# Redirect to your static index.html
|
| 21 |
+
with open("static/index.html", "r") as f:
|
| 22 |
+
html = f.read()
|
| 23 |
+
return html
|
| 24 |
+
|
| 25 |
+
@app.post("/predict")
|
| 26 |
+
async def predict(file: UploadFile = File(...)):
|
| 27 |
+
# Read image bytes from upload
|
| 28 |
+
img_bytes = await file.read()
|
| 29 |
+
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
| 30 |
+
img = img.resize((224, 224))
|
| 31 |
+
img_array = np.array(img) / 255.0
|
| 32 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 33 |
+
|
| 34 |
+
# Predict
|
| 35 |
+
prediction = model.predict(img_array)[0]
|
| 36 |
+
top_index = np.argmax(prediction)
|
| 37 |
+
label = labels[top_index]
|
| 38 |
+
confidence = float(prediction[top_index])
|
| 39 |
+
|
| 40 |
+
return {"label": label, "confidence": confidence}
|