Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -24,23 +24,38 @@ if file_name is not None:
|
|
24 |
|
25 |
# capture image data for face analysis
|
26 |
image_data = np.array(image)
|
27 |
-
#
|
28 |
-
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
# capture image data for face analysis
|
26 |
image_data = np.array(image)
|
27 |
+
# define a list of backends in case face cannot be detected
|
28 |
+
backends = ['opencv', 'mtcnn', 'retinaface', 'mediapipe', 'ssd']
|
29 |
+
# attempt tracker
|
30 |
+
attempt = 0
|
31 |
+
|
32 |
+
# retry loop
|
33 |
+
while True:
|
34 |
+
try:
|
35 |
+
# capture predictions from deepface emotion model
|
36 |
+
predictions = DeepFace.analyze(image_data, actions=['emotion'], detector_backend=backends[attempt])
|
37 |
+
# ensure only the main prediction object is processed,
|
38 |
+
if len(predictions) > 1:
|
39 |
+
# when more than one face is detected by the backend,
|
40 |
+
faces = [(face, face['region']['w'] * face['region']['h']) for face in predictions]
|
41 |
+
# by using the predictions connected to the largest bounding box
|
42 |
+
new_predictions = sorted(faces, key=lambda x: x[1], reverse=True)[0][0]
|
43 |
+
emotion_dict = new_predictions['emotion']
|
44 |
+
else:
|
45 |
+
emotion_dict = predictions['emotion']
|
46 |
+
# capture desired prediction data
|
47 |
+
emotions = list(emotion_dict.keys())
|
48 |
+
probabilities = list(emotion_dict.values())
|
49 |
+
# display in the right column...
|
50 |
+
col2.header("Emotion Probabilities")
|
51 |
+
# ...each emotion category and its probability
|
52 |
+
for i in range(len(emotions)):
|
53 |
+
col2.subheader(f"{emotions[i]}: {probabilities[i]:.2f}%")
|
54 |
+
break
|
55 |
+
except Exception as e:
|
56 |
+
# if the analysis fails to detect a face, try a different backend
|
57 |
+
attempt += 1
|
58 |
+
if attempt < len(backends):
|
59 |
+
print(f"Retrying with backend `{backends[attempt]}` due to error: {str(e)}")
|
60 |
+
else:
|
61 |
+
print(f"Failed to analyze image after attempting all detector backends available. Please upload a new image.")
|