Ajay98 commited on
Commit
dd0129f
·
verified ·
1 Parent(s): c4e4b51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -43
app.py CHANGED
@@ -1,5 +1,3 @@
1
-
2
-
3
  import os
4
  import cv2
5
  from google.oauth2 import service_account
@@ -7,11 +5,14 @@ from googleapiclient.discovery import build
7
  from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
8
  import io
9
  import time
 
 
10
  from PIL import Image
 
11
 
12
- # Load Google Drive API credentials
 
13
  SCOPES = ['https://www.googleapis.com/auth/drive']
14
- SERVICE_ACCOUNT_FILE = r'C:\Users\Ajaya\Downloads\salesforce-api-439514-d6b432a2e20e.json' # Use raw string to avoid Unicode escape issues
15
  credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
16
  drive_service = build('drive', 'v3', credentials=credentials)
17
 
@@ -20,6 +21,10 @@ aadhar_folder_id = '1jXklVbxTni1gnduuKgJ7zI6zVks6s0LP'
20
  cphotos_folder_id = '1JVJMtHuIHxZyxAekT6ZQFkEWePOimIlX'
21
  suspects_folder_id = '1LJE5aw_g5Jvqd5cLZ7UiJ8LyR36JkBKP'
22
 
 
 
 
 
23
  def list_files_in_folder(folder_id):
24
  print(f"Listing files in folder ID: {folder_id}")
25
  query = f"'{folder_id}' in parents and trashed=false"
