File size: 6,370 Bytes
0841889
 
 
74b0d75
 
 
0841889
ee06fbc
 
 
 
 
 
 
 
 
 
74b0d75
 
 
 
 
 
 
 
ee06fbc
74b0d75
 
 
 
 
0841889
74b0d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee06fbc
74b0d75
 
 
 
 
 
 
 
 
 
 
 
ee06fbc
74b0d75
 
 
 
 
 
 
 
 
 
 
 
 
 
ee06fbc
74b0d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee06fbc
74b0d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee06fbc
74b0d75
ee06fbc
74b0d75
b4969dc
74b0d75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0841889
 
ee06fbc
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
71
72
73
74
75
76
77
78
79
80
81
82
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import gradio as gr
import joblib
import numpy as np
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import random

# Load the saved models and pipelines
anxiety_model = joblib.load('Anxiety_best_model.pkl')
anxiety_pipeline = joblib.load('Anxiety_best_pipeline.pkl')
depression_model = joblib.load('Depression_best_model.pkl')
depression_pipeline = joblib.load('Depression_best_pipeline.pkl')
insomnia_model = joblib.load('Insomnia_best_model.pkl')
insomnia_pipeline = joblib.load('Insomnia_best_pipeline.pkl')
ocd_model = joblib.load('OCD_best_model.pkl')
ocd_pipeline = joblib.load('OCD_best_pipeline.pkl')

# Spotify API credentials
SPOTIPY_CLIENT_ID = '79d5de7b9bec45c4bc2ae857e29d89e4'
SPOTIPY_CLIENT_SECRET = '410907e455a24118810bd89ee99d6f68'

# Initialize Spotify client
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=SPOTIPY_CLIENT_ID,
                                                           client_secret=SPOTIPY_CLIENT_SECRET))

# Define the prediction functions
def predict(model, pipeline, inputs):
    inputs_array = np.array(inputs).reshape(1, -1)
    inputs_scaled = pipeline.transform(inputs_array)
    prediction = model.predict(inputs_scaled)
    return prediction[0]

# Function to recommend songs based on the condition and prediction
def recommend_songs(condition, prediction):
    mood_keywords = {
        "Anxiety": ["relaxing", "calming", "soothing"],
        "Depression": ["uplifting", "motivational", "cheerful"],
        "Insomnia": ["sleep", "ambient", "white noise"],
        "OCD": ["focus", "mindfulness", "meditation"]
    }
    
    # Select a random keyword based on the condition
    keyword = random.choice(mood_keywords[condition])
    
    # Adjust the search query based on the prediction value
    if prediction < 3:
        query = f"mild {keyword} music"
    elif prediction < 6:
        query = f"moderate {keyword} music"
    else:
        query = f"intense {keyword} music"

    results = sp.search(q=query, type='track', limit=5)
    songs = []
    for item in results['tracks']['items']:
        song = {
            'name': item['name'],
            'artist': item['artists'][0]['name'],
            'album': item['album']['name'],
            'image_url': item['album']['images'][0]['url'] if item['album']['images'] else None,
            'preview_url': item['preview_url']
        }
        songs.append(song)
    return songs

# Define the main prediction and recommendation function
def predict_and_recommend(condition, *inputs):
    if condition == "Anxiety":
        prediction = predict(anxiety_model, anxiety_pipeline, inputs)
    elif condition == "Depression":
        prediction = predict(depression_model, depression_pipeline, inputs)
    elif condition == "Insomnia":
        prediction = predict(insomnia_model, insomnia_pipeline, inputs)
    else:  # OCD
        prediction = predict(ocd_model, ocd_pipeline, inputs)
    
    songs = recommend_songs(condition, prediction)
    
    return prediction, f"The predicted {condition} level is {prediction:.2f}", songs

# Function to create HTML for song recommendations
def create_song_html(songs):
    if not songs or not isinstance(songs, list):
        return "No songs to display"
    
    html = "<div style='display: flex; flex-wrap: wrap; justify-content: space-around;'>"
    for song in songs:
        html += f"""
        <div style='width: 200px; margin: 10px; text-align: center;'>
            <img src='{song.get('image_url', '')}' style='width: 150px; height: 150px; object-fit: cover;'>
            <h3>{song.get('name', 'Unknown')}</h3>
            <p>{song.get('artist', 'Unknown Artist')}</p>
            <p>{song.get('album', 'Unknown Album')}</p>
            {f'<audio controls src="{song.get("preview_url", "")}"></audio>' if song.get('preview_url') else 'No preview available'}
        </div>
        """
    html += "</div>"
    return html

# Define the main prediction and recommendation function
def predict_and_recommend(condition, *inputs):
    if condition == "Anxiety":
        prediction = predict(anxiety_model, anxiety_pipeline, inputs)
    elif condition == "Depression":
        prediction = predict(depression_model, depression_pipeline, inputs)
    elif condition == "Insomnia":
        prediction = predict(insomnia_model, insomnia_pipeline, inputs)
    else:  # OCD
        prediction = predict(ocd_model, ocd_pipeline, inputs)
    
    songs = recommend_songs(condition, prediction)
    song_html = create_song_html(songs)
    
    return prediction, f"The predicted {condition} level is {prediction:.2f}", song_html

# Define the Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Music & Mental Health Predictor")
    gr.Markdown("### This innovative application predicts levels of anxiety, depression, insomnia, and OCD on a scale of 0 to 10, providing users with personalized insights into their mental health. Based on these predicted values, the app also recommends tailored music tracks designed to help manage and alleviate specific symptoms. By combining mental health assessment with mood-enhancing music recommendations, this tool offers a unique, holistic approach to supporting emotional well-being and self-care.")
    
    with gr.Row():
        condition = gr.Radio(["Anxiety", "Depression", "Insomnia", "OCD"], label="Select Condition")
    
    with gr.Row():
        with gr.Column():
            age = gr.Number(label="Age")
            hours_per_day = gr.Number(label="Hours per day listening to music")
            depression = gr.Number(label="Depression level (0-10)")
            insomnia = gr.Number(label="Insomnia level (0-10)")
            ocd = gr.Number(label="OCD level (0-10)")
            bpm = gr.Number(label="Preferred BPM")
        
        with gr.Column():
            prediction_value = gr.Number(label="Predicted Value")
            prediction_text = gr.Textbox(label="Prediction Description")
            song_recommendations = gr.HTML(label="Recommended Songs")
    
    predict_btn = gr.Button("Predict and Recommend Songs")
    
    predict_btn.click(
        fn=predict_and_recommend,
        inputs=[condition, age, hours_per_day, depression, insomnia, ocd, bpm],
        outputs=[prediction_value, prediction_text, song_recommendations],
    )

# Launch the interface
demo.launch(debug=True)