Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import osimport cv2from google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaIoBaseDownload, MediaFileUploadimport ioimport timeimport torchimport numpy as npfrom PIL import Imagefrom facenet_pytorch import MTCNN, InceptionResnetV1import jsonimport gradio as grfrom concurrent.futures import ThreadPoolExecutor# Load Google Drive API credentialsSERVICE_ACCOUNT_FILE = './.env' # JSON key file pathSCOPES = ['https://www.googleapis.com/auth/drive']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)# Folder IDsaadhar_folder_id = '1Qtb5DYzSFE67Mbb5ZgDIqWUtdJaDD2F4'cphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'# Initialize MTCNN and InceptionResnetV1device = 'cuda' if torch.cuda.is_available() else 'cpu'mtcnn = MTCNN(image_size=160, margin=0, min_face_size=20, device=device)resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)# Multithreaded file downloaddef download_file(file_id, file_name):try:request = drive_service.files().get_media(fileId=file_id)file_io = io.BytesIO()downloader = MediaIoBaseDownload(file_io, request)done = Falsewhile not done:_, done = downloader.next_chunk()file_io.seek(0)with open(file_name, 'wb') as f:f.write(file_io.read())return file_nameexcept Exception as e:print(f"Error downloading file ID: {file_id} - {e}")return Nonedef list_files_in_folder(folder_id):query = f"'{folder_id}' in parents and trashed=false"try:results = drive_service.files().list(q=query, pageSize=1000, fields="files(id, name)").execute()return results.get('files', [])except Exception as e:print(f"Error listing files in folder ID: {folder_id} - {e}")return []def extract_face_embedding(image_path):try:image = Image.open(image_path)face = mtcnn(image)if face is not None:embedding = resnet(face.unsqueeze(0).to(device)).detach().cpu()return embeddingelse:return Noneexcept Exception as e:print(f"Error extracting face embedding for {image_path}. Error: {e}")return Nonedef calculate_similarity(embedding1, embedding2):return torch.nn.functional.cosine_similarity(embedding1, embedding2).item()def 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)aadhar_embeddings = []# Download and process Aadhar images in parallelwith ThreadPoolExecutor() as executor:for file in aadhar_files:file_path = executor.submit(download_file, file['id'], file['name']).result()if file_path:embedding = extract_face_embedding(file_path)if embedding is not None:aadhar_embeddings.append((file['name'], embedding))# Process CCTV images and find matches in parallelfor file in cphotos_files:file_path = download_file(file['id'], file['name'])if not file_path:continueembedding_cctv = extract_face_embedding(file_path)if embedding_cctv is None:continuematched = Falsefor aadhar_name, aadhar_embedding in aadhar_embeddings:similarity = calculate_similarity(embedding_cctv, aadhar_embedding)if similarity > 0.8:matched = Trueprint(f"Match found: {file['name']} with Aadhar file: {aadhar_name}, Similarity: {similarity:.2f}")breakif not matched:upload_file(file_path, suspects_folder_id)print(f"Unmatched image uploaded: {file['name']}")def run_script():start_time = time.time()print("Script started...")process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id)end_time = time.time()return f"Script completed in {end_time - start_time:.2f} seconds."# Gradio interfaceiface = gr.Interface(fn=run_script, inputs=[], outputs="text", description="Run the Image Processing Script")if __name__ == "__main__":iface.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162from concurrent.futures import ThreadPoolExecutor, as_completed# New function for batch processing images in paralleldef batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):# Fetch Aadhar and CCTV filesaadhar_files = list_files_in_folder(aadhar_folder_id)cphotos_files = list_files_in_folder(cphotos_folder_id)# Extract Aadhar embeddings in parallelaadhar_embeddings = []with ThreadPoolExecutor() as executor:future_to_aadhar = {executor.submit(download_file, file['id'], file['name']): file['name'] for file in aadhar_files}for future in as_completed(future_to_aadhar):file_name = future_to_aadhar[future]try:file_path = future.result()if file_path:embedding = extract_face_embedding(file_path)if embedding is not None:aadhar_embeddings.append((file_name, embedding))except Exception as e:print(f"Error processing Aadhar file {file_name}: {e}")# Process CCTV files in parallelunmatched_files = []with ThreadPoolExecutor() as executor:for file in cphotos_files:file_path = download_file(file['id'], file['name'])if not file_path:continueembedding_cctv = extract_face_embedding(file_path)if embedding_cctv is None:continuematched = Falsefor aadhar_name, aadhar_embedding in aadhar_embeddings:similarity = calculate_similarity(embedding_cctv, aadhar_embedding)if similarity > 0.8: # Adjust the threshold as necessarymatched = Trueprint(f"Match found: {file['name']} with Aadhar file: {aadhar_name}, Similarity: {similarity:.2f}")breakif not matched:unmatched_files.append(file_path)print(f"Unmatched image queued for upload: {file['name']}")# Upload unmatched fileswith ThreadPoolExecutor() as executor:for file_path in unmatched_files:executor.submit(upload_file, file_path, suspects_folder_id)# Replace the main function to call the new batch processing functiondef main():start_time = time.time()print("Script started...")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+51-115