def getFavoriteQuestions(user): status, message = False, "Something went wrong" # Get the id of the current user currentUserId = ObjectId(user["_id"]) # Parameters receivedId = request.args.get('id') page = int(request.args.get('page')) if request.args.get( 'page') is not None else 1 results = [] # Get the user model currentUserModel = User({"_id": currentUserId}) currentUser = currentUserModel.data() # Get the wait list curFavoriteQuestions = currentUser.get('favoriteQuestions') curFavoriteQuestions = list( curFavoriteQuestions) if curFavoriteQuestions else [] results = Question.find({"_id": { "$in": curFavoriteQuestions }}, pageNumber=page) status = True message = "Favorite Questions of the user have been obtained" # Response return jsonify({ "success": status, "message": message, "result": results }), 200
def getQuestions(user): # Get the request and validate it requestData = request.get_json() validation = validateFilterQuery(requestData) # Parameters page = int(request.args.get('page')) if request.args.get( 'page') is not None else 1 if validation['success'] is False: return jsonify(validation) # Creating the filter query filterData, message = createFilterQuery(requestData) if filterData: queryDict, sortingAttr, sortOrder = filterData # Sending the query... results = Question.find(queryDict, sortingAttr, sortOrder, page) # Return the response return jsonify({ 'success': True, "questions": results, "message": message }), 200 # Return the response return jsonify({'success': False, "message": message}), 200
def getMostViewedQuestions(user): # Parameters page = int(request.args.get('page')) if request.args.get( 'page') is not None else 1 threshold = int(request.args.get('threshold')) if request.args.get( 'threshold') is not None else 0 sortingAttr = 'viewCount' sortOrder = -1 results = Question.find({"viewCount": { "$gt": threshold }}, sortingAttr, sortOrder, page) # Response return jsonify({"success": True, "result": results}), 200
def getUserQuestions(user): status, message = False, "Something went wrong" # Parameters uploaderId = request.args.get( 'id') # id of the user whose questions are to be shown page = int(request.args.get('page')) if request.args.get( 'page') is not None else 1 # Get the id of the current user currentUserId = ObjectId(user["_id"]) # Get the current user model currentUserModel = User({"_id": currentUserId}) currentUser = currentUserModel.data() # Get the friend list of the current user currentUserFriends = currentUser.get('friends') currentUserFriends = list(currentUserFriends) if currentUserFriends else [] results = [] # Ensure that the other user (uploader) is a friend of ours if ObjectId(uploaderId) in currentUserFriends or str( currentUserId) == uploaderId: # Get the questions results = Question.find({"userId": uploaderId}, pageNumber=page) status, message = True, "Questions are retrieved successfully" else: status, message = False, "To be able to view the questions uploaded by that user, you must be friends" # Response return jsonify({ "success": status, "message": message, "result": results }), 200
def getSimilarQuestions(user): requestData = request.get_json() validation = validateQuestion(requestData) # Invalid if validation['success'] is False: return jsonify(validation) # -- Parameters -- # Page page = int(request.args.get('page')) if request.args.get( 'page') is not None else 1 # Extracting question body from the request questionBody = requestData.get("body") # Loading the model and predicting + some processing model = ft.load_model(ALGO_MODEL_PATH) result = model.predict(questionBody.replace('\n', ' ')) label, reliabilty = result label = label[0] if len(label) > 0 else None label = label.replace('__label__', '').replace('-', ' ') reliabilty = round(float(reliabilty[0]), 3) # Generating the query query = CustomQueryGenerator() query.addElemMatchFields1('labels', {"stringsToMatch": [label]}) queryStatus, queryDict = query.getCompleteQuery() # Query check if not queryStatus: # Return response return jsonify({'success': False, 'message': "Query is not valid"}) # Filtering filtering = requestData.get("filter") sortingAttr, sortOrder = None, None if filtering: # Validating the filter Query data validation = validateFilterQuery(filtering) if validation['success'] is False: return jsonify(validation) # Filtering process filterData, message = createFilterQuery(filtering) if not filterData: # Failed return jsonify({'success': False, "message": message}) filterDict, sortingAttr, sortOrder = filterData queryDict = CustomQueryGenerator.appendTwoQueries( queryDict, filterDict) # Requesting the query results = Question.find(queryDict, sortingAttr=sortingAttr, sortOrder=sortOrder, pageNumber=page, type=QuestionType.ALGO) resultsWithRates = deepcopy(results) # Sorting according to confidence level questionBodyVector = model.get_sentence_vector( str(questionBody).replace('\n', ' ')) questionBodyVector = questionBodyVector.reshape( 1, questionBodyVector.shape[0]) for i, result in enumerate(results['data']): bodyVector = model.get_sentence_vector(result['body'].replace( '\n', ' ')) bodyVector = bodyVector.reshape(1, bodyVector.shape[0]) cosSimilarity = cosine_similarity(questionBodyVector, bodyVector)[0, 0] cosSimilarity = round(cosSimilarity, 3) resultsWithRates['data'][i]['confidenceRate'] = str(cosSimilarity) # Adding the confidence rate to the data instances in the list resultsWithRates['data'] = sorted(resultsWithRates['data'], key=lambda x: x['confidenceRate'], reverse=True) # Return response return jsonify({ 'success': True, 'questions': resultsWithRates, 'label': label, 'confidence_rate': reliabilty })