import os
import numpy as np
import librosa
import joblib

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

DATASET_PATH = "D:/tugas akhir/dataset"

X = []
y = []

print("Processing audio...")

# =========================
# HUMAN
# =========================
human_path = os.path.join(DATASET_PATH, "human")

for file in os.listdir(human_path):
    file_path = os.path.join(human_path, file)

    try:
        audio, sr = librosa.load(file_path, duration=1.5)

        # ❌ filter dimatikan dulu
        # if np.max(np.abs(audio)) < 0.01:
        #     continue

        mfcc = librosa.feature.mfcc(y=audio, sr=sr, n_mfcc=13)
        mfcc_scaled = np.mean(mfcc.T, axis=0)

        X.append(mfcc_scaled)
        y.append(10)

    except:
        print("Error human:", file)

# =========================
# BIRD
# =========================
bird_path = os.path.join(DATASET_PATH, "bird")

for file in os.listdir(bird_path):
    file_path = os.path.join(bird_path, file)

    try:
        audio, sr = librosa.load(file_path, duration=1.5)

        # ❌ filter dimatikan
        # if np.max(np.abs(audio)) < 0.01:
        #     continue

        mfcc = librosa.feature.mfcc(y=audio, sr=sr, n_mfcc=13)
        mfcc_scaled = np.mean(mfcc.T, axis=0)

        X.append(mfcc_scaled)
        y.append(20)

        print("BIRD LOADED:", file)  # debug

    except:
        print("Error bird:", file)

# =========================
# ARRAY
# =========================
X = np.array(X)
y = np.array(y)

print("Total data:", len(X))
print("Class:", set(y))

# =========================
# TRAIN
# =========================
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

model = RandomForestClassifier()
model.fit(X_train, y_train)

# =========================
# EVALUASI
# =========================
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print("Akurasi:", accuracy)

# =========================
# SIMPAN
# =========================
joblib.dump(model, "model_burung.pkl")
print("Model disimpan!")