Spaces:
Build error
Build error
Update app.py
Browse files10 unmodified lines1112131415161718192021225 unmodified lines28293031323334353637383940414243444546474849505152535455564 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041053 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301315 unmodified lines13713813914014114214314414514614714814915015110 unmodified linesfrom facenet_pytorch import MTCNN, InceptionResnetV1import jsonimport gradio as gr# Load Google Drive API credentials from the uploaded JSON fileSERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'SCOPES = ['https://www.googleapis.com/auth/drive']# Load credentials from the JSON filewith open(SERVICE_ACCOUNT_FILE, 'r') as json_file:credentials_info = json.load(json_file)5 unmodified linescphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'# Initialize MTCNN for face detection and InceptionResnetV1 for face recognitionmtcnn = MTCNN(image_size=160, margin=0, min_face_size=20)resnet = InceptionResnetV1(pretrained='vggface2').eval()def list_files_in_folder(folder_id):print(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=1000, fields="files(id, name, mimeType, owners, parents)").execute()files = results.get('files', [])if not files:print(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")else:print(f"Found {len(files)} files in folder ID: {folder_id}.")return filesexcept Exception as e:print(f"Error listing files in folder ID: {folder_id} - {e}")return []def download_file(file_id, file_name):print(f"Attempting to download file: {file_name} (ID: {file_id})")if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):file_name += ".jpg"try:request = drive_service.files().get_media(fileId=file_id)file_io = io.BytesIO()4 unmodified linesfile_io.seek(0)with open(file_name, 'wb') as f:f.write(file_io.read())print(f"Successfully downloaded file: {file_name}")return file_nameexcept Exception as e:print(f"Error downloading file ID: {file_id} - {e}")return Nonedef verify_and_fix_image(image_path):try:with Image.open(image_path) as img:img.verify()with Image.open(image_path) as img:img.save(image_path)print(f"Image verified and cleaned: {image_path}")return Trueexcept Exception as e:print(f"Image verification failed for {image_path}. Error: {e}")return Falsedef upload_file(file_path, folder_id):print(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()print(f"Uploaded file ID: {file.get('id')}")return file.get('id')except Exception as e:print(f"Error uploading file {file_path} to folder ID: {folder_id} - {e}")return Nonedef extract_face_embedding(image_path):try:image = Image.open(image_path)face = mtcnn(image)if face is not None:embedding = resnet(face.unsqueeze(0))return embeddingelse:print(f"No face detected in image: {image_path}")return Noneexcept Exception as e:print(f"Error extracting face embedding for {image_path}. Error: {e}")3 unmodified linesreturn torch.nn.functional.cosine_similarity(embedding1, embedding2).item()def process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):print("Starting processing of images...")aadhar_files = list_files_in_folder(aadhar_folder_id)cphotos_files = list_files_in_folder(cphotos_folder_id)aadhar_embeddings = []for file in aadhar_files:print(f"Processing Aadhar file: {file['name']}")file_path = download_file(file['id'], file['name'])if file_path and verify_and_fix_image(file_path):embedding = extract_face_embedding(file_path)if embedding is not None:aadhar_embeddings.append((file['name'], embedding))for file in cphotos_files:print(f"Processing CCTV file: {file['name']}")file_path = download_file(file['id'], file['name'])if not file_path or not verify_and_fix_image(file_path):continueembedding_cctv = extract_face_embedding(file_path)5 unmodified linessimilarity = calculate_similarity(embedding_cctv, aadhar_embedding)if similarity > 0.8:matched = Trueprint(f"Match found for file: {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']}")print("Processing of images completed.")def run_script():start_time = time.time()print("Script started...")10 unmodified lines1112131415161718192021225 unmodified lines282930313233343536373839404 unmodified lines454647484950515253545556575859606162636465666768697071723 unmodified lines7677787980818283848586878889909192939495969798995 unmodified lines10510610710810911011111211311411511611710 unmodified linesfrom 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)5 unmodified linescphotos_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()4 unmodified linesfile_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}")3 unmodified linesreturn 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)5 unmodified linessimilarity = 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...")
app.py+28-62