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)}"}