Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/tharoosha/Depresio into emo…
Browse files Browse the repository at this point in the history
…tion-graph
  • Loading branch information
Nadil-K committed Oct 31, 2023
2 parents f93e73b + f045bb0 commit 0f4d965
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 47 deletions.
1 change: 1 addition & 0 deletions backend/.cache
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"access_token": "BQBKpbTXdZc6mRoi0aGViqe7TdAV9IvGkfZ1Ojhuz0bQnWZ2bjldoumaP28Ir2SIW0G7ps78Cf4lZj55LIZszkpRDgarAHESTz3n6MOB61Mvzy32DGgHZJxKmKQpTwL3VcTAiAVJyKcprTA-bPrRBAKvl2BAWCaF_ogpPcpBuUqn3NlD68qCQtaOZs51mZF0DWREsIbZyKp2OAsq2HwCxudVDRAR3lWKUrzrAQ", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "AQAZep769iD4hcCGDeW0u_x-yl_3Xw3acR6CDQprtHSE9mVXjGrf6k0dTeQRHpreSM5Zt1AbruOjF2uCS2Tnd5570TLexln-4QsW4wAobc4SYDMthKkNf1_kwGhegBGJ5Qw", "scope": "playlist-read-private user-library-read user-read-recently-played user-top-read", "expires_at": 1698724236}
10 changes: 5 additions & 5 deletions backend/controllers/mlController.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,29 +242,29 @@ export async function youtube_lists(req, res) {
// Define the controller function to execute the Python script
export async function spotify_recommend(req, res) {
try {
const { mood } = req.body;
const { emotion } = req.body;

// Spawn the Python script as a child process
// const pythonProcess = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/spotify_recommendation/spotifyRecommendExecution.py", mood,]);
const pythonProcess = spawn("python3", [ "../backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py", mood,]);
const pythonProcess = spawn("python3", [ "../backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py", emotion,]);

let output = "";
// let output = [];

// Listen for data events from the Python script's stdout
pythonProcess.stdout.on("data", (data) => {
console.log(data.toString())
// console.log(data.toString())
output += data.toString();
});

// Listen for the 'close' event to handle the completion of the Python script
pythonProcess.on("close", (code) => {
if (code === 0) {
try {
const result = JSON.parse(output);
// const result = JSON.parse(output);
// res.status(200).json(result);
// const result = JSON.parse(output); // Parse the output string to JSON
res.status(200).json(result);
res.status(200).send(output);
// res.status(200).json({"result":output});
} catch (error) {
res.status(500).json({ error: "Failed to parse JSON response" });
Expand Down
5 changes: 5 additions & 0 deletions backend/controllers/testing/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
console.log(typeof {"result": ["1HNkqx9Ahdgi1Ixy2xkKkL", "1ei3hzQmrgealgRKFxIcWn", "7eJMfftS33KTjuF7lTsMCx"]})

type = {"result": ["1HNkqx9Ahdgi1Ixy2xkKkL", "1ei3hzQmrgealgRKFxIcWn", "7eJMfftS33KTjuF7lTsMCx"]}

console.log(type.result)
29 changes: 29 additions & 0 deletions backend/controllers/testing/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import json
import sys

def script_run():
try:
result = ['1HNkqx9Ahdgi1Ixy2xkKkL', '1ei3hzQmrgealgRKFxIcWn', '7eJMfftS33KTjuF7lTsMCx']

output = {"result": result}

output_json = json.dumps(output)
print(json.decode(output))


print(output_json)

except Exception as e:
error_message = str(e)
output = {"error2011": error_message}

output_json = json.dumps(output)
print(output_json)
sys.stdout.flush()


if __name__ == "__main__":

# input_mood = sys.argv[1]

script_run()
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,30 @@
def script_run(input_mood):
try:

file_path = '/usr/src/app/ml_models/spotify_recommendation/tokenizer.pkl'
# file_path = '/usr/src/app/ml_models/spotify_recommendation/tokenizer.pkl'
# file_path = '../backend/ml_models/spotify_recommendation/tokenizer.pkl'
if os.path.exists(file_path):
with open('/usr/src/app/ml_models/spotify_recommendation/tokenizer.pkl', 'rb') as f:
# if os.path.exists(file_path):
# with open('/usr/src/app/ml_models/spotify_recommendation/tokenizer.pkl', 'rb') as f:
# with open('../backend/ml_models/spotify_recommendation/tokenizer.pkl', 'rb') as f:
scaler = pickle.load(f)
# scaler = pickle.load(f)

model = tf.keras.models.load_model('/usr/src/app/ml_models/spotify_recommendation/spotify_model')
# model = tf.keras.models.load_model('/usr/src/app/ml_models/spotify_recommendation/spotify_model')
# model = tf.keras.models.load_model('../backend/ml_models/spotify_recommendation/spotify_model')

result = spotifyRecommendScript.getRecommendation(input_mood, model, scaler)
result = json.dumps(result)
# result = spotifyRecommendScript.getRecommendation(input_mood, model, scaler)

# print({input_mood})
# result = '["1HNkqx9Ahdgi1Ixy2xkKkL", "1ei3hzQmrgealgRKFxIcWn", "7eJMfftS33KTjuF7lTsMCx"]'
# result = '["1bzsi0xA8MxBZICdtB23pO", "6XSCLKQcavtn1PaLAhmo1x", "0sfCRhw6gS3b1WepmTVPZE", "6u8KnNnGthVY4PaWiH2mgt", "4FIGOj3O3cyIf6Dg2TDoVv", "0FSk1OsGWoTCS8lA74x5lF", "55eUtE9v3uatR0y0NijM6N", "1bzsi0xA8MxBZICdtB23pO", "6XSCLKQcavtn1PaLAhmo1x", "0sfCRhw6gS3b1WepmTVPZE"]'
result = '["0wjno8lHmDep5uhLVowoSA", "42maX10SkL9u6KM2dCdgPm", "0ABeQP5ffDRiZTe3aorRGn", "3QPFWCPWmL7fed8jCQ8jty", "59s47nDkFz1UNXujnpzEPt", "4c2JHXheN3t6Wh13lqj91s", "6eABugchKfRPyrzUpv7UzJ", "42maX10SkL9u6KM2dCdgPm", "6PJrnbdGmbiXjFceEFlnaR", "4cFm2ZZcb4mQMXwKCeJgzs"]'
# result = json.dumps(result)
# response = str(result)
output = {"result": result}

# output_json = json.dumps(output)
output_json = json.dumps(output)
# sys.stdout.flush()
# print(result)
print(output)
print(output_json)

except Exception as e:
error_message = str(e)
Expand Down Expand Up @@ -87,6 +92,7 @@ def script_run(input_mood):

# Call the function with the received input_mood
script_run(input_mood)
# print({input_mood})

# # script_run("happiness")

Expand Down
142 changes: 109 additions & 33 deletions frontend/src/pages/MusicTherapy.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,77 +29,143 @@ import { useEffect, useState } from 'react';
import { Buffer } from 'buffer';
import { getUsername } from '../helper/helper'
import { getRecommendation } from '../helper/helper'
import useFetch from '../hooks/fetch.hook';
import { useAuthStore } from '../store/store';

// import 'dotenv/config';

import axios from 'axios';
const qs = require('qs');

// const client_id = '07f4d94fc95d4955ad32cdf68dbefa0c'; // Your client id
// const client_secret = 'cd95a4c259a94411b20b6929270c8ab8'; // Your secret
const client_id = process.env.SPOTIFY_CLIENT_ID; // Your client id
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const client_id = '85828d1937e346c8a174c74766c1bb89'; // Your client id
const client_secret = 'de99228ea35a4287bd2f1e25d35dec36'; // Your secret
// const client_id = process.env.SPOTIFY_CLIENT_ID; // Your client id
// const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const redirect_uri = process.env.SPOTIFY_REDIRECT_URI;
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');

const MusicTherapy = () => {
// const { username } = useAuthStore((state) => state.auth);
// const [{ isLoading, apiData, serverError }] = useFetch(`/user/${username}`);

const [accessToken, setAccessToken] = useState('');
const [username, setUsername] = useState(''); // State for the username
const [emotion, setEmotion] = useState('');
const [recommendations, setRecommendations] = useState('');


useEffect(() => {
getUsernameAndFetchData();
// getRecommendation(apiData.username)
}, []);

const getUsernameAndFetchData = async () => {
const getUsernameAndFetchData = async () => {
try {
// Fetch the username
// const userData = await getUsername();
const { username } = await getUsername();
// const fetchedUsername = userData.username;
// setUsername(fetchedUsername); // Update the username state
console.log(username)

const emotionData = await getRecommendation({username});
const emotion = emotionData.data;
setEmotion(emotion)
console.log(emotion)

} catch (error) {
console.error('Error fetching username', error);
}
};

// useEffect(() => {

try {
// Fetch the username
const userData = await getUsername();
const fetchedUsername = userData.username;
setUsername(fetchedUsername); // Update the username state
// const getUsernameAndFetchData = async () => {

const emotionData = await getRecommendation({username});
const emotion = emotionData.data;
setEmotion(emotion)
// try {
// // Fetch the username
// const userData = await getUsername();
// const fetchedUsername = userData.username;
// setUsername(fetchedUsername); // Update the username state
// console.log(username)

} catch (error) {
console.error('Error fetching username', error);
}
// const emotionData = await getRecommendation({username});
// const emotion = emotionData.data;
// setEmotion(emotion)
// console.log(emotion)

// } catch (error) {
// console.error('Error fetching username', error);
// }

};
// };

getUsernameAndFetchData();
}, []);
// getUsernameAndFetchData();
// }, []);





// const handleSubmit = (e) => {

// console.log(emotion)
// console.log("get the emotion done...")
// }




// const [trackData, setTrackData] = useState(null);
const [trackIds, setTrackIds] = useState(['1HNkqx9Ahdgi1Ixy2xkKkL', '1ei3hzQmrgealgRKFxIcWn', '7eJMfftS33KTjuF7lTsMCx']);
const [trackIds, setTrackIds] = useState(['1ei3hzQmrgealgRKFxIcWn', '7eJMfftS33KTjuF7lTsMCx']);
// const [trackIds, setTrackIds] = useState([]);
const [trackData, setTrackData] = useState([]);

useEffect(() => {
axios.get('${process.env.SERVER_ENDPOINT}/api/spotify_recommend', { mood: emotion })
const handleSubmit = (e) => {
console.log(emotion)
console.log("get the emotion done...")
// const emo = JSON.parse(emotion)
console.log(typeof emotion)
// const data = {"mood": emotion}

axios.get(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/spotify_recommend`, { emotion: emotion } )
.then((response) => {
const trackIds = response.data;
console.log(response.data);
// Store the track IDs in the trackData state
setTrackData(trackIds);
// const ytTrackIds = response.data.result;
console.log(response.data.result);
setTrackIds(JSON.parse(response.data.result));
// const parsedArray = JSON.parse(ytTrackIds);
// console.log(typeof parsedArray)
// trackIds.forEach(function(item) {
// console.log(item.id);
// // item = JSON.parse(item)
// setTrackData((prevTrackData) => [...prevTrackData, item.id])
// });

// trackData.map((track, index) =>{
// console.log(typeof track.id)
// })
// console.log(newList)
// newList.forEach(function(item2){
// setTrackData((prevTrackData) => [...prevTrackData, ...ytTrackIds])
// })
// setTrackData([ytTrackIds])
// console.log(trackIds)
// // Store the track IDs in the trackData state
// setTrackData(trackIds);
// console.log(trackIds)
})
.catch((error) => {
console.error(error);
});
});
}

// useEffect(() => {
// axios.get(`${process.env.SERVER_ENDPOINT}/api/spotify_recommend`, { mood: emotion })
// .then((response) => {
// const trackIds = response.data;
// console.log(response.data);
// // Store the track IDs in the trackData state
// setTrackData(trackIds);
// })
// .catch((error) => {
// console.error(error);
// });
// });

const getTrackData = async (accessToken, trackIds) => {
try {
Expand All @@ -121,6 +187,8 @@ const MusicTherapy = () => {
};

useEffect(() => {
getUsernameAndFetchData();

// Retrieve access token from Spotify
axios('https://accounts.spotify.com/api/token', {
headers: {
Expand All @@ -132,10 +200,15 @@ const MusicTherapy = () => {
})
.then((tokenResponse) => {
setAccessToken(tokenResponse.data.access_token);
// console.log(client_id)
// console.log(client_secret)

})
.catch((error) => {
console.error('Error retrieving access token:', error);
});


}, []);

useEffect(() => {
Expand All @@ -158,8 +231,8 @@ const MusicTherapy = () => {
<div className="mt-main-container mt--24 mb--48">
<div className="mt-second-col">
<div>

<h2 className="mb--16">Music recommended for you based on your emotions.</h2>
{/* <button className='btn' onClick={handleSubmit}>View your current emotion</button> */}
<div className="music-flex-cont">
{trackData.length > 0 ? (
trackData.map((track, index) => (
Expand All @@ -171,6 +244,9 @@ const MusicTherapy = () => {
<p>No recommended songs...</p>
)}
</div>

<button className='btn' onClick={handleSubmit}>View your recommendations</button>

{/*
{getAudioFeatures_Track('1HNkqx9Ahdgi1Ixy2xkKkL') ? (
<div>
Expand Down

0 comments on commit 0f4d965

Please sign in to comment.