Ajay98 commited on
Commit
8eded7a
·
verified ·
1 Parent(s): 13a2ad8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -62
app.py CHANGED
@@ -11,12 +11,12 @@ from PIL import Image
11
  from facenet_pytorch import MTCNN, InceptionResnetV1
12
  import json
13
  import gradio as gr
 
14
 
15
- # Load Google Drive API credentials from the uploaded JSON file
16
- SERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'
17
  SCOPES = ['https://www.googleapis.com/auth/drive']
18
 
19
- # Load credentials from the JSON file
20
  with open(SERVICE_ACCOUNT_FILE, 'r') as json_file:
21
  credentials_info = json.load(json_file)
22
 
@@ -28,29 +28,13 @@ aadhar_folder_id = '1Qtb5DYzSFE67Mbb5ZgDIqWUtdJaDD2F4'
28
  cphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'
29
  suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'
30
 
31
- # Initialize MTCNN for face detection and InceptionResnetV1 for face recognition
32
- mtcnn = MTCNN(image_size=160, margin=0, min_face_size=20)
33
- resnet = InceptionResnetV1(pretrained='vggface2').eval()
34
-
35
- def list_files_in_folder(folder_id):
36
- print(f"Listing files in folder ID: {folder_id}")
37
- query = f"'{folder_id}' in parents and trashed=false"
38
- try:
39
- results = drive_service.files().list(q=query, pageSize=1000, fields="files(id, name, mimeType, owners, parents)").execute()
40
- files = results.get('files', [])
41
- if not files:
42
- print(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")
43
- else:
44
- print(f"Found {len(files)} files in folder ID: {folder_id}.")
45
- return files
46
- except Exception as e:
47
- print(f"Error listing files in folder ID: {folder_id} - {e}")
48
- return []
49
 
 
50
  def download_file(file_id, file_name):
51
- print(f"Attempting to download file: {file_name} (ID: {file_id})")
52
- if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
53
- file_name += ".jpg"
54
  try:
55
  request = drive_service.files().get_media(fileId=file_id)
56
  file_io = io.BytesIO()
@@ -61,45 +45,28 @@ def download_file(file_id, file_name):
61
  file_io.seek(0)
62
  with open(file_name, 'wb') as f:
63
  f.write(file_io.read())
64
- print(f"Successfully downloaded file: {file_name}")
65
  return file_name
66
  except Exception as e:
67
  print(f"Error downloading file ID: {file_id} - {e}")
68
  return None
69
 
70
- def verify_and_fix_image(image_path):
71
- try:
72
- with Image.open(image_path) as img:
73
- img.verify()
74
- with Image.open(image_path) as img:
75
- img.save(image_path)
76
- print(f"Image verified and cleaned: {image_path}")
77
- return True
78
- except Exception as e:
79
- print(f"Image verification failed for {image_path}. Error: {e}")
80
- return False
81
-
82
- def upload_file(file_path, folder_id):
83
- print(f"Uploading file: {file_path} to folder ID: {folder_id}")
84
- file_metadata = {'name': os.path.basename(file_path), 'parents': [folder_id]}
85
- media = MediaFileUpload(file_path, resumable=True)
86
  try:
87
- file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
88
- print(f"Uploaded file ID: {file.get('id')}")
89
- return file.get('id')
90
  except Exception as e:
91
- print(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")
92
- return None
93
 
94
  def extract_face_embedding(image_path):
95
  try:
96
  image = Image.open(image_path)
97
  face = mtcnn(image)
98
  if face is not None:
99
- embedding = resnet(face.unsqueeze(0))
100
  return embedding
101
  else:
102
- print(f"No face detected in image: {image_path}")
103
  return None
104
  except Exception as e:
105
  print(f"Error extracting face embedding for {image_path}. Error: {e}")
@@ -109,23 +76,24 @@ def calculate_similarity(embedding1, embedding2):
109
  return torch.nn.functional.cosine_similarity(embedding1, embedding2).item()
110
 
111
  def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):
112
- print("Starting processing of images...")
113
  aadhar_files = list_files_in_folder(aadhar_folder_id)
114
  cphotos_files = list_files_in_folder(cphotos_folder_id)
115
 
116
  aadhar_embeddings = []
117
- for file in aadhar_files:
118
- print(f"Processing Aadhar file: {file['name']}")
119
- file_path = download_file(file['id'], file['name'])
120
- if file_path and verify_and_fix_image(file_path):
121
- embedding = extract_face_embedding(file_path)
122
- if embedding is not None:
123
- aadhar_embeddings.append((file['name'], embedding))
124
-
 
 
 
125
  for file in cphotos_files:
126
- print(f"Processing CCTV file: {file['name']}")
127
  file_path = download_file(file['id'], file['name'])
128
- if not file_path or not verify_and_fix_image(file_path):
129
  continue
130
 
131
  embedding_cctv = extract_face_embedding(file_path)
@@ -137,15 +105,13 @@ def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):
137
  similarity = calculate_similarity(embedding_cctv, aadhar_embedding)
