Update app.py
Browse files
app.py
CHANGED
@@ -1,118 +1,124 @@
|
|
1 |
-
from
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
import
|
8 |
-
|
9 |
-
import
|
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 |
-
return
|
50 |
-
except
|
51 |
-
print(f"Error
|
52 |
-
return None
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
return
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
if file
|
82 |
-
return redirect(request.url)
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
#
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
#
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from asgiref.wsgi import WsgiToAsgi
|
3 |
+
from flask import Flask, render_template, request, redirect, url_for
|
4 |
+
import os
|
5 |
+
import librosa
|
6 |
+
import numpy as np
|
7 |
+
import tensorflow as tf
|
8 |
+
from sklearn.preprocessing import StandardScaler
|
9 |
+
import pickle
|
10 |
+
import subprocess # Untuk menjalankan perintah FFmpeg
|
11 |
+
import threading # Untuk menjalankan penghapusan otomatis file setelah delay
|
12 |
+
from fastapi.middleware.wsgi import WSGIMiddleware
|
13 |
+
|
14 |
+
flask_app = Flask(__name__)
|
15 |
+
|
16 |
+
# Path folder untuk menyimpan file yang diunggah
|
17 |
+
UPLOAD_FOLDER = 'static/uploads'
|
18 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
19 |
+
|
20 |
+
# Load model dan scaler
|
21 |
+
model = tf.keras.models.load_model('model_code1.keras')
|
22 |
+
with open('scaler.pkl', 'rb') as f:
|
23 |
+
scaler = pickle.load(f)
|
24 |
+
|
25 |
+
# Label genre musik
|
26 |
+
genres = ['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']
|
27 |
+
|
28 |
+
# Fungsi untuk menghapus file setelah delay
|
29 |
+
def delete_file_after_delay(file_path, delay=3600):
|
30 |
+
def delete_file():
|
31 |
+
try:
|
32 |
+
if os.path.exists(file_path):
|
33 |
+
os.remove(file_path)
|
34 |
+
print(f"File {file_path} berhasil dihapus setelah {delay} detik.")
|
35 |
+
except Exception as e:
|
36 |
+
print(f"Gagal menghapus file {file_path}: {e}")
|
37 |
+
|
38 |
+
# Jalankan penghapusan file dalam thread baru
|
39 |
+
threading.Timer(delay, delete_file).start()
|
40 |
+
|
41 |
+
# Fungsi untuk mengonversi MP3 ke WAV menggunakan FFmpeg
|
42 |
+
def convert_mp3_to_wav(mp3_path):
|
43 |
+
wav_path = mp3_path.replace('.mp3', '.wav') # Ubah ekstensi ke .wav
|
44 |
+
try:
|
45 |
+
# Jalankan perintah FFmpeg untuk konversi
|
46 |
+
subprocess.run(['ffmpeg', '-i', mp3_path, wav_path], check=True)
|
47 |
+
# Hapus file MP3 setelah berhasil dikonversi
|
48 |
+
os.remove(mp3_path)
|
49 |
+
return wav_path
|
50 |
+
except subprocess.CalledProcessError as e:
|
51 |
+
print(f"Error converting MP3 to WAV: {e}")
|
52 |
+
return None
|
53 |
+
except OSError as e:
|
54 |
+
print(f"Error deleting MP3 file: {e}")
|
55 |
+
return None
|
56 |
+
|
57 |
+
# Fungsi untuk ekstraksi fitur dari file musik
|
58 |
+
def extract_features(file_path):
|
59 |
+
try:
|
60 |
+
y, sr = librosa.load(file_path, duration=30, sr=22050)
|
61 |
+
|
62 |
+
# Ekstraksi fitur
|
63 |
+
mfccs = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13).T, axis=0)
|
64 |
+
chroma = np.mean(librosa.feature.chroma_stft(y=y, sr=sr).T, axis=0)
|
65 |
+
spectral_contrast = np.mean(librosa.feature.spectral_contrast(y=y, sr=sr).T, axis=0)
|
66 |
+
zero_crossings = np.mean(librosa.feature.zero_crossing_rate(y).T, axis=0)
|
67 |
+
tempo, _ = librosa.beat.beat_track(y=y, sr=sr)
|
68 |
+
|
69 |
+
# Menggabungkan semua fitur
|
70 |
+
features = np.hstack([mfccs, chroma, spectral_contrast, zero_crossings, tempo])
|
71 |
+
return features
|
72 |
+
except Exception as e:
|
73 |
+
print(f"Error extracting features: {e}")
|
74 |
+
return None
|
75 |
+
|
76 |
+
|
77 |
+
@flask_app.route('/', methods=['GET', 'POST'])
|
78 |
+
def index():
|
79 |
+
if request.method == 'POST':
|
80 |
+
# Periksa apakah file diunggah
|
81 |
+
if 'file' not in request.files:
|
82 |
+
return redirect(request.url)
|
83 |
+
file = request.files['file']
|
84 |
+
if file.filename == '':
|
85 |
+
return redirect(request.url)
|
86 |
+
|
87 |
+
# Simpan file ke folder yang ditentukan
|
88 |
+
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
|
89 |
+
file.save(file_path)
|
90 |
+
|
91 |
+
# Periksa format file
|
92 |
+
if file.filename.lower().endswith('.mp3'):
|
93 |
+
# Konversi MP3 ke WAV
|
94 |
+
file_path_wav = convert_mp3_to_wav(file_path)
|
95 |
+
if file_path_wav is None:
|
96 |
+
return "Konversi MP3 ke WAV gagal. Pastikan file yang diunggah valid."
|
97 |
+
file_path = file_path_wav # Gunakan file WAV untuk proses berikutnya
|
98 |
+
|
99 |
+
# Ekstraksi fitur dari file yang diunggah
|
100 |
+
features = extract_features(file_path)
|
101 |
+
if features is None:
|
102 |
+
return "Ekstraksi fitur gagal. Coba unggah file lain."
|
103 |
+
|
104 |
+
# Normalisasi fitur menggunakan scaler
|
105 |
+
features_scaled = scaler.transform([features])
|
106 |
+
|
107 |
+
# Prediksi genre menggunakan model
|
108 |
+
prediction = model.predict(features_scaled)
|
109 |
+
predicted_genre = genres[np.argmax(prediction)]
|
110 |
+
|
111 |
+
# Hapus file WAV setelah 30 detik
|
112 |
+
delete_file_after_delay(file_path, delay=30)
|
113 |
+
|
114 |
+
# Kembalikan hasil prediksi
|
115 |
+
return render_template('index.html', file_path=file_path, prediction=predicted_genre)
|
116 |
+
|
117 |
+
return render_template('index.html')
|
118 |
+
|
119 |
+
|
120 |
+
# FastAPI app to mount Flask app
|
121 |
+
app = FastAPI()
|
122 |
+
|
123 |
+
# Mount Flask app inside FastAPI using WSGIMiddleware
|
124 |
+
app.mount("/", WSGIMiddleware(flask_app))
|