blackmamba2408 commited on
Commit
efaf8b2
·
verified ·
1 Parent(s): e406fb4

🚨 EMERGENCY FIX: Ultra-simple app to avoid Gradio schema bug

Browse files
Files changed (1) hide show
  1. app.py +160 -160
app.py CHANGED
@@ -5,181 +5,181 @@ import os
5
  import json
6
 
7
  # Try to import InsightFace
 
8
  try:
9
  from insightface.app.face_analysis import FaceAnalysis
10
  INSIGHTFACE_AVAILABLE = True
11
  print("✓ InsightFace available")
12
- except Exception as e:
13
- INSIGHTFACE_AVAILABLE = False
14
- print(f"InsightFace not available: {e}")
15
 
16
- class SimpleFaceSystem:
17
- def __init__(self):
18
- self.app = None
19
- self.database = {}
20
- self.status = "Initializing..."
21
- self.setup()
22
-
23
- def setup(self):
24
- if INSIGHTFACE_AVAILABLE:
25
- try:
26
- print("Loading InsightFace models...")
27
- self.app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
28
- self.app.prepare(ctx_id=0, det_thresh=0.5, det_size=(640, 640))
29
- self.status = "✓ InsightFace loaded"
30
- print(self.status)
31
- except Exception as e:
32
- print(f"Failed to load InsightFace: {e}")
33
- self.status = f"Demo mode (InsightFace failed: {str(e)[:50]})"
34
- else:
35
- self.status = "Demo mode (InsightFace not available)"
36
-
37
- # Load existing database
38
- try:
39
- if os.path.exists('faces.json'):
40
- with open('faces.json', 'r') as f:
41
- self.database = json.load(f)
42
- print(f"Loaded {len(self.database)} faces from database")
43
- except:
44
- self.database = {}
45
 
46
- def get_embedding(self, image):
47
- if not self.app or not image:
48
- # Demo mode - return random but consistent embedding
49
- if image:
50
- seed = int(np.array(image).mean() * 1000) % 1000
51
- np.random.seed(seed)
52
- emb = np.random.rand(512)
53
- return emb / np.linalg.norm(emb), "Demo embedding"
54
- return None, "No image"
55
-
56
  try:
57
- img_array = np.array(image.convert('RGB'))
58
- faces = self.app.get(img_array)
59
- if not faces:
60
- return None, "No face detected"
61
- face = faces[0]
62
- return face.embedding, f"Face detected (confidence: {face.det_score:.2f})"
63
  except Exception as e:
64
- return None, f"Error: {str(e)}"
 
 
65
 
66
- def add_face(self, image, name):
67
- if not name or not name.strip():
68
- return "Please enter a name", self.get_db_info()
69
-
70
- name = name.strip()
71
- embedding, msg = self.get_embedding(image)
72
-
73
- if embedding is None:
74
- return f"Failed: {msg}", self.get_db_info()
75
-
76
- self.database[name] = embedding.tolist()
77
-
78
- # Save database
79
- try:
80
- with open('faces.json', 'w') as f:
81
- json.dump(self.database, f)
82
- except:
83
- pass
84
-
85
- return f"✓ Added {name} ({msg})", self.get_db_info()
86
 
87
- def match_face(self, image):
88
- if not self.database:
89
- return "Database is empty", ""
90
-
91
- if not image:
92
- return "Please upload an image", ""
93
-
94
- embedding, msg = self.get_embedding(image)
95
- if embedding is None:
96
- return f"Failed: {msg}", ""
97
-
98
- best_match = None
99
- best_score = -1
100
-
101
- for name, stored_emb in self.database.items():
102
- stored_emb = np.array(stored_emb)
103
- score = np.dot(embedding, stored_emb) / (np.linalg.norm(embedding) * np.linalg.norm(stored_emb))
104
- if score > best_score:
105
- best_score = score
106
- best_match = name
107
-
108
- if best_score > 0.6:
109
- return f"✓ Match: {best_match} ({best_score:.2f})", f"Confidence: {best_score*100:.1f}%"
110
- else:
111
- return "❌ No match found", f"Best score: {best_score:.2f} (threshold: 0.6)"
112
 
113
- def get_db_info(self):
114
- if not self.database:
115
- return "Database is empty"
116
- return f"Database has {len(self.database)} faces: {', '.join(list(self.database.keys())[:5])}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- def clear_db(self):
119
- self.database = {}
120
- try:
121
- with open('faces.json', 'w') as f:
122
- json.dump({}, f)
123
- except:
124
- pass
125
- return "Database cleared", ""
 
 
 
 
 
 
126
 
