bram4627 commited on
Commit
be7f8fa
1 Parent(s): fb42e9f

Update app.py

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