Skip to content

Commit

Permalink
youtube recomandation
Browse files Browse the repository at this point in the history
  • Loading branch information
tharoosha committed Nov 1, 2023
1 parent 8c89bff commit 7823148
Show file tree
Hide file tree
Showing 4 changed files with 190 additions and 36 deletions.
Binary file modified backend/ml_models/temp_audio.wav
Binary file not shown.
18 changes: 9 additions & 9 deletions backend/models/User.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ export const UserSchema = new mongoose.Schema({
profile: { type: String},
recommendation: { type: String},

emotions: {
Monday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Tuesday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Wednesday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Thursday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Friday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Saturday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
Sunday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
},
// emotions: {
// Monday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Tuesday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Wednesday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Thursday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Friday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Saturday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// Sunday: { Joy: Number, Surprise: Number, Anger: Number, Sad: Number, Happy: Number },
// },
});

export default mongoose.model.Users || mongoose.model('User', UserSchema );
2 changes: 1 addition & 1 deletion frontend/src/components/chart.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Chart } from 'react-google-charts';

const EmotionLineChart = () => {
const data = [
['Day', 'Joyful', 'Surprise', 'Anger', 'Sad', 'Happy'],
['Day', 'Joy', 'Surprise', 'Anger', 'Sad', 'Happy'],
['Monday', 20, 15, 10, 5, 8],
['Tuesday', 18, 13, 11, 7, 10],
['Wednesday', 22, 17, 9, 4, 6],
Expand Down
206 changes: 180 additions & 26 deletions 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 { getUsername } from '../helper/helper'
import { getRecommendation } from '../helper/helper'
// import 'dotenv/config';

// get_youtube_videos_from_preferences
Expand All @@ -17,12 +19,159 @@ import axios from 'axios';

const YT_RecommendationView = () => {
const [videoIds, setVideoIds] = useState([]);
const [emotion, setEmotion] = useState('');
// const [videoTrack, setVideoTrack] = useState([]);
const [isReviewDialogVisible, setIsReviewDialogVisible] = useState(false);
const [rating, setRating] = useState(0);
const [recommendations, setRecommendations] = useState('');

const emotionCategories = {
'sadness': ['Music', 'Comedy', 'Entertainment', 'Classics', 'Family', 'Pets & Animals', 'People & Blogs'],
'fear': ['Comedy', 'Entertainment', 'Drama', 'Action/Adventure', 'Gaming', 'Pets & Animals'],
'joy': ['Autos & Vehicles', 'Film & Animation', 'Sports', 'Gaming', 'Entertainment', 'Comedy', 'Horror', 'Documentary', 'Videoblogging', 'Travel & Events', 'Science & Technology'],
'surprise': ['Entertainment', 'Pets & Animals', 'Autos & Vehicles', 'Family', 'Sci-Fi/Fantasy', 'Action/Adventure', 'Sports', 'Foreign', 'Thriller', 'Trailers', 'Classics'],
'love': ['Family', 'Pets & Animals', 'Sports', 'People & Blogs', 'Movies', 'Shows', 'Classics'],
'anger': ['Music', 'Short Movies', 'Travel & Events', 'Gaming', 'Science & Technology', 'Entertainment', 'Classics']
};

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

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(() => {
const handleSubmit = (e) => {
console.log(emotion)
console.log("get the emotion done...")

const categories = emotionCategories[emotion];
console.log(categories)
categories.forEach(category=> {
getVideoIdsByCategory(category)
.then(videoIds => {
console.log(`Video IDs for category '${category}':`, videoIds);
videoIds.map((videoId) => {
console.log(videoId);
console.log(`https://www.youtube.com/embed/${videoId}`);
});
})
.catch(error => console.error(error));
});
// })
}

// }, [emotion]);

// useEffect(() => {
// getUsernameAndFetchData();
// }, []);

// 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(() => {
// getVideoIdsByCategory('music')
// .then((videoIds) => {
// console.log("hi", videoIds);
// videoIds.map((videoId) => {
// console.log(videoId);
// console.log(`https://www.youtube.com/embed/${videoId}`);

// });
// })
// .catch(error => console.error(error));
// }, []);

async function getVideoIdsByCategory(category) {
const baseUrl = "https://www.googleapis.com/youtube/v3/search";
const API_KEY = "AIzaSyA3Yj4sKRset4eC-KWDDkiiFckWNdBXdaw";
const videoIds = [];

const params = {
part: 'snippet',
q: category,
type: 'video',
maxResults: 5,
key: API_KEY
};

try {
const response = await axios.get(baseUrl, { params: params });
const data = response.data;

if ('items' in data) {
for (const item of data.items) {
videoIds.push(item.id.videoId);
}
} else {
console.log(`No items found for category '${category}'.`);
}
} catch (error) {
console.error(`Error fetching videos for category '${category}': ${error}`);
}
setVideoIds(videoIds);
return videoIds;
}


const storedData = localStorage.getItem('selectedCategories');

useEffect(() => {
// getVideoIdsByCategory(storedData)
const categories = JSON.parse(storedData);
console.log(categories);

categories.forEach(category=> {
getVideoIdsByCategory(category)
.then(videoIds => {
console.log(`Video IDs for category '${category}':`, videoIds);
videoIds.map((videoId) => {
console.log(videoId);
console.log(`https://www.youtube.com/embed/${videoId}`);
});
})
});

// return videoIds;

}, [storedData])


const handleRating = (selectedRating) => {
setRating(selectedRating);
console.log(selectedRating);
Expand All @@ -43,27 +192,27 @@ const YT_RecommendationView = () => {
localStorage.setItem('rating', rating);
}, [rating]);

useEffect(() => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: storedData,
};
axios
.post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/youtube_list`, storedData)
.then((response) => {
console.log(response);
// const parsedArray = JSON.parse(response.data.replace(/\n/g, ''));
// const videoIdsArray = response.data.split('\n').map(line => line.replace(/[[\]']/g, '')).filter(id => id !== 'undefined');
// videoIdsArray = videoIdsArray.split(', ');
// var videoUrls = JSON.parse(response.data);
// console.log(videoIdsArray)
setVideoIds((response.data.result));
})
.catch((error) => {
console.log(error);
});
}, [storedData]);
// useEffect(() => {
// const requestOptions = {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: storedData,
// };
// axios
// .post(`${process.env.REACT_APP_SERVER_ENDPOINT}/api/youtube_list`, storedData)
// .then((response) => {
// console.log(response.data.result);
// // const parsedArray = JSON.parse(response.data.replace(/\n/g, ''));
// // const videoIdsArray = response.data.split('\n').map(line => line.replace(/[[\]']/g, '')).filter(id => id !== 'undefined');
// // videoIdsArray = videoIdsArray.split(', ');
// // var videoUrls = JSON.parse(response.data);
// // console.log(videoIdsArray)
// setVideoIds(JSON.parse(response.data.result));
// })
// .catch((error) => {
// console.log(error);
// });
// }, [storedData]);


// async function getYoutubeVideosFromPreferences(apiKey, categories, maxResults = 5) {
Expand Down Expand Up @@ -113,7 +262,7 @@ const YT_RecommendationView = () => {
// const listData = JSON.parse(videoIds.replace(/'/g, '"'));

// console.log(listData);
console.log({videoIds})
console.log(videoIds)
// console.log('Loaded Ids ', typeof videoUrls);

return (
Expand All @@ -128,13 +277,14 @@ const YT_RecommendationView = () => {
</div>

<div className="">
{/* console.log(videoIds); */}
<div className="yt-container">
{videoIds.map((videoId) => {
return (
<>
<div className="yt-recommendation-item">
<iframe width="560" height="315" src={`https://www.youtube.com/embed/${videoId}`} title={`YouTube video player for ${videoId}`} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>
<div className="button-container">
{/* <div className="button-container">
<button
style={{
backgroundColor: 'transparent',
Expand All @@ -147,14 +297,15 @@ const YT_RecommendationView = () => {
>
Rate this Video
</button>
</div>
</div> */}
</div>
</>
);
})}
</div>
<div className="popup-inner__button"></div>
</div>

<Link className="btn select-new-pref" to="/preferences">
Select Your New Preferences
</Link>
Expand All @@ -174,7 +325,7 @@ const YT_RecommendationView = () => {
Rate the Recommendations
</h2>
<div className="stars">
{[...Array(5)].map((star, index) => {
{/* {[...Array(5)].map((star, index) => {
return (
<span
key={index}
Expand All @@ -186,14 +337,17 @@ const YT_RecommendationView = () => {
{index < rating ? '★' : '☆'}
</span>
);
})}
})} */}
</div>
<button className="review-submit btn" onClick={() => setIsReviewDialogVisible(false)}>
Submit
</button>
</div>
</div>
)}

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

</div>
</div>
</div>
Expand Down

0 comments on commit 7823148

Please sign in to comment.