def get_events():
    events = session.query(Event).order_by(Event.id.desc()).limit(100).all()
    results = []
    for e in events:
        event = {
            'user': u_ctrl.get_user_as_dictionary(e.user_id),
            'action': e.action,
            'view_type': e.view_type,
            'time_stamp': e.time_stamp,
            'data': None #just a default
        }
        if e.view_type == 'product':
            event['data'] = p_ctrl.get_product_as_dictionary(e.data_id)
            event['comments'] = p_ctrl.get_notes(e.user_id, e.data_id)
        if e.view_type in ['article', 'blog']:
            try:
                site_info_Q = s_ctrl.query_by_id_and_type(e.data_id, e.view_type).one()
                site_info = {}
                for column in site_info_Q.__table__.columns:
                    site_info[column.name] = getattr(site_info_Q, column.name)
                event['data'] = site_info
            except:
                None
            event['comments'] = s_ctrl.get_comments(e.user_id, e.view_type, e.data_id)
        
        results.append(event)

    return {'events':results}
def get_events():
    events = session.query(Event).order_by(Event.id.desc()).limit(100).all()
    results = []
    for e in events:
        event = {
            'user': u_ctrl.get_user_as_dictionary(e.user_id),
            'action': e.action,
            'view_type': e.view_type,
            'time_stamp': e.time_stamp,
            'data': None  #just a default
        }
        if e.view_type == 'product':
            event['data'] = p_ctrl.get_product_as_dictionary(e.data_id)
            event['comments'] = p_ctrl.get_notes(e.user_id, e.data_id)
        if e.view_type in ['article', 'blog']:
            try:
                site_info_Q = s_ctrl.query_by_id_and_type(
                    e.data_id, e.view_type).one()
                site_info = {}
                for column in site_info_Q.__table__.columns:
                    site_info[column.name] = getattr(site_info_Q, column.name)
                event['data'] = site_info
            except:
                None
            event['comments'] = s_ctrl.get_comments(e.user_id, e.view_type,
                                                    e.data_id)

        results.append(event)

    return {'events': results}
def get_personal_recs(user_id):
    #filter by to user id
    recs = session.query(Personal_Rec).filter(Personal_Rec.to_user_id == user_id).all()
    results = []
    for r in recs:
        rec = {'id': r.id}
        #replace from_user_id with full user object
        rec['product'] = p_ctrl.get_product_as_dictionary(r.product_id)
        #replace product_id with full product
        rec['from_user'] = u_ctrl.get_user_as_dictionary(r.from_user_id)
        results.append(rec)
    return results
Esempio n. 4
0
def followers(user_id):
    #ERROR HANDLING
    #if user_id in params does not exists
    if not u_ctrl.userid_exists(user_id):
        return "Invalid user_id", 404

    #GET
    if request.method == 'GET':
        followers = u_ctrl.get_followers(user_id)
        following = u_ctrl.get_followings(user_id)
        response = jsonify({'followers': followers, 'following': following})
        return response, 200

    #POST
    if request.method == 'POST':
        body = request.get_json()
        id_to_follow = body.get('userid')

        #errors
        #make sure following real user
        if not u_ctrl.userid_exists(id_to_follow): #add userid_exists to controller
            return "Could not find user to follow", 404
        #keep user from following self
        if user_id == id_to_follow:
            return "Cannot follow self", 401
        #keep user from following multiple times
        # if u_ctrl.verify_follow(user_id, id_to_follow):
        #     return "Already following", 401
        
        following_id = u_ctrl.add_follow(user_id, id_to_follow)
        if following_id:
            response = jsonify(u_ctrl.get_user_as_dictionary(following_id))
            return response, 201
        else:
            return "Could not follow user", 500

    #DELETE
    if request.method == 'DELETE':
        body = request.get_json()
        id_to_unfollow = body.get('userid')

        #errors
        if not u_ctrl.verify_follow(user_id, id_to_unfollow):
            return "Follower relationship not found", 404

        unfollowed_id = u_ctrl.remove_follow(user_id, id_to_unfollow)
        if unfollowed_id:
            response = jsonify({'user_id': id_to_unfollow})
            return response, 201
        else:
            return "Could not unfollow user", 500
Esempio n. 5
0
def user():
    #Cookie Authentication
    if request.method == 'GET':
        user_id = u_ctrl.verify_session(request)
        #if cookie exists
        if user_id != None:
            #return user data from user id on cookie, and refresh cookie
            response = jsonify(u_ctrl.get_user_as_dictionary(user_id))
            response = u_ctrl.create_session(response, user_id)
            return response, 200
        #otherwise return a 204
        return "No login", 204
    
    #Regular logins
    if request.method == 'POST':
        body = request.get_json()
        #if user does not exist in database
        if not u_ctrl.username_exists(body['username']):
            return 'User does not exist', 404
        #if user has correct password
        if u_ctrl.verify_user(body['username'], body['password']):
            #make response
            user_id = u_ctrl.get_user_id(body['username'])
            response = jsonify(u_ctrl.get_user_as_dictionary(user_id))
            #add session-cookie to response
            response = u_ctrl.create_session(response, user_id)
            #return user object with a 200
            return response, 200
        #return 401 if auth failed
        else:
            return 'Invalid password', 401

    #Destroying sessions on logaou
    if request.method == 'DELETE':
        response = jsonify(response="Session Destroyed")
        response = u_ctrl.destroy_session(response)
        return response, 204
