From f045bb0666215f28d3a62f331e554ac94a8c3108 Mon Sep 17 00:00:00 2001 From: tharoosha Date: Tue, 31 Oct 2023 15:43:22 +0530 Subject: [PATCH] spotify correction --- backend/.cache | 1 + backend/controllers/mlController.js | 10 +- backend/controllers/testing/test.js | 5 + backend/controllers/testing/test.py | 29 ++++ .../spotifyRecommendScript.cpython-311.pyc | Bin 9051 -> 8736 bytes .../spotifyRecommendExecution.py | 24 +-- frontend/src/pages/MusicTherapy.js | 142 ++++++++++++++---- 7 files changed, 164 insertions(+), 47 deletions(-) create mode 100644 backend/.cache create mode 100644 backend/controllers/testing/test.js create mode 100644 backend/controllers/testing/test.py diff --git a/backend/.cache b/backend/.cache new file mode 100644 index 0000000..3b64c95 --- /dev/null +++ b/backend/.cache @@ -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} \ No newline at end of file diff --git a/backend/controllers/mlController.js b/backend/controllers/mlController.js index 4f88196..91e9fce 100644 --- a/backend/controllers/mlController.js +++ b/backend/controllers/mlController.js @@ -242,18 +242,18 @@ 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(); }); @@ -261,10 +261,10 @@ export async function spotify_recommend(req, res) { 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" }); diff --git a/backend/controllers/testing/test.js b/backend/controllers/testing/test.js new file mode 100644 index 0000000..6d8d520 --- /dev/null +++ b/backend/controllers/testing/test.js @@ -0,0 +1,5 @@ +console.log(typeof {"result": ["1HNkqx9Ahdgi1Ixy2xkKkL", "1ei3hzQmrgealgRKFxIcWn", "7eJMfftS33KTjuF7lTsMCx"]}) + +type = {"result": ["1HNkqx9Ahdgi1Ixy2xkKkL", "1ei3hzQmrgealgRKFxIcWn", "7eJMfftS33KTjuF7lTsMCx"]} + +console.log(type.result) \ No newline at end of file diff --git a/backend/controllers/testing/test.py b/backend/controllers/testing/test.py new file mode 100644 index 0000000..232ff7a --- /dev/null +++ b/backend/controllers/testing/test.py @@ -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() diff --git a/backend/ml_models/spotify_recommendation/__pycache__/spotifyRecommendScript.cpython-311.pyc b/backend/ml_models/spotify_recommendation/__pycache__/spotifyRecommendScript.cpython-311.pyc index ad4b964c6d3394ce858bbd2e239c956087d9dede..5b6c8bde19229bf64a000200ac2b8e8d1e7fee5a 100644 GIT binary patch delta 1721 zcmaJ>TWl0n7@jki-Pvom-TS4x+ud&2)zX5-CNu~orKKiqZRrIW4C}HpkS(*j<;+rA z1ECroG#I&@hx#B%6BSKJ1XCXj&jzb8N==PsjEO$@V0@5Bc<}-K|0zXL<3Bs!`7hsp z&i|h|XTKX<-s^eS<8g8zS8BVpFE4qbWcJdQzO%9_Y4VH%11PF(CnBd3-Kn@>wCnDw zNAVE!$-1}Nq%>81iqEngdULf!X|Z&o`xU>H7f^!M7*awoI`wchqC^PCb6Vso%zX`) zu>^f*Ve#muLv>vxK!A5c9x2R?g~23$=X?H#@BI&c)4%wxzdHA^=Sgn7`B91zS6j|; zN<#GmwyFWZq#6WFsUg6$8U}1rBY+t#t45FWSUUY43T;Ef2!m0RJYfbV2aEk_h3G5*Xs|0$<5%zZAJz}tt;LKx%5FLOyO_^#XwOBUh zOsOa5f%m{NIBqZc8Dy&3Z>L*Xf&U5`raN;JZ5z<47nb{j1a{A62b$STYk?nisrvLhm%=9fh_-Vzjq8Hrtv4U4D6Wg9pGe8bB+;!lzX zhL6q0_Ynt1*yr(9;=j`RIt}nME<$NQE}gl2W_kLX+>WnuJ3i`K?;Tk!;d6U@|LyS!_^oQ|y_0LXsrB5{T6lUr zJiX>Tu;=Nil>K_l80ox7==#S$39MWkOB5fGUMj!hH2Moa}`>zF?TB8 zDg(##HME*hr$_brsjlN1Eg2O5jVNqQDu336>dQ#8mFu;mm18DfK59BaZ)o!ky>i5~ zsdboOj=C)p9BMT7U|Kgq76C6I?Lol%v9U*Z6e#Y9DHn^iQdKJ!=^~l}%wbAaB__L{ za_@KvnH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_nG87&oF#xW%SmSwfv4EN6nTS@4oz27 za*F8*2JCjRkJ%sYO>p+dG~7Wh0|&+CjC(x&JF$=E>-WevIBClM-JnN(<7XSbN diff --git a/backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py b/backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py index 75de703..fe63128 100644 --- a/backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py +++ b/backend/ml_models/spotify_recommendation/spotifyRecommendExecution.py @@ -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) @@ -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") diff --git a/frontend/src/pages/MusicTherapy.js b/frontend/src/pages/MusicTherapy.js index 77bf60e..a301c08 100644 --- a/frontend/src/pages/MusicTherapy.js +++ b/frontend/src/pages/MusicTherapy.js @@ -29,20 +29,25 @@ 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(''); @@ -50,56 +55,117 @@ const MusicTherapy = () => { 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 { @@ -121,6 +187,8 @@ const MusicTherapy = () => { }; useEffect(() => { + getUsernameAndFetchData(); + // Retrieve access token from Spotify axios('https://accounts.spotify.com/api/token', { headers: { @@ -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(() => { @@ -158,8 +231,8 @@ const MusicTherapy = () => {
+

Music recommended for you based on your emotions.

- {/* */}
{trackData.length > 0 ? ( trackData.map((track, index) => ( @@ -171,6 +244,9 @@ const MusicTherapy = () => {

No recommended songs...

)}
+ + + {/* {getAudioFeatures_Track('1HNkqx9Ahdgi1Ixy2xkKkL') ? (