Skip to content

Instantly share code, notes, and snippets.

@moritalous
Created June 21, 2022 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritalous/de32b9172ed317ec63290608ec480a12 to your computer and use it in GitHub Desktop.
Save moritalous/de32b9172ed317ec63290608ec480a12 to your computer and use it in GitHub Desktop.
Visualization of heart rate data from Google Fit
import datetime
import json
import os
import matplotlib.pyplot as plt
import pandas as pd
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
CREDENTIALS_JSON = 'token.json'
SCOPES = ['https://www.googleapis.com/auth/fitness.heart_rate.read']
def get_credentials():
credentials = None
if os.path.exists(CREDENTIALS_JSON):
credentials = Credentials.from_authorized_user_file(
CREDENTIALS_JSON, SCOPES)
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'client_secrets.json', scopes=SCOPES)
flow.run_local_server(prompt='consent')
credentials = flow.credentials
with open(CREDENTIALS_JSON, 'w') as token:
token.write(credentials.to_json())
return credentials
def request_fit_data(start: int, end: int, filename: str = None):
response = None
with build('fitness', 'v1', credentials=get_credentials()) as service:
body = {
'aggregateBy': {
'dataTypeName': 'com.google.heart_rate.bpm'
},
'startTimeMillis': start,
'endTimeMillis': end
}
response = service.users().dataset().aggregate(userId='me', body=body).execute()
if filename is not None:
with open(filename, 'w') as f:
json.dump(response, f, indent=4)
return response
def convert_to_dataframe(response: dict):
data = []
for bucket in response['bucket']:
for dataset in bucket['dataset']:
data.extend(list(map(lambda x: {
'time': x['startTimeNanos'], 'fpVal': x['value'][0]['fpVal']}, dataset['point'])))
df = pd.DataFrame(data)
df['time'] = df['time'].astype(
int) + (9 * 60 * 60 * 1000 * 1000 * 1000) # 9時間ずらす
df['time'] = pd.to_datetime(df['time'])
return df
def save_png(filename: str, df: pd.DataFrame):
plt.figure()
df.plot(x='time', y='fpVal')
plt.savefig(filename)
plt.close('all')
if __name__ == '__main__':
start = int(datetime.datetime(year=2022, month=6,
day=20, hour=0).timestamp()) * 1000
end = int(datetime.datetime(year=2022, month=6,
day=21, hour=0).timestamp()) * 1000
data = request_fit_data(start=start, end=end, filename='response.json')
df = convert_to_dataframe(data)
save_png('chart.png', df)
google-api-python-client
google-auth
google-auth-oauthlib
pandas
matplotlib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment