File size: 2,173 Bytes
860a2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from fastapi import FastAPI, File, UploadFile
import tensorflow as tf
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import numpy as np
from PIL import Image, UnidentifiedImageError

# Model yükleme
try:
    model = tf.keras.models.load_model("face_shape_model.h5")
except Exception as e:
    raise RuntimeError(f"Model loading failed: {str(e)}")

# Sınıf isimleri
class_names = ['Heart', 'Oblong', 'Oval', 'Round', 'Square']

# FastAPI uygulamasını başlat
app = FastAPI()


# Resmi yükle ve ön işle
def load_and_preprocess_image(image):
    try:
        # Eğer resim RGBA veya diğer modda ise RGB'ye çevir
        if image.mode != "RGB":
            image = image.convert("RGB")

        # Resmi yeniden boyutlandır
        img = image.resize((224, 224))
        # Array'e çevir ve normalize et
        img_array = img_to_array(img) / 255.0
        # Batch boyutunu ekle
        img_array = np.expand_dims(img_array, axis=0)
        return img_array
    except Exception as e:
        raise ValueError(f"Preprocessing error: {str(e)}")


@app.post("/predict/")
async def predict(file: UploadFile = File(...)):
    try:
        # Yüklenen dosyayı aç
        try:
            image = Image.open(file.file)
        except UnidentifiedImageError as e:
            return {"error": f"Invalid image file: {str(e)}"}

        # Resmi yükle ve ön işle
        img_array = load_and_preprocess_image(image)

        # Tahmin yap
        predictions = model.predict(img_array, verbose=0)
        predicted_class = class_names[np.argmax(predictions[0])]
        confidence = np.max(predictions[0]) * 100

        # Tüm sınıfların olasılıklarını hesapla
        class_probabilities = {
            class_names[i]: float(predictions[0][i] * 100)
            for i in range(len(class_names))
        }

        return {
            "predicted_class": predicted_class,
            "confidence": f"{confidence:.2f}%",
            "class_probabilities": class_probabilities
        }

    except Exception as e:
        return {"error": f"Prediction failed: {str(e)}"}