def authenticate():
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)    
    auth2_client.sleep()
    
    yesterday = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d"))
    yesterday2 = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
    today = str(datetime.datetime.now().strftime("%Y%m%d"))

    fit_statsHR = auth2_client.intraday_time_series('activities/heart', base_date=yesterday2, detail_level='1sec')

    time_list = []
    val_list = []
    for i in fit_statsHR['activities-heart-intraday']['dataset']:
        val_list.append(i['value'])
        time_list.append(i['time'])
    heartdf = pd.DataFrame({'Heart Rate':val_list,'Time':time_list})

    heartdf.to_csv('/Users/anthony/Downloads/python-fitbit-master/Heart/heart'+ \
               yesterday+'.csv', \
               columns=['Time','Heart Rate'], header=True, \
               index = False)
Пример #2
0
def signupPaciente():
    form = RegisterForm_Paciente()

    if form.validate_on_submit():

        hashed_password = generate_password_hash(form.password.data, method='sha256') #geração da hash de segurança
        
        # integração com o fitbit.
        CLIENT_ID = '22BMBD'
        CLIENT_SECRET = '41bf164e37513442e8fc5c3f36f3d876'
        #Solicitação de código de acesso para o cliente
        server=Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
        server.browser_authorize()
        ACCESS_TOKEN=str(server.fitbit.client.session.token['access_token'])
        REFRESH_TOKEN=str(server.fitbit.client.session.token['refresh_token'])
        auth2_client=fitbit.Fitbit(CLIENT_ID,CLIENT_SECRET,oauth2=True,access_token=ACCESS_TOKEN,refresh_token=REFRESH_TOKEN,expires_at=3153600)
            
        
        new_user = Paciente(ProfSaude_id=current_user.id ,username=form.username.data,email=form.email.data,password=hashed_password, name=form.name.data ,age=form.age.data,weight=form.weight.data,height=form.height.data, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
        
        db.session.add(new_user) #adiciona novo usuário no banco de dados
        db.session.commit() #atualiza banco de dados
        flash('Cadastro bem-sucedido')
        return redirect('/dashboard')
    return render_template('signupPaciente.html', form=form)
def getFitbitClient():
    CLIENT_ID = '22DRGH'
    CLIENT_SECRET = '5990430b77b9de227dbdf758b075a868'

    try:
        keys = loads(open("keys.json", 'r').read())
    except FileNotFoundError:
        server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
        server.browser_authorize()

        keys = dict()
        token = server.fitbit.client.session.token
        keys['access_token'] = str(token['access_token'])
        keys['refresh_token'] = str(token['refresh_token'])

        save_keys_to_file(server.fitbit.client.session.token)

    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 refresh_cb=save_keys_to_file,
                                 oauth2=True,
                                 access_token=keys['access_token'],
                                 refresh_token=keys['refresh_token'])

    return auth2_client
def accessAPI():
    #Client ID & Secret is given to us from the FitBit website
    CLIENT_ID = r'22DFZ8'
    CLIENT_SECRET = r'9e72de768392860b178fe36968c788e3'

    #Establish authentication with Fitbit
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()

    #Save these if new access or refresh is needed
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])

    #Connection
    auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

    #calls data and saves into dataframe
    fit_statsHR = auth2_client.intraday_time_series('activities/heart', base_date=today2, detail_level='1sec')

    #reads the dictionary format and iterates through the dictionary values
    time_list = []
    val_list = []

    for i in fit_statsHR['activities-heart-intraday']['dataset']:
        val_list.append(i['value'])
        time_list.append(i['time'])

    heartdf = pd.DataFrame({'HR':val_list,'Time':time_list})

    heartdf.to_csv('data/rawHR/' + 'HR_' + today + '.csv', columns=['Time','HR'], header=True, index = False)
    print("File saved")
Пример #5
0
def get_json(start_date, stop_date):
    # we've got the plain text id and secret in a text file for jerry rigging
    in_file = open(r"fitbit_client_keys.txt", "r")
    app_info = in_file.readlines()
    CLIENT_ID = app_info[0].strip()
    CLIENT_SECRET = app_info[1].strip()
    server = gather.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    # using oauth2 to access
    print(CLIENT_ID)
    server.browser_authorize()
    # getting all of our tokens
    USER_ID = server.fitbit.client.session.token['user_id']
    ACCESS_TOKEN = server.fitbit.client.session.token['access_token']
    REFRESH_TOKEN = server.fitbit.client.session.token['refresh_token']
    # authd client is the actual Fitbit object we'll use to gather information
    authd_client = fitbit.Fitbit(USER_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)
    # Here, we're having collect_daily_activity_data get each of our daily values (each listed in activities)
    # and putting them into JSON format so we can use it in our website
    df = collect_daily_activity_data(authd_client, date, activities,
                                     start_date, stop_date)
    json_format = df.to_json()
    return json_format
 def __init__(self):
     self.server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
     # print(ACCESS_TOKEN, REFRESH_TOKEN)
     self.auth2_client = fitbit.Fitbit(CLIENT_ID,
                                       CLIENT_SECRET,
                                       oauth2=True,
                                       access_token=ACCESS_TOKEN,
                                       refresh_token=REFRESH_TOKEN)
