0

First time using Flask. I'm a DS but never touched HTML and I want to create an app that intakes two fields ("flag" and "userId"), then makes a recommendation based on a collaborative filtering algorithm using a matrix of interests between user ids.

My goal is to allow the app to intake these two fields from a userID login form and their stated "flag" so we can provide topic recommendations back to them. Again new at this, but I know the answer has to use a local database from my computer (Pandas for now), and query the matrix for a recommendation via collaborative filtering.

Now I've seen examples of using Json request and posting, but it's unclear how it uses a local dataframe or model: ex. https://scotch.io/bar-talk/processing-incoming-request-data-in-flask

Any advice on the below code is helpful, i'm currently getting a "Internal Service Error " problem

Thanks

import pandas as pd
import numpy as np
import pandas as pd
import numpy as np
import os
import math as m
import sys
from flask import *


app = Flask(__name__)
@app.route('/output-example', methods=['POST', 'GET'])

Here is where I define the function using collaborative diltering, and takes two inputs "flag" and "userId"

def Reccomend():



#pathInputFiles = '\\mypath'
#fileName_employeeProfiles = 'profiles.csv'
#fileName_distMatrix = 'distanceMatrix.csv'

    employeeProfiles = pd.read_csv('employeeProfiles.csv',
                                   header = 0, index_col = 0)

    distMatrix = pd.read_csv('userDistanceMatrix.csv',
                             header = 0, index_col = 0)

    user_IDs = list(employeeProfiles.index.values)
    n_users = len(user_IDs)

    totalAttributes = len(list(employeeProfiles.columns.values))
    number_employeeAttributes = 3
    number_interestAttributes = 5
    cols_Interest = list(employeeProfiles.columns.values)[number_employeeAttributes:totalAttributes]



    req_data = request.get_json()

    flag = req_data['flag']
    user_ID_new = req_data['user_id']

    #flag = input('Please enter the type of recommendation (peer/interest) : ')

    #user_ID_new = input('Please enter the ID of employee who requires the recommendation : ')

    if flag == 'interest':    
        N = 5
        proximity = distMatrix.loc[user_ID_new,:]
        proximity = proximity.sort_values(ascending = False)
        proximateUsers = list(proximity.index.values)[0:N]
        proximateUsers_Scores = list(distMatrix.loc[user_ID_new,proximateUsers])

        weightedRecommendation = pd.DataFrame(np.zeros(shape = (1,number_interestAttributes)))
        weightedRecommendation.columns = cols_Interest
        weightedRecommendation.index = [user_ID_new]
        for i in list(range(N)):
            weightedRecommendation.loc[user_ID_new,:] = weightedRecommendation.loc[user_ID_new,:] + ((proximateUsers_Scores[i] ** (-1)) * employeeProfiles.loc[proximateUsers[i],cols_Interest])
        weightedRecommendation = weightedRecommendation / N

        recommendedTopic = weightedRecommendation.idxmax(axis = 'columns').loc[user_ID_new]
        return jsonify({'suggestion': list(recommendedTopic)})


    elif flag == 'peer':
        employeeTitle = employeeProfiles.loc[user_ID_new]['StandardTitle']
        employeeLevel = employeeProfiles.loc[user_ID_new]['HierarchyLevel']

        peers = list(employeeProfiles.loc[list(employeeProfiles['StandardTitle'] == employeeTitle) and list(employeeProfiles['HierarchyLevel'] == employeeLevel)].index.values)
        peerInterests = employeeProfiles.loc[peers].loc[:,cols_Interest].sum(axis = 'index') / len(peers)

        return jsonify({'suggestion': list(peerInterests.idmax())})

       # print('Topic ID = ', peerInterests.idxmax(), 'is recommended for user_ID = ', user_ID_new)

    else:

        return'''No Suggestion'''
        #print('Error! Flag incorrectly set... Aborting')
        sys.exit()

This is where I wrap up the app

if __name__ == '__main__':
    app.run(port = 8080)

When I go to the site, I end up getting the following error:

Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Peachazoid
  • 57
  • 1
  • 8

1 Answers1

0

Activate debug mode so you can see specific error in the browser that caused Internal Server Error:

if __name__ == '__main__':

   # debug mode is on 
   app.debug = True    
   app.run(port = 8080)

Also in the terminal, you should be able to see traceback that has more info about the error including call chain, file name and line number. Here is an example:

Traceback (most recent call last):
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/user/virtual_eng_3.5.3/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/user/Projects/aq/untitled/run.py", line 39, in Reccomend
    flag = req_data['flag']
TypeError: 'NoneType' object is not subscriptable
Alex
  • 2,074
  • 1
  • 15
  • 14