ImanAmran commited on
Commit
68f1e27
·
1 Parent(s): cc07a1a

Delete old_app.py

Browse files
Files changed (1) hide show
  1. old_app.py +0 -126
old_app.py DELETED
@@ -1,126 +0,0 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- import numpy as np
4
- from scipy.spatial.distance import cosine
5
- import cv2
6
- import os
7
-
8
- from tensorflow.keras.applications import resnet
9
- from tensorflow.keras import layers, Model
10
-
11
- def create_embedding_model():
12
- base_cnn = resnet.ResNet50(weights="imagenet", input_shape=(200, 200, 3), include_top=False)
13
-
14
- flatten = layers.Flatten()(base_cnn.output)
15
- dense1 = layers.Dense(512, activation="relu")(flatten)
16
- dense1 = layers.BatchNormalization()(dense1)
17
- dense2 = layers.Dense(256, activation="relu")(dense1)
18
- dense2 = layers.BatchNormalization()(dense2)
19
- output = layers.Dense(256)(dense2)
20
-
21
- embedding_model = Model(base_cnn.input, output, name="Embedding")
22
-
23
- trainable = False
24
- for layer in base_cnn.layers:
25
- if layer.name == "conv5_block1_out":
26
- trainable = True
27
- layer.trainable = trainable
28
-
29
- return embedding_model
30
-
31
- # K-mean Clustering
32
- from sklearn.cluster import KMeans
33
- import matplotlib.pyplot as plt
34
-
35
- # Threshold
36
- RECOGNITION_THRESHOLD = 0.1 # Adjust as needed
37
- n_clusters = 5 # You can adjust this based on your data
38
- kmeans = KMeans(n_clusters=n_clusters)
39
-
40
- # Load the embedding model
41
- # embedding_model = tf.keras.models.load_model('base_128.h5')
42
- embedding_model = create_embedding_model()
43
- embedding_model.load_weights('base_128.h5')
44
-
45
- # Database to store embeddings and user IDs
46
- user_embeddings = []
47
- user_ids = []
48
-
49
- # Preprocess the image
50
- def preprocess_image(image):
51
- image = cv2.resize(image, (200, 200)) # Resize image to 200x200
52
- image = tf.keras.applications.resnet50.preprocess_input(image)
53
- return np.expand_dims(image, axis=0)
54
-
55
- # Generate embedding
56
- def generate_embedding(image):
57
- preprocessed_image = preprocess_image(image)
58
- return embedding_model.predict(preprocessed_image)[0]
59
-
60
- # Register new user
61
- def register_user(image, user_id):
62
- try:
63
- embedding = generate_embedding(image)
64
- user_embeddings.append(embedding)
65
- user_ids.append(user_id)
66
- return f"User {user_id} registered successfully."
67
- except Exception as e:
68
- return f"Error during registration: {str(e)}"
69
-
70
- # Recognize user
71
- def recognize_user(image):
72
- try:
73
- new_embedding = generate_embedding(image)
74
-
75
- if len(user_embeddings) < n_clusters:
76
- # Handle the case where there are not enough users for K-means
77
- # For example, you could use nearest neighbor search among existing embeddings
78
- # Here, I'm just returning a message for simplicity
79
- return "Not enough registered users for recognition."
80
-
81
- # Update the KMeans model
82
- kmeans.fit(user_embeddings)
83
- cluster_label = kmeans.predict([new_embedding])[0]
84
- distances = kmeans.transform([new_embedding])[0]
85
- min_distance = np.min(distances)
86
-
87
- if min_distance > RECOGNITION_THRESHOLD:
88
- return "User not recognized."
89
-
90
- # Find the user ID(s) in the closest cluster
91
- recognized_user_ids = [user_ids[i] for i, label in enumerate(kmeans.labels_) if label == cluster_label]
92
- return f"Recognized User(s): {', '.join(recognized_user_ids)}"
93
- except Exception as e:
94
- return f"Error during recognition: {str(e)}"
95
-
96
- def plot_clusters():
97
- # Assuming embeddings are 2-dimensional
98
- plt.figure(figsize=(8, 6))
99
- plt.scatter(*zip(*user_embeddings), c=kmeans.labels_)
100
- plt.title('User Embeddings Clustered by K-Means')
101
- plt.xlabel('Embedding Dimension 1')
102
- plt.ylabel('Embedding Dimension 2')
103
- plt.show()
104
-
105
- def main():
106
- with gr.Blocks() as demo:
107
- gr.Markdown("Facial Recognition System")
108
- with gr.Tab("Register"):
109
- with gr.Row():
110
- img_register = gr.Image()
111
- user_id = gr.Textbox(label="User ID")
112
- register_button = gr.Button("Register")
113
- register_output = gr.Textbox()
114
- register_button.click(register_user, inputs=[img_register, user_id], outputs=register_output)
115
-
116
- with gr.Tab("Recognize"):
117
- with gr.Row():
118
- img_recognize = gr.Image()
119
- recognize_button = gr.Button("Recognize")
120
- recognize_output = gr.Textbox()
121
- recognize_button.click(recognize_user, inputs=[img_recognize], outputs=recognize_output)
122
-
123
- demo.launch(share=True)
124
-
125
- if __name__ == "__main__":
126
- main()