Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,99 +1,100 @@
|
|
1 |
-
import os
|
2 |
-
import pickle
|
3 |
-
import joblib
|
4 |
-
import numpy as np
|
5 |
-
from flask_cors import CORS
|
6 |
-
from flask import Flask, request, render_template, jsonify
|
7 |
-
from werkzeug.utils import secure_filename
|
8 |
-
from extract import extract_features # Import feature extractor
|
9 |
-
|
10 |
-
|
11 |
-
app =
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
"
|
82 |
-
"
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
1 |
+
import os
|
2 |
+
import pickle
|
3 |
+
import joblib
|
4 |
+
import numpy as np
|
5 |
+
from flask_cors import CORS
|
6 |
+
from flask import Flask, request, render_template, jsonify
|
7 |
+
from werkzeug.utils import secure_filename
|
8 |
+
from extract import extract_features # Import feature extractor
|
9 |
+
from fastapi import FastAPI
|
10 |
+
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
CORS(app) # Allow all cross-origin requests
|
14 |
+
|
15 |
+
# Set upload folder and allowed file types
|
16 |
+
UPLOAD_FOLDER = "uploads"
|
17 |
+
ALLOWED_EXTENSIONS = {"wav", "mp3", "ogg", "m4a"}
|
18 |
+
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
|
19 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
20 |
+
|
21 |
+
# Load trained model, scaler, and feature list
|
22 |
+
model_path = "models/gender_model_lr.pkl"
|
23 |
+
scaler_path = "models/scaler_gender_model_lr.pkl"
|
24 |
+
feature_list_path = "models/feature_list.pkl"
|
25 |
+
|
26 |
+
model = joblib.load(model_path)
|
27 |
+
scaler = joblib.load(scaler_path)
|
28 |
+
with open(feature_list_path, "rb") as f:
|
29 |
+
feature_list = pickle.load(f)
|
30 |
+
|
31 |
+
print("β
Model, Scaler, and Feature List Loaded Successfully!")
|
32 |
+
|
33 |
+
# Function to check valid file extensions
|
34 |
+
def allowed_file(filename):
|
35 |
+
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
36 |
+
|
37 |
+
# Route to render the HTML interface
|
38 |
+
@app.route("/")
|
39 |
+
def index():
|
40 |
+
return render_template("index.html")
|
41 |
+
|
42 |
+
# Route to handle file upload and prediction
|
43 |
+
@app.route("/predict", methods=["POST"])
|
44 |
+
def predict():
|
45 |
+
if "audio" not in request.files:
|
46 |
+
print("β No file uploaded")
|
47 |
+
return jsonify({"error": "No file uploaded"}), 400
|
48 |
+
|
49 |
+
file = request.files["audio"]
|
50 |
+
print(f"π₯ Received file: {file.filename}, Type: {file.content_type}") # β
Debugging line
|
51 |
+
|
52 |
+
if file.filename == "":
|
53 |
+
return jsonify({"error": "No selected file"}), 400
|
54 |
+
|
55 |
+
if file and allowed_file(file.filename):
|
56 |
+
filename = secure_filename(file.filename)
|
57 |
+
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
|
58 |
+
file.save(filepath)
|
59 |
+
|
60 |
+
print(f"π’ Processing file: {filename}")
|
61 |
+
|
62 |
+
try:
|
63 |
+
# Extract features
|
64 |
+
features = extract_features(filepath)
|
65 |
+
if features is None:
|
66 |
+
return jsonify({"error": "Feature extraction failed"}), 500
|
67 |
+
|
68 |
+
print(f"π’ Extracted {len(features)} features.")
|
69 |
+
|
70 |
+
# Scale features
|
71 |
+
features_scaled = scaler.transform([features])
|
72 |
+
print("π’ Features scaled successfully.")
|
73 |
+
|
74 |
+
# Predict gender
|
75 |
+
prediction = model.predict(features_scaled)[0]
|
76 |
+
confidence = model.predict_proba(features_scaled)[0]
|
77 |
+
print("π’ Prediction completed.")
|
78 |
+
|
79 |
+
# Format response
|
80 |
+
result = {
|
81 |
+
"gender": "Female" if prediction == 1 else "Male",
|
82 |
+
"confidence": float(max(confidence)),
|
83 |
+
"age_group": "Unknown" # Temporary fix to avoid breaking frontend
|
84 |
+
}
|
85 |
+
|
86 |
+
print(f"β
Result: {result}")
|
87 |
+
|
88 |
+
return jsonify(result)
|
89 |
+
|
90 |
+
except Exception as e:
|
91 |
+
print(f"β Error: {e}")
|
92 |
+
return jsonify({"error": str(e)}), 500
|
93 |
+
finally:
|
94 |
+
os.remove(filepath) # Delete temp file
|
95 |
+
|
96 |
+
return jsonify({"error": "Invalid file format"}), 400
|
97 |
+
|
98 |
+
# Run Flask app
|
99 |
+
if __name__ == "__main__":
|
100 |
+
app.run(debug=True, use_reloader=False) # Disable reloader
|