diff --git a/rowers/ownapistuff.py b/rowers/ownapistuff.py index 49c53e3f..e7195d20 100644 --- a/rowers/ownapistuff.py +++ b/rowers/ownapistuff.py @@ -3,7 +3,7 @@ from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import unicode_literals, absolute_import -# Interactions with Rowsandall.com API. Not fully complete. +# Interactions with Rowsandall.com API. Not fully complete. # Python import oauth2 as oauth @@ -72,7 +72,7 @@ def do_refresh_token(refreshtoken): 'Content-Type': 'application/json'} url = "http://localhost:8000/rowers/o/token" - + response = requests.post(url, data=json.dumps(post_data), headers=headers) @@ -94,14 +94,14 @@ def get_token(code): "code": code, "redirect_uri": "http://localhost:8000/rowers/test_callback", "client_secret": "aapnootmies", - "client_id":1, + "client_id":1, } headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} url = "http://localhost:8000/rowers/o/token/" - - + + response = requests.post(url, data=json.dumps(post_data), headers=headers) @@ -111,7 +111,7 @@ def get_token(code): expires_in = token_json['expires_in'] refresh_token = token_json['refresh_token'] - + return [thetoken,expires_in,refresh_token] def make_authorization_url(request): @@ -190,7 +190,7 @@ def get_ownapi_workout(user,ownapiid): def createownapiworkoutdata(w): filename = w.csvfilename - row = rowingdata(filename) + row = rowingdata(csvfile=filename) averagehr = int(row.df[' HRCur (bpm)'].mean()) maxhr = int(row.df[' HRCur (bpm)'].max()) @@ -206,7 +206,7 @@ def createownapiworkoutdata(w): hr = row.df[' HRCur (bpm)'].astype(int) haslatlon=1 - + try: lat = row.df[' latitude'].values lon = row.df[' longitude'].values @@ -281,7 +281,5 @@ def getidfromresponse(response): t = json.loads(response.text) uri = t['uris'][0] id = uri[len(uri)-13:len(uri)-5] - - return int(id) - + return int(id) diff --git a/rowers/runkeeperstuff.py b/rowers/runkeeperstuff.py index f4a38f10..5e21b11a 100644 --- a/rowers/runkeeperstuff.py +++ b/rowers/runkeeperstuff.py @@ -104,17 +104,17 @@ def get_workout(user,runkeeperid): strokedata = pd.DataFrame.from_dict({ key: pd.Series(value) for key, value in data.items() }) - + return data,strokedata # Create Workout Data for upload to SportTracks def createrunkeeperworkoutdata(w): filename = w.csvfilename try: - row = rowingdata(filename) + row = rowingdata(csvfile=filename) except: return 0 - + averagehr = int(row.df[' HRCur (bpm)'].mean()) maxhr = int(row.df[' HRCur (bpm)'].max()) duration = w.duration.hour*3600 @@ -134,9 +134,9 @@ def createrunkeeperworkoutdata(w): spm = row.df[' Cadence (stokes/min)'].astype(int) spm[0] = spm[1] hr = row.df[' HRCur (bpm)'].astype(int) - + haslatlon=1 - + try: lat = row.df[' latitude'].values lon = row.df[' longitude'].values @@ -148,12 +148,12 @@ def createrunkeeperworkoutdata(w): t = t.tolist() hr = hr.tolist() d = d.tolist() - + # path data if haslatlon: lat = lat.tolist() lon = lon.tolist() - locdata = [] + locdata = [] for e in zip(t,lat,lon): point = {'timestamp':e[0], 'latitude':e[1], @@ -183,7 +183,7 @@ def createrunkeeperworkoutdata(w): newnotes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com' except TypeError: newnotes = 'from '+w.workoutsource+' via rowsandall.com' - + if haslatlon: data = { "type": "Rowing", @@ -222,7 +222,7 @@ def getidfromresponse(response): tester = re.compile('^\/fitnessActivities\/(\d+)$') id = int(tester.match(uri).group(1)) - + return int(id) def geturifromid(access_token,id): @@ -245,7 +245,7 @@ def geturifromid(access_token,id): return res - + # Get user id, having access token # Handy for checking if the API access is working def get_userid(access_token): @@ -256,7 +256,7 @@ def get_userid(access_token): import urllib url = "https://api.runkeeper.com/user" response = requests.get(url,headers=headers) - + try: me_json = response.json() @@ -271,7 +271,7 @@ def get_userid(access_token): return str(res) def default(o): - if isinstance(o, numpy.int64): return int(o) + if isinstance(o, numpy.int64): return int(o) raise TypeError def workout_runkeeper_upload(user,w): @@ -280,7 +280,7 @@ def workout_runkeeper_upload(user,w): r = w.user - + thetoken = runkeeper_open(r.user) # ready to upload. Hurray @@ -291,7 +291,7 @@ def workout_runkeeper_upload(user,w): message = "Data error in Runkeeper Upload" rkid = 0 return message, rkid - + authorizationstring = str('Bearer ' + thetoken) headers = {'Authorization': authorizationstring, 'user-agent': 'sanderroosendaal', @@ -319,7 +319,7 @@ def workout_runkeeper_upload(user,w): message = "Something went wrong in workout_runkeeper_upload_view: %s - %s" % (s.reason,s.text) rkid = 0 return message, rkid - + else: message = "You are not authorized to upload this workout" rkid = 0 @@ -338,7 +338,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', comments = data['notes'] except: comments = '' - + try: utcoffset = tz(data['utcoffset']) except: @@ -362,8 +362,8 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', starttimeunix = arrow.get(rowdatetime).timestamp #starttimeunix = mktime(rowdatetime.utctimetuple()) starttimeunix += utcoffset*3600 - - + + try: title = data['name'] except: @@ -378,7 +378,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', try: l = data['path'] - + res = splitrunkeeperlatlongdata(l,'timestamp','latitude','longitude') times_location = res[0] latcoord = res[1] @@ -390,7 +390,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', loncoord = np.zeros(len(times_distance)) if workouttype in types.otwtypes: workouttype = 'rower' - + try: res = splitrunkeeperdata(data['cadence'],'timestamp','cadence') times_spm = res[0] @@ -398,7 +398,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', except KeyError: times_spm = times_distance spm = 0*times_distance - + try: res = splitrunkeeperdata(data['heart_rate'],'timestamp','heart_rate') hr = res[1] @@ -416,13 +416,13 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', latseries = latseries.groupby(latseries.index).first() except TypeError: latseries = 0.0*distseries - + lonseries = pd.Series(loncoord,index=times_location) try: lonseries = lonseries.groupby(lonseries.index).first() except TypeError: lonseries = 0.0*distseries - + spmseries = pd.Series(spm,index=times_spm) spmseries = spmseries.groupby(spmseries.index).first() hrseries = pd.Series(hr,index=times_hr) @@ -441,7 +441,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', ' HRCur (bpm)' : hrseries, } - + df = pd.DataFrame(d) @@ -451,7 +451,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', df[' ElapsedTime (sec)'] = cum_time velo = df[' Horizontal (meters)'].diff()/df[' ElapsedTime (sec)'].diff() - + df[' Power (watts)'] = 0.0*velo nr_rows = len(velo.values) @@ -471,10 +471,10 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', unixtime[0] = starttimeunix except IndexError: return (0,'No data to import') - + df['TimeStamp (sec)'] = unixtime - + dt = np.diff(cum_time).mean() wsize = round(5./dt) @@ -486,7 +486,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', df = df.fillna(0) df.sort_values(by='TimeStamp (sec)',ascending=True) - + timestr = strftime("%Y%m%d-%H%M%S") # csvfilename ='media/Import_'+str(importid)+'.csv' @@ -505,4 +505,3 @@ def add_workout_from_data(user,importid,data,strokedata,source='runkeeper', notes=comments) return (id,message) - diff --git a/rowers/sporttracksstuff.py b/rowers/sporttracksstuff.py index 48a61fdf..2828a18f 100644 --- a/rowers/sporttracksstuff.py +++ b/rowers/sporttracksstuff.py @@ -65,7 +65,7 @@ def rower_sporttracks_token_refresh(user): r.sporttracksrefreshtoken = refresh_token r.save() - + return r.sporttrackstoken # Get list of workouts available on SportTracks @@ -117,10 +117,10 @@ def get_workout(user,sporttracksid): # Create Workout Data for upload to SportTracks def createsporttracksworkoutdata(w): timezone = pytz.timezone(w.timezone) - + filename = w.csvfilename try: - row = rowingdata(filename) + row = rowingdata(csvfile=filename) except: return 0 @@ -130,7 +130,7 @@ def createsporttracksworkoutdata(w): except KeyError: averagehr = 0 maxhr = 0 - + duration = w.duration.hour*3600 duration += w.duration.minute*60 duration += w.duration.second @@ -148,9 +148,9 @@ def createsporttracksworkoutdata(w): spm = row.df[' Cadence (stokes/min)'].astype(int).values spm[0] = spm[1] hr = row.df[' HRCur (bpm)'].astype(int).values - + haslatlon=1 - + try: lat = row.df[' latitude'].values lon = row.df[' longitude'].values @@ -159,7 +159,7 @@ def createsporttracksworkoutdata(w): except KeyError: haslatlon = 0 - + haspower = 1 try: power = row.df[' Power (watts)'].astype(int).values @@ -200,7 +200,7 @@ def createsporttracksworkoutdata(w): w.notes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com' except TypeError: w.notes = 'from '+w.workoutsource+' via rowsandall.com' - + st = w.startdatetime.astimezone(timezone) st = st.replace(microsecond=0) @@ -246,17 +246,17 @@ def getidfromresponse(response): uri = t['uris'][0] regex = '.*?sporttracks\.mobi\/api\/v2\/fitnessActivities/(\d+)\.json$' m = re.compile(regex).match(uri).group(1) - + id = int(m) - + return int(id) def default(o): - if isinstance(o, numpy.int64): return int(o) + if isinstance(o, numpy.int64): return int(o) raise TypeError - + def workout_sporttracks_upload(user,w): message = "Uploading to SportTracks" stid = 0 @@ -298,7 +298,7 @@ def workout_sporttracks_upload(user,w): message = "Something went wrong in workout_sporttracks_upload_view: %s" % s.reason stid = 0 return message,stid - + else: message = "You are not authorized to upload this workout" stid = 0 @@ -314,7 +314,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', workouttype = data['type'] except KeyError: workouttype = 'other' - + if workouttype not in [x[0] for x in Workout.workouttypes]: workouttype = 'other' try: @@ -322,7 +322,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', except: comments = '' - + r = Rower.objects.get(user=user) try: rowdatetime = iso8601.parse_date(data['start_time']) @@ -359,7 +359,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', try: l = data['location'] - + res = splitstdata(l) times_location = res[0] latlong = res[1] @@ -377,7 +377,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', loncoord = np.zeros(len(times_distance)) if workouttype in mytypes.otwtypes: workouttype = 'rower' - + try: res = splitstdata(data['cadence']) times_spm = res[0] @@ -385,7 +385,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', except KeyError: times_spm = times_distance spm = 0*times_distance - + try: res = splitstdata(data['heartrate']) hr = res[1] @@ -417,7 +417,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', ' HRCur (bpm)' : hrseries, } - + df = pd.DataFrame(d) @@ -427,7 +427,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', df[' ElapsedTime (sec)'] = cum_time velo = df[' Horizontal (meters)'].diff()/df[' ElapsedTime (sec)'].diff() - + df[' Power (watts)'] = 0.0*velo nr_rows = len(velo.values) @@ -444,10 +444,10 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', unixtime = cum_time+starttimeunix unixtime[0] = starttimeunix - + df['TimeStamp (sec)'] = unixtime - + dt = np.diff(cum_time).mean() wsize = round(5./dt) @@ -459,7 +459,7 @@ def add_workout_from_data(user,importid,data,strokedata,source='sporttracks', df = df.fillna(0) df.sort_values(by='TimeStamp (sec)',ascending=True) - + timestr = strftime("%Y%m%d-%H%M%S") # csvfilename ='media/Import_'+str(importid)+'.csv' diff --git a/rowers/stravastuff.py b/rowers/stravastuff.py index 6c75da2c..d8663c97 100644 --- a/rowers/stravastuff.py +++ b/rowers/stravastuff.py @@ -86,7 +86,7 @@ def rower_strava_token_refresh(user): r.save() return r.stravatoken - + # Make authorization URL including random string def make_authorization_url(request): return imports_make_authorization_url(oauth_data) @@ -130,7 +130,7 @@ def get_strava_workouts(rower): thetoken = strava_open(rower.user) except NoTokenError: return 0 - + res = get_strava_workout_list(rower.user,limit_n=10) if (res.status_code != 200): @@ -142,11 +142,11 @@ def get_strava_workouts(rower): 'elapsed_time':item['elapsed_time'], 'start_date':item['start_date'], } for item in res.json()] - + alldata = {} for item in res.json(): alldata[item['id']] = item - + wfailed = Workout.objects.filter(user=rower,uploadedtostrava=-1) @@ -159,12 +159,12 @@ def get_strava_workouts(rower): dd = datetime.min + timedelta( seconds=int(elapsed_time) ) - - + + if datetime.time(dd) == w.duration: w.uploadedtostrava = int(stravaid) w.save() - + knownstravaids = [ w.uploadedtostrava for w in Workout.objects.filter(user=rower) ] @@ -174,7 +174,7 @@ def get_strava_workouts(rower): ] knownstravaids = uniqify(knownstravaids+tombstones) - + newids = [stravaid for stravaid in stravaids if not stravaid in knownstravaids] for stravaid in newids: @@ -220,10 +220,10 @@ def create_async_workout(alldata,user,stravaid,debug=False): try: c2intervaltype = data['workout_type'] - + except KeyError: c2intervaltype = '' - + try: title = data['name'] except KeyError: @@ -237,22 +237,22 @@ def create_async_workout(alldata,user,stravaid,debug=False): workoutdate = rowdatetime.astimezone( pytz.timezone(thetimezone) ).strftime('%Y-%m-%d') - + starttime = rowdatetime.astimezone( pytz.timezone(thetimezone) ).strftime('%H:%m:%S') - + totaltime = data['elapsed_time'] duration = dataprep.totaltime_sec_to_string(totaltime) weightcategory = 'hwt' - + # Create CSV file name and save data to CSV file csvfilename ='media/mailbox_attachments/{code}_{importid}.csv'.format( importid=stravaid, code = uuid4().hex[:16] ) - + # Check if workout has stroke data, and get the stroke data @@ -268,7 +268,7 @@ def create_async_workout(alldata,user,stravaid,debug=False): csvfilename, workouttype = workouttype, ) - + return 1 from rowers.utils import get_strava_stream @@ -282,11 +282,11 @@ def get_workout(user,stravaid): except NoTokenError: s = "Token error" return custom_exception_handler(401,s) - + r = Rower.objects.get(user=user) if (r.stravatoken == '') or (r.stravatoken is None): s = "Token doesn't exist. Need to authorize" - return custom_exception_handler(401,s) + return custom_exception_handler(401,s) elif (r.stravatokenexpirydate is not None and timezone.now()>r.stravatokenexpirydate): s = "Token expired. Needs to refresh." return custom_exception_handler(401,s) @@ -321,9 +321,9 @@ def get_workout(user,stravaid): else: duration = int(workoutsummary['elapsed_time']) t = pd.Series(range(duration+1)) - + nr_rows = len(t) - + if nr_rows == 0: return (0,"Error: Time data had zero length") @@ -336,7 +336,7 @@ def get_workout(user,stravaid): if power is None: power = np.zeros(nr_rows) - + if hr is None: hr = np.zeros(nr_rows) @@ -365,7 +365,7 @@ def get_workout(user,stravaid): strokelength = velo*60./(spm) strokelength[np.isinf(strokelength)] = 0.0 - + pace = 500./(1.0*velo2) pace[np.isinf(pace)] = 0.0 @@ -379,16 +379,16 @@ def get_workout(user,stravaid): 'power':power, 'strokelength':strokelength, }) - + # startdatetime = datetime.datetime.strptime(startdatetime,"%Y-%m-%d-%H:%M:%S") return [workoutsummary,df] - + # Generate Workout data for Strava (a TCX file) def createstravaworkoutdata(w,dozip=True): filename = w.csvfilename try: - row = rowingdata(filename) + row = rowingdata(csvfile=filename) except IOError: data = dataprep.read_df_sql(w.id) try: @@ -402,12 +402,12 @@ def createstravaworkoutdata(w,dozip=True): index_label='index', compression='gzip') try: - row = rowingdata(filename) + row = rowingdata(csvfile=filename) except IOError: return '','Error - could not find rowing data' else: - return '','Error - could not find rowing data' - + return '','Error - could not find rowing data' + tcxfilename = filename[:-4]+'.tcx' try: newnotes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com' @@ -441,7 +441,7 @@ def handle_stravaexport(f2,workoutname,stravatoken,description='', client = stravalib.Client(access_token=stravatoken) act = client.upload_activity(f2,'tcx.gz',name=workoutname) - + try: res = act.wait(poll_interval=5.0,timeout=30) message = 'Workout successfully synchronized to Strava' @@ -474,10 +474,10 @@ def add_workout_from_data(user,importid,data,strokedata, if workouttype.lower() == 'rowing': workouttype = 'rower' - + if 'summary_polyline' in data['map'] and workouttype=='rower': workouttype = 'water' - + if workouttype not in [x[0] for x in Workout.workouttypes]: workouttype = 'other' try: @@ -497,14 +497,14 @@ def add_workout_from_data(user,importid,data,strokedata, rowdatetime = iso8601.parse_date(data['start_date']) except ParseError: rowdatetime = iso8601.parse_date(data['date']) - - + + try: intervaltype = data['workout_type'] - + except KeyError: intervaltype = '' - + try: title = data['name'] except KeyError: @@ -550,7 +550,7 @@ def add_workout_from_data(user,importid,data,strokedata, spm = strokedata.loc[:,'spm'] except KeyError: spm = 0*dist2 - + try: hr = strokedata.loc[:,'hr'] except KeyError: @@ -568,7 +568,7 @@ def add_workout_from_data(user,importid,data,strokedata, #if power.std() == 0 and power.mean() == 0: # power = 2.8*velo**3 - + # save csv # Create data frame with all necessary data to write to csv df = pd.DataFrame({'TimeStamp (sec)':unixtime, @@ -590,10 +590,10 @@ def add_workout_from_data(user,importid,data,strokedata, ' ElapsedTime (sec)':seconds }) - + df.sort_values(by='TimeStamp (sec)',ascending=True) - + timestr = strftime("%Y%m%d-%H%M%S") @@ -623,7 +623,7 @@ def workout_strava_upload(user,w): thetoken = strava_open(user) except NoTokenError: return "Please connect to Strava first",0 - + message = "Uploading to Strava" stravaid=-1 r = Rower.objects.get(user=user) @@ -652,7 +652,7 @@ def workout_strava_upload(user,w): except WindowsError: pass return message,stravaid - + w.uploadedtostrava = res w.save() try: @@ -704,7 +704,7 @@ def handle_strava_import_stroke_data(title, startdatetime = workoutsummary['start_date'] r = type('Rower', (object,), {"stravatoken": stravatoken}) - + spm = get_strava_stream(r,'cadence',stravaid) hr = get_strava_stream(r,'heartrate',stravaid) t = get_strava_stream(r,'time',stravaid) @@ -729,10 +729,10 @@ def handle_strava_import_stroke_data(title, if power is None: power = np.zeros(nr_rows) - + if hr is None: hr = np.zeros(nr_rows) - + if velo is None: velo = np.zeros(nr_rows) @@ -747,7 +747,7 @@ def handle_strava_import_stroke_data(title, velo2 = savgol_filter(velo,windowsize,3) else: velo2 = velo - + if coords is not None: try: lat = coords[:,0] @@ -774,7 +774,7 @@ def handle_strava_import_stroke_data(title, unixtime = starttimeunix+t strokedistance = 60.*velo2/spm - + nr_strokes = len(t) df = pd.DataFrame({'TimeStamp (sec)':unixtime, @@ -810,13 +810,13 @@ workouttype {workouttype}""".format( stravaid=stravaid, workouttype=workouttype ) - + msg = Message(mailbox=workoutsbox, from_header=useremail, subject=title, body=body) msg.save() - + a = MessageAttachment(message=msg,document=csvfilename[6:]) a.save() diff --git a/rowers/tpstuff.py b/rowers/tpstuff.py index 6a412e74..efdf9e8f 100644 --- a/rowers/tpstuff.py +++ b/rowers/tpstuff.py @@ -64,7 +64,7 @@ def get_token(code): headers = { 'Content-Type': 'application/x-www-form-urlencoded', } - + response = requests.post("https://oauth.trainingpeaks.com/oauth/token", data=post_data) @@ -78,7 +78,7 @@ def get_token(code): thetoken = 0 expires_in = 0 refresh_token = 0 - + return thetoken,expires_in,refresh_token # Make authorization URL including random string @@ -97,7 +97,7 @@ def getidfromresponse(response): def createtpworkoutdata(w): filename = w.csvfilename - row = rowingdata(filename) + row = rowingdata(csvfile=filename) tcxfilename = filename[:-4]+'.tcx' try: newnotes = w.notes+'\n from '+w.workoutsource+' via rowsandall.com' @@ -105,7 +105,7 @@ def createtpworkoutdata(w): newnotes = 'from '+w.workoutsource+' via rowsandall.com' row.exporttotcx(tcxfilename,notes=newnotes) - + return tcxfilename @@ -120,7 +120,7 @@ def tp_check(access_token): headers=headers) return resp - + def uploadactivity(access_token,filename,description='', name='Rowsandall.com workout'): @@ -159,8 +159,8 @@ def uploadactivity(access_token,filename,description='', return resp.json()[0]["Id"],"ok",200,"" return 0,0,0,0 - - + + def workout_tp_upload(user,w): message = "Uploading to TrainingPeaks" tpid = 0 @@ -169,7 +169,7 @@ def workout_tp_upload(user,w): thetoken = tp_open(r.user) # need some code if token doesn't refresh - + if (checkworkoutuser(user,w)): tcxfile = createtpworkoutdata(w) @@ -205,5 +205,5 @@ def workout_tp_upload(user,w): message = "You are not allowed to export this workout to TP" tpid = 0 return message,tpid - + return message,tpid diff --git a/rowers/underarmourstuff.py b/rowers/underarmourstuff.py index e88ae9a3..2d18a21f 100644 --- a/rowers/underarmourstuff.py +++ b/rowers/underarmourstuff.py @@ -89,7 +89,7 @@ def get_workout(user,underarmourid): strokedata = pd.DataFrame.from_dict({ key: pd.Series(value) for key, value in data.items() }) - + return data,strokedata @@ -97,10 +97,10 @@ def get_workout(user,underarmourid): def createunderarmourworkoutdata(w): filename = w.csvfilename try: - row = rowingdata(filename) + row = rowingdata(csvfile=filename) except: return 0 - + st = w.startdatetime.astimezone(pytz.timezone(w.timezone)) start_time = st.isoformat() @@ -126,16 +126,16 @@ def createunderarmourworkoutdata(w): t = row.df.loc[:,'TimeStamp (sec)'].values #-row.df.ix[0,'TimeStamp (sec)'] # t += arrow.get(st).timestamp - + # t[0] = t[1] d = row.df.loc[:,'cum_dist'].values d[0] = d[1] t = t.astype(float).tolist() - - + + d = d.astype(int).tolist() spm = row.df[' Cadence (stokes/min)'].astype(int).tolist() spm[0] = spm[1] @@ -146,10 +146,10 @@ def createunderarmourworkoutdata(w): speedmean = float(row.df[' AverageBoatSpeed (m/s)'].mean()) speed = speed.replace(np.inf,0).tolist() - - + + haslatlon=1 - + try: lat = row.df[' latitude'].tolist() lon = row.df[' longitude'].tolist() @@ -158,10 +158,10 @@ def createunderarmourworkoutdata(w): except KeyError: haslatlon = 0 - + # path data if haslatlon: - locdata = [] + locdata = [] for e in zip(t,lat.values,lon.values): point = { 'lat':e[1], @@ -187,7 +187,7 @@ def createunderarmourworkoutdata(w): spmdata = [] for e in zip(t,spm): spmdata.append([e[0],e[1]]) - + timeseries = { "distance": distancedata, @@ -215,7 +215,7 @@ def createunderarmourworkoutdata(w): if haslatlon: timeseries["position"] = locdata - + data = { "start_datetime": start_time, "name": name, @@ -235,7 +235,7 @@ def get_idfromuri(user,links): typeid = links['activity_type'][0]['id'] typename = get_typefromid(typeid,user) - + return id,typename def getidfromresponse(response): @@ -256,7 +256,7 @@ def refresh_ua_actlist(user): 'Content-Type': 'application/json'} url = "https://api.ua.com/v7.1/activity_type/" response = requests.get(url,headers=headers) - + me_json = response.json() types = me_json["_embedded"]["activity_types"] w = {int(t["_links"]["self"][0]["id"]):t["name"] for t in types} @@ -290,11 +290,11 @@ def get_typefromid(typeid,user): res = me_json['name'] except KeyError: res = 0 - - return res - - + return res + + + # Get user id, having access token # Handy for checking if the API access is working def get_userid(access_token): @@ -313,11 +313,11 @@ def get_userid(access_token): res = me_json['id'] except KeyError: res = 0 - + return res def default(o): - if isinstance(o, numpy.int64): return int(o) + if isinstance(o, numpy.int64): return int(o) raise TypeError @@ -338,7 +338,7 @@ def workout_ua_upload(user,w): message = "Data error" uaid = 0 return message, uaid - + authorizationstring = str('Bearer ' + thetoken) headers = {'Authorization': authorizationstring, 'Api-Key': UNDERARMOUR_CLIENT_KEY, @@ -357,7 +357,7 @@ def workout_ua_upload(user,w): w.save() elif (response.status_code == 201 or response.status_code==200): uaid = getidfromresponse(response) - w.uploadedtounderarmour = uaid + w.uploadedtounderarmour = uaid w.save() return 'Successfully synchronized with MapMyFitness',uaid else: @@ -365,7 +365,7 @@ def workout_ua_upload(user,w): message = "Something went wrong in workout_underarmour_upload_view: %s - %s" % (s.reason,s.text) uaid = 0 return message, uaid - + else: message = "You are not authorized to upload this workout" uaid = 0 @@ -384,7 +384,7 @@ def add_workout_from_data(user,importid,data,strokedata, comments = data['notes'] except: comments = '' - + try: thetimezone = tz(data['start_locale_timezone']) except: @@ -405,8 +405,8 @@ def add_workout_from_data(user,importid,data,strokedata, rowdatetime = datetime.strptime(data['date'],"%Y-%m-%d %H:%M:%S") rowdatetime = thetimezone.localize(rowdatetime).astimezone(utc) starttimeunix = arrow.get(rowdatetime).timestamp - - + + try: title = data['name'] except: @@ -414,7 +414,7 @@ def add_workout_from_data(user,importid,data,strokedata, timeseries = data['time_series'] - # position, distance, speed, cadence, power, + # position, distance, speed, cadence, power, try: res = splituadata(timeseries['distance']) @@ -427,7 +427,7 @@ def add_workout_from_data(user,importid,data,strokedata, try: l = timeseries['position'] - + res = splituadata(l) times_location = res[0] latlong = res[1] @@ -445,7 +445,7 @@ def add_workout_from_data(user,importid,data,strokedata, loncoord = np.zeros(len(times_distance)) if workouttype in otwtypes: workouttype = 'rower' - + try: res = splituadata(timeseries['cadence']) times_spm = res[0] @@ -453,7 +453,7 @@ def add_workout_from_data(user,importid,data,strokedata, except KeyError: times_spm = times_distance spm = 0*times_distance - + try: res = splituadata(timeseries['heartrate']) hr = res[1] @@ -485,7 +485,7 @@ def add_workout_from_data(user,importid,data,strokedata, ' HRCur (bpm)' : hrseries, } - + df = pd.DataFrame(d) @@ -495,7 +495,7 @@ def add_workout_from_data(user,importid,data,strokedata, df[' ElapsedTime (sec)'] = cum_time velo = df[' Horizontal (meters)'].diff()/df[' ElapsedTime (sec)'].diff() - + df[' Power (watts)'] = 0.0*velo nr_rows = len(velo.values) @@ -512,17 +512,17 @@ def add_workout_from_data(user,importid,data,strokedata, unixtime = cum_time+starttimeunix unixtime[0] = starttimeunix - + df['TimeStamp (sec)'] = unixtime - + dt = np.diff(cum_time).mean() wsize = round(5./dt) df = df.fillna(0) df.sort_values(by='TimeStamp (sec)',ascending=True) - + timestr = strftime("%Y%m%d-%H%M%S") csvfilename ='media/{code}_{importid}.csv'.format( @@ -540,4 +540,3 @@ def add_workout_from_data(user,importid,data,strokedata, notes=comments) return (id,message) -