SuriRaja commited on
Commit
58574bf
Β·
verified Β·
1 Parent(s): ff7673e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -76
app.py CHANGED
@@ -1,92 +1,80 @@
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)
 
 
 
 
 
 
1
  import streamlit as st
2
  import cv2
 
3
  import numpy as np
4
+ import requests
5
  import tempfile
 
6
  import mediapipe as mp
7
+ import os
8
 
9
  # === CONFIGURATION ===
10
+ API_KEY = "AIzaSy...your_public_API_key..." # Replace with a valid public API key if needed
11
+ CCTVFEED_IDS = ['1KJRkSf2SKEZ1mXS9_si65IwMBtjs6p4n']
12
+ REG_FOLDER_ID = '1qkcR7nQTEtiMH9OFUv2bGxVn08E3dKjF'
13
+ INTRUDER_FOLDER_ID = '1PPAUWU-wMx7fek73p-hqPqYQypYtG8Ob'
14
 
15
+ # === SETUP ===
16
  mp_face_detection = mp.solutions.face_detection
17
+ mp_drawing = mp.solutions.drawing_utils
18
+ face_detector = mp_face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5)
19
+
20
+ # === FUNCTIONS ===
21
+ def get_drive_video_links(folder_id):
22
+ api_url = f"https://www.googleapis.com/drive/v3/files?q='{folder_id}'+in+parents&key={API_KEY}&fields=files(id,name,mimeType)"
23
+ response = requests.get(api_url)
24
+ files = response.json().get("files", [])
25
+
26
+ st.write(f"πŸ” Found {len(files)} files in folder `{folder_id}`")
27
+ for f in files:
28
+ st.write(f" - **{f['name']}** | `{f['mimeType']}`")
29
+
30
+ video_links = []
31
+ for f in files:
32
+ if f["mimeType"] in ["video/mp4", "video/x-msvideo", "video/avi"]:
33
+ link = f"https://drive.google.com/uc?id={f['id']}&export=download"
34
+ video_links.append((f["name"], link))
35
+ return video_links
36
+
37
+ def download_video(link):
38
+ response = requests.get(link, stream=True)
39
+ temp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
40
+ for chunk in response.iter_content(chunk_size=1024*1024):
41
+ temp.write(chunk)
42
+ temp.close()
43
+ return temp.name
44
+
45
+ def detect_faces_from_video(video_path):
46
+ cap = cv2.VideoCapture(video_path)
47
+ frames_with_faces = 0
 
 
 
48
 
49
  while cap.isOpened():
50
  ret, frame = cap.read()
51
  if not ret:
52
  break
53
+ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
54
+ results = face_detector.process(rgb)
 
 
 
 
 
55
  if results.detections:
56
+ frames_with_faces += 1
57
+ for det in results.detections:
58
+ mp_drawing.draw_detection(frame, det)
 
 
 
 
 
 
 
 
 
 
 
59
  cap.release()
60
+ return frames_with_faces
61
+
62
+ # === STREAMLIT UI ===
63
+ st.title("πŸ” Intruder Detection from CCTV Feed")
64
+ st.write("Streaming videos from Google Drive, detecting faces using MediaPipe.")
65
+
66
+ with st.spinner("Fetching videos..."):
67
+ total_detections = 0
68
+ for folder_id in CCTVFEED_IDS:
69
+ videos = get_drive_video_links(folder_id)
70
+ for vname, link in videos:
71
+ st.subheader(f"πŸŽ₯ {vname}")
72
+ video_file = download_video(link)
73
+ faces = detect_faces_from_video(video_file)
74
+ os.remove(video_file)
75
+ if faces > 0:
76
+ st.success(f"βœ… Detected faces in {faces} frames.")
77
+ total_detections += 1
78
+ else:
79
+ st.warning("⚠️ No faces detected.")
80
+ st.info(f"πŸ”Ž Completed. Videos with detected faces: {total_detections}")