srinuksv commited on
Commit
ecaec72
·
verified ·
1 Parent(s): c36d2cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -58
app.py CHANGED
@@ -1,63 +1,122 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from keras_facenet import FaceNet
5
  import gradio as gr
6
+
7
+ # Initialize FaceNet model
8
+ embedder = FaceNet()
9
+
10
+ def img_to_encoding(image, embedder):
11
+ try:
12
+ if image is None:
13
+ print("Debug: Image is None")
14
+ return None
15
+ if not isinstance(image, np.ndarray):
16
+ print(f"Debug: Image is not a numpy array, type(image)={type(image)}")
17
+ return None
18
+
19
+ print(f"Debug: Image shape = {image.shape}, dtype = {image.dtype}")
20
+
21
+ # Convert BGR to RGB and resize to 160x160
22
+ img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
23
+ img = cv2.resize(img, (160, 160))
24
+
25
+ # Get the embedding
26
+ embedding = embedder.embeddings([img])[0]
27
+ return embedding
28
+ except Exception as e:
29
+ print(f"Error in img_to_encoding: {e}")
30
+ return None
31
+
32
+ database = {}
33
+
34
+ def register_user(image, username):
35
+ try:
36
+ if not os.path.exists('images'):
37
+ os.makedirs('images')
38
+
39
+ if image is None or image.size == 0:
40
+ print("Debug: Invalid image input")
41
+ return "Error: Uploaded image is empty or invalid."
42
+
43
+ print(f"Debug: Image received for registration, username={username}")
44
+
45
+ # Save the image to disk
46
+ img_path = f'images/{username}.jpg'
47
+ success = cv2.imwrite(img_path, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
48
+
49
+ if not success:
50
+ print("Debug: Failed to save image to disk")
51
+ return "Error: Failed to save the image."
52
+
53
+ encoding = img_to_encoding(image, embedder)
54
+ if encoding is None:
55
+ return "Error: Failed to process the image."
56
+
57
+ database[username] = encoding
58
+ return f"User '{username}' registered successfully!"
59
+ except Exception as e:
60
+ print(f"Error during registration: {e}")
61
+ return f"Error during registration: {e}"
62
+
63
+ def verify_user(image):
64
+ try:
65
+ if image is None or image.size == 0:
66
+ print("Debug: Invalid image input for verification")
67
+ return "Error: Uploaded image is empty or invalid."
68
+
69
+ print("Debug: Image received for verification")
70
+
71
+ encoding = img_to_encoding(image, embedder)
72
+ if encoding is None:
73
+ return "Error: Failed to process the image."
74
+
75
+ min_dist = 1000
76
+ identity = None
77
+
78
+ for (name, db_enc) in database.items():
79
+ dist = np.linalg.norm(encoding - db_enc)
80
+ if dist < min_dist:
81
+ min_dist = dist
82
+ identity = name
83
+
84
+ if min_dist > 5:
85
+ return "Identity not recognized."
86
+ else:
87
+ return f"It's {identity}, the distance is {min_dist}."
88
+ except Exception as e:
89
+ print(f"Error during verification: {e}")
90
+ return f"Error during verification: {e}"
91
+
92
+ # Gradio Interface for Registration
93
+ register_interface = gr.Interface(
94
+ fn=register_user,
95
+ inputs=[gr.Image(type="numpy", label="Take a Photo or Upload"), gr.Textbox(label="Username")],
96
+ outputs="text",
97
+ title="Register User",
98
+ description="Take a photo or upload an image and enter a username to register."
99
  )
100
 
101
+ # Gradio Interface for Verification
102
+ verify_interface = gr.Interface(
103
+ fn=verify_user,
104
+ inputs=gr.Image(type="numpy", label="Take a Photo or Upload"),
105
+ outputs="text",
106
+ title="Verify User",
107
+ description="Take a photo or upload an image to verify the user's identity."
108
+ )
109
+
110
+ # Combine the interfaces into a single application
111
+ app = gr.Blocks()
112
+
113
+ with app:
114
+ gr.Markdown("# Face Identification System")
115
+ with gr.Tab("Register"):
116
+ register_interface.render()
117
+ with gr.Tab("Verify"):
118
+ verify_interface.render()
119
 
120
+ # Run the Gradio application
121
  if __name__ == "__main__":
122
+ app.launch()