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.