File size: 1,910 Bytes
3a24a7b
 
55365d8
3a24a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55365d8
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
import os
import cv2
import numpy as np
from keras.models import load_model

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MODEL_PATH = os.path.join(BASE_DIR, 'data', 'model', 'retina.h5')
IMAGE_SIZE = (224, 224) # Standard per la maggior parte delle CNN (VGG/ResNet)

model = None

def load_resources():
    global model
    if model is None and os.path.exists(MODEL_PATH):
        try:
            print(f"Caricamento modello Retina da {MODEL_PATH}...")
            model = load_model(MODEL_PATH, compile=False)
            print("✅ Modello Retina caricato.")
        except Exception as e:
            print(f"❌ Errore caricamento modello Retina: {e}")

# Caricamento all'avvio
load_resources()

def predict_diabetic_retinopathy(image_array):
    # Restituiamo sempre DUE valori (Diagnosi, Percentuale) anche in caso di errore
    if model is None:
        return "❌ Errore: Modello non trovato", "0%"
    
    if image_array is None:
        return "⚠️ Nessuna immagine caricata", "0%"

    try:
        # 2. PREPROCESSING
        img_resized = cv2.resize(image_array, IMAGE_SIZE)
        img_normalized = img_resized.astype('float32') / 255.0
        img_batch = np.expand_dims(img_normalized, axis=0)

        # 3. PREDIZIONE
        prediction_score = model.predict(img_batch, verbose=0)[0][0]
        positive_prob = float(prediction_score)

        # 4. LOGICA DIAGNOSI
        if positive_prob > 0.5:
            diagnosis = "⚠️ Presenza Retinopatia Diabetica"
        else:
            diagnosis = "✅ Nessuna Retinopatia Diabetica"

        # 5. FORMATTAZIONE PERCENTUALE
        percentage = positive_prob * 100
        probability = f"{percentage:.2f}%" # Formattazione f-string più pulita

        return diagnosis, probability

    except Exception as e:
        print(f"Errore analisi retina: {e}")
        return "❌ Errore durante l'analisi", "0%"