Manubett1234 commited on
Commit
2326dfd
Β·
verified Β·
1 Parent(s): 8571199

Update app.py

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