127
- # Initialize system
128
- print("Starting FaceMatch system...")
129
- face_system = SimpleFaceSystem()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- # Create interface
132
- def create_app():
133
- with gr.Blocks(title="FaceMatch Pro") as app:
134
- gr.Markdown("# 🎯 FaceMatch Pro")
135
- gr.Markdown("### Professional Face Recognition System")
136
-
137
- # Status
138
- gr.Textbox(value=face_system.status, label="System Status", interactive=False)
139
-
140
- with gr.Tab("Add Face"):
141
- with gr.Row():
142
- add_img = gr.Image(type="pil", label="Upload Photo")
143
- with gr.Column():
144
- add_name = gr.Textbox(label="Name", placeholder="Enter person's name")
145
- add_btn = gr.Button("Add to Database", variant="primary")
146
- add_result = gr.Textbox(label="Result", lines=2)
147
- add_info = gr.Textbox(label="Database Info", lines=3, value=face_system.get_db_info())
148
-
149
- add_btn.click(
150
- face_system.add_face,
151
- inputs=[add_img, add_name],
152
- outputs=[add_result, add_info]
153
- )
154
-
155
- with gr.Tab("Match Face"):
156
- with gr.Row():
157
- match_img = gr.Image(type="pil", label="Upload Photo to Match")
158
- with gr.Column():
159
- match_btn = gr.Button("Find Match", variant="primary")
160
- match_result = gr.Textbox(label="Match Result", lines=2)
161
- match_conf = gr.Textbox(label="Confidence", lines=2)
162
-
163
- match_btn.click(
164
- face_system.match_face,
165
- inputs=[match_img],
166
- outputs=[match_result, match_conf]
167
- )
168
-
169
- with gr.Tab("Database"):
170
- db_info = gr.Textbox(label="Database Contents", lines=5, value=face_system.get_db_info())
171
- with gr.Row():
172
- refresh_btn = gr.Button("Refresh")
173
- clear_btn = gr.Button("Clear Database", variant="stop")
174
- clear_result = gr.Textbox(label="Result", lines=2)
175
-
176
- refresh_btn.click(lambda: face_system.get_db_info(), outputs=[db_info])
177
- clear_btn.click(face_system.clear_db, outputs=[clear_result, db_info])
178
-
179
- return app
180
 
181
- # Create and launch
182
- demo = create_app()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
  if __name__ == "__main__":
185
  demo.launch()
 
5
  import json
6
 
7
  # Try to import InsightFace
8
+ INSIGHTFACE_AVAILABLE = False
9
  try:
10
  from insightface.app.face_analysis import FaceAnalysis
11
  INSIGHTFACE_AVAILABLE = True
12
  print("✓ InsightFace available")
13
+ except:
14
+ print("InsightFace not available, using demo mode")
 
15
 
16
+ # Global variables
17
+ face_app = None
18
+ face_database = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ def setup_models():
21
+ global face_app
22
+ if INSIGHTFACE_AVAILABLE:
 
 
 
 
 
 
 
23
  try:
24
+ print("Loading InsightFace models...")
25
+ face_app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
26
+ face_app.prepare(ctx_id=0, det_thresh=0.5, det_size=(640, 640))
27
+ print(" InsightFace models loaded")
28
+ return "✓ InsightFace models loaded successfully"
 
29
  except Exception as e:
30
+ print(f"Failed to load InsightFace: {e}")
31
+ return f"Demo mode (InsightFace failed: {str(e)[:50]})"
32
+ return "Demo mode (InsightFace not available)"
33
 
34
+ def load_database():
35
+ global face_database
36
+ try:
37
+ if os.path.exists('faces.json'):
38
+ with open('faces.json', 'r') as f:
39
+ face_database = json.load(f)
40
+ print(f"Loaded {len(face_database)} faces from database")
41
+ except:
42
+ face_database = {}
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ def save_database():
45
+ try:
46
+ with open('faces.json', 'w') as f:
47
+ json.dump(face_database, f)
48
+ except:
49
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ def get_embedding(image):
52
+ global face_app
53
+ if not face_app or not image:
54
+ # Demo mode - return random but consistent embedding
55
+ if image:
56
+ seed = int(np.array(image).mean() * 1000) % 1000
57
+ np.random.seed(seed)
58
+ emb = np.random.rand(512)
59
+ return emb / np.linalg.norm(emb), "Demo embedding"
60
+ return None, "No image"
61
+
62
+ try:
63
+ img_array = np.array(image.convert('RGB'))
64
+ faces = face_app.get(img_array)
65
+ if not faces:
66
+ return None, "No face detected"
67
+ face = faces[0]
68
+ return face.embedding, f"Face detected (confidence: {face.det_score:.2f})"
69
+ except Exception as e:
70
+ return None, f"Error: {str(e)}"
71
 
