Spaces:
Sleeping
Sleeping
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 | |
from fastapi import FastAPI | |
app = FastAPI() | |
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 | |
def index(): | |
return render_template("index.html") | |
# Route to handle file upload and prediction | |
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 | |