Upload 32 files
Browse files- app.py +146 -0
- clean_requirements.txt +93 -0
- comparison2.py +187 -0
- knn.py +35 -0
- logisticregression.py +35 -0
- randomforest.py +35 -0
- requirements.txt +1 -0
- svm.py +35 -0
app.py
CHANGED
|
@@ -9,6 +9,10 @@ from cnn_emotion import detect_emotion as detect_emotion_cnn
|
|
| 9 |
from cnn_resnet import detect_cnn_resnetemotion
|
| 10 |
|
| 11 |
from cnn import detect_cnn
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
import logging
|
| 14 |
|
|
@@ -29,6 +33,21 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
|
| 29 |
def home():
|
| 30 |
return render_template('index.html')
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
@app.route('/vit')
|
| 34 |
def index_vit():
|
|
@@ -136,5 +155,132 @@ def cnn():
|
|
| 136 |
logging.error(f"Failed to save file: {e}")
|
| 137 |
return jsonify({"error": str(e)}), 500
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
if __name__ == "__main__":
|
| 140 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 9 |
from cnn_resnet import detect_cnn_resnetemotion
|
| 10 |
|
| 11 |
from cnn import detect_cnn
|
| 12 |
+
from knn import detect_knn
|
| 13 |
+
from svm import detect_svm
|
| 14 |
+
from randomforest import detect_rf
|
| 15 |
+
from logisticregression import detect_lr
|
| 16 |
|
| 17 |
import logging
|
| 18 |
|
|
|
|
| 33 |
def home():
|
| 34 |
return render_template('index.html')
|
| 35 |
|
| 36 |
+
@app.route('/knn')
|
| 37 |
+
def index_knn():
|
| 38 |
+
return render_template('knn.html')
|
| 39 |
+
|
| 40 |
+
@app.route('/svm')
|
| 41 |
+
def index_svm():
|
| 42 |
+
return render_template('svm.html')
|
| 43 |
+
|
| 44 |
+
@app.route('/logistic_regression')
|
| 45 |
+
def index_lr():
|
| 46 |
+
return render_template('lr.html')
|
| 47 |
+
|
| 48 |
+
@app.route('/randomforest')
|
| 49 |
+
def index_rf():
|
| 50 |
+
return render_template('rf.html')
|
| 51 |
|
| 52 |
@app.route('/vit')
|
| 53 |
def index_vit():
|
|
|
|
| 155 |
logging.error(f"Failed to save file: {e}")
|
| 156 |
return jsonify({"error": str(e)}), 500
|
| 157 |
|
| 158 |
+
@app.route('/knn', methods=['POST'])
|
| 159 |
+
def knnn():
|
| 160 |
+
if "frame" not in request.files:
|
| 161 |
+
logging.warning("No frame in request")
|
| 162 |
+
return jsonify({"error": "No frame received"}), 400
|
| 163 |
+
file = request.files["frame"]
|
| 164 |
+
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
|
| 165 |
+
logging.info(f"File saved to {filepath}")
|
| 166 |
+
file.save(filepath)
|
| 167 |
+
try:
|
| 168 |
+
emotion, image_base64 = detect_knn(filepath)
|
| 169 |
+
return jsonify({"emotion": emotion, "image": image_base64})
|
| 170 |
+
except Exception as e:
|
| 171 |
+
logging.error(f"Failed to save file: {e}")
|
| 172 |
+
return jsonify({"error": str(e)}), 500
|
| 173 |
+
|
| 174 |
+
@app.route('/svm', methods=['POST'])
|
| 175 |
+
def svmm():
|
| 176 |
+
if "frame" not in request.files:
|
| 177 |
+
logging.warning("No frame in request")
|
| 178 |
+
return jsonify({"error": "No frame received"}), 400
|
| 179 |
+
file = request.files["frame"]
|
| 180 |
+
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
|
| 181 |
+
logging.info(f"File saved to {filepath}")
|
| 182 |
+
file.save(filepath)
|
| 183 |
+
try:
|
| 184 |
+
emotion, image_base64 = detect_svm(filepath)
|
| 185 |
+
return jsonify({"emotion": emotion, "image": image_base64})
|
| 186 |
+
except Exception as e:
|
| 187 |
+
logging.error(f"Failed to save file: {e}")
|
| 188 |
+
return jsonify({"error": str(e)}), 500
|
| 189 |
+
|
| 190 |
+
@app.route('/randomforest', methods=['POST'])
|
| 191 |
+
def rff():
|
| 192 |
+
if "frame" not in request.files:
|
| 193 |
+
logging.warning("No frame in request")
|
| 194 |
+
return jsonify({"error": "No frame received"}), 400
|
| 195 |
+
file = request.files["frame"]
|
| 196 |
+
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
|
| 197 |
+
logging.info(f"File saved to {filepath}")
|
| 198 |
+
file.save(filepath)
|
| 199 |
+
try:
|
| 200 |
+
emotion, image_base64 = detect_rf(filepath)
|
| 201 |
+
return jsonify({"emotion": emotion, "image": image_base64})
|
| 202 |
+
except Exception as e:
|
| 203 |
+
logging.error(f"Failed to save file: {e}")
|
| 204 |
+
return jsonify({"error": str(e)}), 500
|
| 205 |
+
|
| 206 |
+
@app.route('/logistic_regression', methods=['POST'])
|
| 207 |
+
def lr():
|
| 208 |
+
if "frame" not in request.files:
|
| 209 |
+
logging.warning("No frame in request")
|
| 210 |
+
return jsonify({"error": "No frame received"}), 400
|
| 211 |
+
file = request.files["frame"]
|
| 212 |
+
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
|
| 213 |
+
logging.info(f"File saved to {filepath}")
|
| 214 |
+
file.save(filepath)
|
| 215 |
+
try:
|
| 216 |
+
emotion, image_base64 = detect_lr(filepath)
|
| 217 |
+
return jsonify({"emotion": emotion, "image": image_base64})
|
| 218 |
+
except Exception as e:
|
| 219 |
+
logging.error(f"Failed to save file: {e}")
|
| 220 |
+
return jsonify({"error": str(e)}), 500
|
| 221 |
+
|
| 222 |
+
@app.route("/reports")
|
| 223 |
+
def show_reports():
|
| 224 |
+
svm_report = """[RESULTS] SVM Classification Report
|
| 225 |
+
precision recall f1-score support
|
| 226 |
+
angry 0.33 0.35 0.34 779
|
| 227 |
+
disgust 0.56 0.16 0.25 92
|
| 228 |
+
fear 0.33 0.25 0.29 838
|
| 229 |
+
happy 0.59 0.68 0.63 1473
|
| 230 |
+
neutral 0.42 0.44 0.43 987
|
| 231 |
+
sad 0.35 0.33 0.34 977
|
| 232 |
+
surprise 0.57 0.54 0.55 596
|
| 233 |
+
accuracy 0.45 5742
|
| 234 |
+
macro avg 0.45 0.39 0.40 5742
|
| 235 |
+
weighted avg 0.44 0.45 0.44 5742"""
|
| 236 |
+
|
| 237 |
+
rf_report = """[RESULTS] Random Forest Classification Report
|
| 238 |
+
precision recall f1-score support
|
| 239 |
+
angry 0.38 0.20 0.26 779
|
| 240 |
+
disgust 1.00 0.27 0.43 92
|
| 241 |
+
fear 0.39 0.21 0.28 838
|
| 242 |
+
happy 0.47 0.82 0.60 1473
|
| 243 |
+
neutral 0.40 0.43 0.41 987
|
| 244 |
+
sad 0.37 0.31 0.34 977
|
| 245 |
+
surprise 0.71 0.50 0.58 596
|
| 246 |
+
accuracy 0.45 5742
|
| 247 |
+
macro avg 0.53 0.39 0.41 5742
|
| 248 |
+
weighted avg 0.45 0.45 0.42 5742"""
|
| 249 |
+
|
| 250 |
+
knn_report = """[RESULTS] k-NN Classification Report
|
| 251 |
+
precision recall f1-score support
|
| 252 |
+
angry 0.34 0.35 0.35 779
|
| 253 |
+
disgust 0.39 0.36 0.38 92
|
| 254 |
+
fear 0.38 0.31 0.34 838
|
| 255 |
+
happy 0.53 0.75 0.62 1473
|
| 256 |
+
neutral 0.39 0.42 0.40 987
|
| 257 |
+
sad 0.40 0.21 0.28 977
|
| 258 |
+
surprise 0.56 0.47 0.51 596
|
| 259 |
+
accuracy 0.45 5742
|
| 260 |
+
macro avg 0.43 0.41 0.41 5742
|
| 261 |
+
weighted avg 0.44 0.45 0.43 5742"""
|
| 262 |
+
|
| 263 |
+
lr_report = """[RESULTS] Logistic Regression Classification Report
|
| 264 |
+
precision recall f1-score support
|
| 265 |
+
angry 0.33 0.31 0.32 779
|
| 266 |
+
disgust 0.56 0.15 0.24 92
|
| 267 |
+
fear 0.32 0.22 0.26 838
|
| 268 |
+
happy 0.57 0.70 0.63 1473
|
| 269 |
+
neutral 0.41 0.43 0.42 987
|
| 270 |
+
sad 0.34 0.31 0.32 977
|
| 271 |
+
surprise 0.51 0.55 0.53 596
|
| 272 |
+
accuracy 0.44 5742
|
| 273 |
+
macro avg 0.43 0.38 0.39 5742
|
| 274 |
+
weighted avg 0.43 0.44 0.43 5742"""
|
| 275 |
+
|
| 276 |
+
return render_template(
|
| 277 |
+
"classification_reports.html",
|
| 278 |
+
svm_report=svm_report,
|
| 279 |
+
rf_report=rf_report,
|
| 280 |
+
knn_report=knn_report,
|
| 281 |
+
lr_report=lr_report
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
if __name__ == "__main__":
|
| 286 |
app.run(host="0.0.0.0", port=7860)
|
clean_requirements.txt
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py==2.2.2
|
| 2 |
+
astunparse==1.6.3
|
| 3 |
+
blinker==1.9.0
|
| 4 |
+
cachetools==5.5.2
|
| 5 |
+
certifi==2025.1.31
|
| 6 |
+
charset-normalizer==3.4.1
|
| 7 |
+
click==8.1.8
|
| 8 |
+
clip @ git+https://github.com/openai/CLIP.git@dcba3cb2e2827b402d2701e7e1c7d9fed8a20ef1
|
| 9 |
+
colorama==0.4.6
|
| 10 |
+
contourpy==1.3.1
|
| 11 |
+
cycler==0.12.1
|
| 12 |
+
filelock==3.18.0
|
| 13 |
+
Flask==3.1.0
|
| 14 |
+
flask-cors==5.0.1
|
| 15 |
+
flatbuffers==25.2.10
|
| 16 |
+
fonttools==4.57.0
|
| 17 |
+
fsspec==2025.3.2
|
| 18 |
+
ftfy==6.3.1
|
| 19 |
+
gast==0.4.0
|
| 20 |
+
google-auth==2.38.0
|
| 21 |
+
google-auth-oauthlib==1.0.0
|
| 22 |
+
google-pasta==0.2.0
|
| 23 |
+
grpcio==1.71.0
|
| 24 |
+
h5py==3.13.0
|
| 25 |
+
huggingface-hub==0.30.2
|
| 26 |
+
idna==3.10
|
| 27 |
+
imageio==2.37.0
|
| 28 |
+
itsdangerous==2.2.0
|
| 29 |
+
Jinja2==3.1.6
|
| 30 |
+
joblib==1.4.2
|
| 31 |
+
keras==2.15.0
|
| 32 |
+
kiwisolver==1.4.8
|
| 33 |
+
lazy_loader==0.4
|
| 34 |
+
libclang==18.1.1
|
| 35 |
+
Markdown==3.8
|
| 36 |
+
markdown-it-py==3.0.0
|
| 37 |
+
MarkupSafe==3.0.2
|
| 38 |
+
matplotlib==3.7.2
|
| 39 |
+
mdurl==0.1.2
|
| 40 |
+
ml-dtypes==0.2.0
|
| 41 |
+
mpmath==1.3.0
|
| 42 |
+
namex==0.0.8
|
| 43 |
+
networkx==3.4.2
|
| 44 |
+
numpy==1.26.4
|
| 45 |
+
oauthlib==3.2.2
|
| 46 |
+
opencv-python==4.11.0.86
|
| 47 |
+
opencv-python-headless==4.11.0.86
|
| 48 |
+
opt_einsum==3.4.0
|
| 49 |
+
optree==0.15.0
|
| 50 |
+
packaging==24.2
|
| 51 |
+
pandas==2.2.3
|
| 52 |
+
pillow==11.1.0
|
| 53 |
+
protobuf==4.25.6
|
| 54 |
+
pyasn1==0.6.1
|
| 55 |
+
pyasn1_modules==0.4.2
|
| 56 |
+
Pygments==2.19.1
|
| 57 |
+
pyparsing==3.0.9
|
| 58 |
+
python-dateutil==2.9.0.post0
|
| 59 |
+
pytz==2025.2
|
| 60 |
+
PyYAML==6.0.2
|
| 61 |
+
regex==2024.11.6
|
| 62 |
+
requests==2.31.0
|
| 63 |
+
requests-oauthlib==2.0.0
|
| 64 |
+
rich==14.0.0
|
| 65 |
+
rsa==4.9
|
| 66 |
+
safetensors==0.5.3
|
| 67 |
+
scikit-image==0.25.2
|
| 68 |
+
scikit-learn==1.6.1
|
| 69 |
+
scipy==1.15.2
|
| 70 |
+
seaborn==0.12.2
|
| 71 |
+
six==1.17.0
|
| 72 |
+
sympy==1.13.1
|
| 73 |
+
tensorboard==2.15.2
|
| 74 |
+
tensorboard-data-server==0.7.2
|
| 75 |
+
tensorboard-plugin-wit==1.8.1
|
| 76 |
+
tensorflow==2.15.0
|
| 77 |
+
tensorflow-estimator==2.15.0
|
| 78 |
+
tensorflow-intel==2.15.0
|
| 79 |
+
tensorflow-io-gcs-filesystem==0.31.0
|
| 80 |
+
termcolor==3.0.1
|
| 81 |
+
threadpoolctl==3.6.0
|
| 82 |
+
tifffile==2025.3.30
|
| 83 |
+
tokenizers==0.21.1
|
| 84 |
+
torch==2.1.2
|
| 85 |
+
torchvision==0.16.2
|
| 86 |
+
tqdm==4.67.1
|
| 87 |
+
transformers==4.51.2
|
| 88 |
+
typing_extensions==4.5.0
|
| 89 |
+
tzdata==2025.2
|
| 90 |
+
urllib3==2.4.0
|
| 91 |
+
wcwidth==0.2.13
|
| 92 |
+
Werkzeug==3.1.3
|
| 93 |
+
wrapt==1.14.1
|
comparison2.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import os
|
| 2 |
+
# import joblib
|
| 3 |
+
# import json
|
| 4 |
+
# import numpy as np
|
| 5 |
+
# import tensorflow as tf
|
| 6 |
+
# from tqdm import tqdm
|
| 7 |
+
# from skimage.io import imread
|
| 8 |
+
# from skimage.transform import resize
|
| 9 |
+
# from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
|
| 10 |
+
# from tensorflow.keras.models import model_from_json
|
| 11 |
+
# from transformers import CLIPProcessor, CLIPModel
|
| 12 |
+
# from torchvision import transforms
|
| 13 |
+
# from PIL import Image
|
| 14 |
+
# from sklearn.model_selection import train_test_split
|
| 15 |
+
|
| 16 |
+
# # ========== Constants ==========
|
| 17 |
+
# IMG_SIZE = 48
|
| 18 |
+
# DATASET_PATH = "train"
|
| 19 |
+
# EMOTIONS = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']
|
| 20 |
+
# MODEL_PATH = '' # Update with the correct path to your model files
|
| 21 |
+
|
| 22 |
+
# # ========== Feature Extraction ==========
|
| 23 |
+
# def extract_hog(img):
|
| 24 |
+
# from skimage.feature import hog
|
| 25 |
+
# return hog(img, pixels_per_cell=(8, 8), cells_per_block=(2, 2), feature_vector=True)
|
| 26 |
+
|
| 27 |
+
# def extract_lbp(img):
|
| 28 |
+
# from skimage.feature import local_binary_pattern
|
| 29 |
+
# lbp = local_binary_pattern(img, P=8, R=1, method="uniform")
|
| 30 |
+
# (hist, _) = np.histogram(lbp.ravel(), bins=np.arange(0, 10), range=(0, 9))
|
| 31 |
+
# hist = hist.astype("float")
|
| 32 |
+
# hist /= (hist.sum() + 1e-7)
|
| 33 |
+
# return hist
|
| 34 |
+
|
| 35 |
+
# def extract_gabor(img):
|
| 36 |
+
# import cv2
|
| 37 |
+
# filters = []
|
| 38 |
+
# ksize = 31
|
| 39 |
+
# for theta in np.arange(0, np.pi, np.pi / 4):
|
| 40 |
+
# kernel = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)
|
| 41 |
+
# filters.append(kernel)
|
| 42 |
+
# feats = [np.mean(cv2.filter2D(img, cv2.CV_8UC3, k)) for k in filters]
|
| 43 |
+
# return feats
|
| 44 |
+
|
| 45 |
+
# def extract_features(img):
|
| 46 |
+
# features = []
|
| 47 |
+
# features.extend(extract_hog(img))
|
| 48 |
+
# features.extend(extract_lbp(img))
|
| 49 |
+
# features.extend(extract_gabor(img))
|
| 50 |
+
# return features
|
| 51 |
+
|
| 52 |
+
# # ========== Dataset Loader ==========
|
| 53 |
+
# def load_dataset_features():
|
| 54 |
+
# X, y = [], []
|
| 55 |
+
# for label in EMOTIONS:
|
| 56 |
+
# folder = os.path.join(DATASET_PATH, label)
|
| 57 |
+
# if not os.path.exists(folder): continue
|
| 58 |
+
# for file in tqdm(os.listdir(folder), desc=f"Extracting {label}"):
|
| 59 |
+
# path = os.path.join(folder, file)
|
| 60 |
+
# try:
|
| 61 |
+
# img = imread(path, as_gray=True)
|
| 62 |
+
# img = resize(img, (IMG_SIZE, IMG_SIZE), anti_aliasing=True)
|
| 63 |
+
# feat = extract_features(img)
|
| 64 |
+
# X.append(feat)
|
| 65 |
+
# y.append(EMOTIONS.index(label))
|
| 66 |
+
# except Exception as e:
|
| 67 |
+
# print(f"[WARN] Skipped {file}: {e}")
|
| 68 |
+
# return np.array(X), np.array(y)
|
| 69 |
+
|
| 70 |
+
# def load_images():
|
| 71 |
+
# images, labels = [], []
|
| 72 |
+
# for label in EMOTIONS:
|
| 73 |
+
# folder = os.path.join(DATASET_PATH, label)
|
| 74 |
+
# if not os.path.exists(folder): continue
|
| 75 |
+
# for file in os.listdir(folder):
|
| 76 |
+
# path = os.path.join(folder, file)
|
| 77 |
+
# try:
|
| 78 |
+
# img = imread(path, as_gray=False)
|
| 79 |
+
# img = resize(img, (IMG_SIZE, IMG_SIZE), anti_aliasing=True)
|
| 80 |
+
# images.append(img)
|
| 81 |
+
# labels.append(EMOTIONS.index(label))
|
| 82 |
+
# except:
|
| 83 |
+
# continue
|
| 84 |
+
# return np.array(images), np.array(labels)
|
| 85 |
+
|
| 86 |
+
# # ========== Evaluation Metrics ==========
|
| 87 |
+
# def evaluate_model(y_true, y_pred, model_name):
|
| 88 |
+
# print(f"\n[RESULTS] {model_name}")
|
| 89 |
+
# print("Accuracy:", accuracy_score(y_true, y_pred))
|
| 90 |
+
# print("Precision:", precision_score(y_true, y_pred, average='weighted'))
|
| 91 |
+
# print("Recall:", recall_score(y_true, y_pred, average='weighted'))
|
| 92 |
+
# print("F1 Score:", f1_score(y_true, y_pred, average='weighted'))
|
| 93 |
+
# print("Confusion Matrix:\n", confusion_matrix(y_true, y_pred))
|
| 94 |
+
|
| 95 |
+
# # ========== Classical Models ==========
|
| 96 |
+
# # def evaluate_classical_models():
|
| 97 |
+
# # X_test, y_test = load_dataset_features()
|
| 98 |
+
# # for model_file in ["k-nn_model.joblib", "logistic_regression_model.joblib", "random_forest_model.joblib", "svm_model.joblib"]:
|
| 99 |
+
# # model = joblib.load(model_file)
|
| 100 |
+
# # y_pred = model.predict(X_test)
|
| 101 |
+
# # evaluate_model(y_test, y_pred, model_file)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# def evaluate_classical_models():
|
| 105 |
+
# print("\n[INFO] Evaluating classical ML models...\n")
|
| 106 |
+
# X, y = load_dataset_features()
|
| 107 |
+
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 108 |
+
|
| 109 |
+
# model_files = {
|
| 110 |
+
# 'KNN': 'k-nn_model.joblib',
|
| 111 |
+
# 'Logistic Regression': 'logistic_regression_model.joblib',
|
| 112 |
+
# 'Random Forest': 'random_forest_model.joblib',
|
| 113 |
+
# 'SVM': 'svm_model.joblib',
|
| 114 |
+
# }
|
| 115 |
+
|
| 116 |
+
# for name, file in model_files.items():
|
| 117 |
+
# print(f"\n--- {name} ---")
|
| 118 |
+
# model_path = os.path.join(MODEL_PATH, file)
|
| 119 |
+
# model = joblib.load(model_path)
|
| 120 |
+
|
| 121 |
+
# expected_input_size = model.n_features_in_
|
| 122 |
+
# if X_test.shape[1] != expected_input_size:
|
| 123 |
+
# print(f"[WARNING] Feature size mismatch for {name}: "
|
| 124 |
+
# f"Expected {expected_input_size}, Got {X_test.shape[1]}. Skipping...")
|
| 125 |
+
# continue
|
| 126 |
+
|
| 127 |
+
# y_pred = model.predict(X_test)
|
| 128 |
+
# acc = accuracy_score(y_test, y_pred)
|
| 129 |
+
# prec = precision_score(y_test, y_pred, average='weighted', zero_division=0)
|
| 130 |
+
# rec = recall_score(y_test, y_pred, average='weighted', zero_division=0)
|
| 131 |
+
# f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)
|
| 132 |
+
|
| 133 |
+
# print(f"Accuracy: {acc:.4f}")
|
| 134 |
+
# print(f"Precision: {prec:.4f}")
|
| 135 |
+
# print(f"Recall: {rec:.4f}")
|
| 136 |
+
# print(f"F1 Score: {f1:.4f}")
|
| 137 |
+
# print("Confusion Matrix:")
|
| 138 |
+
# print(confusion_matrix(y_test, y_pred))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# # ========== CNN/RNN Models ==========
|
| 142 |
+
# def evaluate_keras_model(model_path, X_test, y_test, model_name):
|
| 143 |
+
# model = tf.keras.models.load_model(model_path)
|
| 144 |
+
# y_pred = np.argmax(model.predict(X_test), axis=1)
|
| 145 |
+
# evaluate_model(y_test, y_pred, model_name)
|
| 146 |
+
|
| 147 |
+
# def evaluate_json_model(json_path, weights_path, X_test, y_test, model_name):
|
| 148 |
+
# with open(json_path, 'r') as f:
|
| 149 |
+
# model = model_from_json(f.read())
|
| 150 |
+
# model.load_weights(weights_path)
|
| 151 |
+
# y_pred = np.argmax(model.predict(X_test), axis=1)
|
| 152 |
+
# evaluate_model(y_test, y_pred, model_name)
|
| 153 |
+
|
| 154 |
+
# # ========== ViT/CLIP Model ==========
|
| 155 |
+
# def evaluate_clip_model():
|
| 156 |
+
# processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 157 |
+
# model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 158 |
+
# X_test, y_test = load_images()
|
| 159 |
+
# y_pred = []
|
| 160 |
+
|
| 161 |
+
# for i in tqdm(range(len(X_test))):
|
| 162 |
+
# img = Image.fromarray((X_test[i] * 255).astype(np.uint8))
|
| 163 |
+
# text = [f"a face showing {emotion} emotion" for emotion in EMOTIONS]
|
| 164 |
+
# inputs = processor(text=text, images=img, return_tensors="pt", padding=True)
|
| 165 |
+
# outputs = model(**inputs)
|
| 166 |
+
# logits_per_image = outputs.logits_per_image
|
| 167 |
+
# pred = logits_per_image.argmax().item()
|
| 168 |
+
# y_pred.append(pred)
|
| 169 |
+
|
| 170 |
+
# evaluate_model(y_test, y_pred, "ViT-B/32 (CLIP)")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# # ========== Run All ==========
|
| 175 |
+
# if __name__ == '__main__':
|
| 176 |
+
# # evaluate_classical_models()
|
| 177 |
+
|
| 178 |
+
# X_raw, y_raw = load_images()
|
| 179 |
+
# X_raw = X_raw.reshape(-1, IMG_SIZE, IMG_SIZE)
|
| 180 |
+
|
| 181 |
+
# # X_raw = X_raw.reshape(-1, IMG_SIZE, IMG_SIZE, 3)
|
| 182 |
+
|
| 183 |
+
# evaluate_keras_model("emotion_detector_model.h5", X_raw, y_raw, "CNN Emotion Model")
|
| 184 |
+
# evaluate_keras_model("cnn_rnn_model_from_dir.h5", X_raw, y_raw, "CNN + RNN Emotion Model")
|
| 185 |
+
# evaluate_json_model("model_cleaned.json", "model.weights.h5", X_raw, y_raw, "Custom JSON + Weights Model")
|
| 186 |
+
|
| 187 |
+
# # evaluate_clip_model()
|
knn.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import base64
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
import logging
|
| 6 |
+
import joblib
|
| 7 |
+
|
| 8 |
+
# Load KNN model globally
|
| 9 |
+
knn_model = joblib.load('k-nn_model.joblib')
|
| 10 |
+
|
| 11 |
+
# Emotion classes
|
| 12 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 13 |
+
|
| 14 |
+
def detect_knn(image_path):
|
| 15 |
+
frame = cv2.imread(image_path)
|
| 16 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 17 |
+
resized = cv2.resize(gray, (48, 48)) # 48x48
|
| 18 |
+
norm_img = resized / 255.0
|
| 19 |
+
|
| 20 |
+
# Feature extraction similar to training: horizontal chunks
|
| 21 |
+
chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] # 6 chunks of 8px
|
| 22 |
+
sequence = np.stack([chunk.flatten() for chunk in chunks]) # (6, 384)
|
| 23 |
+
features = sequence.flatten() # (2304,)
|
| 24 |
+
features = features[:994] # match training shape
|
| 25 |
+
|
| 26 |
+
features = features.reshape(1, -1)
|
| 27 |
+
|
| 28 |
+
prediction = knn_model.predict(features)[0]
|
| 29 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 30 |
+
emotion = class_labels[prediction]
|
| 31 |
+
|
| 32 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
| 33 |
+
frame_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 34 |
+
|
| 35 |
+
return emotion, frame_base64
|
logisticregression.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import base64
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
import logging
|
| 6 |
+
import joblib
|
| 7 |
+
|
| 8 |
+
# Load KNN model globally
|
| 9 |
+
knn_model = joblib.load('logistic_regression_model.joblib')
|
| 10 |
+
|
| 11 |
+
# Emotion classes
|
| 12 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 13 |
+
|
| 14 |
+
def detect_lr(image_path):
|
| 15 |
+
frame = cv2.imread(image_path)
|
| 16 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 17 |
+
resized = cv2.resize(gray, (48, 48)) # 48x48
|
| 18 |
+
norm_img = resized / 255.0
|
| 19 |
+
|
| 20 |
+
# Feature extraction similar to training: horizontal chunks
|
| 21 |
+
chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] # 6 chunks of 8px
|
| 22 |
+
sequence = np.stack([chunk.flatten() for chunk in chunks]) # (6, 384)
|
| 23 |
+
features = sequence.flatten() # (2304,)
|
| 24 |
+
features = features[:994] # match training shape
|
| 25 |
+
|
| 26 |
+
features = features.reshape(1, -1)
|
| 27 |
+
|
| 28 |
+
prediction = knn_model.predict(features)[0]
|
| 29 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 30 |
+
emotion = class_labels[prediction]
|
| 31 |
+
|
| 32 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
| 33 |
+
frame_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 34 |
+
|
| 35 |
+
return emotion, frame_base64
|
randomforest.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import base64
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
import logging
|
| 6 |
+
import joblib
|
| 7 |
+
|
| 8 |
+
# Load KNN model globally
|
| 9 |
+
knn_model = joblib.load('random_forest_model.joblib')
|
| 10 |
+
|
| 11 |
+
# Emotion classes
|
| 12 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 13 |
+
|
| 14 |
+
def detect_rf(image_path):
|
| 15 |
+
frame = cv2.imread(image_path)
|
| 16 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 17 |
+
resized = cv2.resize(gray, (48, 48)) # 48x48
|
| 18 |
+
norm_img = resized / 255.0
|
| 19 |
+
|
| 20 |
+
# Feature extraction similar to training: horizontal chunks
|
| 21 |
+
chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] # 6 chunks of 8px
|
| 22 |
+
sequence = np.stack([chunk.flatten() for chunk in chunks]) # (6, 384)
|
| 23 |
+
features = sequence.flatten() # (2304,)
|
| 24 |
+
features = features[:994] # match training shape
|
| 25 |
+
|
| 26 |
+
features = features.reshape(1, -1)
|
| 27 |
+
|
| 28 |
+
prediction = knn_model.predict(features)[0]
|
| 29 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 30 |
+
emotion = class_labels[prediction]
|
| 31 |
+
|
| 32 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
| 33 |
+
frame_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 34 |
+
|
| 35 |
+
return emotion, frame_base64
|
requirements.txt
CHANGED
|
@@ -11,3 +11,4 @@ tqdm
|
|
| 11 |
git+https://github.com/openai/CLIP.git
|
| 12 |
scikit-image
|
| 13 |
joblib
|
|
|
|
|
|
| 11 |
git+https://github.com/openai/CLIP.git
|
| 12 |
scikit-image
|
| 13 |
joblib
|
| 14 |
+
scikit-learn
|
svm.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import base64
|
| 4 |
+
from tensorflow.keras.preprocessing import image
|
| 5 |
+
import logging
|
| 6 |
+
import joblib
|
| 7 |
+
|
| 8 |
+
# Load KNN model globally
|
| 9 |
+
knn_model = joblib.load('svm_model.joblib')
|
| 10 |
+
|
| 11 |
+
# Emotion classes
|
| 12 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 13 |
+
|
| 14 |
+
def detect_svm(image_path):
|
| 15 |
+
frame = cv2.imread(image_path)
|
| 16 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 17 |
+
resized = cv2.resize(gray, (48, 48)) # 48x48
|
| 18 |
+
norm_img = resized / 255.0
|
| 19 |
+
|
| 20 |
+
# Feature extraction similar to training: horizontal chunks
|
| 21 |
+
chunks = [norm_img[:, i*8:(i+1)*8] for i in range(6)] # 6 chunks of 8px
|
| 22 |
+
sequence = np.stack([chunk.flatten() for chunk in chunks]) # (6, 384)
|
| 23 |
+
features = sequence.flatten() # (2304,)
|
| 24 |
+
features = features[:994] # match training shape
|
| 25 |
+
|
| 26 |
+
features = features.reshape(1, -1)
|
| 27 |
+
|
| 28 |
+
prediction = knn_model.predict(features)[0]
|
| 29 |
+
class_labels = ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']
|
| 30 |
+
emotion = class_labels[prediction]
|
| 31 |
+
|
| 32 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
| 33 |
+
frame_base64 = base64.b64encode(buffer).decode('utf-8')
|
| 34 |
+
|
| 35 |
+
return emotion, frame_base64
|