Нужна помощь в добавлении функции в мой проектCSS

Разбираемся в CSS
Ответить
Anonymous
 Нужна помощь в добавлении функции в мой проект

Сообщение Anonymous »

Проблема:
У меня есть веб-приложение, в котором я получаю похожие видео с YouTube на основе выбранной эмоции. В настоящее время при нажатии кнопки «Получить похожие видео» отображаются видеоролики, соответствующие выбранной эмоции. Однако я хочу реализовать функцию, при которой при каждом нажатии кнопки отображаются разные видеоролики, даже с одной и той же эмоцией.
Текущая реализация:
Вот моя текущая настройка:
HTML

Код: Выделить всё





Emotion Support



#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;
}



Toggle High Contrast

How are you feeling?

Select an emotion:

Fear
Anxiety
Sadness
Depression
Guilt
Shame
Anger
Irritability


Get Recommendations
Get Related Videos




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 => `

${video.video_title}

https://www.youtube.com/embed/${video.video_id}

`).join('');
document.getElementById('videos').innerHTML = videosHtml;
} else {
document.getElementById('videos').innerText = 'No videos found';
}
});
});




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/
')
def send_static(path):
return send_from_directory('static', path)

if __name__ == '__main__':
app.run(debug=True)

Дополнительная информация:
Каждый раз при нажатии кнопки «Получить похожие видео» я хочу получить новый набор видео, связанных с выбранной эмоцией, даже если эмоция остается. одинаковый. Как я могу изменить текущую настройку, чтобы добиться этого?


Подробнее здесь: https://stackoverflow.com/questions/786 ... my-project
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»