Jishan2019 commited on
Commit
c95d0b4
·
verified ·
1 Parent(s): 6f2d6cf

Update file

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +192 -37
src/streamlit_app.py CHANGED
@@ -1,40 +1,195 @@
1
- import altair as alt
2
  import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
  import numpy as np
3
+ import cv2
4
  import streamlit as st
5
+ from PIL import Image
6
+ import onnxruntime as ort
7
+ from huggingface_hub import hf_hub_download
8
 
9
+
10
+ # =========================
11
+ # App UI
12
+ # =========================
13
+ st.set_page_config(page_title="Emotion Detector", page_icon="🙂", layout="centered")
14
+ st.title("🙂 Emotion Detector (Fast)")
15
+ st.caption("Upload a JPG/PNG → detect face(s) → predict emotion for each face.")
16
+
17
+
18
+ # =========================
19
+ # Model labels (FER+ / 8 classes)
20
+ # =========================
21
+ EMOTIONS = ["neutral", "happiness", "surprise", "sadness", "anger", "disgust", "fear", "contempt"]
22
+
23
+
24
+ # =========================
25
+ # Helpers
26
+ # =========================
27
+ def softmax(x: np.ndarray) -> np.ndarray:
28
+ x = x - np.max(x)
29
+ e = np.exp(x)
30
+ return e / (np.sum(e) + 1e-12)
31
+
32
+
33
+ def pil_to_bgr(pil_img: Image.Image) -> np.ndarray:
34
+ rgb = np.array(pil_img.convert("RGB"))
35
+ return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
36
+
37
+
38
+ def bgr_to_pil(bgr: np.ndarray) -> Image.Image:
39
+ rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
40
+ return Image.fromarray(rgb)
41
+
42
+
43
+ def downscale_for_detection(bgr: np.ndarray, max_side: int = 1200):
44
+ """Downscale big images to speed up face detection; return scaled image + scale factors."""
45
+ h, w = bgr.shape[:2]
46
+ m = max(h, w)
47
+ if m <= max_side:
48
+ return bgr, 1.0
49
+ scale = max_side / float(m)
50
+ new_w = int(w * scale)
51
+ new_h = int(h * scale)
52
+ resized = cv2.resize(bgr, (new_w, new_h), interpolation=cv2.INTER_AREA)
53
+ return resized, scale
54
+
55
+
56
+ # =========================
57
+ # Cached resources
58
+ # =========================
59
+ @st.cache_resource
60
+ def load_face_detector():
61
+ # Lightweight, offline face detector
62
+ return cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
63
+
64
+
65
+ @st.cache_resource
66
+ def load_onnx_session():
67
+ """
68
+ Streamlit Cloud friendly:
69
+ - Downloads ONNX model once (cached by HF hub + Streamlit cache)
70
+ - Uses CPUExecutionProvider
71
+ - Conservative threads to avoid contention on shared CPUs
72
+ """
73
+ model_path = hf_hub_download(
74
+ repo_id="onnxmodelzoo/emotion-ferplus-12-int8",
75
+ filename="emotion-ferplus-12-int8.onnx",
76
+ )
77
+
78
+ so = ort.SessionOptions()
79
+ so.intra_op_num_threads = 2
80
+ so.inter_op_num_threads = 1
81
+
82
+ sess = ort.InferenceSession(model_path, sess_options=so, providers=["CPUExecutionProvider"])
83
+ input_name = sess.get_inputs()[0].name
84
+ input_type = sess.get_inputs()[0].type # e.g., tensor(uint8) or tensor(float)
85
+ return sess, input_name, input_type
86
+
87
+
88
+ face_detector = load_face_detector()
89
+ sess, input_name, input_type = load_onnx_session()
90
+
91
+
92
+ def detect_faces(bgr: np.ndarray):
93
+ gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
94
+ faces = face_detector.detectMultiScale(
95
+ gray,
96
+ scaleFactor=1.1,
97
+ minNeighbors=5,
98
+ minSize=(60, 60),
99
+ )
100
+ return faces # list of (x, y, w, h)
101
+
102
+
103
+ def preprocess_face(face_bgr: np.ndarray) -> np.ndarray:
104
+ """
105
+ Model expects: (1, 1, 64, 64) grayscale.
106
+ """
107
+ gray = cv2.cvtColor(face_bgr, cv2.COLOR_BGR2GRAY)
108
+ resized = cv2.resize(gray, (64, 64), interpolation=cv2.INTER_AREA)
109
+ x = resized.reshape(1, 1, 64, 64)
110
+
111
+ # Match the model’s expected dtype
112
+ if "uint8" in input_type:
113
+ x = x.astype(np.uint8)
114
+ else:
115
+ x = x.astype(np.float32)
116
+ return x
117
+
118
+
119
+ def predict_emotion(face_bgr: np.ndarray):
120
+ x = preprocess_face(face_bgr)
121
+ scores = sess.run(None, {input_name: x})[0].reshape(-1) # (8,)
122
+ probs = softmax(scores)
123
+ best_idx = int(np.argmax(probs))
124
+ return best_idx, probs
125
+
126
+
127
+ # =========================
128
+ # Upload + run
129
+ # =========================
130
+ uploaded = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
131
+
132
+ if not uploaded:
133
+ st.info("Upload a JPG/PNG to start.")
134
+ st.stop()
135
+
136
+ img = Image.open(uploaded).convert("RGB")
137
+ bgr_full = pil_to_bgr(img)
138
+
139
+ st.image(img, caption="Uploaded image", use_container_width=True)
140
+
141
+ # Speed optimization: downscale before detection
142
+ bgr_det, scale = downscale_for_detection(bgr_full, max_side=1200)
143
+
144
+ t0 = time.time()
145
+ faces_det = detect_faces(bgr_det)
146
+
147
+ if len(faces_det) == 0:
148
+ st.warning("No face detected. Try a closer, front-facing photo with better lighting.")
149
+ st.stop()
150
+
151
+ # Convert detected face boxes back to full-res coordinates
152
+ faces = []
153
+ inv_scale = 1.0 / scale
154
+ for (x, y, w, h) in faces_det:
155
+ fx = int(x * inv_scale)
156
+ fy = int(y * inv_scale)
157
+ fw = int(w * inv_scale)
158
+ fh = int(h * inv_scale)
159
+ faces.append((fx, fy, fw, fh))
160
+
161
+ st.success(f"Detected {len(faces)} face(s).")
162
+
163
+ # Draw bounding boxes on full-res image for display
164
+ boxed = bgr_full.copy()
165
+ for (x, y, w, h) in faces:
166
+ cv2.rectangle(boxed, (x, y), (x + w, y + h), (0, 255, 0), 2)
167
+
168
+ st.image(bgr_to_pil(boxed), caption="Detected faces", use_container_width=True)
169
+
170
+ st.subheader("Predictions")
171
+
172
+ for i, (x, y, w, h) in enumerate(faces, start=1):
173
+ face = bgr_full[y:y+h, x:x+w]
174
+
175
+ t1 = time.time()
176
+ best_idx, probs = predict_emotion(face)
177
+ ms = (time.time() - t1) * 1000.0
178
+
179
+ best_label = EMOTIONS[best_idx]
180
+ best_prob = float(probs[best_idx])
181
+
182
+ c1, c2 = st.columns([1, 2])
183
+ with c1:
184
+ st.image(bgr_to_pil(face), caption=f"Face #{i}", use_container_width=True)
185
+ with c2:
186
+ st.success(f"Face #{i}: **{best_label}** ({best_prob*100:.1f}%) — {ms:.1f} ms")
187
+ order = np.argsort(-probs)
188
+ for j in order:
189
+ st.progress(float(probs[j]), text=f"{EMOTIONS[int(j)]}: {probs[j]*100:.1f}%")
190
+
191
+ total_ms = (time.time() - t0) * 1000.0
192
+ st.caption(f"Total processing time: {total_ms:.1f} ms (includes face detection + all faces inference)")
193
+
194
+ st.divider()
195
+ st.caption("Developed by Dr. Jishan Ahmed")