138
  if similarity > 0.8:
139
  matched = True
140
- print(f"Match found for file: {file['name']} with Aadhar file: {aadhar_name}, Similarity: {similarity:.2f}")
141
  break
142
 
143
  if not matched:
144
  upload_file(file_path, suspects_folder_id)
145
  print(f"Unmatched image uploaded: {file['name']}")
146
 
147
- print("Processing of images completed.")
148
-
149
  def run_script():
150
  start_time = time.time()
151
  print("Script started...")
 
11
  from facenet_pytorch import MTCNN, InceptionResnetV1
12
  import json
13
  import gradio as gr
14
+ from concurrent.futures import ThreadPoolExecutor
15
 
16
+ # Load Google Drive API credentials
17
+ SERVICE_ACCOUNT_FILE = './.env' # JSON key file path
18
  SCOPES = ['https://www.googleapis.com/auth/drive']
19
 
 
20
  with open(SERVICE_ACCOUNT_FILE, 'r') as json_file:
21
  credentials_info = json.load(json_file)
22
 
 
28
  cphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'
29
  suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'
30
 
31
+ # Initialize MTCNN and InceptionResnetV1
32
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
33
+ mtcnn = MTCNN(image_size=160, margin=0, min_face_size=20, device=device)
34
+ resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Multithreaded file download
37
  def download_file(file_id, file_name):
 
 
 
38
  try:
39
  request = drive_service.files().get_media(fileId=file_id)
40
  file_io = io.BytesIO()
 
45
  file_io.seek(0)
46
  with open(file_name, 'wb') as f:
47
  f.write(file_io.read())
 
48
  return file_name
49
  except Exception as e:
50
  print(f"Error downloading file ID: {file_id} - {e}")
51
  return None
52
 
53
+ def list_files_in_folder(folder_id):
54
+ query = f"'{folder_id}' in parents and trashed=false"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  try:
56
+ results = drive_service.files().list(q=query, pageSize=1000, fields="files(id, name)").execute()
57
+ return results.get('files', [])
 
58
  except Exception as e:
59
+ print(f"Error listing files in folder ID: {folder_id} - {e}")
60
+ return []
61
 
62
  def extract_face_embedding(image_path):
63
  try:
64
  image = Image.open(image_path)
65
  face = mtcnn(image)
66
  if face is not None:
67
+ embedding = resnet(face.unsqueeze(0).to(device)).detach().cpu()
68
  return embedding
69
  else:
 
70
  return None
71
  except Exception as e:
72
  print(f"Error extracting face embedding for {image_path}. Error: {e}")
 
76
  return torch.nn.functional.cosine_similarity(embedding1, embedding2).item()
77
 
78
  def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):
 
79
  aadhar_files = list_files_in_folder(aadhar_folder_id)
80
  cphotos_files = list_files_in_folder(cphotos_folder_id)
81
 
82
  aadhar_embeddings = []
83
+
84
+ # Download and process Aadhar images in parallel
85
+ with ThreadPoolExecutor() as executor:
86
+ for file in aadhar_files:
87
+ file_path = executor.submit(download_file, file['id'], file['name']).result()
88
+ if file_path:
89
+ embedding = extract_face_embedding(file_path)
90
+ if embedding is not None:
91
+ aadhar_embeddings.append((file['name'], embedding))
92
+
93
+ # Process CCTV images and find matches in parallel
94
  for file in cphotos_files:
 
95
  file_path = download_file(file['id'], file['name'])
96
+ if not file_path:
97
  continue
98
 
99
  embedding_cctv = extract_face_embedding(file_path)
 
105
  similarity = calculate_similarity(embedding_cctv, aadhar_embedding)
106
  if similarity > 0.8:
107
  matched = True
108
+ print(f"Match found: {file['name']} with Aadhar file: {aadhar_name}, Similarity: {similarity:.2f}")
109
  break
110
 
111
  if not matched:
112
  upload_file(file_path, suspects_folder_id)
113
  print(f"Unmatched image uploaded: {file['name']}")
114
 
 
 
115
  def run_script():
116
  start_time = time.time()
117
  print("Script started...")