syedwaqarumer commited on
Commit
a212f38
·
verified ·
1 Parent(s): a300b92

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -40
app.py CHANGED
@@ -1,42 +1,86 @@
1
- import cv2
2
  import pandas as pd
3
- import gradio as gr
4
- from deepface import DeepFace
5
-
6
- # Load the CSV data
7
- csv_path = '/content/photo.csv' # Path to your CSV
8
- data = pd.read_csv(csv_path)
9
-
10
- # Function to match the recognized face with data in the CSV
11
- def get_person_data(image_filename):
12
- person = data[data['filename'] == image_filename]
13
- if not person.empty:
14
- return f"Name: {person.iloc[0]['name']}, CNIC: {person.iloc[0]['cnic']}, Age: {person.iloc[0]['age']}, Hometown: {person.iloc[0]['hometown']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  else:
16
- return "Person not recognized"
17
-
18
- # Function to process the uploaded image for face recognition
19
- def recognize_face(image):
20
- result = DeepFace.analyze(image, actions=['emotion'], enforce_detection=False)
21
- for face in result:
22
- x, y, w, h = face['region']['x'], face['region']['y'], face['region']['w'], face['region']['h']
23
- face_img = image[y:y+h, x:x+w]
24
-
25
- try:
26
- identity = DeepFace.find(img_path=face_img, db_path='/content/images', enforce_detection=False)
27
- if not identity.empty:
28
- matched_image = identity.iloc[0]['identity'].split('/')[-1]
29
- person_info = get_person_data(matched_image)
30
- return person_info
31
- except:
32
- return "No match found"
33
-
34
- return "No face detected"
35
-
36
- # Gradio Interface
37
- iface = gr.Interface(fn=recognize_face,
38
- inputs=gr.inputs.Image(type="numpy"),
39
- outputs=gr.outputs.Textbox(),
40
- live=True)
41
-
42
- iface.launch()
 
1
+ import face_recognition
2
  import pandas as pd
3
+ import numpy as np # Import numpy
4
+
5
+ # Assuming the uploaded CSV file is named 'photo.csv' and the folder containing images is named 'image'
6
+ image_dir = "image"
7
+ info_path = "photo.csv"
8
+
9
+ def load_dataset():
10
+ """Loads the dataset from CSV and image folder."""
11
+ try:
12
+ data = pd.read_csv(info_path)
13
+ print(f"CSV file loaded successfully: {info_path}")
14
+ except FileNotFoundError:
15
+ print(f"Error: CSV file not found at {info_path}")
16
+ return None, None, None
17
+ except Exception as e:
18
+ print(f"Error reading CSV file: {e}")
19
+ return None, None, None
20
+
21
+ known_face_encodings = []
22
+ known_face_names = []
23
+ for index, row in data.iterrows():
24
+ image_path = f"{image_dir}/{row['Name']}"
25
+ try:
26
+ image = face_recognition.load_image_file(image_path)
27
+ face_encoding = face_recognition.face_encodings(image)
28
+ if len(face_encoding) > 0:
29
+ known_face_encodings.append(face_encoding[0])
30
+ known_face_names.append(row['Name'])
31
+ else:
32
+ print(f"No face detected in {image_path}")
33
+ except FileNotFoundError:
34
+ print(f"Error: Image file not found at {image_path}")
35
+ except Exception as e:
36
+ print(f"Error processing image: {e}")
37
+ continue
38
+
39
+ return known_face_encodings, known_face_names, data
40
+
41
+ def recognize_face(img):
42
+ """Recognizes faces in an image."""
43
+ try:
44
+ face_locations = face_recognition.face_locations(img)
45
+ face_encodings = face_recognition.face_encodings(img, face_locations)
46
+
47
+ for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
48
+ matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
49
+ name = "Unknown"
50
+
51
+ face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
52
+ best_match_index = np.argmin(face_distances)
53
+ if matches[best_match_index]:
54
+ name = known_face_names[best_match_index]
55
+ person_info = data[data['Name'] == name]
56
+ cnic = person_info['CNIC'].values[0]
57
+ age = person_info['Age'].values[0]
58
+ hometown = person_info['Hometown'].values[0]
59
+ return f"{name}\nCNIC: {cnic}\nAge: {age}\nHometown: {hometown}"
60
+ return "No face detected."
61
+ except Exception as e:
62
+ return f"An error occurred: {e}"
63
+
64
+ # Load the dataset
65
+ known_face_encodings, known_face_names, data = load_dataset()
66
+
67
+ if known_face_encodings and data is not None:
68
+ # Define the function to be used by the app
69
+ def app(image):
70
+ """Main function of the app that takes an image and returns the recognized face information."""
71
+ return recognize_face(image)
72
+ else:
73
+ print("Error: Failed to load dataset or encode faces.")
74
+
75
+ # Launch the app (if data loaded successfully)
76
+ if known_face_encodings and data is not None:
77
+ from PIL import Image # Optional dependency for handling potential image format issues
78
+
79
+ def preprocess_image(image):
80
+ """Preprocess the uploaded image if necessary (e.g., convert to RGB)."""
81
+ if isinstance(image, Image.Image):
82
+ return np.array(image.convert('RGB'))
83
  else:
84
+ return image
85
+
86
+ app = app.preprocess(preprocess_image) # Apply preprocessing if needed