-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhoop.py
More file actions
278 lines (238 loc) · 9.07 KB
/
whoop.py
File metadata and controls
278 lines (238 loc) · 9.07 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# Import packages
from settings import (
requests,
os,
json,
dt,
relativedelta,
pd,
np,
)
# Import methods from compute.py
from compute import (
format_date_as_string,
format_date_str_as_datetime,
convert_milliseconds_to_hours,
)
'''
Method: fetch_user_data
Summary: Fetches the WHOOP access token for a specific user
'''
def fetch_user_data(
username,
password,
):
try:
# Make a post request to fetch user info
r = requests.post(
'https://api-7.whoop.com/oauth/token',
json={
'grant_type': 'password',
'issueRefresh': True,
'username': username,
'password': password,
}
)
# Get request data as json
r_json = r.json()
# Parse user_info from r_json
user_info = r_json['user']
# Parse user_id from user_info
user_id = user_info['id']
# Parse access_token from r_json
access_token = r_json['access_token']
return {
# 'user_info': user_info,
'user_id': user_id,
'access_token': access_token,
}
except KeyError:
raise ValueError('Credentials could not be verified')
'''
Method: fetch_cycles_data
Summary: Fetches all the WHOOP health data for the specified user during a specified time period
'''
def fetch_cycles_data(
user_id,
access_token,
date,
):
# Define cycles endpoint url
cycles_url = f'https://api-7.whoop.com/users/{user_id}/cycles'
# Define params for cycle data request using the specified start_date and end_date values
start_date = format_date_as_string(date)
end_date = format_date_as_string(dt.datetime.now())
params = {
'start': start_date,
'end': end_date,
}
# Define headers for cycle data request
headers = {
'Authorization': f'bearer {access_token}'
}
# Make a post request to fetch cycles data
cycles_data = requests.get(
cycles_url,
params = params,
headers = headers,
)
# Get JSON from cycles_data
cycles_data = cycles_data.json()
return cycles_data
'''
Method: fetch_specific_whoop_data
Summary: Fetches strain, sleep, or recovery data from cycles
'''
def fetch_specific_whoop_data(
cycles_data,
whoop_data_type,
):
# If the whoop_data_type is not one of the possible values,
# return an error
if (
(whoop_data_type.lower() != 'strain')
& (whoop_data_type.lower() != 'sleep')
& (whoop_data_type.lower() != 'recovery')
):
raise ValueError('whoop_data_type must be `strain`, `sleep`, or `recovery`')
# Define an empty list of whoop_data
whoop_data = []
# Loop through each day in cycles_data
for day in cycles_data:
# Run the method for the correct data type
if whoop_data_type.lower() == 'strain':
whoop_data += format_strain_data(day)
elif whoop_data_type.lower() == 'sleep':
whoop_data += format_sleep_data(day)
elif whoop_data_type.lower() == 'recovery':
whoop_data += format_recovery_data(day)
return whoop_data
'''
Method: format_sleep_data
Summary: Formats WHOOP sleep data
'''
def format_sleep_data(
user_data,
):
# Grab date from user_data and covert to a datetime object
date_string = user_data['days'][0]
date = format_date_str_as_datetime(date_string)
# Get sleep_data from user_data
sleep_data = user_data['sleep']
# Define a list named formatted_sleep_data that will contain formatted
# dictionaries of sleep_data
formatted_sleep_data = []
# Loop through each sleep cycle for the user
for sleep in sleep_data['sleeps']:
# Add formatted data to sleep_data_dict
sleep_data_dict = {
'date': date,
'needBreakdown_baseline': convert_milliseconds_to_hours(sleep_data['needBreakdown']['baseline']),
'needBreakdown_debt': convert_milliseconds_to_hours(sleep_data['needBreakdown']['debt']),
'needBreakdown_naps': convert_milliseconds_to_hours(sleep_data['needBreakdown']['naps']),
'needBreakdown_strain': convert_milliseconds_to_hours(sleep_data['needBreakdown']['strain']),
'needBreakdown_total': convert_milliseconds_to_hours(sleep_data['needBreakdown']['total']),
'qualityDuration': convert_milliseconds_to_hours(sleep_data['qualityDuration']),
'score': sleep_data['score'],
'cyclesCount': sleep['cyclesCount'],
'disturbanceCount': sleep['disturbanceCount'],
# 'id': sleep['id'],
'inBedDuration': convert_milliseconds_to_hours(sleep['inBedDuration']),
'isNap': sleep['isNap'],
# 'latencyDuration': sleep['latencyDuration'],
'lightSleepDuration': convert_milliseconds_to_hours(sleep['lightSleepDuration']),
# 'noDataDuration': convert_milliseconds_to_hours(sleep['noDataDuration']),
# 'qualityDuration': convert_milliseconds_to_hours(sleep['qualityDuration']),
'remSleepDuration': convert_milliseconds_to_hours(sleep['remSleepDuration']),
'respiratoryRate': sleep['respiratoryRate'],
# 'responded': sleep['responded'],
# 'score': sleep['score'],
# 'sleepConsistency': sleep['sleepConsistency'],
'slowWaveSleepDuration': convert_milliseconds_to_hours(sleep['slowWaveSleepDuration']),
# 'source': sleep['source'],
# 'state': sleep['state'],
# 'surveyResponseId': sleep['surveyResponseId'],
# 'timezoneOffset': sleep['timezoneOffset'],
# 'wakeDuration': sleep['wakeDuration'],
}
# Append formatted_sleep_data to sleep_data_dict
formatted_sleep_data.append(sleep_data_dict)
return formatted_sleep_data
'''
Method: format_strain_data
Summary: Formats WHOOP strain data
'''
def format_strain_data(
user_data,
):
# Grab date from user_data and covert to a datetime object
date_string = user_data['days'][0]
date = format_date_str_as_datetime(date_string)
# Get strain_data from user_data
strain_data = user_data['strain']
# Define a list named formatted_strain_data that will contain formatted
# dictionaries of strain_data
formatted_strain_data = []
# Add formatted data to strain_data_dict
strain_data_dict = {
'date': date,
'averageHeartRate': strain_data['averageHeartRate'],
'kilojoules': strain_data['kilojoules'],
'maxHeartRate': strain_data['maxHeartRate'],
'rawScore': strain_data['rawScore'],
'score': strain_data['score'],
# 'overallState': strain_data['state'],
# 'altitudeChange': workout['altitudeChange'] or np.NaN,
# 'altitudeGain': workout['altitudeGain'] or np.NaN,
# 'averageHeartRate': workout['averageHeartRate'] or np.NaN,
# 'cumulativeWorkoutStrain': workout['cumulativeWorkoutStrain'] or np.NaN,
# 'distance': workout['distance'] or np.NaN,
# 'gpsEnabled': workout['gpsEnabled'] or np.NaN,
# 'id': workout['id'] or np.NaN,
# 'kilojoules': workout['kilojoules'] or np.NaN,
# 'maxHeartRate': workout['maxHeartRate'] or np.NaN,
# 'rawScore': workout['rawScore'] or np.NaN,
# 'responded': workout['responded'] or np.NaN,
# 'score': workout['score'] or np.NaN,
# 'source': workout['source'] or np.NaN,
# 'sportId': workout['sportId'] or np.NaN,
# 'state': workout['state'] or np.NaN,
# 'surveyResponseId': workout['surveyResponseId'] or np.NaN,
# 'timezoneOffset': workout['timezoneOffset'] or np.NaN,
# 'zones': workout['zones'] or np.NaN,
}
# Append formatted_strain_data to strain_data_dict
formatted_strain_data.append(strain_data_dict)
return formatted_strain_data
'''
Method: format_recovery_data
Summary: Formats WHOOP recovery data
'''
def format_recovery_data(
user_data,
):
# Grab date from user_data and covert to a datetime object
date_string = user_data['days'][0]
date = format_date_str_as_datetime(date_string)
# Get recovery_data from user_data
recovery_data = user_data['recovery']
# Define a list named formatted_recovery_data that will contain formatted
# dictionaries of recovery_data
formatted_recovery_data = []
# Define a dictionary of recovery data
recovery_data_dict = {
'date': date,
# 'blackoutUntil': recovery_data['blackoutUntil'],
# 'calibrating': recovery_data['calibrating'],
'heartRateVariabilityRmssd': recovery_data['heartRateVariabilityRmssd'],
# 'id': recovery_data['id'],
# 'responded': recovery_data['responded'],
'restingHeartRate': recovery_data['restingHeartRate'],
'score': recovery_data['score'],
# 'state': recovery_data['state'],
# 'surveyResponseId': recovery_data['surveyResponseId'],
# 'timestamp': recovery_data['timestamp'],
}
# Append recovery_data_dict to formatted_recovery_data
formatted_recovery_data.append(recovery_data_dict)
return formatted_recovery_data