-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
70 lines (55 loc) · 2.54 KB
/
Copy pathapp.py
File metadata and controls
70 lines (55 loc) · 2.54 KB
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
import os
import numpy as np
import librosa
import tensorflow as tf
from flask import Flask, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
from sklearn.preprocessing import LabelEncoder
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Suppresses INFO, WARNING, and ERROR logs
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0' # Disables oneDNN custom ops (optional)
# Initialize Flask app
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
# Load model and label encoder
model = tf.keras.models.load_model("saved_models/audio_classification.keras")
encoder = LabelEncoder()
encoder.classes_ = np.load("classes.npy", allow_pickle=True)
# Feature extraction
def extract_features(file_path):
audio, sample_rate = librosa.load(file_path, res_type='kaiser_fast')
mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)
mfccs_scaled = np.mean(mfccs.T, axis=0)
return mfccs_scaled.reshape(1, -1)
# Routes
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
if "file" not in request.files:
return render_template("index.html", prediction=None, error="No file part")
file = request.files["file"]
if file.filename == "" or file.filename is None:
return render_template("index.html", prediction=None, error="No selected file")
filename = secure_filename(file.filename)
if not filename:
return render_template("index.html", prediction=None, error="Invalid filename")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
try:
features = extract_features(filepath)
prediction = model.predict(features)
predicted_index = np.argmax(prediction, axis=1)
predicted_label = encoder.inverse_transform(predicted_index)[0]
return render_template("index.html", prediction=predicted_label, audio_file=filename)
except Exception as e:
return render_template("index.html", prediction=None, error=str(e))
return render_template("index.html", prediction=None)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == "__main__":
# Create uploads directory if it doesn't exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Use environment variables for production
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)