Ejemplo n.º 1
0
 def get(self, request):
     """return all upcoming matches. Matches need to start later than now"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"CSGO Upcoming Matches")
         upcoming_matches = Match.objects.filter(
             date__range=(datetime.now(), datetime.now() +
                          timedelta(days=15))).order_by("date")
         upcoming_matches = MatchSerializer(upcoming_matches,
                                            context={
                                                'request': request
                                            },
                                            many=True).data
         for match in upcoming_matches:
             match.update({
                 "nnPickedTeam":
                 match["Team_1"]["name"]
                 if match["team_1_confidence"] >= match["team_2_confidence"]
                 else match["Team_2"]["name"]
             })
             match.update({
                 "svmPickedTeam":
                 match["Team_1"]["name"] if float(match["prediction_svm"])
                 == 0 else match["Team_2"]["name"]
             })
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'upcoming_matches': upcoming_matches
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Ejemplo n.º 2
0
 def get(self, request):
     """return json of stats that the model produces"""
     check, json_message, response_status = check_authorization(request)
     if check:
         result_list = []
         # multi threading is about 4 times faster than single threaded
         threads = [None] * 9
         results = [None] * 54
         threads_all = [None] * 9
         results_all = [None] * 18
         index_threads = 0
         index_results = 0
         index_threads_all = 0
         index_results_all = 0
         for odd in np.arange(1, 1.9, 0.1):
             odd = round(odd, 2)
             threads[index_threads] = Thread(
                 target=self.get_query_dict_groups,
                 args=(odd, results, index_results))
             threads[index_threads].start()
             index_threads += 1
             index_results += 6
             threads_all[index_threads_all] = Thread(
                 target=self.get_query_dict_all,
                 args=(odd, results_all, index_results_all))
             threads_all[index_threads_all].start()
             index_threads_all += 1
             index_results_all += 2
         for i in range(len(threads)):
             threads[i].join()
         for i in range(len(threads_all)):
             threads_all[i].join()
         results = results + results_all
         if None not in results:
             results = sorted(results, key=lambda k: k["odds"])
         return Response(
             {
                 'message': {
                     "message": "fine",
                     "messageType": "success"
                 },
                 'stats': results
             },
             status=response_status)
     else:
         return Response(json_message, status=response_status)
Ejemplo n.º 3
0
 def get(self, request):
     """return the result of the matches"""
     check, json_message, response_status = check_authorization(request)
     if check:
         with connection.cursor() as cursor:
             cursor.execute(
                 f"select m.Team_1_id, m.Team_2_id, DATE(m.date) as date , m.team_1_win, m.team_2_win, "
                 f"m.odds_team_1, m.odds_team_2, m.team_1_confidence, m.team_2_confidence, m.prediction_svm, "
                 f"m.name as Team1, t.name as Team2, m.mode, "
                 f"CASE m.team_1_confidence >= m.team_2_confidence WHEN TRUE THEN m.name ELSE t.name END AS nnPickedTeam, "
                 f"CASE m.prediction_svm = 0 WHEN TRUE THEN m.name ELSE t.name END AS svmPickedTeam, "
                 f"CASE m.team_1_win = 1 WHEN TRUE THEN m.name ELSE t.name END AS winningTeam "
                 f"FROM (SELECT name, id FROM csgo_api_team) as t INNER JOIN ("
                 f"select m.Team_1_id, m.Team_2_id, m.date, m.team_1_win, m.team_2_win, "
                 f"m.odds_team_1, m.odds_team_2, m.team_1_confidence, m.team_2_confidence, m.prediction_svm, t.name, m.mode "
                 f"FROM (SELECT name, id FROM csgo_api_team) as t INNER JOIN ("
                 f"select m.Team_1_id, m.Team_2_id, m.date, mr.team_1_win, mr.team_2_win, "
                 f"m.odds_team_1, m.odds_team_2, m.team_1_confidence, m.team_2_confidence, m.prediction_svm, m.mode "
                 f"From csgo_api_matchResult as mr "
                 f"INNER JOIN csgo_api_match as m "
                 f"ON mr.Team_1_id = m.Team_1_id AND mr.Team_2_id = m.Team_2_id AND m.date = mr.date"
                 f") as m "
                 f"ON t.id = m.Team_1_id"
                 f") as m "
                 f"ON t.id = m.Team_2_id")
             columns = [col[0] for col in cursor.description]
             res = [dict(zip(columns, row)) for row in cursor.fetchall()]
         return Response(
             {
                 'message': {
                     "message": "fine",
                     "messageType": "success"
                 },
                 'matchResult': res
             },
             status=response_status)
     else:
         return Response(json_message, status=response_status)
Ejemplo n.º 4
0
 def get(self, request):
     """return all teams"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"Here are the teams")
         teams = Team.objects.all().order_by("end_date")
         team_set = list({team.name: team for team in teams}.values())
         team_set.sort(key=lambda x: x.name)
         teams = TeamsPredictionSerializer(team_set,
                                           context={
                                               'request': request
                                           },
                                           many=True).data
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'teams': teams
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Ejemplo n.º 5
0
 def get(self, request, id):
     """return the team given by an id"""
     check, json_message, response_status = check_authorization(request)
     if check:
         message = Message("success", f"Here is the Team")
         team = Team.objects.filter(id=id)
         if not team.exists():
             message = Message("error", f"No team found")
             json_rep = json.dumps({'message': message.repr_json()},
                                   cls=ComplexEncoder)
             return Response(json_rep, status=response_status)
         team = team.first()
         team = TeamSerializer(team, context={'request': request}).data
         json_rep = json.dumps(
             {
                 'message': message.repr_json(),
                 'team': team
             },
             cls=ComplexEncoder)
         json_rep = json.loads(json_rep)
         return Response(json_rep, status=response_status)
     else:
         return Response(json_message, status=response_status)
