Files changed (1) hide show
  1. app.py +121 -109
app.py CHANGED
@@ -1,134 +1,146 @@
1
  import gradio as gr
2
  import joblib
3
  import numpy as np
 
 
 
4
 
5
  # Load the saved models and pipelines
6
  anxiety_model = joblib.load('Anxiety_best_model.pkl')
7
  anxiety_pipeline = joblib.load('Anxiety_best_pipeline.pkl')
8
-
9
  depression_model = joblib.load('Depression_best_model.pkl')
10
  depression_pipeline = joblib.load('Depression_best_pipeline.pkl')
11
-
12
  insomnia_model = joblib.load('Insomnia_best_model.pkl')
13
  insomnia_pipeline = joblib.load('Insomnia_best_pipeline.pkl')
14
-
15
  ocd_model = joblib.load('OCD_best_model.pkl')
16
  ocd_pipeline = joblib.load('OCD_best_pipeline.pkl')
17
 
 
 
 
 
 
 
 
 
18
  # Define the prediction functions
19
- def Anxiety_predict(input1, input2, input3, input4, input5, input6):
20
- inputs = np.array([input1, input2, input3, input4, input5, input6]).reshape(1, -1)
21
- inputs_scaled = anxiety_pipeline.transform(inputs)
22
- prediction = anxiety_model.predict(inputs_scaled)
23
- return prediction[0], f"The predicted value is {prediction[0]:.2f}"
24
 
25
- def Depression_predict(input1, input2, input3, input4, input5, input6):
26
- inputs = np.array([input1, input2, input3, input4, input5, input6]).reshape(1, -1)
27
- inputs_scaled = depression_pipeline.transform(inputs)
28
- prediction = depression_model.predict(inputs_scaled)
29
- return prediction[0], f"The predicted value is {prediction[0]:.2f}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- def Insomnia_predict(input1, input2, input3, input4, input5, input6):
32
- inputs = np.array([input1, input2, input3, input4, input5, input6]).reshape(1, -1)
33
- inputs_scaled = insomnia_pipeline.transform(inputs)
34
- prediction = insomnia_model.predict(inputs_scaled)
35
- return prediction[0], f"The predicted value is {prediction[0]:.2f}"
 
 
 
 
 
 
 
36
 
37
- def OCD_predict(input1, input2, input3, input4, input5, input6):
38
- inputs = np.array([input1, input2, input3, input4, input5, input6]).reshape(1, -1)
39
- inputs_scaled = ocd_pipeline.transform(inputs)
40
- prediction = ocd_model.predict(inputs_scaled)
41
- return prediction[0], f"The predicted value is {prediction[0]:.2f}"
 
 
 
 
 
 
 
 
 
42
 
43
- # Define the Gradio interfaces
44
- anxiety_iface = gr.Interface(
45
- fn=Anxiety_predict,
46
- inputs=[
47
- gr.Number(label="Age"),
48
- gr.Number(label="Hours per day"),
49
- gr.Number(label="Depression"),
50
- gr.Number(label="Insomnia"),
51
- gr.Number(label="OCD"),
52
- gr.Number(label="BPM")
53
- ],
54
- outputs=[
55
- gr.Number(label="Predicted Value"),
56
- gr.Textbox(label="Prediction Description")
57
- ],
58
- title="Music & Mental Health Predictor - Anxiety",
59
- description="Enter 5 numeric values to get a prediction.",
60
- theme=gr.themes.Soft(),
61
- examples=[[18, 3, 0, 1, 0, 156]]
62
- )
63
- depression_iface = gr.Interface(
64
- fn=Depression_predict,
65
- inputs=[
66
- gr.Number(label="Age"),
67
- gr.Number(label="Hours per day"),
68
- gr.Number(label="Insomnia"),
69
- gr.Number(label="Anxiety"),
70
- gr.Number(label="OCD"),
71
- gr.Number(label="BPM")
72
- ],
73
- outputs=[
74
- gr.Number(label="Predicted Value"),
75
- gr.Textbox(label="Prediction Description")
76
- ],
77
- title="Music & Mental Health Predictor - Depression",
78
- description="Enter 5 numeric values to get a prediction.",
79
- theme=gr.themes.Soft(),
80
- examples=[[18, 3, 0, 1, 0, 156]]
81
- )
82
- insomnia_iface = gr.Interface(
83
- fn=Insomnia_predict,
84
- inputs=[
85
- gr.Number(label="Age"),
86
- gr.Number(label="Hours per day"),
87
- gr.Number(label="Depression"),
88
- gr.Number(label="Anxiety"),
89
- gr.Number(label="OCD"),
90
- gr.Number(label="BPM")
91
- ],
92
- outputs=[
93
- gr.Number(label="Predicted Value"),
94
- gr.Textbox(label="Prediction Description")
95
- ],
96
- title="Music & Mental Health Predictor - Insomnia",
97
- description="Enter 5 numeric values to get a prediction.",
98
- theme=gr.themes.Soft(),
99
- examples=[[18, 3, 0, 1, 0, 156]]
100
- )
101
 
