SuriRaja commited on
Commit
de236dc
·
verified ·
1 Parent(s): 62b0fd7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -67
app.py CHANGED
@@ -1,74 +1,92 @@
1
-
2
- import os
3
  import cv2
 
 
 
 
4
  import mediapipe as mp
5
- import gradio as gr
6
- import shutil
7
- from datetime import datetime
8
 
9
- # Create output directory
10
- OUTPUT_DIR = "output_faces"
11
- if os.path.exists(OUTPUT_DIR):
12
- shutil.rmtree(OUTPUT_DIR)
13
- os.makedirs(OUTPUT_DIR)
14
 
 
15
  mp_face_detection = mp.solutions.face_detection
16
- mp_drawing = mp.solutions.drawing_utils
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def extract_faces_from_video(video_path):
19
- video_cap = cv2.VideoCapture(video_path)
20
- basename = os.path.basename(video_path)
21
- video_name = os.path.splitext(basename)[0]
22
  frame_count = 0
23
- saved_count = 0
24
-
25
- with mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5) as face_detection:
26
- while video_cap.isOpened():
27
- success, frame = video_cap.read()
28
- if not success:
29
- break
30
-
31
- frame_count += 1
32
- rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
33
- results = face_detection.process(rgb_frame)
34
-
35
- if results.detections:
36
- for i, detection in enumerate(results.detections):
37
- bbox = detection.location_data.relative_bounding_box
38
- h, w, _ = frame.shape
39
- x_min = int(bbox.xmin * w)
40
- y_min = int(bbox.ymin * h)
41
- box_w = int(bbox.width * w)
42
- box_h = int(bbox.height * h)
43
-
44
- # Ensure bounding box within frame
45
- x_min = max(0, x_min)
46
- y_min = max(0, y_min)
47
- x_max = min(w, x_min + box_w)
48
- y_max = min(h, y_min + box_h)
49
-
50
- cropped_face = frame[y_min:y_max, x_min:x_max]
51
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
52
- filename = f"{OUTPUT_DIR}/{video_name}_frame{frame_count}_face{i+1}_{timestamp}.jpg"
53
- cv2.imwrite(filename, cropped_face)
54
- saved_count += 1
55
-
56
- video_cap.release()
57
- return f"✅ Processed {frame_count} frames. {saved_count} face(s) saved from {video_name}."
58
-
59
- def process_videos(videos):
60
- logs = []
61
- for video in videos:
62
- logs.append(extract_faces_from_video(video))
63
- return "\n".join(logs)
64
-
65
- demo = gr.Interface(
66
- fn=process_videos,
67
- inputs=gr.File(file_types=[".mp4", ".avi"], label="Upload video files", file_count="multiple"),
68
- outputs="text",
69
- title="Face Detection using MediaPipe",
70
- description="Upload MP4 or AVI videos. Faces will be saved to `output_faces/` folder."
71
- )
72
-
73
- if __name__ == "__main__":
74
- demo.launch()
 
1
+ import streamlit as st
 
2
  import cv2
3
+ import requests
4
+ import numpy as np
5
+ import tempfile
6
+ import time
7
  import mediapipe as mp
 
 
 
8
 
9
+ # === CONFIGURATION ===
10
+ CCTVFEED_IDS = ['1KJRkSf2SKEZ1mXS9_si65IwMBtjs6p4n'] # List of folder IDs (Google Drive)
11
+ SUPPORTED_EXTENSIONS = ['.mp4', '.avi']
 
 
12
 
13
+ # === INITIALIZE FACE DETECTION ===
14
  mp_face_detection = mp.solutions.face_detection
15
+ face_detection = mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5)
16
+
17
+ # === HELPER FUNCTIONS ===
18
+
19
+ def list_gdrive_folder_files(folder_id):
20
+ """Returns list of (filename, download_url) from public Google Drive folder."""
21
+ api_url = f"https://drive.google.com/embeddedfolderview?id={folder_id}#grid"
22
+ resp = requests.get(api_url)
23
+ file_lines = resp.text.splitlines()
24
+ links = []
25
+ for line in file_lines:
26
+ if 'data-id=' in line and any(ext in line for ext in SUPPORTED_EXTENSIONS):
27
+ try:
28
+ file_id = line.split('data-id="')[1].split('"')[0]
29
+ file_name = line.split('data-title="')[1].split('"')[0]
30
+ download_url = f"https://drive.google.com/uc?id={file_id}"
31
+ links.append((file_name, download_url))
32
+ except Exception:
33
+ continue
34
+ return links
35
+
36
+ def stream_and_process_video(video_url, filename):
37
+ """Streams video frame-by-frame and runs face detection."""
38
+ st.markdown(f"### 🎥 Processing `{filename}`")
39
+ vid_bytes = requests.get(video_url, stream=True).content
40
+ tfile = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
41
+ tfile.write(vid_bytes)
42
+ cap = cv2.VideoCapture(tfile.name)
43
 
 
 
 
 
44
  frame_count = 0
45
+ face_count = 0
46
+
47
+ frame_display = st.empty()
48
+ stats_display = st.empty()
49
+
50
+ while cap.isOpened():
51
+ ret, frame = cap.read()
52
+ if not ret:
53
+ break
54
+ frame_count += 1
55
+
56
+ # Convert BGR to RGB
57
+ image_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
58
+ results = face_detection.process(image_rgb)
59
+
60
+ # Draw faces
61
+ if results.detections:
62
+ for detection in results.detections:
63
+ bboxC = detection.location_data.relative_bounding_box
64
+ ih, iw, _ = frame.shape
65
+ x, y, w, h = int(bboxC.xmin * iw), int(bboxC.ymin * ih), int(bboxC.width * iw), int(bboxC.height * ih)
66
+ cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
67
+ face_count += 1
68
+
69
+ # Resize for display
70
+ display_frame = cv2.resize(frame, (640, 360))
71
+ frame_display.image(display_frame, channels="BGR")
72
+
73
+ stats_display.markdown(f"**Frames Processed:** {frame_count} | **Faces Detected So Far:** {face_count}")
74
+ time.sleep(1 / 24.0) # Approx. 24 FPS
75
+
76
+ cap.release()
77
+ st.success(f"✅ Done! `{filename}`: {frame_count} frames, {face_count} faces detected.")
78
+
79
+ # === MAIN UI ===
80
+
81
+ st.title("🚨 CCTV Face Detection from Google Drive")
82
+ st.markdown("Detects faces in `.mp4` and `.avi` videos from your public Google Drive folder.")
83
+
84
+ for folder_id in CCTVFEED_IDS:
85
+ videos = list_gdrive_folder_files(folder_id)
86
+ if not videos:
87
+ st.warning(f"No valid videos found in folder ID: {folder_id}")
88
+ continue
89
+
90
+ for name, url in videos:
91
+ if st.button(f"▶️ Run Face Detection on `{name}`"):
92
+ stream_and_process_video(url, name)