# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/Madhav2204/LGMVIP-DataScience/blob/main/Task_10_ML_Facial_recognition_to_detect_mood_and_suggest_songs_accordingly.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="ZCXzUsjtwNzy"
# # Author : <NAME>

# + [markdown] id="eDNxMjAOwSGT"
# Task-10 : ML Facial recognition to detect mood and suggest songs accordingly 

# + [markdown] id="wYDrVTSGwX8y"
# Dataset Link: https://www.kaggle.com/msambare/fer2013

# + id="6zLBEMLKx0s7"
import numpy as np
import pandas as pd
import os
import datetime
import matplotlib.pyplot as plt
import tensorflow as tf
from keras import regularizers
from keras.utils.vis_utils import plot_model
from tensorflow.keras.optimizers import Adam, RMSprop, SGD
from keras.preprocessing.image import ImageDataGenerator, load_img,img_to_array
from keras.layers import Conv2D, Dense, BatchNormalization, Activation, Dropout, MaxPooling2D, Flatten
from keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard, EarlyStopping, ReduceLROnPlateau
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score, cross_val_predict
from sklearn.datasets import make_classification
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

# + id="qwQDjxW4wCuF" colab={"base_uri": "https://localhost:8080/", "height": 165} outputId="e4f9d39f-da1a-441f-818d-ba4b387e9603"
print(os.listdir("train"))

# + id="-Zc31PHnjkMD"


# + id="0uU4nhdNwfI3"
def load_dataset(directory):
  x, y = [],[]
  i=1
  for subdir in listdir(directory):
    path = directory + subdir + '/'
    faces = load_faces(path)
    labels = [subdir for _ in range(len(faces))]
    print("%d There are %d images in the class %s:"%(i,len(faces),subdir))
    x.extend(faces)
    y.extend(labels)
    i=i+1
  return asarray(x),asarray(y)  


trainX,trainY = load_dataset('/content/drive/MyDrive/Indian-celebrities/')
print(trainX.shape,trainY.shape)
savez_compressed('/content/drive/MyDrive/PROJECTS/face recog + mood/Indian-celeb-dataset.npz',trainX,trainY)

# + colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 74} id="f33RkIHHyHVQ" outputId="0ac292b2-eebd-40d7-af74-fd71c272901a"
from google.colab import files
uploaded = files.upload()

# + id="3vKcvnxhyLEC"
data = pd.read_csv('/content/drive/My Drive/projects/train.csv')
test_data = pd.read_csv('/content/drive/My Drive/projects/test.csv')

# + id="lVU1nxOt33oq"
spotify_df.dropna(subset=['consolidates_genre_lists'], inplace=True)

# + colab={"base_uri": "https://localhost:8080/"} id="RL6gBEE4375d" outputId="357e57cb-c7cd-446f-a2a1-434490265bcd"
spotify_df.isna().sum()

# + colab={"base_uri": "https://localhost:8080/", "height": 346} id="ht0aQ4Bt3_hs" outputId="863484f4-b900-499b-a946-8404ccf5e7f4"
spotify_df.head(3)

# + id="eF_cwYDJ4B5u"
mood_prep = spotify_df[['duration_ms', 'danceability', 'acousticness', 'energy', 'instrumentalness',
       'liveness', 'valence', 'loudness', 'speechiness', 'tempo']]

# + colab={"base_uri": "https://localhost:8080/"} id="n4TiIeWm4E8Y" outputId="8cdbea3a-20b5-4a25-93bf-f38d1d95b77a"
col_features = mood_prep.columns[:]
col_features

# + id="BuhroSjY4Gez"
mood_trans = MinMaxScaler().fit_transform(mood_prep[col_features])
mood_trans_np = np.array(mood_prep[col_features])

# + colab={"base_uri": "https://localhost:8080/"} id="XcjftPuv4IOh" outputId="8c03358d-6353-42a9-cd5a-8795baef682f"
mood_trans_np[10011]

# + colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY>", "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": ""}}, "base_uri": "https://localhost:8080/", "height": 74} id="X_3J59g94Je-" outputId="cbe1c4f3-7353-4ce8-d165-fa1246f65eb1"
from google.colab import files
uploaded = files.upload()

# + id="8B4ShRwB4LE7"
df = pd.read_csv('data_moods.csv')