102
- ocd_iface = gr.Interface(
103
- fn=OCD_predict,
104
- inputs=[
105
- gr.Number(label="Age"),
106
- gr.Number(label="Hours per day"),
107
- gr.Number(label="Insomnia"),
108
- gr.Number(label="Anxiety"),
109
- gr.Number(label="Depression"),
110
- gr.Number(label="BPM")
111
- ],
112
- outputs=[
113
- gr.Number(label="Predicted Value"),
114
- gr.Textbox(label="Prediction Description")
115
- ],
116
- title="Music & Mental Health Predictor - OCD",
117
- description="Enter 5 numeric values to get a prediction.",
118
- theme=gr.themes.Soft(),
119
- examples=[[18, 3, 0, 1, 0, 156]]
120
- )
121
 
122
- # Create a tabbed interface
123
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
124
- with gr.Tab("Anxiety"):
125
- anxiety_iface.render()
126
- with gr.Tab("Depression"):
127
- depression_iface.render()
128
- with gr.Tab("Insomnia"):
129
- insomnia_iface.render()
130
- with gr.Tab("OCD"):
131
- ocd_iface.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  # Launch the interface
134
  demo.launch(debug=True)
 
1
  import gradio as gr
2
  import joblib
3
  import numpy as np
4
+ import spotipy
5
+ from spotipy.oauth2 import SpotifyClientCredentials
6
+ import random
7
 
8
  # Load the saved models and pipelines
9
  anxiety_model = joblib.load('Anxiety_best_model.pkl')
10
  anxiety_pipeline = joblib.load('Anxiety_best_pipeline.pkl')
 
11
  depression_model = joblib.load('Depression_best_model.pkl')
12
  depression_pipeline = joblib.load('Depression_best_pipeline.pkl')
 
13
  insomnia_model = joblib.load('Insomnia_best_model.pkl')
14
  insomnia_pipeline = joblib.load('Insomnia_best_pipeline.pkl')
 
15
  ocd_model = joblib.load('OCD_best_model.pkl')
16
  ocd_pipeline = joblib.load('OCD_best_pipeline.pkl')
17
 
18
+ # Spotify API credentials
19
+ SPOTIPY_CLIENT_ID = '79d5de7b9bec45c4bc2ae857e29d89e4'
20
+ SPOTIPY_CLIENT_SECRET = '410907e455a24118810bd89ee99d6f68'
21
+
22
+ # Initialize Spotify client
23
+ sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=SPOTIPY_CLIENT_ID,
24
+ client_secret=SPOTIPY_CLIENT_SECRET))
25
+
26
  # Define the prediction functions
27
+ def predict(model, pipeline, inputs):
28
+ inputs_array = np.array(inputs).reshape(1, -1)
29
+ inputs_scaled = pipeline.transform(inputs_array)
30
+ prediction = model.predict(inputs_scaled)
31
+ return prediction[0]
32
 
33
+ # Function to recommend songs based on the condition and prediction
34
+ def recommend_songs(condition, prediction):
35
+ mood_keywords = {
36
+ "Anxiety": ["relaxing", "calming", "soothing"],
37
+ "Depression": ["uplifting", "motivational", "cheerful"],
38
+ "Insomnia": ["sleep", "ambient", "white noise"],
39
+ "OCD": ["focus", "mindfulness", "meditation"]
40
+ }
41
+
42
+ # Select a random keyword based on the condition
43
+ keyword = random.choice(mood_keywords[condition])
44
+
45
+ # Adjust the search query based on the prediction value
46
+ if prediction < 3:
47
+ query = f"mild {keyword} music"
48
+ elif prediction < 6:
49
+ query = f"moderate {keyword} music"
50
+ else:
51
+ query = f"intense {keyword} music"
52
 
