forked from mcharatzoglou/Fitbit-API-MongoDB-Streamlit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export_dataframes.py
355 lines (295 loc) · 16 KB
/
export_dataframes.py
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import pymongo
from datetime import date, datetime
import pandas as pd
class MongoClientDataframes:
def __init__(self, connection_string, database, collection):
# Connect to the MongoDB database and collection specified by the arguments
try:
self.mongo_client = pymongo.MongoClient(connection_string)
self.db = self.mongo_client[database]
self.collection = self.db[collection]
except Exception as e:
# If there is an error, set the connection variables to None and raise an exception
self.mongo_client = None
self.db = None
self.collection = None
raise Exception(e)
def dataframe_heart_rate(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for heart rate data between the start and end dates
query = {
"type": "heart", # Select documents with "type" equal to "heart"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract heart rate data from the MongoDB documents and store it as a list of dictionaries
data = [
{
'date': result['date'], # Date of the document
'time': item['time'], # Time of the heart rate measurement
'heart_rate': item['value'] # Heart rate value
}
for result in results
for item in result['heartIntraday'] # Loop through the heart rate measurements for each document
]
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"heart_rate_data_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_heart_summary(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for heart rate data between the start and end dates
query = {
"type": "heart", # Select documents with "type" equal to "heart"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract heart rate data from the MongoDB documents and store it as a list of dictionaries
data = [
{
'date': result['date'], # Date of the document
'caloriesOut': item['caloriesOut'], # Number calories burned with the specified heart rate zone
'max': item['max'], # Maximum range for the heart rate zone
'min': item['min'], # Minimum range for the heart rate zone
'minutes': item['minutes'], # Number minutes withing the specified heart rate zone
'name': item['name'] # Name of the heart rate zone
}
for result in results
for item in result['heartRateZones'] # Loop through the heart rate measurements for each document
]
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"heart_rate_summary_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_heart_resting_heart_rate(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for heart rate data between the start and end dates
query = {
"type": "heart", # Select documents with "type" equal to "heart"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract heart rate data from the MongoDB documents and store it as a list of dictionaries
data = []
for result in results:
if 'restingHeartrate' in result:
data.append({
'date': result['date'],
'restingHeartRate': result['restingHeartrate'] # Resting heart rate value for the day (daily)
})
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"heart_resting_heart_rate_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_hrv(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for heart rate data between the start and end dates
query = {
"type": "hrv", # Select documents with "type" equal to "heart"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract heart rate data from the MongoDB documents and store it as a list of dictionaries
data = []
for result in results:
data.append({
'date': result['date'],
'daily_rmssd': result['dailyRmssd'], # The Root Mean Square of Successive Differences (RMSSD) between heart beats. It measures short-term variability in the user’s daily heart rate in milliseconds (ms).
'deep_rmssd': result['deepRmssd'] # The Root Mean Square of Successive Differences (RMSSD) between heart beats. It measures short-term variability in the user’s heart rate while in deep sleep, in milliseconds (ms).
})
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"heart_hrv_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_sleep(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for sleep data between the start and end dates
query = {
"type": "sleep", # Select documents with "type" equal to "sleep"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract sleep data from the MongoDB documents and store it as a list of dictionaries
data = []
for result in results:
print(result)
for item in result['data']:
measurement = {
'date': item['dateTime'],
'level': item['level'],
'seconds': item['seconds']
}
data.append(measurement)
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"sleep_data_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_sleep_metrics(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for sleep data between the start and end dates
query = {
"type": "sleep", # Select documents with "type" equal to "sleep"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract sleep data from the MongoDB documents and store it as a list of dictionaries
data = []
for item in results:
measurement = {
'date': item['date'],
'duration': item['metrics']['duration'],
'efficiency': item['metrics']['efficiency'],
'startTime': item['metrics']['startTime'],
'endTime': item['metrics']['endTime'],
'minutesAsleep': item['metrics']['minutesAsleep'],
'minutesAwake': item['metrics']['minutesAwake'],
'minutesToFallAsleep': item['metrics']['minutesToFallAsleep'],
'minutesAfterWakeup': item['metrics']['minutesAfterWakeup'],
'timeInBed': item['metrics']['timeInBed'],
}
data.append(measurement)
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"sleep_metrics_data_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
def dataframe_sleep_summary(self, start_date=None, end_date=None):
# If start_date and end_date are not specified, set them to today's date
start_date = start_date or datetime.now().date()
end_date = end_date or datetime.now().date()
# Convert the start and end dates to datetime objects
start_datetime = datetime.combine(start_date, datetime.min.time())
end_datetime = datetime.combine(end_date, datetime.max.time())
# Format the start and end dates as strings in "YYYY-MM-DD" format
date_format = "%Y-%m-%d"
start_date_string = start_datetime.strftime(date_format)
end_date_string = end_datetime.strftime(date_format)
# Query the MongoDB collection for sleep data between the start and end dates
query = {
"type": "sleep", # Select documents with "type" equal to "sleep"
"date": { # Select documents where "date" is between the start and end dates
"$gte": start_date_string, # Greater than or equal to start date
"$lte": end_date_string # Less than or equal to end date
}
}
results = self.collection.find(query)
# Extract sleep data from the MongoDB documents and store it as a list of dictionaries
data = []
rows = []
for doc in results:
date = doc['date']
for stage in ['deep', 'light', 'rem', 'wake']:
if stage in doc['summary']:
minutes = doc['summary'][stage]['minutes']
count = doc['summary'][stage]['count']
rows.append([date, stage, minutes, count])
df = pd.DataFrame(rows, columns=['date', 'stage', 'totalMinutesAsleep', 'totalSleepRecords'])
# Save the dataframe to a CSV file with a descriptive file name
# filename = f"sleep_summary_data_{start_date_string}_{end_date_string}.csv"
# df.to_csv(filename, index=False)
# Return the pandas dataframe
return df
# EXAMPLE CODE
client = MongoClientDataframes(
connection_string="MONGO_URL_GOES_HERE",
database="DATABASE_HERE",
collection="COLLECTION_HERE",
)
startTime = date(year = 2023, month =3, day = 27)
endTime = date(year = 2023, month = 4, day = 27)
#client.dataframe_heart_rate(start_date=startTime)
#client.dataframe_heart_summary(start_date=startTime)
#client.dataframe_heart_resting_heart_rate(start_date=startTime)
#client.dataframe_hrv(start_date=startTime)
#client.dataframe_sleep(start_date=startTime)
#client.dataframe_sleep_metrics(start_date=startTime)
#client.dataframe_sleep_summary(start_date=startTime)