# + id="cj45sGrz4XFV"
cl_features = df.columns[6:-3]
X= MinMaxScaler().fit_transform(df[cl_features])
X2 = np.array(df[cl_features])
Y = df['mood']

# + colab={"base_uri": "https://localhost:8080/", "height": 174} id="5y2lseJE4Ym6" outputId="3cd0aa6b-fb7b-42e2-eb83-605bc55dbddd"
encoder = LabelEncoder()
encoder.fit(Y)
encoded_y = encoder.transform(Y)


dummy_y = utils.to_categorical(encoded_y)

X_train,X_test,Y_train,Y_test = train_test_split(X,encoded_y,test_size=0.2,random_state=15)

target = pd.DataFrame({'mood':df['mood'].tolist(),'encode':encoded_y}).drop_duplicates().sort_values(['encode'],ascending=True)
target


# + id="rl6DmEnF4a20"
def base_model():
    model = Sequential()
    model.add(Dense(8,input_dim=10,activation='relu'))
    model.add(Dense(4,activation='softmax'))
    model.compile(loss='categorical_crossentropy',optimizer='adam',
                 metrics=['accuracy'])
    return model


# + id="Dujw2l-l4dqe"
#Configure the model
estimator = KerasClassifier(build_fn=base_model,epochs=300,batch_size=200,verbose=0)

# + colab={"base_uri": "https://localhost:8080/"} id="Ks0-zd0Y4fO6" outputId="85a58698-abd6-414c-cb06-4fa7c3e50b12"
#Evaluate the model using KFold cross validation
kfold = KFold(n_splits=10,shuffle=True)
results = cross_val_score(estimator,X,encoded_y,cv=kfold)
print("Baseline: %.2f%% (%.2f%%)" % (results.mean()*100,results.std()*100))

# + id="FHqtsMhA4hpa"
estimator.fit(X_train,Y_train)
y_preds = estimator.predict(X_test)

# + colab={"base_uri": "https://localhost:8080/"} id="sXkk7GOr4qyn" outputId="c8fac799-a4f5-4daf-b1cf-dfd076dc928e"
y_preds

# + colab={"base_uri": "https://localhost:8080/"} id="6UOdkzs05NoF" outputId="633c66a2-74d1-4fa9-a04c-0bba62d6b1d5"
#Join the model and the scaler in a Pipeline
pip = Pipeline([('minmaxscaler',MinMaxScaler()),('keras',KerasClassifier(build_fn=base_model,epochs=300, batch_size=200,verbose=0))])
#Fit the Pipeline
pip.fit(X2,encoded_y)


# + id="A_ijI6LW5PWV"
def predict_mood(preds):
    
#     pipe = Pipeline([('minmaxscaler',MinMaxScaler()),('keras',KerasClassifier(build_fn=base_model,epochs=300, batch_size=200,verbose=0))])
#     #Fit the Pipeline
#     pipe.fit(X2,encoded_y)

    preds_features = np.array(preds[:]).reshape(-1,1).T

    #Predict the features of the song
    results = pip.predict(preds_features)

    mood = np.array(target['mood'][target['encode']==int(results)])

    return str(mood[0])
    #print(f"{name_song} by {artist} is a {mood[0].upper()} song")


# + id="M5uFsitB5S3I" colab={"base_uri": "https://localhost:8080/", "height": 346} outputId="69d4583d-e414-47de-8bf2-781b1d0378f7"
res = []

for i in range(len(mood_trans_np)):
  res.append(predict_mood(mood_trans_np[i]))

# + id="pSaY_FR-5Vaf"
spotify_df.shape

# + id="FbzH77K95Wwq"
print(len(res))

# + id="rzHYVbZb5Yqy"
spotify_df['Mood'] = np.resize(res,len(spotify_df))

# + id="LwBgVE0F5aFw"
from google.colab import files
uploaded = files.upload()

# + id="ZrmuknuB5iMb"
spotify_df.to_csv('kaggleMusicMoodFinal.csv')

# + id="f7IiLg0W5m-A"
res.count("Sad")

# + id="l1IVoMnv5nA1"
res.count("Happy")

# + id="5R2S4vni6_pJ"
res.count("Energetic")

# + id="oOwV9OG96_sE"
res.count("Calm")

# + id="dWM1EpEu7AQQ"
spotify_df.shape

StarcoderdataJupyterScriptsDedupFiltered