def test_predict_match_too_short(): with open(os.path.dirname(__file__) + "/data/EUW-4236896092.json", "r") as f: data = json.load(f) try: roleml.predict(data, data["timeline"]) assert False except exceptions.MatchTooShort: assert True except: assert False
def test_predict_match_ARAM(): with open(os.path.dirname(__file__) + "/data/EUW-4458819927.json", "r") as f: data = json.load(f) try: roleml.predict(data, data["timeline"]) assert False except exceptions.IncorrectMap: assert True except: assert False
def test_predict_match_too_short(): with open(os.path.dirname(__file__) + "/data/EUW-4236896092.json", "r") as f: data = json.load(f) match = create_Cass_match(data) try: roleml.predict(match.to_dict(), match.timeline.to_dict(), True) assert False except: assert True
def analyzeMatch(match, summoner): p = match.participants[summoner] roleml.change_role_formatting('full') match.timeline.load() roleml.predict(match.to_dict(), match.timeline.to_dict(), True) roleml.add_cass_predicted_roles(match) role = p.predicted_role # role= p.role.value champ = champList[str(p.champion.id)] return role, champ
async def run(self): empty = False try: while not self.stopped: tasks = await self.get_tasks() if len(tasks) == 0: if not empty: self.logging.info("Found no tasks, Sleeping") empty = True await asyncio.sleep(15) continue empty = False results = [] for task in tasks: try: results.append([ json.dumps( roleml.predict( json.loads(task["details"]), json.loads(task["timeline"]), )), task["match_id"], ]) except (IncorrectMap, MatchTooShort): results.append(["{}", task["match_id"]]) await self.update_db(results) self.logging.info("Predicted %s matches.", len(results)) await asyncio.sleep(5) except Exception as err: traceback.print_tb(err.__traceback__) self.logging.info(err)
def roles(): req_data = request.get_json() getMatch = req_data['match'] getTimeline = req_data['timeline'] match = json.loads(getMatch) timeline = json.loads(getTimeline) prediction = roleml.predict(match, timeline) return prediction
def roleml(self): try: roles = roleml.predict(self._meta.raw_data, self._meta.raw_timeline) except AttributeError as e: raise TypeError( "This method requires timeline data to execute") from e for team in self.teams: for participant in team.participants: participant.timeline.position = roles[participant.id] participant.timeline._meta.data['position'] = roles[ participant.id] return roles
def test_label_riot_api(clean_game_na): roleml.change_role_formatting("rgapi") roles = { 1: { "lane": "BOTTOM", "role": "DUO_SUPPORT" }, 2: { "lane": "JUNGLE", "role": "NONE" }, 3: { "lane": "TOP", "role": "SOLO" }, 4: { "lane": "BOTTOM", "role": "DUO_CARRY" }, 5: { "lane": "MIDDLE", "role": "SOLO" }, 6: { "lane": "TOP", "role": "SOLO" }, 7: { "lane": "BOTTOM", "role": "DUO_CARRY" }, 8: { "lane": "BOTTOM", "role": "DUO_SUPPORT" }, 9: { "lane": "JUNGLE", "role": "NONE" }, 10: { "lane": "MIDDLE", "role": "SOLO" }, } assert roles == roleml.predict(clean_game_na["game"], clean_game_na["game"]["timeline"])
def test_label_full(clean_game_na): roleml.change_role_formatting("full") roles = { 1: "BOTTOM_DUO_SUPPORT", 2: "JUNGLE_NONE", 3: "TOP_SOLO", 4: "BOTTOM_DUO_CARRY", 5: "MIDDLE_SOLO", 6: "TOP_SOLO", 7: "BOTTOM_DUO_CARRY", 8: "BOTTOM_DUO_SUPPORT", 9: "JUNGLE_NONE", 10: "MIDDLE_SOLO", } assert roles == roleml.predict(clean_game_na["game"], clean_game_na["game"]["timeline"])
def test_label_clean(clean_game_na): roleml.change_role_formatting("clean") roles = { 1: "supp", 2: "jungle", 3: "top", 4: "bot", 5: "mid", 6: "top", 7: "bot", 8: "supp", 9: "jungle", 10: "mid", } assert roles == roleml.predict(clean_game_na["game"], clean_game_na["game"]["timeline"])
def test_predict_1(): with open(os.path.dirname(__file__) + "/data/NA-3023745286.json", "r") as f: data = json.load(f) roles = { 1: 'supp', 2: 'jungle', 3: 'top', 4: 'bot', 5: 'mid', 6: 'top', 7: 'bot', 8: 'supp', 9: 'jungle', 10: 'mid' } assert roles == roleml.predict(data, data["timeline"])
def test_predict_2(): with open(os.path.dirname(__file__) + "/data/EUW-3692606327.json", "r") as f: data = json.load(f) roles = { 1: 'supp', 2: 'top', 3: 'mid', 4: 'jungle', 5: 'bot', 6: 'top', 7: 'supp', 8: 'mid', 9: 'jungle', 10: 'bot' } match = create_Cass_match(data) assert roles == roleml.predict(match.to_dict(), match.timeline.to_dict(), True)
def analyze_match_history(self, account_id, match_history): role_list = [] outcome_list = [] payload = {"api_key": self.api_key} for match in match_history["matches"]: match_id = match["gameId"] match_r = requests.get( f"https://na1.api.riotgames.com/lol/match/v4/matches/{match_id}", params=payload) match_j = match_r.json() timeline_r = requests.get( f"https://na1.api.riotgames.com/lol/match/v4/timelines/by-match/{match_id}", params=payload) timeline_j = timeline_r.json() participant_id = self.get_participant_id(account_id, match_j) try: role = roleml.predict(match_j, timeline_j)[participant_id] role_list.append(role) game_outcome = self.get_game_outcome(participant_id, match_j) outcome_list.append(game_outcome) # Match was less than 15 minutes. except: continue return self.get_main_role(role_list), self.get_win_loss(outcome_list)
def get_accs_matches_info(players_matches): match_dto = {} for player in players_matches: match_dto[player] = [] count = 0 for match in players_matches[player]: match_info = riotApi.match.by_id(region, match['gameId']) if (filter_matches(match_info)): match_timeline = riotApi.match.timeline_by_match( region, match['gameId']) match_champ_id = match['champion'] predict_positions = roleml.predict(match_info, match_timeline) participant = match_info_procesing(match_info, match_champ_id) participant['position'] = predict_positions[ participant['participantId']] match_dto[player].append(participant) count += 1 else: continue match_dto[player].append(count) return match_dto
def test_predict_match_too_short(short_game): with pytest.raises(exceptions.MatchTooShort): roleml.predict(short_game["game"], short_game["game"]["timeline"])
def test_recent_game(clean_game_na): with pytest.warns(None) as record: roleml.predict(clean_game_na["game"], clean_game_na["game"]["timeline"]) assert not record
def test_old_game_pro(pro_game, caplog): with caplog.at_level(logging.WARNING): roleml.predict(pro_game["game"], pro_game["game"]["timeline"]) assert caplog.text
def _get_roles(self, match_raw, timeline_raw): # predict the role using api data return roleml.predict(match_raw, timeline_raw)
def write_match(match, timeline): role_index = {'top': 0, 'jgl': 1, 'mid': 2, 'bot': 3, 'sup': 4} try: roles = roleml.predict(match, timeline, True) except: print("game too short: %s" % match['id'], file=sys.stderr) return True match['creation'] = match['creation'].timestamp match['duration'] = match['duration'].seconds for i in match['participants']: i['side'] = i['side'].value for i in match['teams']: i['side'] = i['side'].value for j in i['participants']: j['side'] = j['side'].value m = match match_id = m['id'] game_id = m['id'] blue_ban_ids = m['teams'][0]['bans'] red_ban_ids = m['teams'][1]['bans'] blue_bans = [champs.get(_x, '') for _x in blue_ban_ids] red_bans = [champs.get(_x, '') for _x in red_ban_ids] blue_bans = [_x if _x == '' else _x.name for _x in blue_bans] red_bans = [_x if _x == '' else _x.name for _x in red_bans] match_id = m['id'] version = m['version'] version = ".".join(version.split('.')[:2]) result = 1 if m['teams'][0]['isWinner'] else 0 creation = m['creation'] duration = m['duration'] region = m['region'] load_game(match_id, version, result, creation, duration, region) load_bans(match_id, region, 1, blue_bans[0], blue_bans[1], blue_bans[2], blue_bans[3], blue_bans[4]) load_bans(match_id, region, 0, red_bans[0], red_bans[1], red_bans[2], red_bans[3], red_bans[4]) blue_champs = [0, 0, 0, 0, 0] red_champs = [0, 0, 0, 0, 0] blue_team = [0, 0, 0, 0, 0] red_team = [0, 0, 0, 0, 0] for p, pid in zip(m['participants'], range(1, len(m['participants']) + 1)): name = p['summonerName'] champ_id = p['championId'] k = p['stats']['kills'] d = p['stats']['deaths'] a = p['stats']['assists'] cc = p['stats']['timeCCingOthers'] gold_spent = p['stats']['goldSpent'] damage = p['stats']['totalDamageDealtToChampions'] heal = p['stats']['totalHeal'] tank = p['stats']['totalDamageTaken'] cs10 = round(p['timeline']['creepsPerMinDeltas'].get('0-10', 0), 1) cs20 = round( p['timeline']['creepsPerMinDeltas'].get('0-10', 0) + p['timeline']['creepsPerMinDeltas'].get('10-20', 0), 1) g10 = round(p['timeline']['goldPerMinDeltas'].get('0-10', 0), 1) g20 = round( p['timeline']['goldPerMinDeltas'].get('0-10', 0) + p['timeline']['goldPerMinDeltas'].get('10-20', 0), 1) xp10 = round(p['timeline']['xpPerMinDeltas'].get('0-10', 0), 1) xp20 = round( p['timeline']['xpPerMinDeltas'].get('0-10', 0) + p['timeline']['xpPerMinDeltas'].get('10-20', 0), 1) role = roles[pid][:3].replace('jun', 'jgl') champ = champs[champ_id].name if champ[ 0] not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ': print("Bad champ name") return False is_blue = 1 if p['side'] == 100 else 0 side_res = result if is_blue else 1 - result load_lane_info(match_id, region, role, is_blue, name, champ, side_res) load_stats(match_id, region, role, is_blue, champ, side_res, k, d, a, cc, gold_spent, damage, heal, tank, cs10, cs20, g10, g20, xp10, xp20) if p['side'] == 100: blue_champs[role_index[role]] = champ blue_team[role_index[role]] = name else: red_champs[role_index[role]] = champ red_team[role_index[role]] = name return True
def test_predict_1(clean_game_na): assert clean_game_na["expected_roles"] == roleml.predict( clean_game_na["game"], clean_game_na["game"]["timeline"])
def test_predict_match_too_short(short_game): match = create_cass_match(short_game["game"]) with pytest.raises(roleml.exceptions.MatchTooShort): roleml.predict(match.to_dict(), match.timeline.to_dict(), True)
def test_predict_2(clean_game_euw): match = create_cass_match(clean_game_euw["game"]) assert clean_game_euw["expected_roles"] == roleml.predict(match.to_dict(), match.timeline.to_dict(), True)
def test_predict_match_aram(aram_game): with pytest.raises(exceptions.IncorrectMap): roleml.predict(aram_game["game"], aram_game["game"]["timeline"])
def request_match_data(match_id): URL_match = f'https://{region}.api.riotgames.com/lol/match/v4/matches/{match_id}' URL_timeline = f'https://{region}.api.riotgames.com/lol/match/v4/timelines/by-match/{match_id}' timeline_response = call_api(url=URL_timeline, headers=HEADERS) match_response = call_api(url=URL_match, headers=HEADERS) if not timeline_response or not match_response: return None try: match = match_response.json() timeline = timeline_response.json() accurateRoles = bool(timeline and match['gameDuration'] > 720) ## Flagging if accurate roles are available except KeyError: accurateRoles = False if accurateRoles: participants_roles = roleml.predict(match, timeline) try: participants = match['participants'] # key error teams = match['teams'] team_1 = [] team_2 = [] won = 0 for player in participants: if player['teamId'] == 100: if accurateRoles: team_1.append([ get_champion_from_id(player['championId']), participants_roles[player['participantId']] ]) else: team_1.append([ get_champion_from_id(player['championId']), player['timeline']['lane'] ]) elif player['teamId'] == 200: if accurateRoles: team_2.append([ get_champion_from_id(player['championId']), participants_roles[player['participantId']] ]) else: team_2.append([ get_champion_from_id(player['championId']), player['timeline']['lane'] ]) if (teams[0]["teamId"] == 100): if (teams[0]['win'] == 'Win'): won = 1 else: won = 2 elif (teams[0]["teamId"] == 200): if (teams[0]['win'] == 'Win'): won = 2 else: won = 1 return [team_1, team_2, won] except KeyError: return None
def test_predict_empty_lane_frequency(empty_lane_frequency_game): roleml.predict(empty_lane_frequency_game["game"], empty_lane_frequency_game["game"]["timeline"]) assert True