File size: 1,584 Bytes
7fd55e3
f2f1372
7fd55e3
f2f1372
7fd55e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f1372
 
7fd55e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f1372
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from PIL import Image
import numpy as np
import tensorflow as tf
import pickle
import io

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.mount("/", StaticFiles(directory=".", html=True), name="static")

model = tf.keras.models.load_model("model_2.h5")
with open("label_encoder.pkl", "rb") as f:
    label_encoder = pickle.load(f)

class_names = label_encoder.inverse_transform(np.arange(len(label_encoder.classes_)))

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    contents = await file.read()
    image = Image.open(io.BytesIO(contents)).convert("RGB")
    image = image.resize((224, 224))
    img_array = np.array(image) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    prediction = model.predict(img_array)[0]
    predicted_index = np.argmax(prediction)
    predicted_label = class_names[predicted_index]
    confidence = float(prediction[predicted_index]) * 100

    all_probs = {
        class_names[i]: float(prob)
        for i, prob in enumerate(prediction)
    }

    return JSONResponse(content={
        "predicted_label": predicted_label,
        "confidence": round(confidence, 2),
        "all_probabilities": all_probs
    })

@app.get("/")
def redirect_to_ui():
    return RedirectResponse("/index.html")