Deevyankar commited on
Commit
752e7ef
Β·
verified Β·
1 Parent(s): 404cd12

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -50
app.py CHANGED
@@ -5,20 +5,29 @@ import pickle
5
  import torch
6
  import time
7
  import pandas as pd
8
- import sklearn
 
 
 
 
 
 
 
 
9
 
10
  # Load ML model
11
  model = pickle.load(open('model.pkl', 'rb'))
12
 
13
- # Load YOLOv7 model (COCO pretrained: person=0, cellphone=67)
14
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
15
- yolo_model = torch.hub.load('WongKinYiu/yolov7', 'custom', 'yolov7.pt', source='local').to(device)
 
16
 
17
  # Streamlit UI setup
18
- st.set_page_config(page_title="YOLOv7 Attention Detector", layout='wide')
19
- st.title("πŸŽ₯ Real-Time Attention Detector (YOLOv7 Face + Phone)")
20
-
21
  run = st.checkbox('Start Webcam')
 
22
  FRAME_WINDOW = st.image([])
23
  attention_log = []
24
  start_time = time.time()
@@ -31,46 +40,28 @@ if run:
31
  st.warning("⚠️ Cannot access webcam.")
32
  break
33
 
34
- h, w, _ = frame.shape
35
-
36
- # YOLOv7 detection (face + phone)
37
- results = yolo_model([frame])
38
- faces, phones = [], []
39
-
40
- for det in results.xyxy[0]:
41
- x1, y1, x2, y2, conf, cls = map(float, det[:6])
42
- cls_id = int(cls)
43
- if cls_id == 0: # person β†’ treat as face
44
- faces.append((int(x1), int(y1), int(x2 - x1), int(y2 - y1), conf))
45
- if cls_id == 67: # cellphone
46
- phones.append((int(x1), int(y1), int(x2 - x1), int(y2 - y1), conf))
47
-
48
- for i, (face_x, face_y, face_w, face_h, face_conf) in enumerate(faces):
49
- pose_x, pose_y = face_x + face_w // 2, face_y + face_h // 2
50
-
51
- phone_detected = int(any(
52
- face_x < p[0] + p[2] < face_x + face_w and face_y < p[1] + p[3] < face_y + face_h
53
- for p in phones
54
- ))
55
-
56
- if phones:
57
- phone_x, phone_y, phone_w, phone_h, phone_conf = phones[0]
58
- else:
59
- phone_x, phone_y, phone_w, phone_h, phone_conf = 0, 0, 0, 0, 0
60
-
61
- feature_vector = np.array([[1, face_x, face_y, face_w, face_h, face_conf,
62
- 0, 0, pose_x, pose_y, phone_detected,
63
- phone_x, phone_y, phone_w, phone_h, 0.8]])
64
-
65
- pred = model.predict(feature_vector)[0]
66
- attention_text = 'Attentive' if pred == 0 else 'Inattentive'
67
-
68
- attention_log.append({'face_id': i + 1, 'time': time.time() - start_time, 'state': attention_text})
69
-
70
- color = (0, 255, 0) if pred == 0 else (0, 0, 255)
71
- cv2.rectangle(frame, (face_x, face_y), (face_x + face_w, face_y + face_h), color, 2)
72
- cv2.putText(frame, f'Face {i + 1}: {attention_text}', (face_x, face_y - 10),
73
- cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
74
 
75
  FRAME_WINDOW.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
76
 
@@ -79,14 +70,14 @@ if run:
79
 
80
  cap.release()
81
 
82
- # Dashboard
83
  if attention_log:
84
  df = pd.DataFrame(attention_log)
85
  attentive = df[df['state'] == 'Attentive'].shape[0]
86
  inattentive = df[df['state'] == 'Inattentive'].shape[0]
87
  st.markdown("### πŸ“Š Attention Statistics")
88
- st.write(f"βœ… Attentive: {attentive}")
89
- st.write(f"⚠️ Inattentive: {inattentive}")
90
  st.dataframe(df.tail(10))
91
  st.line_chart(df.groupby('time')['state'].apply(lambda x: (x == 'Attentive').mean()))
92
  st.download_button("Download Log as CSV", df.to_csv(index=False), file_name="attention_log.csv")
 
5
  import torch
6
  import time
7
  import pandas as pd
8
+ import sys
9
+ import os
10
+
11
+ # Add YOLOv7 repository to the system path
12
+ sys.path.append(os.path.join(os.getcwd(), 'yolov7'))
13
+
14
+ from models.experimental import attempt_load
15
+ from utils.general import non_max_suppression, scale_coords
16
+ from utils.datasets import letterbox
17
 
18
  # Load ML model
19
  model = pickle.load(open('model.pkl', 'rb'))
20
 
21
+ # Load YOLOv7 model
22
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
23
+ yolo_model = attempt_load('yolov7.pt', map_location=device)
24
+ yolo_model.eval()
25
 
26
  # Streamlit UI setup
27
+ st.set_page_config(page_title="Multi-Face Attention Detector", layout='wide')
28
+ st.title("πŸŽ₯ Real-Time Multi-Face Attention Detector")
 
29
  run = st.checkbox('Start Webcam')
30
+
31
  FRAME_WINDOW = st.image([])
32
  attention_log = []
33
  start_time = time.time()
 
40
  st.warning("⚠️ Cannot access webcam.")
41
  break
42
 
43
+ img = letterbox(frame, new_shape=640)[0]
44
+ img = img[:, :, ::-1].transpose(2, 0, 1)
45
+ img = np.ascontiguousarray(img)
46
+ img = torch.from_numpy(img).to(device)
47
+ img = img.float()
48
+ img /= 255.0
49
+ if img.ndimension() == 3:
50
+ img = img.unsqueeze(0)
51
+
52
+ # Inference
53
+ pred = yolo_model(img)[0]
54
+ pred = non_max_suppression(pred, 0.25, 0.45, classes=None, agnostic=False)
55
+
56
+ # Process detections
57
+ for i, det in enumerate(pred):
58
+ if len(det):
59
+ det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
60
+ for *xyxy, conf, cls in reversed(det):
61
+ label = f'{int(cls)} {conf:.2f}'
62
+ cv2.rectangle(frame, (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]), int(xyxy[3])), (0, 255, 0), 2)
63
+ cv2.putText(frame, label, (int(xyxy[0]), int(xyxy[1]) - 10),
64
+ cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  FRAME_WINDOW.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
67
 
 
70
 
71
  cap.release()
72
 
73
+ # Process log for dashboard
74
  if attention_log:
75
  df = pd.DataFrame(attention_log)
76
  attentive = df[df['state'] == 'Attentive'].shape[0]
77
  inattentive = df[df['state'] == 'Inattentive'].shape[0]
78
  st.markdown("### πŸ“Š Attention Statistics")
79
+ st.write(f"βœ… Attentive detections: {attentive}")
80
+ st.write(f"⚠️ Inattentive detections: {inattentive}")
81
  st.dataframe(df.tail(10))
82
  st.line_chart(df.groupby('time')['state'].apply(lambda x: (x == 'Attentive').mean()))
83
  st.download_button("Download Log as CSV", df.to_csv(index=False), file_name="attention_log.csv")