David Driscoll commited on
Commit
e5a1544
·
1 Parent(s): 81307fe

Added Gradio multi-analysis app

Browse files
Files changed (2) hide show
  1. app.py +156 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ from torchvision import models, transforms
6
+ from PIL import Image
7
+ import mediapipe as mp
8
+ from fer import FER # Facial emotion recognition
9
+
10
+ # -----------------------------
11
+ # Initialize Models and Helpers
12
+ # -----------------------------
13
+
14
+ # MediaPipe Pose for posture analysis
15
+ mp_pose = mp.solutions.pose
16
+ pose = mp_pose.Pose()
17
+ mp_drawing = mp.solutions.drawing_utils
18
+
19
+ # MediaPipe Face Detection for face detection
20
+ mp_face_detection = mp.solutions.face_detection
21
+ face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.5)
22
+
23
+ # Object Detection Model: Faster R-CNN (pretrained on COCO)
24
+ object_detection_model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
25
+ object_detection_model.eval()
26
+ obj_transform = transforms.Compose([transforms.ToTensor()])
27
+
28
+ # Facial Emotion Detection using FER (this model will detect emotions from a face)
29
+ emotion_detector = FER(mtcnn=True)
30
+
31
+ # -----------------------------
32
+ # Define Analysis Functions
33
+ # -----------------------------
34
+
35
+ def analyze_posture(frame_rgb, output_frame):
36
+ """Runs pose estimation and draws landmarks on the frame."""
37
+ pose_results = pose.process(frame_rgb)
38
+ posture_text = "No posture detected"
39
+ if pose_results.pose_landmarks:
40
+ posture_text = "Posture detected"
41
+ # Draw the pose landmarks on the output image (convert back to BGR for OpenCV)
42
+ mp_drawing.draw_landmarks(
43
+ output_frame, pose_results.pose_landmarks, mp_pose.POSE_CONNECTIONS,
44
+ mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=2),
45
+ mp_drawing.DrawingSpec(color=(0, 0, 255), thickness=2)
46
+ )
47
+ return posture_text
48
+
49
+ def analyze_emotion(frame):
50
+ """Detects emotion from faces using FER. Returns the dominant emotion."""
51
+ # FER expects RGB images
52
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
53
+ emotions = emotion_detector.detect_emotions(frame_rgb)
54
+ if emotions:
55
+ # Use the first detected face and its top emotion
56
+ top_emotion, score = max(emotions[0]["emotions"].items(), key=lambda x: x[1])
57
+ emotion_text = f"{top_emotion} ({score:.2f})"
58
+ else:
59
+ emotion_text = "No face detected for emotion analysis"
60
+ return emotion_text
61
+
62
+ def analyze_objects(frame_rgb, output_frame):
63
+ """Performs object detection and draws bounding boxes for detections above a threshold."""
64
+ image_pil = Image.fromarray(frame_rgb)
65
+ img_tensor = obj_transform(image_pil)
66
+ with torch.no_grad():
67
+ detections = object_detection_model([img_tensor])[0]
68
+
69
+ threshold = 0.8
70
+ detected_boxes = detections["boxes"][detections["scores"] > threshold]
71
+ for box in detected_boxes:
72
+ box = box.int().cpu().numpy()
73
+ cv2.rectangle(output_frame, (box[0], box[1]), (box[2], box[3]), (255, 255, 0), 2)
74
+ object_text = f"Detected {len(detected_boxes)} object(s)" if len(detected_boxes) else "No objects detected"
75
+ return object_text
76
+
77
+ def analyze_faces(frame_rgb, output_frame):
78
+ """Detects faces using MediaPipe and draws bounding boxes."""
79
+ face_results = face_detection.process(frame_rgb)
80
+ face_text = "No faces detected"
81
+ if face_results.detections:
82
+ face_text = f"Detected {len(face_results.detections)} face(s)"
83
+ h, w, _ = output_frame.shape
84
+ for detection in face_results.detections:
85
+ bbox = detection.location_data.relative_bounding_box
86
+ x = int(bbox.xmin * w)
87
+ y = int(bbox.ymin * h)
88
+ box_w = int(bbox.width * w)
89
+ box_h = int(bbox.height * h)
90
+ cv2.rectangle(output_frame, (x, y), (x + box_w, y + box_h), (0, 0, 255), 2)
91
+ return face_text
92
+
93
+ # -----------------------------
94
+ # Main Analysis Function
95
+ # -----------------------------
96
+
97
+ def analyze_webcam(frame):
98
+ """
99
+ Runs posture analysis, facial emotion analysis, object detection, and face detection
100
+ on the given webcam frame. Returns an annotated image and a textual summary.
101
+ """
102
+ if frame is None:
103
+ return None, "No frame provided."
104
+
105
+ # The input frame is in BGR (as from OpenCV). Create a copy for drawing.
106
+ output_frame = frame.copy()
107
+
108
+ # Convert frame to RGB for analysis
109
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
110
+
111
+ # Run analyses
112
+ posture_result = analyze_posture(frame_rgb, output_frame)
113
+ emotion_result = analyze_emotion(frame)
114
+ object_result = analyze_objects(frame_rgb, output_frame)
115
+ face_result = analyze_faces(frame_rgb, output_frame)
116
+
117
+ # Compose the result summary text
118
+ summary = (
119
+ f"Posture Analysis: {posture_result}\n"
120
+ f"Emotion Analysis: {emotion_result}\n"
121
+ f"Object Detection: {object_result}\n"
122
+ f"Face Detection: {face_result}"
123
+ )
124
+
125
+ # Optionally, overlay some of the summary text on the image
126
+ cv2.putText(output_frame, f"Emotion: {emotion_result}", (10, 30),
127
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
128
+ cv2.putText(output_frame, f"Objects: {object_result}", (10, 70),
129
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
130
+ cv2.putText(output_frame, f"Faces: {face_result}", (10, 110),
131
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
132
+
133
+ return output_frame, summary
134
+
135
+ # -----------------------------
136
+ # Gradio Interface Setup
137
+ # -----------------------------
138
+
139
+ # We output both an image (with drawn annotations) and a text summary.
140
+ interface = gr.Interface(
141
+ fn=analyze_webcam,
142
+ inputs=gr.Image(source="webcam", streaming=True, label="Webcam Feed"),
143
+ outputs=[
144
+ gr.Image(type="numpy", label="Annotated Output"),
145
+ gr.Textbox(label="Analysis Summary")
146
+ ],
147
+ title="Real-Time Multi-Analysis App",
148
+ description=(
149
+ "This app performs real-time posture analysis, facial emotion detection, "
150
+ "object detection, and face detection using your webcam."
151
+ ),
152
+ live=True
153
+ )
154
+
155
+ if __name__ == "__main__":
156
+ interface.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ torchvision
4
+ opencv-python
5
+ numpy
6
+ mediapipe
7
+ Pillow
8
+ fer