ktejeshnaidu commited on
Commit
71c1ed1
·
verified ·
1 Parent(s): a8faaa3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -131
app.py CHANGED
@@ -1,132 +1,121 @@
1
- import gradio as gr
2
- import cv2
3
- import numpy as np
4
- from model import EmotionPredictor
5
-
6
-
7
- # Initialize the predictor
8
- predictor = EmotionPredictor()
9
-
10
- # Load Haar Cascade for face detection
11
- face_cascade = cv2.CascadeClassifier(
12
- cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
13
- )
14
-
15
- if face_cascade.empty():
16
- raise RuntimeError("Failed to load Haar Cascade")
17
-
18
-
19
- def predict_emotion(image):
20
- """
21
- Predict emotion from an image.
22
-
23
- Args:
24
- image: PIL Image or numpy array
25
-
26
- Returns:
27
- annotated image and emotion prediction
28
- """
29
- if image is None:
30
- return None, "No image provided"
31
-
32
- # Convert PIL Image to numpy array if needed
33
- if isinstance(image, np.ndarray):
34
- frame = image
35
- else:
36
- frame = np.array(image)
37
-
38
- # Convert RGB to BGR for OpenCV
39
- if len(frame.shape) == 3 and frame.shape[2] == 3:
40
- frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
41
- else:
42
- frame_bgr = frame
43
-
44
- # Convert to grayscale for face detection
45
- gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
46
-
47
- # Detect faces
48
- detected = face_cascade.detectMultiScale(
49
- gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
50
- )
51
-
52
- if len(detected) == 0:
53
- return frame, "No face detected"
54
-
55
- # Get the largest face
56
- faces = [max(detected, key=lambda r: r[2]*r[3])]
57
-
58
- # Process the face
59
- output_frame = frame_bgr.copy()
60
- emotions = []
61
-
62
- for (x, y, w, h) in faces:
63
- # Extract face region
64
- face_rgb = cv2.cvtColor(frame_bgr[y:y+h, x:x+w], cv2.COLOR_BGR2RGB)
65
-
66
- # Predict emotion
67
- emotion = predictor.predict(face_rgb)
68
- emotions.append(emotion)
69
-
70
- # Draw rectangle and label
71
- cv2.rectangle(output_frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
72
- cv2.putText(
73
- output_frame, emotion, (x, y - 10),
74
- cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2
75
- )
76
-
77
- # Convert back to RGB for display
78
- output_frame_rgb = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB)
79
-
80
- # Return annotated image and detected emotion
81
- emotion_text = ", ".join(emotions) if emotions else "No emotion detected"
82
-
83
- return output_frame_rgb, f"Detected emotion(s): {emotion_text}"
84
-
85
-
86
- # Create Gradio interface
87
- with gr.Blocks(title="Smilo😃 - Real-Time Emotion Detection") as demo:
88
- gr.HTML("""
89
- <div style="background: linear-gradient(90deg, #FF9933 0%, #D0B264 50%, #469F93 100%);
90
- padding: 40px;
91
- border-radius: 12px;
92
- text-align: center;
93
- color: white;
94
- font-family: 'Helvetica Neue', Arial, sans-serif;
95
- margin-bottom: 20px;">
96
- <h1 style="color: white; margin: 0; margin-bottom: 10px; font-weight: 900; font-size: 3.5em; display: flex; align-items: center; justify-content: center; gap: 10px;">
97
- Smilo <span style="font-size: 0.9em;">😃</span>
98
- </h1>
99
- <p style="color: #f0f0f0; font-size: 1.2em; margin: 0; font-weight: 400; letter-spacing: 0.5px;">Real-Time Emotion Detection powered by PyTorch</p>
100
- </div>
101
- """)
102
-
103
- with gr.Row():
104
- with gr.Column():
105
- image_input = gr.Image(
106
- label="Input Image",
107
- type="pil",
108
- sources=["upload", "webcam"]
109
- )
110
- submit_btn = gr.Button("Predict Emotion", variant="primary")
111
-
112
- with gr.Column():
113
- image_output = gr.Image(label="Annotated Image")
114
- emotion_output = gr.Textbox(label="Prediction Result", interactive=False)
115
-
116
- # Connect the function to the button
117
- submit_btn.click(
118
- fn=predict_emotion,
119
- inputs=[image_input],
120
- outputs=[image_output, emotion_output]
121
- )
122
-
123
- # Also run prediction when image is uploaded
124
- image_input.change(
125
- fn=predict_emotion,
126
- inputs=[image_input],
127
- outputs=[image_output, emotion_output]
128
- )
129
-
130
-
131
- if __name__ == "__main__":
132
  demo.launch()
 