@@ -30,8 +35,6 @@ def list_files_in_folder(folder_id):
30
  print(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")
31
  else:
32
  print(f"Found {len(files)} files in folder ID: {folder_id}.")
33
- for file in files:
34
- print(f"Found file: Name={file['name']}, ID={file['id']}, Type={file['mimeType']}, Owner={file['owners'][0]['displayName']}, Parent Folder ID={file['parents']}")
35
  return files
36
  except Exception as e:
37
  print(f"Error listing files in folder ID: {folder_id} - {e}")
@@ -83,62 +86,62 @@ def upload_file(file_path, folder_id):
83
  print(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")
84
  return None
85
 
86
- def detect_face(image_path):
87
- print(f"Detecting faces in image: {image_path}")
88
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
89
- image = cv2.imread(image_path)
90
- if image is None:
91
- print(f"Error reading image: {image_path}. The file may not be a valid image.")
92
- return False
93
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
94
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
95
- face_detected = len(faces) > 0
96
- print(f"Faces detected: {face_detected} in image: {image_path}")
97
- return face_detected
 
 
 
 
 
98
 
99
  def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):
100
  print("Starting processing of images...")
101
  aadhar_files = list_files_in_folder(aadhar_folder_id)
102
  cphotos_files = list_files_in_folder(cphotos_folder_id)
103
 
104
- aadhar_faces = []
 
105
  for file in aadhar_files:
106
  print(f"Processing Aadhar file: {file['name']}")
107
  file_path = download_file(file['id'], file['name'])
108
- if file_path and verify_and_fix_image(file_path) and detect_face(file_path):
109
- img = cv2.imread(file_path)
110
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
111
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
112
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
113
- if len(faces) > 0:
114
- aadhar_faces.append((file['name'], faces, img))
115
 
 
116
  for file in cphotos_files:
117
  print(f"Processing CCTV file: {file['name']}")
118
  file_path = download_file(file['id'], file['name'])
119
  if not file_path or not verify_and_fix_image(file_path):
120
  continue
 
 
 
 
 
121
  matched = False
122
- if detect_face(file_path):
123
- img_c = cv2.imread(file_path)
124
- gray_c = cv2.cvtColor(img_c, cv2.COLOR_BGR2GRAY)
125
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
126
- faces_c = face_cascade.detectMultiScale(gray_c, scaleFactor=1.1, minNeighbors=5)
127
- if len(faces_c) > 0:
128
- for aadhar_name, aadhar_face_regions, aadhar_img in aadhar_faces:
129
- for (x, y, w, h) in aadhar_face_regions:
130
- aadhar_face = aadhar_img[y:y+h, x:x+w]
131
- for (xc, yc, wc, hc) in faces_c:
132
- cctv_face = img_c[yc:yc+hc, xc:xc+wc]
133
- if aadhar_face.shape == cctv_face.shape and not (cv2.subtract(aadhar_face, cctv_face).any()):
134
- matched = True
135
- print(f"Match found for file: {file['name']} with Aadhar file: {aadhar_name}")
136
- break
137
- if matched:
138
- break
139
  if not matched:
140
  upload_file(file_path, suspects_folder_id)
141
  print(f"Unmatched image uploaded: {file['name']}")
 
142
  print("Processing of images completed.")
143
 
144
  def main():
 
 
 
1
  import os
2
  import cv2
3
  from google.oauth2 import service_account
 
5
  from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
6
  import io
7
  import time
8
+ import torch
9
+ import numpy as np
10
  from PIL import Image
11
+ from facenet_pytorch import MTCNN, InceptionResnetV1
12
 
13
+ # Load Google Drive API credentials from the uploaded JSON file
14
+ SERVICE_ACCOUNT_FILE = './salesforce-api-439514-d6b432a2e20e.json' # Assuming the JSON file is in the root directory
15
  SCOPES = ['https://www.googleapis.com/auth/drive']
 
16
  credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
17
  drive_service = build('drive', 'v3', credentials=credentials)
18
 
 
21
  cphotos_folder_id = '1JVJMtHuIHxZyxAekT6ZQFkEWePOimIlX'
22
  suspects_folder_id = '1LJE5aw_g5Jvqd5cLZ7UiJ8LyR36JkBKP'
23
 
24
+ # Initialize MTCNN for face detection and InceptionResnetV1 for face recognition
25
+ mtcnn = MTCNN(image_size=160, margin=0, min_face_size=20)
26
+ resnet = InceptionResnetV1(pretrained='vggface2').eval()
27
+
28
  def list_files_in_folder(folder_id):
29
  print(f"Listing files in folder ID: {folder_id}")
30
  query = f"'{folder_id}' in parents and trashed=false"
 
35
  print(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")
36
  else:
37
  print(f"Found {len(files)} files in folder ID: {folder_id}.")
 
 
38
  return files
39
  except Exception as e:
40
  print(f"Error listing files in folder ID: {folder_id} - {e}")
 
86
  print(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")
87
  return None
88
 
89
+ def extract_face_embedding(image_path):
90
+ try:
91
+ image = Image.open(image_path)
92
+ face = mtcnn(image) # Detect and crop the face
93
+ if face is not None:
94
+ embedding = resnet(face.unsqueeze(0)) # Get the face embedding
95
+ return embedding
96
+ else:
97
+ print(f"No face detected in image: {image_path}")
98
+ return None
99
+ except Exception as e:
100
+ print(f"Error extracting face embedding for {image_path}. Error: {e}")
101
+ return None
102
+
103
+ def calculate_similarity(embedding1, embedding2):
104
+ # Calculate cosine similarity between two embeddings
105
+ return torch.nn.functional.cosine_similarity(embedding1, embedding2).item()
106
 
107
  def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):
108
  print("Starting processing of images...")
109
  aadhar_files = list_files_in_folder(aadhar_folder_id)
110
  cphotos_files = list_files_in_folder(cphotos_folder_id)
111
 
112
+ # Extract embeddings for all Aadhar images
113
+ aadhar_embeddings = []
114
  for file in aadhar_files:
115
  print(f"Processing Aadhar file: {file['name']}")
116
  file_path = download_file(file['id'], file['name'])
117
+ if file_path and verify_and_fix_image(file_path):
118
+ embedding = extract_face_embedding(file_path)
119
+ if embedding is not None:
120
+ aadhar_embeddings.append((file['name'], embedding))
 
 
 
121
 
122
+ # Compare each CCTV image with all Aadhar embeddings
123
  for file in cphotos_files:
124
  print(f"Processing CCTV file: {file['name']}")
125
  file_path = download_file(file['id'], file['name'])
126
  if not file_path or not verify_and_fix_image(file_path):
127
  continue
128
+
129
+ embedding_cctv = extract_face_embedding(file_path)
130
+ if embedding_cctv is None:
131
+ continue
132
+
133
  matched = False
134
+ for aadhar_name, aadhar_embedding in aadhar_embeddings:
135
+ similarity = calculate_similarity(embedding_cctv, aadhar_embedding)
136
+ if similarity > 0.8: # Adjust the threshold as necessary
137
+ matched = True
138
+ print(f"Match found for file: {file['name']} with Aadhar file: {aadhar_name}, Similarity: {similarity:.2f}")
139
+ break
140
+
 
 
 
 
 
 
 
 
 
 
141
  if not matched:
142
  upload_file(file_path, suspects_folder_id)
143
  print(f"Unmatched image uploaded: {file['name']}")
144
+
145
  print("Processing of images completed.")
146
 
147
  def main():