ktejeshnaidu commited on
Commit
bce5327
·
verified ·
1 Parent(s): f9b64ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -0
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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(share=True)