Skip to content

Commit

Permalink
url added to env
Browse files Browse the repository at this point in the history
  • Loading branch information
tharoosha committed Oct 30, 2023
1 parent d0d870b commit 06d2811
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 31 deletions.
1 change: 0 additions & 1 deletion .cache

This file was deleted.

46 changes: 46 additions & 0 deletions backend/controllers/appController.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,4 +314,50 @@ export async function resetPassword(req,res){
}
}

/** POST: http://localhost:5001/api/emotions/retrieve */
/** Middleware for saving emotions for a user */
export async function saveEmotions(req, res, next) {
try {
const { username, emotions } = req.body;

// Check if the user exists
const user = await UserModel.findOne({ username });

if (!user) {
return res.status(404).send({ error: "User not found" });
}

// Update the user's emotions field with the new data
user.emotions = emotions;

await user.save();

next();
} catch (error) {
return res.status(500).send({ error: "Server Error" });
}
}



/** POST: http://localhost:5001/api/emotions/save */
/** Middleware for retrieving emotions for a user */
export async function retrieveEmotions(req, res, next) {
try {
const { username } = req.method === "GET" ? req.query : req.body;

// Check if the user exists
const user = await UserModel.findOne({ username });

if (!user) {
return res.status(404).send({ error: "User not found" });
}

// Assuming that emotions are stored as a field in the user model
req.userEmotions = user.emotions;

next();
} catch (error) {
return res.status(500).send({ error: "Server Error" });
}
}
7 changes: 4 additions & 3 deletions backend/controllers/mlController.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,11 @@ export async function speech_to_text(req, res) {
*/

export async function emotion_analyzer(req, res) {
const { tweet } = req.body;
const { message } = req.body;
try {
console.log(tweet)
console.log(message)
const process = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/emotion_detection/emotionScript.py", tweet,]);
// const process = spawn("python3", ["../backend/ml_models/emotion_detection/emotionScript.py", tweet,]);
// const process = spawn("python3", ["../backend/ml_models/emotion_detection/emotionScript.py", message,]);

let emotion = ""
process.stdout.on("data", (data) => {
Expand All @@ -155,6 +155,7 @@ export async function emotion_analyzer(req, res) {
const jsonData = JSON.parse(emotion);
// const joy = jsonData.emotion;
// console.log(joy);
// console.log(emotion);
res.status(200).send(jsonData);
} catch (error) {
res.status(500).json({ error: "Failed to parse JSON response" });
Expand Down
2 changes: 1 addition & 1 deletion backend/ml_models/spotify_recommendation/.cache
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"access_token": "BQC80QFI4ychDG5CWRViF_eHXkYOT42vHCZY1aPIIPlhVcy4eKZLJA5c2CUdutVIBQTa-5hrNyKT_G6LY154cQythJwSjrfoM2AbG2dUdgAj8Seb63tdcbVVGQ_bGdTfu0WrCDUHTkzz26k5YmB9RKkP8qTWaXLIe1AQyTSnj43YBHe8Za2b8k-ZNl94NVoc68nAmiVZJ0fg5q9q_CnSU4-vPNolZYhCNI429g", "token_type": "Bearer", "expires_in": 3600, "scope": "playlist-read-private user-library-read user-read-recently-played user-top-read", "expires_at": 1698560410, "refresh_token": "AQDPFQQaeVerMmQwRulEXf-J4KgjjUINngJ-7MU19CyzrhZMYfh20NqYWXpHpc-XVrLBe7_gig_4zOmcnQCE2DvOrjAUUaK5YigF0Wg2C4f-NYpccD2MBMTl7qZ4vm3falU"}
{"access_token": "BQC9OMFKcpyPnUKxRzR2QITzzr8GhYPCH2KCS8hk4na6TntReXKzKR91CKupGAvUBqcg0SLic6eae5RFdO4fv0Z1sPNj1cyRsShXpuV7EixiC3HDNGajiGKqRtcd0Ox8gotnH9tj2W09qijsnUuQ-V_M67mc0qRjjQN7nH5lTUBJTxIyfrt6AU27MDdITmZ4Y2POvDLupBjEWxnB3TYWaGuSo-4SxfCb78njbw", "token_type": "Bearer", "expires_in": 3600, "scope": "playlist-read-private user-library-read user-read-recently-played user-top-read", "expires_at": 1698634377, "refresh_token": "AQDPFQQaeVerMmQwRulEXf-J4KgjjUINngJ-7MU19CyzrhZMYfh20NqYWXpHpc-XVrLBe7_gig_4zOmcnQCE2DvOrjAUUaK5YigF0Wg2C4f-NYpccD2MBMTl7qZ4vm3falU"}
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
from sklearn.model_selection import train_test_split
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress INFO and WARNING messages
import tensorflow as tf
from sklearn.preprocessing import StandardScaler
from tensorflow.keras import layers, models
from tensorflow.keras.optimizers.legacy import Adam
import pickle
import os

import config as cf
import contextlib

Expand Down Expand Up @@ -152,8 +154,8 @@ def getRecommendation(mood, model, scaler):
df_recentSongs = getRecentlyPlayed()

# Use contextlib.redirect_stdout to suppress output
with contextlib.redirect_stdout(None):
df2 = pd.DataFrame(model.predict(scaler.fit_transform(df_recentSongs.iloc[:, 1:])))
# with contextlib.redirect_stdout(None):
df2 = pd.DataFrame(model.predict(scaler.fit_transform(df_recentSongs.iloc[:, 1:])))

# df2 = pd.DataFrame(model.predict(scaler.fit_transform(df_recentSongs.iloc[:, 1:])))
df2['Mood']=df2.apply(get_max_index, axis=1)
Expand Down
20 changes: 16 additions & 4 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"antd": "^5.5.1",
"axios": "^1.4.0",
"buffer": "^6.0.3",
"dotenv": "^16.3.1",
"extendable-media-recorder": "^9.1.3",
"extendable-media-recorder-wav-encoder": "^7.0.99",
"formik": "^2.4.2",
Expand Down
33 changes: 19 additions & 14 deletions frontend/src/pages/AI_Assistant.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import useFetch from '../hooks/fetch.hook';
import { useAuthStore } from '../store/store';
import { MediaRecorder, register } from 'extendable-media-recorder';
import { connect } from 'extendable-media-recorder-wav-encoder';
// import 'dotenv/config';


import axios from 'axios';

Expand Down Expand Up @@ -38,14 +40,14 @@ const AI_Assistant = () => {
}
}, [response]);

useEffect(() => {
axios.get('http://localhost:5001/api/spotify_recommend', { mood: emotion })
.then((response) => {
setRecommendations(response.data);
console.log(response.data);
})
.catch((error) => console.error(error))
}, [emotion]);
// useEffect(() => {
// axios.get('${process.env.SERVER_ENDPOINT}/api/spotify_recommend', { mood: emotion })
// .then((response) => {
// setRecommendations(response.data);
// console.log(response.data);
// })
// .catch((error) => console.error(error))
// }, [emotion]);

const startRecording = async () => {
if (isRecording) {
Expand Down Expand Up @@ -80,7 +82,7 @@ const AI_Assistant = () => {

// Send the audio data to the Node.js backend
axios
.post('http://localhost:5001/api/voice-input', formData)
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/voice-input`, formData)
.then((response) => {
console.log(response.data.result);
let data = response.data.result;
Expand All @@ -94,7 +96,7 @@ const AI_Assistant = () => {
// console.log(chatLog)
// Make an HTTP request to the backend API to analyze user input using axios
axios
.post('http://localhost:5001/api/analyze', { message: voice_message })
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/analyze`, { message: voice_message })
.then((response) => {
const updatedChatLogWithAI = [...chatLog, { user: 'User', message: voice_message }, { user: 'AI_Consultant', message: response.data.result }];
setChatLog(updatedChatLogWithAI);
Expand All @@ -103,7 +105,7 @@ const AI_Assistant = () => {
.catch((error) => console.error(error));

axios
.post('http://localhost:5001/api/emotion_analyze', { message: voice_message })
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/emotion_analyze`, { message: voice_message })
.then((response) => {
setEmotion(response.data.emotion);
// console.log(response.data.emotion)
Expand All @@ -128,10 +130,13 @@ const AI_Assistant = () => {
e.preventDefault();
const updatedChatLog = [...chatLog, { user: 'User', message: message }];
setChatLog(updatedChatLog);
// console.log('{$process.env.REACT_APP_SERVER_ENDPOINT}')



// Make an HTTP request to the backend API to analyze user input using axios
axios
.post('http://localhost:5001/api/analyze', { message: message })
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/analyze`, { message: message })
.then((response) => {
const updatedChatLogWithAI = [...updatedChatLog, { user: 'AI_Consultant', message: response.data.result }];
setChatLog(updatedChatLogWithAI);
Expand All @@ -141,10 +146,10 @@ const AI_Assistant = () => {
.catch((error) => console.error(error));

axios
.post('http://localhost:5001/api/emotion_analyze', { message: message })
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/emotion_analyze`, { message: message })
.then((response) => {
setEmotion(response.data.emotion);
console.log(response.data.emotion)
console.log(emotion)
})
.catch((error) => console.error(error));
// Clear the input field after submitting
Expand Down
10 changes: 6 additions & 4 deletions frontend/src/pages/MusicTherapy.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ import profileImg from '../images/chat-user.svg';
import chevronDown from '../images/chevron-down.svg';
import { useEffect, useState } from 'react';
import { Buffer } from 'buffer';
// 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 = '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 redirect_uri = process.env.SPOTIFY_REDIRECT_URI;
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');

Expand Down
4 changes: 3 additions & 1 deletion frontend/src/pages/YT_RecommendationView.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import Footer from '../components/Footer';
import '../styles/YT_RecommendationView.scss';
import { Link } from 'react-router-dom';
import axios from 'axios';
// import 'dotenv/config';

// get_youtube_videos_from_preferences

/** POST: http://localhost:5001/api/youtube_list */
Expand Down Expand Up @@ -47,7 +49,7 @@ const YT_RecommendationView = () => {
body: storedData,
};
axios
.post('http://localhost:5001/api/youtube_list', storedData)
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/youtube_list`, storedData)
.then((response) => {
console.log(typeof response.data);
setVideoIds(response.data);
Expand Down

0 comments on commit 06d2811

Please sign in to comment.