Ejemplo n.º 6
0
 def get(self, request):
     """checks if the user sent has the right permissions to get the data"""
     _, json_message, response_status = check_authorization(request)
     return Response(json_message, status=response_status)
Ejemplo n.º 7
0
    def post(self, request):
        """make a prediction on two given teams"""
        check, json_message, response_status = check_authorization(request)
        if check:
            data = json.loads(request.body or "{}")
            # check if the teams are correct
            check_teams, response = self.check_teams(data)
            if not check_teams:
                return response
            # check if the players are correct
            check_player_team_1, response = self.check_players_in_team(
                data, "team_1")
            if not check_player_team_1:
                return response
            check_player_team_2, response = self.check_players_in_team(
                data, "team_1")
            if not check_player_team_2:
                return response
            # check if a single player is correct
            check_players, response = self.check_players(data)
            if not check_players:
                return response
            # check if the values are correct
            validate_data, response = self.validate_data(data)
            if not validate_data:
                return response

            message = Message("success", f"Prediction")
            # create a prediction array and make a prediction
            prediction_array = np.array(
                [[data["team_1"]["winning_percentage"]]])
            prediction_array = np.concatenate(
                (prediction_array,
                 self.get_team_player_array(
                     data["team_1"]["Player_1"], data["team_1"]["Player_2"],
                     data["team_1"]["Player_3"], data["team_1"]["Player_4"],
                     data["team_1"]["Player_5"])),
                axis=1)
            prediction_array = np.concatenate(
                (prediction_array,
                 np.array([[data["team_2"]["winning_percentage"]]])),
                axis=1)
            prediction_array = np.concatenate(
                (prediction_array,
                 self.get_team_player_array(
                     data["team_2"]["Player_1"], data["team_2"]["Player_2"],
                     data["team_2"]["Player_3"], data["team_2"]["Player_4"],
                     data["team_2"]["Player_5"])),
                axis=1)
            # if data["mode"] == "BO1":
            #     prediction_model = settings.PREDICTION_MODEL_ALL_WINS
            #     prediction_model_svm = settings.PREDICTION_MODEL_SVM_ALL_WINS
            # else:
            #     prediction_model = settings.PREDICTION_MODEL_BO3_WINS
            #     prediction_model_svm = settings.PREDICTION_MODEL_SVM_BO3_WINS
            # get the right model
            prediction_model = settings.PREDICTION_MODEL_ALL_WINS
            prediction_model_svm = settings.PREDICTION_MODEL_SVM_ALL_WINS

            prediction_svm = prediction_model_svm.predict(prediction_array)
            team_2_confidence = round(
                prediction_model.predict(prediction_array)[0][0], 4)
            team_1_confidence = round(1 - team_2_confidence, 4)
            team_1_confidence = team_1_confidence.item()
            team_2_confidence = team_2_confidence.item()
            team_2_confidence = round(team_2_confidence, 4)
            team_1_confidence = round(team_1_confidence, 4)
            json_rep = json.dumps(
                {
                    'message': message.repr_json(),
                    'prediction': {
                        "team_1_confidence": team_1_confidence,
                        "team_2_confidence": team_2_confidence,
                        "prediction_svm": prediction_svm[0]
                    }
                },
                cls=ComplexEncoder)
            json_rep = json.loads(json_rep)
            return Response(json_rep, status=response_status)
        else:
            return Response(json_message, status=response_status)