53
+ results = sp.search(q=query, type='track', limit=5)
54
+ songs = []
55
+ for item in results['tracks']['items']:
56
+ song = {
57
+ 'name': item['name'],
58
+ 'artist': item['artists'][0]['name'],
59
+ 'album': item['album']['name'],
60
+ 'image_url': item['album']['images'][0]['url'] if item['album']['images'] else None,
61
+ 'preview_url': item['preview_url']
62
+ }
63
+ songs.append(song)
64
+ return songs
65
 
66
+ # Define the main prediction and recommendation function
67
+ def predict_and_recommend(condition, *inputs):
68
+ if condition == "Anxiety":
69
+ prediction = predict(anxiety_model, anxiety_pipeline, inputs)
70
+ elif condition == "Depression":
71
+ prediction = predict(depression_model, depression_pipeline, inputs)
72
+ elif condition == "Insomnia":
73
+ prediction = predict(insomnia_model, insomnia_pipeline, inputs)
74
+ else: # OCD
75
+ prediction = predict(ocd_model, ocd_pipeline, inputs)
76
+
77
+ songs = recommend_songs(condition, prediction)
78
+
79
+ return prediction, f"The predicted {condition} level is {prediction:.2f}", songs
80
 
81
+ # Function to create HTML for song recommendations
82
+ def create_song_html(songs):
83
+ if not songs or not isinstance(songs, list):
84
+ return "No songs to display"
85
+
86
+ html = "<div style='display: flex; flex-wrap: wrap; justify-content: space-around;'>"
87
+ for song in songs:
88
+ html += f"""
89
+ <div style='width: 200px; margin: 10px; text-align: center;'>
90
+ <img src='{song.get('image_url', '')}' style='width: 150px; height: 150px; object-fit: cover;'>
91
+ <h3>{song.get('name', 'Unknown')}</h3>
92
+ <p>{song.get('artist', 'Unknown Artist')}</p>
93
+ <p>{song.get('album', 'Unknown Album')}</p>
94
+ {f'<audio controls src="{song.get("preview_url", "")}"></audio>' if song.get('preview_url') else 'No preview available'}
95
+ </div>
96
+ """
97
+ html += "</div>"
98
+ return html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ # Define the main prediction and recommendation function
101
+ def predict_and_recommend(condition, *inputs):
102
+ if condition == "Anxiety":
103
+ prediction = predict(anxiety_model, anxiety_pipeline, inputs)
104
+ elif condition == "Depression":
105
+ prediction = predict(depression_model, depression_pipeline, inputs)
106
+ elif condition == "Insomnia":
107
+ prediction = predict(insomnia_model, insomnia_pipeline, inputs)
108
+ else: # OCD
109
+ prediction = predict(ocd_model, ocd_pipeline, inputs)
110
+
111
+ songs = recommend_songs(condition, prediction)
112
+ song_html = create_song_html(songs)
113
+
114
+ return prediction, f"The predicted {condition} level is {prediction:.2f}", song_html
 
 
 
 
115
 
116
+ # Define the Gradio interface
117
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
118
+ gr.Markdown("# Music & Mental Health Predictor")
119
+
120
+ with gr.Row():
121
+ condition = gr.Radio(["Anxiety", "Depression", "Insomnia", "OCD"], label="Select Condition")
122
+
123
+ with gr.Row():
124
+ with gr.Column():
125
+ age = gr.Number(label="Age")
126
+ hours_per_day = gr.Number(label="Hours per day listening to music")
127
+ depression = gr.Number(label="Depression level (0-10)")
128
+ insomnia = gr.Number(label="Insomnia level (0-10)")
129
+ ocd = gr.Number(label="OCD level (0-10)")
130
+ bpm = gr.Number(label="Preferred BPM")
131
+
132
+ with gr.Column():
133
+ prediction_value = gr.Number(label="Predicted Value")
134
+ prediction_text = gr.Textbox(label="Prediction Description")
135
+ song_recommendations = gr.HTML(label="Recommended Songs")
136
+
137
+ predict_btn = gr.Button("Predict and Recommend Songs")
138
+
139
+ predict_btn.click(
140
+ fn=predict_and_recommend,
141
+ inputs=[condition, age, hours_per_day, depression, insomnia, ocd, bpm],
142
+ outputs=[prediction_value, prediction_text, song_recommendations],
143
+ )
144
 
145
  # Launch the interface
146
  demo.launch(debug=True)