Пример #7
0
def hello_world():
    CLIENT_ID = '22D5TC'
    CLIENT_SECRET = '77e03cdf3389696430af37becf5c8291'

    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET, redirect_uri="https://sherlie.iqube.io/callback")
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)

    return 'Hello World!'
Пример #8
0
def contact_server(CLIENT_ID, CLIENT_SECRET):
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)

    return auth2_client
Пример #9
0
def authorize_application(_creds):
    print("   NOTE: CherryPy spins up a webserver on localhost so that you can auth \n")
    print("   If you are on Ubuntu Server, use a commandline browser:")
    print("     sudo apt-get install elinks \n")
    print("   Then, when running this python program, elinks will auto open.")
    print("   NOTE: press enter and q to exit elinks after completed (when you see: 'ENGINE Waiting for child threads')\n")
    # redirect_uri is required if you have more than one callback_url registered in your FitbitApp
    # otherwise it can be removed.
    # however, in order to use the gather_keys_oauth2 cherrypy example, it requires http://127.0.0.1:8080/ set in your app
    server = Oauth2.OAuth2Server(_creds['client_id'],_creds['client_secret'],redirect_uri=_creds['callback_url'])
    server.browser_authorize()
    token_saver(server.fitbit.client.session.token)
Пример #10
0
	def authFitBitConnection(self, instance):
		# print('The button <%s> is being pressed' % instance.text)
		CLIENT_ID = '22BMFK'
		CLIENT_SECRET = '8750dfbe95041b1c60f2584fe975c2b2'	
		server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
		server.browser_authorize()
		ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
		REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
		self.auth2_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
		self.yesterday2 = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
		self.yesterday = str((datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d"))
		self.today = str(datetime.datetime.now().strftime("%Y%m%d"))
Пример #11
0
def auth():
    server = Oauth2.OAuth2Server(secrets.CLIENT_ID, secrets.CLIENT_SECRET)
    server.remote_authorize()

    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(secrets.CLIENT_ID,
                                 secrets.CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN,
                                 system=fitbit.Fitbit.METRIC)
    return auth2_client
Пример #12
0
def getOauthClient(c_id, c_secret, oauth_call_back):
  try:
    ACCESS_TOKEN = SET_ACCESS_TOKEN
    REFRESH_TOKEN = SET_REFRESH_TOKEN
    auth2_client = fitbit.Fitbit(c_id, c_secret, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN, system=None)
  except BaseException as e:
    print("Got exception: {}".format(str(e)))
    server = Oauth2.OAuth2Server(client_id=c_id, client_secret=c_secret, redirect_uri=oauth_call_back)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(c_id, c_secret, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN, system=None)
  return auth2_client
Пример #13
0
    def initialize_fitbit_api(self):
        server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
        server.browser_authorize()
        ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
        REFRESH_TOKEN = str(
            server.fitbit.client.session.token['refresh_token'])
        auth2_client = fitbit.Fitbit(CLIENT_ID,
                                     CLIENT_SECRET,
                                     oauth2=True,
                                     access_token=ACCESS_TOKEN,
                                     refresh_token=REFRESH_TOKEN)
        auth2_client.API_VERSION = 1.2

        self.sleep_auth2 = auth2_client
Пример #14
0
def get_fitbit_client(fb_id, fb_secret):
    server = Oauth2.OAuth2Server(fb_id, fb_secret)
    server.browser_authorize()
    access_token = str(server.fitbit.client.session.token['access_token'])
    refresh_token = str(server.fitbit.client.session.token['refresh_token'])
    client = fitbit.Fitbit(fb_id,
                           fb_secret,
                           oauth2=True,
                           access_token=access_token,
                           refresh_token=refresh_token,
                           system="en_UK")
    # Keep cherry webserver log and app log seperated
    time.sleep(1)
    return client
Пример #15
0
def getClient():
    CLIENT_ID = '22D35M'
    CLIENT_SECRET = 'c3650774498361a6eb297da3f066b581'

    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)

    return auth2_client
def get_averange_hbt_from_server(client_id, client_secret, days):
    # If the input days are wrong return -1.
    if days < 1 and isinstance(days, int):
        print("Wrong input days.")
        return 0

    rest_hbr_list = []

    # Initialize sever connection.
    server = oauth2.OAuth2Server(client_id, client_secret)
    server.browser_authorize()
    access_token = str(server.fitbit.client.session.token['access_token'])
    refresh_token = str(server.fitbit.client.session.token['refresh_token'])

    client = fitbit.Fitbit(client_id,
                           client_secret,
                           oauth2=True,
                           access_token=access_token,
                           refresh_token=refresh_token)

    # Get the rest heartbeat rate data of few days before.
    for day in range(1, days):
        fit_stats_hr = client.intraday_time_series(
            'activities/heart',
            base_date=generate_date(day),
            detail_level='15min')

        values = fit_stats_hr['activities-heart'][0]['value']

        if 'restingHeartRate' in values:
            rest_hbr_list.append(values['restingHeartRate'])
            print("Date: %s, Rest heartbeat rate: %d" %
                  (fit_stats_hr['activities-heart'][0]['dateTime'],
                   values['restingHeartRate']))

    # Get averange.
    if len(rest_hbr_list) != 0:
        result = numpy.mean(rest_hbr_list)
        print("Got averange HBR data from fitbit server: ", result)
        return result
    else:
        return 0
Пример #17
0
def main():
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)

    yesterday = str((datetime.datetime.now() -
                     datetime.timedelta(days=1)).strftime("%Y%m%d"))
    yesterday2 = str((datetime.datetime.now() -
                      datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
    today = str(datetime.datetime.now().strftime("%Y%m%d"))

    fit_statsHR = auth2_client.intraday_time_series('activities/heart',
                                                    base_date=yesterday2,
                                                    detail_level='1sec')
Пример #18
0
def instantiate_fitbit_kurt():
    """
    Use gather_keys_oauth2 class to gather tokens and instantiate a.

    'Kurt' Fitbit class.
    """
    import gather_keys_oauth2
    import os

    CLIENT_ID = os.environ['client_id']
    SECRET = os.environ['secret']
    server = gather_keys_oauth2.OAuth2Server(CLIENT_ID, SECRET)
    server.browser_authorize()
    access_token = server.fitbit.client.session.token['access_token']
    refresh_token = server.fitbit.client.session.token['refresh_token']
    expires_at = server.fitbit.client.session.token['expires_at']
    kurt = Fitbit(CLIENT_ID,
                  SECRET,
                  access_token=access_token,
                  refresh_token=refresh_token,
                  expires_at=expires_at,
                  refresh_cb=refresh_cb)
    return kurt
Пример #19
0
CLIENT_SECRET_SPOTIFY = '98fe97db700b44f4ad0743b945e3084b'
CALLBACK_SPOTIFY = 'http://localhost:8888/callback/'
SPOTIFY_USER = '******'
SCOPE = 'user-modify-playback-state user-read-playback-state'
token = util.prompt_for_user_token(SPOTIFY_USER, SCOPE, CLIENT_ID_SPOTIFY,
                                   CLIENT_SECRET_SPOTIFY, CALLBACK_SPOTIFY)
playing_device = None
Current_Date = datetime.now()
Date = str(Current_Date)[:10]

if token:
    print("Valid Token")
    playing_device = None
    sp = spotipy.Spotify(auth=token)
    all_devices = sp.devices()['devices']
    server = Oauth2.OAuth2Server(CLIENT_ID_FITBIT, CLIENT_SECRET_FITBIT)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    client = fitbit.Fitbit(client_id=CLIENT_ID_FITBIT,
                           client_secret=CLIENT_SECRET_FITBIT,
                           access_token=ACCESS_TOKEN,
                           refresh_token=REFRESH_TOKEN)
    if os.path.exists('logid.txt'):
        with open('logid.txt', 'r') as f:
            client.delete_sleep(f.readline()[:-1])
        os.remove('logid.txt')
    while 1:
        #Handles if you start program before midnight but go to sleep after midnight
        if Date != str(datetime.now())[:10]:
            Current_Date = datetime.now()
Пример #20
0
def getAuth2Client():

    # Open the tokens.txt file as f
    with open('tokens.txt') as f:

        # Make an array out of the different lines of the file
        content = f.readlines()

    # Clean the array values so that they work
    content = [x.strip() for x in content]

    # Sets up the date-time to check if a new api call is required
    dt = int(time.time())
    lastdt = int(content[2])
    expireTime = 10 * 60  # (10 min in UNIX time)

    # User specific data, read from line 1 and 2 of tokens file
    CLIENT_ID = content[0]
    CLIENT_SECRET = content[1]

    # Print Days, Hours, Minutes, Seconds since last server refresh,
    # see
    # timeLastCalled()
    timeLastCalled(dt, lastdt)

    # Determine if a new server call is required to refresh tokens
    if ((dt - lastdt) >= expireTime):

        print('\n-----Calling server for new tokens-----\n')

        # Refreshses tokens
        server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
        server.browser_authorize()

        # Retrieves new tokens from FitBit
        ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
        REFRESH_TOKEN = str(
            server.fitbit.client.session.token['refresh_token'])

        print('\n-----Writing new tokens to tokens.txt-----')

        # Writes updated information to tokens.txt for next run of program
        with open('tokens.txt', 'w') as f:
            f.write(str(CLIENT_ID) + '\n')
            f.write(str(CLIENT_SECRET) + '\n')
            f.write(str(dt) + '\n')  # (Current Unix Time)
            f.write(str(ACCESS_TOKEN) + '\n')
            f.write(str(REFRESH_TOKEN) + '\n')

    else:  # (If a server call was not required, take previous tokens)
        ACCESS_TOKEN = content[3]
        REFRESH_TOKEN = content[4]

    # Use those tokens and ID's to make the auth2_client that will be used for
    # API calls
    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)

    # Return the client
    return auth2_client
Пример #21
0
def instantiate_server():
    CLIENT_ID, CLIENT_SECRET = get_fitbit_client_id(
    ), get_fitbit_client_secret()
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    return CLIENT_ID, CLIENT_SECRET, server
Пример #22
0
def my_link():
    calm = ""
    FinalEmotion = ""
    count = 0
    heartRateNeutralStart = 80
    heartRateNeutralEnd = 100
    heartRateDummyValue = 110

    #EMOTIONS and their corresponding FRAGRANCES
    angryFragrance = "rose"
    happyFragrance = "lavender"
    sadFragrance = "woods"
    surprisedFragrance = "citrus"
    calmFragrance = "ocean"

    #DEFAULT USER PREFERENCES
    Sophie = "lavender"
    Claire = "ocean"
    Josephine = "ocean"
    Benoit = "rose"
    Faustine = "woods"
    Harvey = "citrus"
    Emile = "rose"

    CLIENT_ID = '22BQWT'
    CLIENT_SECRET = 'dfc33d81a41114e8feff6d022216842e'

    values_dict = {
        'angry': 'angry',
        'happy': 'happy',
        'surprised': 'surprised',
        'sad': 'sad'
    }

    question = request.form['questionnaire']
    userName = request.form['userName']
    print("userName = "******"question =", question)
    # ********************GOOGLE VISION*************************************

    #open('pri.txt', 'w').close()

    #Emotions
    emo = ['Angry', 'Surprised', 'Sad', 'Happy']
    likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
                       'LIKELY', 'VERY_LIKELY')

    ############## Spanish version #################
    #emo = ['Bravo', 'Sorprendido','Triste', 'Feliz']
    #string = 'Sin emocion'

    #from google.oauth2 import service_account
    #credentials = service_account.Credentials.from_service_account_file('key.json')
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "E:\Flask_Web_app\key.json"

    # Instantiates a client
    vision_client = vision.ImageAnnotatorClient()

    cv2.imshow('Video', np.empty((5, 5), dtype=float))

    compressRate = 1
    while cv2.getWindowProperty('Video', 0) >= 0:
        video_capture = cv2.VideoCapture(0)
        ret, img = video_capture.read()
        img = cv2.resize(img, (0, 0), fx=compressRate, fy=compressRate)

        ok, buf = cv2.imencode(".jpeg", img)
        image = vision.types.Image(content=buf.tostring())

        response = vision_client.face_detection(image=image)
        faces = response.face_annotations
        len(faces)
        for face in faces:
            x = face.bounding_poly.vertices[0].x
            y = face.bounding_poly.vertices[0].y
            x2 = face.bounding_poly.vertices[2].x
            y2 = face.bounding_poly.vertices[2].y
            cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 0), 2)

            sentiment = [
                likelihood_name[face.anger_likelihood],
                likelihood_name[face.surprise_likelihood],
                likelihood_name[face.sorrow_likelihood],
                likelihood_name[face.joy_likelihood]
            ]
            #likelihood_name[face.under_exposed_likelihood],
            #likelihood_name[face.blurred_likelihood],
            #likelihood_name[face.headwear_likelihood]]

            with open("pri.txt", "a") as text_file:
                for item, item2 in zip(emo, sentiment):
                    print(item, ":", item2, file=text_file)

            string = 'No sentiment'

            if not (all(item == 'VERY_UNLIKELY' for item in sentiment)):
                if any(item == 'VERY_LIKELY' for item in sentiment):
                    state = sentiment.index('VERY_LIKELY')
                    # the order of enum type Likelihood is:
                    #'LIKELY', 'POSSIBLE', 'UNKNOWN', 'UNLIKELY', 'VERY_LIKELY', 'VERY_UNLIKELY'
                    # it makes sense to do argmin if VERY_LIKELY is not present, one would espect that VERY_LIKELY
                    # would be the first in the order, but that's not the case, so this special case must be added
                else:
                    state = np.argmin(sentiment)

                string = emo[state]

            cv2.putText(img, string, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
                        (0, 0, 255), 2)

        cv2.imshow("Video", img)
        cv2.waitKey(1)
        video_capture.release()

    # When everything is done, release the capture
    cv2.destroyAllWindows()

    dictList = []
    with open('pri.txt', 'r') as f:
        for line in f:
            elements = line.rstrip().split(":")
            dictList.append(dict(zip(elements[::2], elements[1::2])))

    for i in range(0, len(dictList)):
        for key in dictList[i]:
            varx = dictList[i][key].lstrip()
            dictList[i][key] = varx

    dictnew = {}

    for k, v in [(key, d[key]) for d in dictList for key in d]:
        if k not in dictnew:
            dictnew[k] = [v]
        else:
            dictnew[k].append(v)

    def counter(dict1):
        dictnew = {
            'Angry ': [{
                'VERY_LIKELY': 0
            }, {
                'LIKELY': 0
            }, {
                'POSSIBLE': 0
            }, {
                'UNLIKELY': 0
            }, {
                'VERY_UNLIKELY': 0
            }],
            'Surprised ': [{
                'VERY_LIKELY': 0
            }, {
                'LIKELY': 0
            }, {
                'POSSIBLE': 0
            }, {
                'UNLIKELY': 0
            }, {
                'VERY_UNLIKELY': 0
            }],
            'Sad ': [{
                'VERY_LIKELY': 0
            }, {
                'LIKELY': 0
            }, {
                'POSSIBLE': 0
            }, {
                'UNLIKELY': 0
            }, {
                'VERY_UNLIKELY': 0
            }],
            'Happy ': [{
                'VERY_LIKELY': 0
            }, {
                'LIKELY': 0
            }, {
                'POSSIBLE': 0
            }, {
                'UNLIKELY': 0
            }, {
                'VERY_UNLIKELY': 0
            }]
        }

        for key in dict1.keys():
            for k in dictnew.keys():
                if key == k:
                    for j in range(0, len(dict1[key])):
                        for m in range(0, 5):
                            for n in dictnew[key][m].keys():
                                if n == dict1[key][j]:
                                    dictnew[key][m][n] = dictnew[key][m][n] + 1

        for k in dictnew.keys():
            dictnew[k][4]['VERY_UNLIKELY'] = 0

        return dictnew

    dictnew = counter(dictnew)

    def score(dict1):
        order = ['VERY_LIKELY', 'LIKELY', 'POSSIBLE', 'UNLIKELY']
        scoredict = {'Angry ': 0, 'Surprised ': 0, 'Sad ': 0, 'Happy ': 0}
        for key in dict1.keys():
            for j in range(0, len(dict1[key])):
                for n in dictnew[key][j].keys():
                    if dictnew[key][j][n] > 0:
                        scoredict[key] = scoredict[key] + dictnew[key][j][n]

        listvar = []
        var1 = 0
        final = {
            'Angry ': 'VERY_UNLIKELY',
            'Surprised ': 'VERY_UNLIKELY',
            'Sad ': 'VERY_UNLIKELY',
            'Happy ': 'VERY_UNLIKELY'
        }
        for k in scoredict.keys():
            if scoredict[k] > var1:
                listvar.clear()
                listvar.append({k: scoredict[k]})
                var1 = scoredict[k]
            elif scoredict[k] == var1:
                listvar.append({k: scoredict[k]})
        semi = []
        varneed = 0

        for p in range(0, len(listvar)):
            for kites in listvar[p].keys():
                for key in dict1.keys():
                    if key == kites:
                        for l in range(0, 4):
                            for locks in dict1[key][l].keys():
                                if dict1[key][l][locks] > 0:
                                    if len(semi) > 0:
                                        for z in semi[0].keys():
                                            if order.index(
                                                    semi[0][z]) > order.index(
                                                        locks):
                                                semi.pop()

                                                semi.append({key: locks})

                                    else:
                                        semi.append({key: locks})

        for keys in semi[0].keys():
            final[keys] = semi[0][keys]
        for key, value in final.items():
            if (key == "Angry "):
                angry = value
                values_dict["angry"] = angry
            if (key == "Surprised "):
                surprised = value
                values_dict["surprised"] = surprised
            if (key == "Sad "):
                sad = value
                values_dict["sad"] = sad
            if (key == "Happy "):
                happy = value
                values_dict["happy"] = happy
        return (scoredict, listvar, final)

    scoredict, listvar, final = score(dictnew)

    #open('pri.txt', 'w').close()

    #*******************FITBIT*******************************

    #Server authentication
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    server.browser_authorize()
    ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
    REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
    auth2_client = fitbit.Fitbit(CLIENT_ID,
                                 CLIENT_SECRET,
                                 oauth2=True,
                                 access_token=ACCESS_TOKEN,
                                 refresh_token=REFRESH_TOKEN)
    yesterday = str((datetime.datetime.now() -
                     datetime.timedelta(days=1)).strftime("%Y%m%d"))
    yesterday2 = str((datetime.datetime.now() -
                      datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
    today = str(datetime.datetime.now().strftime("%Y-%m-%d"))
    fit_statsHR = auth2_client.intraday_time_series('activities/heart',
                                                    base_date=today,
                                                    detail_level='1sec')
    time_list = []
    val_list = []
    for i in fit_statsHR['activities-heart-intraday']['dataset']:
        val_list.append(i['value'])
        time_list.append(i['time'])
    heartdf = pd.DataFrame({'Heart Rate': val_list, 'Time': time_list})
    if len(val_list) == 0:
        heartRate = heartRateDummyValue  #if FitBit is not synced today then the list is empty.Value 90 assigned to heartRate if fitbit is not synced today.
    else:
        heartRate = val_list[
            -1]  #Latest value from fitbit app is assigned to heartRate
    print(f'HeartRate={heartRate}')  #Prints heartRate in Terminal

    #***********************ALGORITHM************************************
    #assign heartRate
    if (heartRate < heartRateNeutralStart):
        heartBeat = "below"
    elif (heartRate > heartRateNeutralEnd):
        heartBeat = "above"
    else:
        heartBeat = "neutral"
    for emotion, value in values_dict.items():
        print(emotion, " = ", value)
        if (value == "VERY_LIKELY"
            ):  #1st branch of algorithm-one emotion is VERY_LIKELY
            FinalEmotion = emotion
    if (FinalEmotion == ""
        ):  #3rd branch of algorithm-all emotions are VERY_UNLIKELY
        for emotion, value in values_dict.items():
            if (value == "VERY_UNLIKELY"):
                count += 1
        if (count == 4):
            if (heartBeat == "above"):
                if (question == "left"):
                    FinalEmotion = "angry"
                elif (question == "right"):
                    FinalEmotion = "happy"
                elif (question == "neutral"):
                    FinalEmotion = "Print emotion from Emotion Table"
                elif (question == "angry"):
                    FinalEmotion = "angry"
                elif (question == "happy"):
                    FinalEmotion = "happy"
                elif (question == "calm"):
                    FinalEmotion = "calm"
                elif (question == "sad"):
                    FinalEmotion = "sad"
            elif (heartBeat == "below"):
                if (question == "left"):
                    FinalEmotion = "sad"
                elif (question == "right"):
                    FinalEmotion = "calm"
                elif (question == "neutral"):
                    FinalEmotion = "Print emotion from Emotion Table"
                elif (question == "angry"):
                    FinalEmotion = "angry"
                elif (question == "happy"):
                    FinalEmotion = "happy"
                elif (question == "calm"):
                    FinalEmotion = "calm"
                elif (question == "sad"):
                    FinalEmotion = "sad"
            elif (heartBeat == "neutral"):
                if (question == "left"):
                    FinalEmotion = "Print emotion from Emotion Table"
                elif (question == "right"):
                    FinalEmotion = "Print emotion from Emotion Table"
                elif (question == "neutral"):
                    FinalEmotion = "Print emotion from Emotion Table"
                elif (question == "angry"):
                    FinalEmotion = "angry"
                elif (question == "happy"):
                    FinalEmotion = "happy"
                elif (question == "calm"):
                    FinalEmotion = "calm"
                elif (question == "sad"):
                    FinalEmotion = "sad"
    if (FinalEmotion == ""):  #2nd branch of algorithm -neutral
        if (heartBeat == "above"):
            if (question == "left"):
                FinalEmotion = "angry"
            elif (question == "right"):
                FinalEmotion = "happy"
            elif (question == "neutral"):
                FinalEmotion = "Print emotion from Emotion Table"
            elif (question == "angry"):
                FinalEmotion = "angry"
            elif (question == "happy"):
                FinalEmotion = "happy"
            elif (question == "calm"):
                FinalEmotion = "calm"
            elif (question == "sad"):
                FinalEmotion = "sad"
        elif (heartBeat == "below"):
            if (question == "left"):
                FinalEmotion = "sad"
            elif (question == "right"):
                FinalEmotion = "calm"
            elif (question == "neutral"):
                FinalEmotion = "Print emotion from Emotion Table"
            elif (question == "angry"):
                FinalEmotion = "angry"
            elif (question == "happy"):
                FinalEmotion = "happy"
            elif (question == "calm"):
                FinalEmotion = "calm"
            elif (question == "sad"):
                FinalEmotion = "sad"
        elif (heartBeat == "neutral"):
            if (question == "left"):
                FinalEmotion = "Print emotion from Emotion Table"
            elif (question == "right"):
                FinalEmotion = "Print emotion from Emotion Table"
            elif (question == "neutral"):
                FinalEmotion = "Print emotion from Emotion Table"
            elif (question == "angry"):
                FinalEmotion = "angry"
            elif (question == "happy"):
                FinalEmotion = "happy"
            elif (question == "calm"):
                FinalEmotion = "calm"
            elif (question == "sad"):
                FinalEmotion = "sad"
    #prints final emotion in the terminal
    print(f'Final Emotion={FinalEmotion}')
    #Pop up window displays result
    popup = tk.Tk()
    popup.wm_title("Result")
    if (FinalEmotion == "angry"):
        label = ttk.Label(popup,
                          text="Hi " + userName +
                          "!\n You are angry !\n Enjoy the " + angryFragrance +
                          " fragrance!")
    elif (FinalEmotion == "happy"):
        label = ttk.Label(popup,
                          text="Hi " + userName +
                          "!\n You are happy!\n Enjoy the " + happyFragrance +
                          " fragrance!")
    elif (FinalEmotion == "calm"):
        label = ttk.Label(popup,
                          text="Hi " + userName +
                          "!\n You are calm!\n Enjoy the " + calmFragrance +
                          " fragrance!")
    elif (FinalEmotion == "sad"):
        label = ttk.Label(popup,
                          text="Hi " + userName +
                          "!\n You are sad!\n Enjoy the " + sadFragrance +
                          " fragrance!")
    elif (FinalEmotion == "Print emotion from Emotion Table"):
        if (userName == "Sophie"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Sophie + " !")
        elif (userName == "Claire"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Claire + " !")
        elif (userName == "Josephine"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Josephine + " !")
        elif (userName == "Benoit"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Benoit + " !")
        elif (userName == "Faustine"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Faustine + " !")
        elif (userName == "Harvey"):
            label = ttk.Label(
                popup,
                text="Hi " + userName +
                "! \n You are neutral.\n Enjoy your prefered fragrance " +
                Harvey + " !")
    elif (FinalEmotion == "surprised"):
        label = ttk.Label(popup,
                          text="Hi \n You are surprised!\n Enjoy the " +
                          surprisedFragrance + " fragrance!")
    else:
        label = ttk.Label(popup, text="test case")
    label.pack(side="top", fill="x", pady=10)
    B1 = ttk.Button(popup, text="ok", command=popup.destroy)
    B1.pack()
    popup.mainloop()
    #Retains and displays the web page

    #arduino code starts
    # initialize connection to Arduino
    # if your arduino was running on a serial port other than '/dev/ttyACM0/'
    # declare: a = Arduino(serial_port='/dev/ttyXXXX')
    a = Arduino()
    time.sleep(3)

    # declare the pins we're using
    LED_PIN = 50
    ANALOG_PIN = 0
    emotion = 50
    # initialize the digital pin as output
    a.set_pin_mode(emotion, 'O')
    print('Arduino initialized')

    # if we make a post request on the webpage aka press button then do stuff
    # if request.method == 'POST':
    # if we press the turn on button

    # print("emotion =", emotion)
    # if request.form['submit'] == 'start' :
    #     # emotion = FinalEmotion
    if FinalEmotion == "angry":
        emotion = 42  ##enter the pin assigned
    elif FinalEmotion == "happy":
        emotion = 50  ##enter the pin assigned
    elif FinalEmotion == "sad":
        emotion = 48  ##enter the pin assigned
    elif FinalEmotion == "calm":
        emotion = 46  ##enter the pin assigned
    elif FinalEmotion == "surprised":
        emotion = 44  ##enter the pin assigned
    else:
        emotion = 46  ##enter the pin assigned

    print('TURN ON')
    try:
        #turn off the LED on arduino
        for i in range(0, 100):
            a.digital_write(i, 0)
        # turn on LED on arduino
        print("emotion inside catch type =", type(emotion))
        print("emotion inside catch value =", emotion)
        # a.set_pin_mode(emotion,'O')
        a.digital_write(emotion, 1)
    except:
        print("already entered")

    return (''), 204
Пример #23
0
 def _authorize(self):
     try:
         server = Oauth2.OAuth2Server(self.client_id, self.client_secret)
         server.browser_authorize()
     except Exception as e:
         print(traceback.format_exc())
Пример #24
0
    try:
        creds['client_id'] = config[section].get("client_id")
        creds['client_secret'] = config[section].get("client_secret")
    except Exception:
        print(
            "Couldn't find credentials. Make sure they are in the following format:"
        )
        print("""
        [Fitbit]
            CLIENT_ID=<client id here>
            CLIENT_SECRET=<client secret here>

        """)
        exit(1)

    server = oauth2.OAuth2Server(creds['client_id'], creds['client_secret'])
    server.browser_authorize()

    creds['access_token'] = str(
        server.fitbit.client.session.token['access_token'])
    creds['refresh_token'] = str(
        server.fitbit.client.session.token['refresh_token'])
    creds['expires_at'] = str(server.fitbit.client.session.token['expires_at'])

    print("""
        Your Oauth Info:

        Access Token: {access}

        Refresh Token: {refresh}
        Expires at: {expire}
Пример #25
0
else:
    start_date = dt.datetime.strptime(args.start_date, '%Y-%m-%d')
    if start_date > yesterday:
        raise 'Start date must be before yesterday'

    delta = yesterday - start_date

    dates = []

    for i in range(delta.days + 1):
        dates.append(start_date + dt.timedelta(days=i))

client_id = os.environ['FITBIT_CLIENT_ID']
client_secret = os.environ['FITBIT_CLIENT_SECRET']

server = Oauth2.OAuth2Server(client_id, client_secret)
server.browser_authorize()

access_token = str(server.fitbit.client.session.token['access_token'])
refresh_token = str(server.fitbit.client.session.token['refresh_token'])

print(access_token)
print(refresh_token)

client = fitbit.Fitbit(client_id,
                       client_secret,
                       oauth2=True,
                       access_token=access_token,
                       refresh_token=refresh_token)

heading = ['date', 'steps', 'calories']
Пример #26
0
def query_fitbit(delta=0):
    """
    Initiates fitbit client and server, returns  fitbit activity data relative to last calendar Sunday.
    If session token has expired, refreshes token and writes updated credentials to json file "json/creds.json".
    Outputs progress bars to terminal.
    :param delta: number of days to offset api call from getting data relative to most recent sunday
    :return fitbit_data: nested list [[steps], [distances]]
    """
    # TODO: put (re)authentication into separate function

    # get credentials from json file
    with open('json/creds.json') as src:
        data = json.load(src)
    CLIENT_ID = data['fitbit-clientID']
    CLIENT_SECRET = data['fitbit-secret']
    ACCESS_TOKEN = data['fitbit-token']
    REFRESH_TOKEN = data['fitbit-refresh-token']

    # create server and  client
    server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
    auth2_client = bit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN,
                              refresh_token=REFRESH_TOKEN)

    # get end and base date for api call
    today = str(datetime.datetime.now().strftime("%Y-%m-%d"))
    # sunday = str(get_sunday().strftime("%Y-%m-%d"))
    sunday = str(get_base_sunday(delta).strftime("%Y-%m-%d"))

    # catch 401 error / refresh the token if token has expired (pops up browser window)
    try:
        auth2_client.time_series(resource="activities/steps", base_date=sunday, end_date=today)
    except bit.exceptions.HTTPUnauthorized:
        server.browser_authorize()
        ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
        REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])

        # rewrite new credentials into json file
        with open("json/creds.json", "r") as jsonFile:
            creds = json.load(jsonFile)
        tmp1 = creds['fitbit-token']
        creds['fitbit-token'] = ACCESS_TOKEN
        tmp2 = creds['fitbit-refresh-token']
        creds['fitbit-refresh-token'] = REFRESH_TOKEN
        with open("json/creds.json", "w") as jsonFile:
            json.dump(creds, jsonFile)
        auth2_client = bit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN,
                                  refresh_token=REFRESH_TOKEN)

    # steps and distance query
    print("Querying fitbit...")
    # format: {'activities-steps': [{'dateTime': '2020-05-25', 'value': '11519'}, {'dateTime': '2020-05-26', 'value': '3428'}]}
    # {'activities-distance': [{'dateTime': '2020-05-25', 'value': '4.93872658484712'}, {'dateTime': '2020-05-26', 'value': '1.46974170786144'}]}
    steps_log = auth2_client.time_series(resource="activities/steps", base_date=sunday, end_date=today)
    dist_log = auth2_client.time_series(resource="activities/distance", base_date=sunday, end_date=today)

    # convert to dict-array
    # f [{'dateTime': '2020-05-25', 'value': '4.93872658484712'}, {'dateTime': '2020-05-26', 'value': '1.46974170786144'}]
    steps_log = steps_log['activities-steps']
    dist_log = dist_log['activities-distance']

    # reformat
    # steps: ['11519', '3428']  dist: ['4.93872658484712', '1.46974170786144']
    steps, dist, fitbit_data = [], [], []
    for i in range(0, len(steps_log)):
        steps_log[i].pop('dateTime')
        dist_log[i].pop('dateTime')
        steps.append(int(steps_log[i]['value']))
        # truncate to 3 decimal places
        d = float("%.3F" % float(dist_log[i]['value']))
        dist.append(d)

    # reformat
    #    --- steps ---                 ---  dist ---
    # [['11519', '3428'], ['4.93872658484712', '1.46974170786144']]
    fitbit_data.append(steps)
    fitbit_data.append(dist)

    return fitbit_data
Пример #27
0
import fitbit
import gather_keys_oauth2 as Oauth2
import pandas as pd
import datetime
CLIENT_ID = '22B58Z'
CLIENT_SECRET = '69ea96ed78c676d5bb9023696597b4cc'

server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET)
server.browser_authorize()
ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
auth2_client = fitbit.Fitbit(CLIENT_ID,
                             CLIENT_SECRET,
                             oauth2=True,
                             access_token=ACCESS_TOKEN,
                             refresh_token=REFRESH_TOKEN)

yesterday = str(
    (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d"))
yesterday2 = str((datetime.datetime.now() -
                  datetime.timedelta(days=1)).strftime("%Y-%m-%d"))
today = str(datetime.datetime.now().strftime("%Y%m%d"))

fit_statsHR = auth2_client.intraday_time_series('activities/heart',
                                                base_date=yesterday2,
                                                detail_level='1sec')

time_list = []
val_list = []
for i in fit_statsHR['activities-heart-intraday']['dataset']:
    val_list.append(i['value'])
Пример #28
0
from ast import literal_eval

settings_dict = literal_eval(settings_str)


def date_fr_str(d):
    return datetime.datetime.date(datetime.datetime.strptime(d, '%Y-%m-%d'))


def date_fr_datetime(d):
    return datetime.datetime.date(d)


#connect to fitbit server
server = oauth2.OAuth2Server(settings_dict['client_id'],
                             settings_dict['client_secret'])
server.browser_authorize()

ACCESS_TOKEN = str(server.fitbit.client.session.token['access_token'])
REFRESH_TOKEN = str(server.fitbit.client.session.token['refresh_token'])
auth2_client = fitbit.Fitbit(settings_dict['client_id'],
                             settings_dict['client_secret'],
                             oauth2=True,
                             access_token=ACCESS_TOKEN,
                             refresh_token=REFRESH_TOKEN)

initialdate = settings_dict['initialdate']
dateinterval = 30

#check we have a log of the historical fitbit data available
if os.path.exists('fitbit_data.pickle'):