Problem:
I have a web application where I’m fetching related YouTube videos based on the selected emotion. Currently, clicking the “Get Related Videos” button displays videos corresponding to the selected emotion. However, I want to implement a feature where each click on the button shows different videos, even for the same emotion.
Current Implementation:
Here’s my current setup:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Emotion Support</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='high_contrast.css') }}" id="contrast-css" disabled>
<style>
#contrast-toggle-btn {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
width: auto;
}
</style>
</head>
<body>
<button id="contrast-toggle-btn">Toggle High Contrast</button>
<div class="content">
<h1>How are you feeling?</h1>
<div>
<label for="emotion">Select an emotion:</label>
<select id="emotion" name="emotion">
<option value="fear">Fear</option>
<option value="anxiety">Anxiety</option>
<option value="sadness">Sadness</option>
<option value="depression">Depression</option>
<option value="guilt">Guilt</option>
<option value="shame">Shame</option>
<option value="anger">Anger</option>
<option value="irritability">Irritability</option>
</select>
</div>
<div>
<button id="get-recommendations">Get Recommendations</button>
<button id="get-videos">Get Related Videos</button>
</div>
<div id="recommendations"></div>
<div id="videos"></div>
</div>
<script>
document.getElementById('contrast-toggle-btn').addEventListener('click', function() {
var contrastCss = document.getElementById('contrast-css');
contrastCss.disabled = !contrastCss.disabled;
});
document.getElementById('get-recommendations').addEventListener('click', function() {
var emotion = document.getElementById('emotion').value;
fetch('/get_recommendations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ emotion: emotion }),
})
.then(response => response.json())
.then(data => {
if (data.recommendations) {
document.getElementById('recommendations').innerText = data.recommendations;
} else {
document.getElementById('recommendations').innerText = 'No recommendations found';
}
});
});
document.getElementById('get-videos').addEventListener('click', function() {
var emotion = document.getElementById('emotion').value;
var randomParam = Math.random().toString(36).substring(7); // Generate a random string
fetch(`/get_related_videos?emotion=${emotion}&random=${randomParam}`)
.then(response => response.json())
.then(data => {
if (data.videos) {
var videosHtml = data.videos.map(video => `
<div>
<h3>${video.video_title}</h3>
<iframe width="560" height="315" src="https://www.youtube.com/embed/${video.video_id}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
`).join('');
document.getElementById('videos').innerHTML = videosHtml;
} else {
document.getElementById('videos').innerText = 'No videos found';
}
});
});
</script>
</body>
</html>
Python app.py
from flask import Flask, render_template, request, jsonify, send_from_directory
import requests
import random
app = Flask(__name__)
YOUTUBE_API_KEY = 'the key'
# Predefined responses for different emotions
emotion_responses = {
'fear': [
"It's okay to feel fear. Take deep breaths and try grounding exercises.",
"Talk to a friend or family member about your fears. Sharing can help lighten the load."
],
'anxiety': [
"Practice mindfulness or meditation to calm your mind.",
"Write down your worries and make a plan to tackle them one by one."
],
'sadness': [
"Allow yourself to feel sad, but also try to engage in activities that bring you joy.",
"Reach out to loved ones for support. Talking about your feelings can help."
],
'depression': [
"Seek professional help if you're feeling overwhelmed. Therapy can make a difference.",
"Create a daily routine that includes activities you enjoy and find fulfilling."
],
'guilt': [
"Forgive yourself for past mistakes. Everyone makes them.",
"Apologize to anyone you may have hurt and learn from the experience."
],
'shame': [
"Remember that everyone makes mistakes. Be kind to yourself.",
"Talk to someone you trust about your feelings of shame. You are not alone."
],
'anger': [
"Take deep breaths and count to ten before reacting.",
"Find a healthy way to release anger, such as exercise or journaling."
],
'irritability': [
"Identify your triggers and try to avoid them when possible.",
"Practice relaxation techniques like deep breathing or progressive muscle relaxation."
]
}
def fetch_youtube_videos(emotion, page_token=''):
try:
# Construct the YouTube API request URL
api_url = f'https://www.googleapis.com/youtube/v3/search?key={YOUTUBE_API_KEY}&part=snippet&type=video&q=How%20to%20feel%20better%20from%20{emotion}&maxResults=5&pageToken={page_token}'
# Make the API request to fetch video data
response = requests.get(api_url)
response.raise_for_status() # Raise exception for HTTP errors
# Parse the JSON response
video_data = response.json()
if 'items' not in video_data:
return None, None
videos = []
for item in video_data.get('items', []):
video_title = item['snippet']['title']
video_id = item['id']['videoId']
videos.append({
'video_title': video_title,
'video_id': video_id
})
next_page_token = video_data.get('nextPageToken', '')
return videos, next_page_token
except requests.exceptions.RequestException as e:
return None, str(e)
except KeyError as e:
return None, str(e)
@app.after_request
def add_header(response):
if 'Cache-Control' not in response.headers:
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
@app.route('/')
def index():
return render_template('project.html')
@app.route('/get_recommendations', methods=['POST'])
def get_recommendations():
try:
data = request.get_json()
emotion = data.get('emotion')
if not emotion:
return jsonify({'error': 'Emotion parameter is missing'}), 400
# Retrieve predefined responses for the given emotion
responses = emotion_responses.get(emotion, [])
if not responses:
return jsonify({'error': 'No recommendations found for this emotion'}), 404
# Select a random recommendation
random_response = random.choice(responses)
return jsonify({'recommendations': random_response})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/get_related_videos', methods=['GET'])
def get_related_videos():
try:
emotion = request.args.get('emotion')
if not emotion:
return jsonify({'error': 'Emotion parameter is missing'}), 400
page_token = request.args.get('pageToken', '')
# Fetch videos using the YouTube API
videos, next_page_token = fetch_youtube_videos(emotion, page_token)
if videos is None:
return jsonify({'error': 'Failed to fetch related videos'}), 500
return jsonify({'videos': videos, 'nextPageToken': next_page_token})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/static/<path:path>')
def send_static(path):
return send_from_directory('static', path)
if __name__ == '__main__':
app.run(debug=True)
Additional Details:
Each time the “Get Related Videos” button is clicked, I want to recieve a new set of videos related to the selected emotion, even if the emotion remains the same. How can I modify my current setup to achieve this?