1
+ import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
+ from model import EmotionPredictor
5
+
6
+ # Initialize the predictor
7
+ predictor = EmotionPredictor()
8
+
9
+ # Load Haar Cascade for face detection
10
+ face_cascade = cv2.CascadeClassifier(
11
+ cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
12
+ )
13
+
14
+ if face_cascade.empty():
15
+ raise RuntimeError("Failed to load Haar Cascade")
16
+
17
+ def predict_emotion(image):
18
+ """
19
+ Predict emotion from an image.
20
+
21
+ Args:
22
+ image: PIL Image or numpy array
23
+
24
+ Returns:
25
+ annotated image and emotion prediction
26
+ """
27
+ if image is None:
28
+ return None, "No image provided"
29
+
30
+ # Convert PIL Image to numpy array if needed
31
+ if isinstance(image, np.ndarray):
32
+ frame = image
33
+ else:
34
+ frame = np.array(image)
35
+
36
+ # Convert RGB to BGR for OpenCV
37
+ if len(frame.shape) == 3 and frame.shape[2] == 3:
38
+ frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
39
+ else:
40
+ frame_bgr = frame
41
+
42
+ # Convert to grayscale for face detection
43
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
44
+
45
+ # Detect faces
46
+ detected = face_cascade.detectMultiScale(
47
+ gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)
48
+ )
49
+
50
+ if len(detected) == 0:
51
+ return frame, "No face detected"
52
+
53
+ # Get the largest face
54
+ faces = [max(detected, key=lambda r: r[2]*r[3])]
55
+
56
+ # Process the face
57
+ output_frame = frame_bgr.copy()
58
+ emotions = []
59
+
60
+ for (x, y, w, h) in faces:
61
+ # Extract face region
62
+ face_rgb = cv2.cvtColor(frame_bgr[y:y+h, x:x+w], cv2.COLOR_BGR2RGB)
63
+
64
+ # Predict emotion
65
+ emotion = predictor.predict(face_rgb)
66
+ emotions.append(emotion)
67
+
68
+ # Draw rectangle and label
69
+ cv2.rectangle(output_frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
70
+ cv2.putText(
71
+ output_frame, emotion, (x, y - 10),
72
+ cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2
73
+ )
74
+
75
+ # Convert back to RGB for display
76
+ output_frame_rgb = cv2.cvtColor(output_frame, cv2.COLOR_BGR2RGB)
77
+
78
+ # Return annotated image and detected emotion
79
+ emotion_text = ", ".join(emotions) if emotions else "No emotion detected"
80
+
81
+ return output_frame_rgb, f"Detected emotion(s): {emotion_text}"
82
+
83
+ # Create Gradio interface
84
+ with gr.Blocks(title="Smilo😃 - Real-Time Emotion Detection") as demo:
85
+ gr.HTML("""
86
+ <div style="background: linear-gradient(90deg, #FF9933 0%, #D0B264 50%, #469F93 100%);
87
+ padding: 40px;
88
+ border-radius: 12px;
89
+ text-align: center;
90
+ color: white;
91
+ font-family: 'Helvetica Neue', Arial, sans-serif;
92
+ margin-bottom: 20px;">
93
+ <h1 style="color: white; margin: 0; margin-bottom: 10px; font-weight: 900; font-size: 3.5em; display: flex; align-items: center; justify-content: center; gap: 10px;">
94
+ Smilo <span style="font-size: 0.9em;">😃</span>
95
+ </h1>
96
+ <p style="color: #f0f0f0; font-size: 1.2em; margin: 0; font-weight: 400; letter-spacing: 0.5px;">Real-Time Emotion Detection powered by PyTorch</p>
97
+ </div>
98
+ """)
99
+
100
+ with gr.Row():
101
+ with gr.Column():
102
+ image_input = gr.Image(
103
+ label="Input Image",
104
+ type="pil",
105
+ sources=["upload", "webcam"]
106
+ )
107
+ submit_btn = gr.Button("Predict Emotion", variant="primary")
108
+
109
+ with gr.Column():
110
+ image_output = gr.Image(label="Annotated Image")
111
+ emotion_output = gr.Textbox(label="Prediction Result", interactive=False)
112
+
113
+ # Connect the function strictly to the button to prevent webcam API spam
114
+ submit_btn.click(
115
+ fn=predict_emotion,
116
+ inputs=[image_input],
117
+ outputs=[image_output, emotion_output]
118
+ )
119
+
120
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
121
  demo.launch()