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 ad4b964..5b6c8bd 100644 Binary files a/backend/ml_models/spotify_recommendation/__pycache__/spotifyRecommendScript.cpython-311.pyc and b/backend/ml_models/spotify_recommendation/__pycache__/spotifyRecommendScript.cpython-311.pyc differ 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') ? (