Skip to content

Commit

Permalink
emotion and spotify connection init
Browse files Browse the repository at this point in the history
  • Loading branch information
tharoosha committed Oct 30, 2023
1 parent 4870145 commit bb10372
Show file tree
Hide file tree
Showing 14 changed files with 256 additions and 179 deletions.
46 changes: 23 additions & 23 deletions .github/workflows/vercel-deploy.yml
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
name: Vercel CD
# name: Vercel CD

on:
# workflow_run:
# workflows: [Docker Image CI]
# types:
# - completed
push:
branches: [ "main" ]
# on:
# # workflow_run:
# # workflows: [Docker Image CI]
# # types:
# # - completed
# push:
# branches: [ "main" ]

jobs:
deploy:
runs-on: ubuntu-latest
# jobs:
# deploy:
# runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2
# steps:
# - name: Checkout code
# uses: actions/checkout@v2

- name: Deploy to Vercel
working-directory: frontend
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
run: |
npm install --global vercel
vercel pull --yes --environment=preview --token=$VERCEL_TOKEN
vercel build --token=$VERCEL_TOKEN
vercel deploy --prebuilt --token=$VERCEL_TOKEN
# - name: Deploy to Vercel
# working-directory: frontend
# env:
# VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
# run: |
# npm install --global vercel
# vercel pull --yes --environment=preview --token=$VERCEL_TOKEN
# vercel build --token=$VERCEL_TOKEN
# vercel deploy --prebuilt --token=$VERCEL_TOKEN
63 changes: 0 additions & 63 deletions app.py

This file was deleted.

