Spaces:
Build error
Build error
Update app.py
Browse files1234562 unmodified lines9101112131415161718191 unmodified line2122232425262728293031323334353637383940411 unmodified line434445464748495051525354555657585960616263646566676 unmodified lines74757677787980818283841 unmodified line868788899091929394959697989910010110210310410510610710810911010 unmodified lines12112212312412512612712812913014 unmodified lines1451461471481491501511521531 unmodified line155156157158159160161162163164165166167168169170171172173174175176177178179180181182import osimport jsonimport loggingimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom google.oauth2 import service_account2 unmodified linesfrom PIL import Imageimport torchimport iofrom deepface import DeepFacefrom scipy.spatial.distance import cosine # Import for cosine similarity calculation# Set up logginglogging.basicConfig(level=logging.DEBUG)# Load Google Drive API credentialsSERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'1 unmodified linetry:if not os.path.exists(SERVICE_ACCOUNT_FILE):logging.error(f"Service account file '{SERVICE_ACCOUNT_FILE}' not found.")raise FileNotFoundError(f"Service account file '{SERVICE_ACCOUNT_FILE}' not found.")with open(SERVICE_ACCOUNT_FILE, 'r') as json_file:credentials_info = json.load(json_file)credentials = service_account.Credentials.from_service_account_info(credentials_info, scopes=SCOPES)drive_service = build('drive', 'v3', credentials=credentials)logging.debug("Google Drive API credentials loaded successfully.")except json.JSONDecodeError as e:logging.error(f"Error parsing JSON service account file: {e}")except FileNotFoundError as e:logging.error(f"Service account file missing: {e}")except Exception as e:logging.error(f"Unexpected error while loading credentials: {e}")raise# Folder IDsaadhar_folder_id = '1Qtb5DYzSFE67Mbb5ZgDIqWUtdJaDD2F4'1 unmodified linesuspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'# Limit the number of threads for scalabilityMAX_THREADS = 3def list_files_in_folder(folder_id):logging.debug(f"Listing files in folder ID: {folder_id}")query = f"'{folder_id}' in parents and trashed=false"try:results = drive_service.files().list(q=query, pageSize=50, fields="files(id, name, mimeType)").execute()files = results.get('files', [])if not files:logging.warning(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")else:logging.debug(f"Found {len(files)} files in folder ID: {folder_id}.")return filesexcept Exception as e:logging.error(f"Error listing files in folder ID: {folder_id} - {e}")return []def download_file(file_id, file_name):logging.debug(f"Attempting to download file: {file_name} (ID: {file_id})")if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):file_name += ".jpg"try:6 unmodified linesfile_io.seek(0)with open(file_name, 'wb') as f:f.write(file_io.read())logging.debug(f"Successfully downloaded file: {file_name}")return file_nameexcept Exception as e:logging.error(f"Error downloading file ID: {file_id} - {e}")return Nonedef extract_face_embedding(image_path):try:1 unmodified lineembedding = DeepFace.represent(img_path=image_path, model_name='VGG-Face')[0]["embedding"]return embeddingexcept Exception as e:logging.error(f"Error extracting face encoding for {image_path}. Error: {e}")return Nonedef calculate_similarity(encoding1, encoding2):# Use cosine similarity directlydistance = cosine(encoding1, encoding2)similarity = 1 - distancereturn similaritydef compare_faces_with_encodings(encoding_cctv, aadhar_encodings, threshold=0.7):for aadhar_name, aadhar_encoding in aadhar_encodings:similarity = calculate_similarity(encoding_cctv, aadhar_encoding)if similarity > threshold:logging.info(f"Match found: Similarity = {similarity:.2f} with Aadhar file: {aadhar_name}")return Truereturn Falsedef batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):logging.debug("Starting processing of images...")aadhar_files = list_files_in_folder(aadhar_folder_id)cphotos_files = list_files_in_folder(cphotos_folder_id)10 unmodified linesif encoding is not None:aadhar_encodings.append((file['name'], encoding))except Exception as e:logging.error(f"Error processing Aadhar file {file['name']}: {e}")if not aadhar_encodings:logging.warning("No valid Aadhar face encodings found. Exiting.")return# Extract CCTV encodings and compare concurrently14 unmodified linesmatched = compare_faces_with_encodings(encoding_cctv, aadhar_encodings)if not matched:unmatched_files.append(file_path)logging.info(f"Unmatched image queued for upload: {file['name']}")except Exception as e:logging.error(f"Error processing CCTV file {file['name']}: {e}")# Upload unmatched files concurrentlywith ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:1 unmodified linefor future in as_completed(upload_futures):try:future.result()logging.info(f"Successfully uploaded unmatched image to suspects folder.")except Exception as e:logging.error(f"Error uploading unmatched file: {e}")def upload_file(file_path, folder_id):logging.debug(f"Uploading file: {file_path} to folder ID: {folder_id}")file_metadata = {'name': os.path.basename(file_path), 'parents': [folder_id]}media = MediaFileUpload(file_path, resumable=True)try:file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()logging.debug(f"Uploaded file ID: {file.get('id')}")return file.get('id')except Exception as e:logging.error(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")return Nonedef main():start_time = time.time()logging.debug("Script started...")batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id)end_time = time.time()logging.debug(f"Script completed in {end_time - start_time:.2f} seconds.")if __name__ == "__main__":main()123452 unmodified lines8910111213141 unmodified line1617181920212223242526272829303132331 unmodified line3536373839404142434445464748495051526 unmodified lines5960616263646566671 unmodified line69707172737475767778798081828384858687888910 unmodified lines10010110210310410510610710810914 unmodified lines1241251261271281291301311321 unmodified line134135136137138139140141142143144145146147148149150151152153154155156157import osimport jsonimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom google.oauth2 import service_account2 unmodified linesfrom PIL import Imageimport torchimport iofrom deepface import DeepFace # Use DeepFace for advanced face recognition# Load Google Drive API credentialsSERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'1 unmodified linetry:if not os.path.exists(SERVICE_ACCOUNT_FILE):raise FileNotFoundError(f"Service account file '{SERVICE_ACCOUNT_FILE}' not found.")with open(SERVICE_ACCOUNT_FILE, 'r') as json_file:credentials_info = json.load(json_file)credentials = service_account.Credentials.from_service_account_info(credentials_info, scopes=SCOPES)drive_service = build('drive', 'v3', credentials=credentials)except json.JSONDecodeError as e:raise Exception(f"Error parsing JSON service account file: {e}")except FileNotFoundError as e:raise Exception(f"Service account file missing: {e}")except Exception as e:raise Exception(f"Unexpected error while loading credentials: {e}")# Folder IDsaadhar_folder_id = '1Qtb5DYzSFE67Mbb5ZgDIqWUtdJaDD2F4'1 unmodified linesuspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'# Limit the number of threads for scalabilityMAX_THREADS = 5def list_files_in_folder(folder_id):query = f"'{folder_id}' in parents and trashed=false"try:results = drive_service.files().list(q=query, pageSize=50, fields="files(id, name, mimeType)").execute()files = results.get('files', [])return filesexcept Exception as e:raise Exception(f"Error listing files in folder ID: {folder_id} - {e}")def download_file(file_id, file_name):if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):file_name += ".jpg"try:6 unmodified linesfile_io.seek(0)with open(file_name, 'wb') as f:f.write(file_io.read())return file_nameexcept Exception as e:raise Exception(f"Error downloading file ID: {file_id} - {e}")def extract_face_embedding(image_path):try:1 unmodified lineembedding = DeepFace.represent(img_path=image_path, model_name='VGG-Face')[0]["embedding"]return embeddingexcept Exception as e:raise Exception(f"Error extracting face encoding for {image_path}. Error: {e}")def calculate_similarity(encoding1, encoding2):# Use cosine similarity for comparisonsimilarity = DeepFace.find(img_path1=encoding1, img_path2=encoding2, distance_metric='cosine')[0]return 1 - similarity # Convert distance to similaritydef compare_faces_with_encodings(encoding_cctv, aadhar_encodings, threshold=0.7):for aadhar_name, aadhar_encoding in aadhar_encodings:similarity = calculate_similarity(encoding_cctv, aadhar_encoding)if similarity > threshold:return Truereturn Falsedef batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):aadhar_files = list_files_in_folder(aadhar_folder_id)cphotos_files = list_files_in_folder(cphotos_folder_id)10 unmodified linesif encoding is not None:aadhar_encodings.append((file['name'], encoding))except Exception as e:print(f"Error processing Aadhar file {file['name']}: {e}")if not aadhar_encodings:print("No valid Aadhar face encodings found. Exiting.")return# Extract CCTV encodings and compare concurrently14 unmodified linesmatched = compare_faces_with_encodings(encoding_cctv, aadhar_encodings)if not matched:unmatched_files.append(file_path)print(f"Unmatched image queued for upload: {file['name']}")except Exception as e:print(f"Error processing CCTV file {file['name']}: {e}")# Upload unmatched files concurrentlywith ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:1 unmodified linefor future in as_completed(upload_futures):try:future.result()print(f"Successfully uploaded unmatched image to suspects folder.")except Exception as e:print(f"Error uploading unmatched file: {e}")def upload_file(file_path, folder_id):file_metadata = {'name': os.path.basename(file_path), 'parents': [folder_id]}media = MediaFileUpload(file_path, resumable=True)try:file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()return file.get('id')except Exception as e:raise Exception(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")def main():start_time = time.time()batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id)end_time = time.time()print(f"Script completed in {end_time - start_time:.2f} seconds.")if __name__ == "__main__":main()
app.py+19-44