-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathback - Copy.py
More file actions
191 lines (158 loc) · 5.94 KB
/
back - Copy.py
File metadata and controls
191 lines (158 loc) · 5.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import requests
from datetime import datetime, timedelta
import os
import random
import json
app = Flask(__name__)
# 允许所有域名访问
CORS(app, resources={r"/api/*": {"origins": "*"}})
# WeatherAPI.com configuration
WEATHER_API_KEY = 'cdd42fe5558541e3985160543250401'
WEATHER_BASE_URL = 'http://api.weatherapi.com/v1/current.json'
# Music recommendations based on weather
WEATHER_MUSIC = {
'Sunny': [
"Here Comes the Sun - The Beatles",
"Walking on Sunshine - Katrina & The Waves",
"Sun Is Shining - Bob Marley"
],
'Cloudy': [
"Cloudy Day - Tones and I",
"Clouds - NF",
"The Sound of Silence - Simon & Garfunkel"
],
'Rainy': [
"Purple Rain - Prince",
"Rain - The Beatles",
"Umbrella - Rihanna"
],
'Overcast': [
"Riders on the Storm - The Doors",
"November Rain - Guns N' Roses",
"Set Fire to the Rain - Adele"
]
}
# Vitamin D recommendations based on weather
VITAMIN_ADVICE = {
'Sunny': "Moderate vitamin D supplementation recommended.",
'Cloudy': "Consider increasing vitamin D intake on cloudy days.",
'Rainy': "Vitamin D supplementation highly recommended during rainy weather.",
'Overcast': "Regular vitamin D supplementation important during overcast days."
}
# Task descriptions
TASK_DESCRIPTIONS = {
'outdoor': {
'title': 'Go Outside',
'description': 'Take a 5-minute break outside. Even brief exposure to nature can boost your mood and energy levels.',
'icon': '🏃♂️'
},
'vitamin': {
'title': 'Vitamin Supplement',
'description': 'Support your body with essential nutrients, especially during low-sunlight periods.',
'icon': '💊'
},
'music': {
'title': 'Listen to Music',
'description': 'Let music elevate your mood with weather-appropriate tunes.',
'icon': '🎵'
},
'meditation': {
'title': '10-Minute Meditation',
'description': 'Focus on the present moment through mindful meditation.',
'icon': '🧘'
},
'reading': {
'title': 'Reading',
'description': 'Engage your mind with a good book.',
'icon': '📚'
}
}
@app.route('/')
def serve_index():
return send_from_directory('static', 'index.html')
@app.route('/api/weather')
def get_weather():
lat = request.args.get('lat')
lon = request.args.get('lon')
try:
# Call WeatherAPI.com
response = requests.get('http://api.weatherapi.com/v1/current.json', params={
'key': 'cdd42fe5558541e3985160543250401',
'q': f"{lat},{lon}",
'aqi': 'no'
})
if response.status_code != 200:
return jsonify({'error': 'Weather API error'}), 500
data = response.json()
# Calculate base energy based on weather and time
base_energy = calculate_base_energy(data)
# Get music recommendations based on weather
weather_condition = data['current']['condition']['text']
music_list = get_music_recommendations(weather_condition)
# Get vitamin advice
vitamin_advice = get_vitamin_advice(weather_condition)
return jsonify({
'weather': {
'condition': weather_condition,
'temperature': data['current']['temp_c'],
'icon': data['current']['condition']['icon'],
'is_day': data['current']['is_day']
},
'base_energy': base_energy,
'music_recommendations': music_list,
'vitamin_advice': vitamin_advice
})
except Exception as e:
return jsonify({'error': str(e)}), 500
def calculate_base_energy(weather_data):
"""Calculate base energy level (40-60%) based on weather conditions"""
base_energy = 50
# Adjust for day/night
if not weather_data['current']['is_day']:
base_energy = max(40, base_energy - 5)
# Adjust for weather condition
condition = weather_data['current']['condition']['text'].lower()
if 'sunny' in condition or 'clear' in condition:
base_energy = min(60, base_energy + 5)
elif 'rain' in condition or 'cloudy' in condition:
base_energy = max(40, base_energy - 5)
return base_energy
def get_music_recommendations(weather_condition):
"""Get music recommendations based on weather"""
for weather_type, songs in WEATHER_MUSIC.items():
if weather_type.lower() in weather_condition.lower():
return random.sample(songs, min(3, len(songs)))
return random.sample(sum(WEATHER_MUSIC.values(), []), 3)
def get_vitamin_advice(weather_condition):
"""Get vitamin D recommendations based on weather"""
for weather_type, advice in VITAMIN_ADVICE.items():
if weather_type.lower() in weather_condition.lower():
return advice
return VITAMIN_ADVICE['Cloudy'] # Default advice
@app.route('/api/tasks')
def get_tasks():
"""Get all available tasks"""
return jsonify(TASK_DESCRIPTIONS)
@app.route('/api/complete-task', methods=['POST'])
def complete_task():
"""Handle task completion"""
data = request.json
task_type = data.get('task_type')
current_energy = data.get('current_energy', 0)
if task_type not in TASK_DESCRIPTIONS:
return jsonify({'error': 'Invalid task type'}), 400
# Generate random energy boost (5-15)
energy_boost = random.randint(5, 15)
new_energy = min(100, current_energy + energy_boost)
return jsonify({
'task_type': task_type,
'energy_boost': energy_boost,
'new_energy': new_energy,
'message': f'Task completed! Energy boost: {energy_boost}'
})
# 修改 Python 后端代码中的运行部分
if __name__ == '__main__':
# 明确指定端口,避免端口冲突
app.run(debug=True, port=5000)