Spaces:
Sleeping
Sleeping
File size: 3,354 Bytes
1c19314 |
1 2 3 4 5 6 7 8 9 10 11 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 100 |
import os
import pickle
import joblib
import numpy as np
from flask_cors import CORS
from flask import Flask, request, render_template, jsonify
from werkzeug.utils import secure_filename
from extract import extract_features # Import feature extractor
# Initialize Flask app
app = Flask(__name__)
CORS(app) # Allow all cross-origin requests
# Set upload folder and allowed file types
UPLOAD_FOLDER = "uploads"
ALLOWED_EXTENSIONS = {"wav", "mp3", "ogg", "m4a"}
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# Load trained model, scaler, and feature list
model_path = "models/gender_model_lr.pkl"
scaler_path = "models/scaler_gender_model_lr.pkl"
feature_list_path = "models/feature_list.pkl"
model = joblib.load(model_path)
scaler = joblib.load(scaler_path)
with open(feature_list_path, "rb") as f:
feature_list = pickle.load(f)
print("β
Model, Scaler, and Feature List Loaded Successfully!")
# Function to check valid file extensions
def allowed_file(filename):
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
# Route to render the HTML interface
@app.route("/")
def index():
return render_template("index.html")
# Route to handle file upload and prediction
@app.route("/predict", methods=["POST"])
def predict():
if "audio" not in request.files:
print("β No file uploaded")
return jsonify({"error": "No file uploaded"}), 400
file = request.files["audio"]
print(f"π₯ Received file: {file.filename}, Type: {file.content_type}") # β
Debugging line
if file.filename == "":
return jsonify({"error": "No selected file"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
file.save(filepath)
print(f"π’ Processing file: {filename}")
try:
# Extract features
features = extract_features(filepath)
if features is None:
return jsonify({"error": "Feature extraction failed"}), 500
print(f"π’ Extracted {len(features)} features.")
# Scale features
features_scaled = scaler.transform([features])
print("π’ Features scaled successfully.")
# Predict gender
prediction = model.predict(features_scaled)[0]
confidence = model.predict_proba(features_scaled)[0]
print("π’ Prediction completed.")
# Format response
result = {
"gender": "Female" if prediction == 1 else "Male",
"confidence": float(max(confidence)),
"age_group": "Unknown" # Temporary fix to avoid breaking frontend
}
print(f"β
Result: {result}")
return jsonify(result)
except Exception as e:
print(f"β Error: {e}")
return jsonify({"error": str(e)}), 500
finally:
os.remove(filepath) # Delete temp file
return jsonify({"error": "Invalid file format"}), 400
# Run Flask app
if __name__ == "__main__":
app.run(debug=True, use_reloader=False) # Disable reloader
|