hipples commited on
Commit
ac6d752
·
1 Parent(s): f2c7501

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -20
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
- # capture predictions from deepface emotion model
28
- predictions = DeepFace.analyze(image_data, actions=['emotion'])
29
- # ensure only the main prediction object is processed,
30
- if len(predictions) > 1:
31
- # when more than one face is detected by the backend,
32
- faces = [(face, face['region']['w'] * face['region']['h']) for face in predictions]
33
- # by using the predictions connected to the largest bounding box
34
- new_predictions = sorted(faces, key=lambda x: x[1], reverse=True)[0][0]
35
- emotion_dict = new_predictions['emotion']
36
- else:
37
- emotion_dict = predictions['emotion']
38
- # capture desired prediction data
39
- emotions = list(emotion_dict.keys())
40
- probabilities = list(emotion_dict.values())
41
-
42
- # display in the right column...
43
- col2.header("Emotion Probabilities")
44
- # ...each emotion category and its probability
45
- for i in range(len(emotions)):
46
- col2.subheader(f"{emotions[i]}: {probabilities[i]:.2f}%")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")