Dapphari commited on
Commit
f321dde
·
verified ·
1 Parent(s): f0431c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -41
app.py CHANGED
@@ -1,44 +1,94 @@
1
  import gradio as gr
2
- from tensorflow.keras.models import load_model
3
- from PIL import Image, ImageOps
4
  import numpy as np
5
 
6
- # Load the trained model
7
- model = load_model("model/keras_model.h5", compile=False)
8
-
9
- # Load the emotion labels
10
- emotion_labels = open("model/labels.txt", "r").readlines()
11
-
12
- # Define the prediction function
13
- def predict_emotion(image):
14
- # Convert image to RGB and preprocess
15
- image = image.convert("RGB")
16
- size = (224, 224)
17
- image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
18
- image_array = np.asarray(image)
19
-
20
- # Normalize the image
21
- normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
22
- data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
23
- data[0] = normalized_image_array
24
-
25
- # Predict the emotion
26
- prediction = model.predict(data)
27
- index = np.argmax(prediction)
28
- emotion = emotion_labels[index].strip()
29
- confidence_score = prediction[0][index]
30
-
31
- # Return the predicted emotion and confidence score
32
- return f"Emotion: {emotion}, Confidence Score: {confidence_score:.2f}"
33
-
34
- # Define the Gradio interface
35
- interface = gr.Interface(
36
- fn=predict_emotion,
37
- inputs=gr.Image(type="pil"),
38
- outputs="text",
39
- title="Emotion Detection",
40
- description="Upload an image to detect the emotion.",
41
- )
42
-
43
- # Launch the interface
44
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import tensorflow as tf
 
3
  import numpy as np
4
 
5
+ def load_labels(filename):
6
+ with open(filename, "r") as file:
7
+ return [line.strip() for line in file.readlines()]
8
+
9
+ # Function to load the trained model and predict emotion
10
+ def model_prediction(test_image):
11
+ model = tf.keras.models.load_model("model/keras_model.h5")
12
+ image = tf.keras.preprocessing.image.load_img(test_image, target_size=(48, 48), color_mode="grayscale")
13
+ input_arr = tf.keras.preprocessing.image.img_to_array(image) / 255.0
14
+ input_arr = np.expand_dims(input_arr, axis=0)
15
+ predictions = model.predict(input_arr)
16
+ return predictions
17
+
18
+ labels = load_labels("labels.txt")
19
+
20
+ def get_color(value):
21
+ if value >= 75:
22
+ return "label_red"
23
+ elif value >= 50:
24
+ return "label_yellow"
25
+ else:
26
+ return "label_green"
27
+
28
+ def create_colored_box(value):
29
+ color_class = get_color(value)
30
+ return gr.Label(value=f"{value:.2f}%", elem_id=color_class)
31
+
32
+ def predict_emotion(test_image):
33
+ predictions = model_prediction(test_image)
34
+ emotion_index = np.argmax(predictions)
35
+ emotion_probability = predictions[0][emotion_index] * 100
36
+ emotion_name = labels[emotion_index]
37
+
38
+ # Predict level of danger based on emotion
39
+ danger_level = 0
40
+ if emotion_name == "sad":
41
+ danger_level = min(100, emotion_probability * 1.2)
42
+ elif emotion_name == "fearful":
43
+ danger_level = min(100, emotion_probability * 1.5)
44
+ elif emotion_name == "fake_expression":
45
+ danger_level = 70 # Example fixed percentage for fake expression
46
+
47
+ return (
48
+ emotion_name,
49
+ create_colored_box(emotion_probability),
50
+ create_colored_box(danger_level)
51
+ )
52
+
53
+ def home():
54
+ return (
55
+ "# Welcome to Emotion Analysis for Women Safety! 🌟\n\n"
56
+ "Our mission is to analyze facial emotions and assess the level of potential danger based on detected expressions. "
57
+ "This tool is designed to assist in identifying situations where immediate action might be needed to ensure safety.\n\n"
58
+ "### Features\n"
59
+ "- Detect facial emotions with high accuracy.\n"
60
+ "- Predict potential danger levels based on emotion analysis.\n"
61
+ "- User-friendly interface for seamless experience.\n\n"
62
+ "### How to Use\n"
63
+ "1. Upload an image showing the face.\n"
64
+ "2. View detected emotions and danger percentage.\n"
65
+ "3. Take necessary actions based on insights."
66
+ )
67
+
68
+ with gr.Blocks(css="""
69
+ .label_green { background-color: green; color: white; }
70
+ .label_yellow { background-color: yellow; color: black; }
71
+ .label_red { background-color: red; color: white; }
72
+ """) as demo:
73
+ gr.Markdown("# Emotion Analysis for Women Safety")
74
+ gr.Image("logo.webp")
75
+ with gr.Tabs():
76
+ with gr.TabItem("Home"):
77
+ gr.Markdown(home())
78
+ with gr.TabItem("Emotion Analysis"):
79
+ gr.Markdown("## Upload a facial image for emotion analysis:")
80
+ test_image = gr.Image(type="filepath", label="Upload Image")
81
+
82
+ with gr.Row():
83
+ predict_btn = gr.Button("Analyze Emotion")
84
+ emotion_label = gr.Label(label="Detected Emotion")
85
+ probability_label = gr.Label(label="Emotion Probability")
86
+ danger_label = gr.Label(label="Danger Level (%)")
87
+
88
+ predict_btn.click(predict_emotion, inputs=test_image, outputs=[
89
+ emotion_label,
90
+ probability_label,
91
+ danger_label
92
+ ])
93
+
94
+ demo.launch()