def add_personal_rec(from_user_id, to_user_id, p):
    product_id = p_ctrl.verify_product_by_name_and_brand(p['product_name'], p['brand_name'])
    if not product_id:
        p_ctrl.add_product_to_products(p['product_name'], p['brand_name'], p.get('category',''))
    #check that rec doesn't already exists
    if session.query(Personal_Rec).filter(Personal_Rec.from_user_id == from_user_id, Personal_Rec.to_user_id == to_user_id, Personal_Rec.product_id == product_id).count() > 0:
        return None
    #add recomendation
    rec_id = session.add(Personal_Rec(from_user_id, to_user_id, product_id))
    session.commit()
    #response info
    rec = {'id': rec_id}
    rec['product'] = p_ctrl.get_product_as_dictionary(product_id)
    rec['to_user'] = u_ctrl.get_user_as_dictionary(to_user_id)
    return rec
Esempio n. 7
0
def newUser():
    body = request.get_json()
    #if user is not already in db
    if not u_ctrl.username_exists(body['username']):
        #add user to db
        u_ctrl.make_new_user(body)
        #make response
        user_id = u_ctrl.get_user_id(body['username'])
        response = jsonify(u_ctrl.get_user_as_dictionary(user_id))
        #add session-cookie to response
        response = u_ctrl.create_session(response, user_id)
        #return user object with a 201
        # when creating a new user save some mock recommendations
        r_ctrl.populate_new_user_recommendations(user_id)
        # work_queue.enqueue("find_prob",[user_id])

        return response, 201
    #else return a 302 for Found
    else:
        return 'Username already exists', 302
Esempio n. 8
0
def find_prob(user_id):

    # 1885
    # fetch user from database
    all_prod_likes_file = open('../data/number_all_prod_likes.json', 'r')
    all_prod_likes = json.loads(all_prod_likes_file.read())
    all_prod_likes_file.close()

    all_users_file = open('../data/number_all_user_reviews.json', 'r')
    all_users = json.loads(all_users_file.read())
    all_users_file.close()
    counter = 0

    # ******** fetch user info from database *********
    from db_controller import user_controller as u_ctrl
    user_info = u_ctrl.get_user_as_dictionary(user_id)

    from db_controller import product_controller as p_ctrl
    products = p_ctrl.get_products_by_user_id(user_id)

    # age processing
    if user_info['birthday'] != '':
        birthday = user_info['birthday']
        from datetime import date
        age = int(date.today().year) - int(birthday[0:4])
    else:
        age = None

    current_user = {
        'age': age,
        'location': user_info['location'],
        'skin_tone': user_info['skin_tone'],
        'reviews': []
    }
    # 'reviews':[{'rating':1,'productID':'sephorid'}]
    # ********* built up current user from db fetch **************
    for product in products:
        current_user['reviews'].append({
            'rating': product['product_rating'],
            'productID': product['sephora_id']
        })

    # ******** fetch products ids to check against from file **********
    productIDs = []
    for prod in all_prod_likes:
        counter += 1
        productIDs.append(prod)
        if counter > 1100:
            break
        # if counter > 11004:
        #   break
        # if counter > productNum:

    # keep store here
    res = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
    storage = {}
    # iterate over specified prodicts and return probability values
    for productID in productIDs:
        prod_like_ref = all_prod_likes[productID]
        user_prod_likes = prod_like_ref['L']
        user_prod_dislikes = prod_like_ref['D']

        # user:simIndex
        storage_like_simIndex = {}
        storage_dislike_simIndex = {}
        for name in user_prod_likes:
            # name = str(name)
            b = str(name)
            user = all_users[b]
            index = compoundSimilarityIndex(current_user, user)
            storage_like_simIndex[b] = index

        for name in user_prod_dislikes:
            # name = str[name]python3
            b = str(name)
            user = all_users[b]
            index = compoundSimilarityIndex(current_user, user)
            storage_dislike_simIndex[b] = index

        probability = prob_user_likes_product(productID, storage_like_simIndex,
                                              storage_dislike_simIndex)

        # select maximum values algo
        nextTupl = False
        for index, tupl in enumerate(res):
            # cascade change
            if nextTupl != False:
                temp = res[index]
                res[index] = nextTupl
                nextTupl = temp
            elif probability > tupl[0]:
                nextTupl = res[index]
                res[index] = (probability, productID)

        storage[productID] = probability

    #return top 5 in a tuple
    # print(res)
    # unpack and push to db
    r_ctrl.remove_recommendation(user_id)
    # remove all recommendations from db
    for index, tupl in enumerate(res):
        rank = index + 1
        sephora_product_id = tupl[1]
        # save to database
        # make sure this saves the other id, not the sephora id
        product_id = p_ctrl.get_product_id_by_sephora_product_id(
            sephora_product_id)
        # product = p_ctrl.get_product_as_dictionary(product_id)
        res = r_ctrl.add_recommendation(user_id, product_id, rank)


