File size: 1,833 Bytes
6666885
 
 
49c15d7
6666885
8a4b60f
 
 
 
 
 
 
 
6666885
 
 
 
40ba247
 
6666885
40ba247
6666885
 
 
 
 
 
 
 
 
 
8a4b60f
 
 
40ba247
 
8a4b60f
40ba247
 
 
 
 
 
 
8a4b60f
 
 
40ba247
8a4b60f
 
 
 
 
40ba247
 
 
8a4b60f
6666885
 
49c15d7
6666885
49c15d7
6666885
 
8a4b60f
6666885
 
49c15d7
 
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
import tensorflow as tf
import numpy as np
import cv2
import gradio as gr

# Load model once at startup
try:
    model = tf.keras.models.load_model('eyeStateModel.h5', compile=False)
    print("Model loaded successfully!")
except Exception as e:
    print(f"Error loading model: {str(e)}")
    model = None

def preprocess_image(image):
    # Convert to RGB if needed
    if len(image.shape) == 2:
        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
    elif len(image.shape) == 3 and image.shape[2] == 4:
        image = cv2.cvtColor(image, cv2.COLOR_BGRA2RGB)
    
    # Resize image to 224x224
    image = cv2.resize(image, (224, 224))
    
    # Normalize pixel values
    image = image / 255.0
    
    # Add batch dimension
    image = np.expand_dims(image, axis=0)
    return image

def predict_eye_state(image):
    if model is None:
        return {"Error": 1.0}
        
    try:
        if image is None:
            return {"Error": 1.0}
        
        # Preprocess the image
        processed_image = preprocess_image(image)
        
        # Make prediction
        prediction = model.predict(processed_image)
        
        # Get confidence scores
        closed_conf = float(prediction[0][0])
        open_conf = float(prediction[0][1])
        
        # Return dictionary with numeric values
        return {
            "Eyes Closed": closed_conf,
            "Eyes Open": open_conf
        }
        
    except Exception as e:
        print(f"Error in prediction: {str(e)}")
        return {"Error": 1.0}

# Create Gradio interface
demo = gr.Interface(
    fn=predict_eye_state,
    inputs=gr.Image(),
    outputs=gr.Label(num_top_classes=2),
    title="Eye State Detection",
    description="Upload an image of eyes to detect if they are open or closed."
)

if __name__ == "__main__":
    demo.launch()