120 changes: 79 additions & 41 deletions backend/controllers/appController.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function verifyUser(req, res, next){
*/
export async function register(req, res){
try{
const {username, password, profile, email} = req.body;
const {username, password, profile, email, recommendation } = req.body;
// check the existing user
const existUsername = new Promise((resolve, reject) => {
UserModel.findOne({username: username}).exec().then(
Expand Down Expand Up @@ -74,7 +74,8 @@ export async function register(req, res){
username: username,
password: hashedPassword,
profile: profile || '',
email: email
email: email,
recommendation: recommendation || '',
});

// return save result as a response
Expand Down Expand Up @@ -314,50 +315,87 @@ 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) {
/** PUT: http://localhost:5001/api/updateRecommendation */
export async function updateRecommendation(req, res) {

// const { username, recommendations } = req.body;

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();
// const userId = req.query.id;
const { userId } = req.user;

if (userId) {
// const user = await UserModel.findOne({ username });
const body = req.body;
// if (!user) {
// return res.status(404).send({ error: "User not found" });
// }

// update the data
UserModel.updateOne({ _id : userId }, body).exec().then(
(response) => {
res.status(201).send({ msg : "Record Updated...!"})
}
)

// user.recommendations = recommendations;

// await user.save();

// return res.status(200).send({ message: "Recommendations updated successfully" });
}else {
return res.status(401).send({ error : "User Not Found...!"});
}

} catch (error) {
return res.status(500).send({ error: "Server Error" });
return res.status(500).send({ error: "Failed to update recommendations" });
}
}



/** 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" });
/** GET: http://localhost:5001/api/recommendation/:username */
export async function getRecommendation(req, res) {

const {username} = req.params;
try{
if (!username) return res.status(501).send({error: "Invalid Username"});

// UserModel.findOne({username},function(err,user){
// if (err) return res.status(500).send({err});
// if(!user) return res.status(501).send({ error : "Couldn't Find the User"});
// return res.status(201).send(user);
// })

UserModel.findOne({username: username}).exec()
.then(
user =>{
/** remove password from user */
// mongoose return unnecessary data with object so convert it into json
const { password, recommendation, ...rest } = Object.assign({}, user.toJSON());

return res.status(201).send(recommendation);
}
)
.catch(
error => {return res.status(501).send({ error : "Couldn't Find the User"});}
)
}catch(error){
return res.status(404).send({error: "Cannot Find User Data"});
}
}


// try {
// const user = await UserModel.findOne({ username });

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

// const recommendations = user.recommendations;

// return res.status(200).send({ recommendations });
// } catch (error) {
// return res.status(500).send({ error: "Failed to retrieve recommendations" });
// }
}
26 changes: 15 additions & 11 deletions backend/controllers/mlController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { spawn } from "child_process";
import { error } from "console";
import { writeFileSync, unlinkSync } from 'fs';
import process from "process";

/** POST: http://localhost:5001/api/analyze */
/**
Expand All @@ -13,6 +14,8 @@ export async function analyzer(req, res) {
try {
// const process = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/Chatbot/chatbotkb.py", message,]);
const process = spawn("python3", ["../backend/ml_models/Chatbot/chatbotkb.py", message,]);
// const process = spawn("python3", [`${process.env.BACKEND_URL}/chatbotkb.py`, message,]);
console.log(message)

let result = "";

Expand Down Expand Up @@ -64,14 +67,15 @@ export async function speech_to_text(req, res) {
// })
// res.send(req.file)
let audioData = req.file.buffer;
const tempFilePath = '/usr/src/app/ml_models/temp_audio.wav';
// const tempFilePath = '/usr/src/app/ml_models/temp_audio.wav';
const tempFilePath = '../backend/ml_models/temp_audio.wav';
writeFileSync(tempFilePath, audioData); // Save the audio data to a temp file
// console.log("file is created..")
// writeFileSync(filePath, req.file.buffer);

// Spawn the Python script as a child process
const pythonProcess = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/Chatbot/Voice_GPT3.py", tempFilePath,]);
// const pythonProcess = spawn("python3", [ "../backend/ml_models/Chatbot/Voice_GPT3.py", tempFilePath]);
// const pythonProcess = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/Chatbot/Voice_GPT3.py", tempFilePath,]);
const pythonProcess = spawn("python3", [ "../backend/ml_models/Chatbot/Voice_GPT3.py", tempFilePath]);
// const pythonProcess = spawn("python3", [ "../backend/ml_models/Chatbot/Voice_GPT3.py", audioData]);

// // Write the audio data directly to the Python script's stdin
Expand Down Expand Up @@ -133,8 +137,8 @@ export async function emotion_analyzer(req, res) {
const { message } = req.body;
try {
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", 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", message,]);

let emotion = ""
process.stdout.on("data", (data) => {
Expand Down Expand Up @@ -185,10 +189,10 @@ export async function youtube_lists(req, res) {
const { categories } = req.body;
try {
// console.log(tweet)
const process = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/recommanded_system/youtube_search.py", categories,]);
// const process = spawn("python3", ["../backend/ml_models/recommanded_system/youtube_search.py", categories,]);
// const process = spawn("/usr/src/app/venv/bin/python3", ["/usr/src/app/ml_models/recommanded_system/youtube_search.py", categories,]);
const process = spawn("python3", ["../backend/ml_models/recommanded_system/youtube_search.py", categories,]);

let youtube_list = ""
let youtube_list = []
process.stdout.on("data", (data) => {
youtube_list = data;
});
Expand All @@ -200,7 +204,7 @@ export async function youtube_lists(req, res) {
// const jsonStr = response.slice(jsonStart);

// // # Parse the JSON
// const jsonData = JSON.parse(jsonStr);
// const jsonData = JSON.parse(youtube_list);

// // # Extract the "emotion" field
// const emotion = jsonData.emotion;
Expand Down Expand Up @@ -241,8 +245,8 @@ export async function spotify_recommend(req, res) {
const { mood } = 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("/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,]);

let output = "";
// let output = [];
Expand Down
4 changes: 2 additions & 2 deletions backend/ml_models/Chatbot/chatbotkb.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ def answerMe(question):
# create_Index("/Volumes/Transcend/Development/Depresio/ml_models/Chatbot/Knowledge")

# get query
storage_context = StorageContext.from_defaults(persist_dir = '/usr/src/app/ml_models/Chatbot/Store')
# storage_context = StorageContext.from_defaults(persist_dir = '../backend/ml_models/Chatbot/Store')
# storage_context = StorageContext.from_defaults(persist_dir = '/usr/src/app/ml_models/Chatbot/Store')
storage_context = StorageContext.from_defaults(persist_dir = '../backend/ml_models/Chatbot/Store')
index = load_index_from_storage(storage_context)

query_engine = index.as_query_engine()
Expand Down
8 changes: 4 additions & 4 deletions backend/ml_models/emotion_detection/emotionScript.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,14 @@ def initialize():


# with open('/usr/src/app/ml_models/emotion_detection/tokenizer.pkl', 'rb') as f:
with open('tokenizer.pkl', 'rb') as f:
# with open('tokenizer.pkl', 'rb') as f:

# with open('../backend/ml_models/emotion_detection/tokenizer.pkl', 'rb') as f:
with open('../backend/ml_models/emotion_detection/tokenizer.pkl', 'rb') as f:
tokenizer = pickle.load(f)

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


#################################################################################################################################################################################
Expand Down
Loading

0 comments on commit bb10372

Please sign in to comment.