72
+ def add_face_to_database(image, name):
73
+ if not name or not name.strip():
74
+ return "Please enter a name"
75
+
76
+ name = name.strip()
77
+ embedding, msg = get_embedding(image)
78
+
79
+ if embedding is None:
80
+ return f"Failed: {msg}"
81
+
82
+ face_database[name] = embedding.tolist()
83
+ save_database()
84
+
85
+ return f"✓ Added {name} ({msg}). Database now has {len(face_database)} faces."
86
 
87
+ def match_face_in_database(image):
88
+ if not face_database:
89
+ return "Database is empty. Please add faces first."
90
+
91
+ if not image:
92
+ return "Please upload an image"
93
+
94
+ embedding, msg = get_embedding(image)
95
+ if embedding is None:
96
+ return f"Failed: {msg}"
97
+
98
+ best_match = None
99
+ best_score = -1
100
+
101
+ for name, stored_emb in face_database.items():
102
+ stored_emb = np.array(stored_emb)
103
+ score = np.dot(embedding, stored_emb) / (np.linalg.norm(embedding) * np.linalg.norm(stored_emb))
104
+ if score > best_score:
105
+ best_score = score
106
+ best_match = name
107
+
108
+ if best_score > 0.6:
109
+ return f"✓ Match Found: {best_match} (confidence: {best_score*100:.1f}%)"
110
+ else:
111
+ return f"❌ No match found. Best score: {best_score*100:.1f}% (threshold: 60%)"
112
+
113
+ def get_database_status():
114
+ if not face_database:
115
+ return "Database is empty"
116
+ names = list(face_database.keys())[:5]
117
+ if len(face_database) > 5:
118
+ names.append(f"... and {len(face_database)-5} more")
119
+ return f"Database has {len(face_database)} faces: {', '.join(names)}"
120
 
121
+ def clear_database():
122
+ global face_database
123
+ face_database = {}
124
+ save_database()
125
+ return "Database cleared successfully"
126
+
127
+ # Initialize
128
+ print("Starting FaceMatch system...")
129
+ status_msg = setup_models()
130
+ load_database()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ # Create interface using legacy Interface (more stable than Blocks)
133
+ with gr.Blocks(title="FaceMatch Pro") as demo:
134
+ gr.Markdown("# 🎯 FaceMatch Pro")
135
+ gr.Markdown("### Professional Face Recognition System")
136
+
137
+ # Status
138
+ gr.Markdown(f"**System Status:** {status_msg}")
139
+ gr.Markdown(f"**Database Status:** {get_database_status()}")
140
+
141
+ # Add Face Interface
142
+ gr.Markdown("## Add Face to Database")
143
+ with gr.Row():
144
+ add_image_input = gr.Image(type="pil", label="Upload Photo")
145
+ add_name_input = gr.Textbox(label="Person Name", placeholder="Enter name...")
146
+
147
+ add_button = gr.Button("Add to Database", variant="primary")
148
+ add_output = gr.Textbox(label="Result", lines=2)
149
+
150
+ add_button.click(
151
+ fn=add_face_to_database,
152
+ inputs=[add_image_input, add_name_input],
153
+ outputs=add_output
154
+ )
155
+
156
+ # Match Face Interface
157
+ gr.Markdown("## Find Face Match")
158
+ match_image_input = gr.Image(type="pil", label="Upload Photo to Match")
159
+ match_button = gr.Button("Find Match", variant="primary")
160
+ match_output = gr.Textbox(label="Match Result", lines=3)
161
+
162
+ match_button.click(
163
+ fn=match_face_in_database,
164
+ inputs=match_image_input,
165
+ outputs=match_output
166
+ )
167
+
168
+ # Database Management
169
+ gr.Markdown("## Database Management")
170
+ status_button = gr.Button("Check Database Status")
171
+ clear_button = gr.Button("Clear Database", variant="stop")
172
+ db_output = gr.Textbox(label="Database Status", lines=2)
173
+
174
+ status_button.click(
175
+ fn=get_database_status,
176
+ outputs=db_output
177
+ )
178
+
179
+ clear_button.click(
180
+ fn=clear_database,
181
+ outputs=db_output
182
+ )
183
 
184
  if __name__ == "__main__":
185
  demo.launch()