# print(productIDs)
# start = time.clock()
# probs  = find_prob(productIDs,current_user)
# print(probs)
# end = time.clock()
# interval = end - start
# print(interval)
# print(probs[1])

# get rid of anons

# print similarityIndex(sampleUser0,sampleUser1)
# print similarityIndex(sampleUser0,sampleUser3)

# diff is high
# shift info to a mongodb
# make async worker go off and fetch stuff
# make other cool visualizations with data
# a graph of products

# make new file of usernames removed go through motions and push that up
# with rec engine
Esempio n. 9
0
def find_prob(user_id):

    # 1885                                                                                                                                                                      
    # fetch user from database                                                                                                                                                                                                      
    all_prod_likes_file = open('../data/number_all_prod_likes.json','r')
    all_prod_likes = json.loads(all_prod_likes_file.read())
    all_prod_likes_file.close()

    all_users_file = open('../data/number_all_user_reviews.json','r')
    all_users = json.loads(all_users_file.read())
    all_users_file.close()
    counter = 0

    # ******** fetch user info from database *********
    from db_controller import user_controller as u_ctrl
    user_info = u_ctrl.get_user_as_dictionary(user_id)

    from db_controller import product_controller as p_ctrl
    products = p_ctrl.get_products_by_user_id(user_id)

    # age processing
    if user_info['birthday'] != '':
        birthday = user_info['birthday']
        from datetime import date
        age = int(date.today().year) - int(birthday[0:4])
    else: 
        age = None

    current_user = {
        'age':age,
        'location':user_info['location'],
        'skin_tone':user_info['skin_tone'],
        'reviews':[]
    }
    # 'reviews':[{'rating':1,'productID':'sephorid'}]
    # ********* built up current user from db fetch **************
    for product in products:
        current_user['reviews'].append({
            'rating':product['product_rating'],
            'productID':product['sephora_id']
            })

    # ******** fetch products ids to check against from file **********
    productIDs = []
    for prod in all_prod_likes:
        counter +=1
        productIDs.append(prod)
        if counter > 1100:
                break
        # if counter > 11004:
        #   break
        # if counter > productNum:

    # keep store here
    res = [(0,0),(0,0),(0,0),(0,0),(0,0)]
    storage={}
    # iterate over specified prodicts and return probability values
    for productID in productIDs:
        prod_like_ref = all_prod_likes[productID]
        user_prod_likes = prod_like_ref['L']
        user_prod_dislikes = prod_like_ref['D']

        # user:simIndex
        storage_like_simIndex = {}
        storage_dislike_simIndex = {}
        for name in user_prod_likes:
            # name = str(name)
            b = str(name)
            user = all_users[b]
            index = compoundSimilarityIndex(current_user,user)
            storage_like_simIndex[b] = index

        for name in user_prod_dislikes:
            # name = str[name]python3
            b = str(name)
            user = all_users[b]
            index = compoundSimilarityIndex(current_user,user)
            storage_dislike_simIndex[b] = index

        probability = prob_user_likes_product(productID,storage_like_simIndex,storage_dislike_simIndex)

        # select maximum values algo
        nextTupl = False
        for index,tupl in enumerate(res):
            # cascade change
            if nextTupl != False:
                temp = res[index] 
                res[index] = nextTupl
                nextTupl = temp
            elif probability>tupl[0]:
                nextTupl = res[index]
                res[index] = (probability,productID)

        storage[productID] = probability

    #return top 5 in a tuple
    # print(res)
    # unpack and push to db
    r_ctrl.remove_recommendation(user_id)
    # remove all recommendations from db
    for index,tupl in enumerate(res):
        rank = index+1
        sephora_product_id = tupl[1]
        # save to database
        # make sure this saves the other id, not the sephora id
        product_id = p_ctrl.get_product_id_by_sephora_product_id(sephora_product_id)
        # product = p_ctrl.get_product_as_dictionary(product_id)
        res = r_ctrl.add_recommendation(user_id, product_id, rank)

# print(productIDs)
# start = time.clock()
# probs  = find_prob(productIDs,current_user)
# print(probs)
# end = time.clock()
# interval = end - start
# print(interval)
# print(probs[1])

# get rid of anons 

# print similarityIndex(sampleUser0,sampleUser1)
# print similarityIndex(sampleUser0,sampleUser3)

# diff is high
# shift info to a mongodb
# make async worker go off and fetch stuff
# make other cool visualizations with data
# a graph of products 

# make new file of usernames removed go through motions and push that up 
# with rec engine
Esempio n. 10
0
def userProfile(user_id):
    if request.method == 'GET':
        user = u_ctrl.get_user_as_dictionary(user_id)
        userProducts = p_ctrl.get_products_by_user_id(user_id)
        response = jsonify({'user': user, 'userProducts': userProducts})
        return response, 200