PK!worldcup18/__init__.pyPK!d55worldcup18/api_parser.py# - *- coding: utf- 8 - *- from __future__ import print_function, absolute_import, unicode_literals import requests import datetime import pytz from tzlocal import get_localzone from collections import defaultdict from worldcup18.utils import iso_to_datetime, get_nice_date class WorldCupData: def __init__(self): self.raw_data = self.get_worldcup_data() @staticmethod def get_worldcup_data(): url = "https://raw.githubusercontent.com/lsv/fifa-worldcup-2018/master/data.json" response = requests.get(url) data = response.json() return data def get_key_info(self, key_, id_, attr=None): objects = self.raw_data[key_] try: object_dict = [obj for obj in objects if obj["id"] == id_][0] except IndexError: raise ValueError("There is no {} with id: {}".format(key_, id_)) if attr: return object_dict[attr] else: return object_dict def get_team_info(self, id_, attr=None): return self.get_key_info("teams", id_, attr) def get_stadium_info(self, id_, attr=None): return self.get_key_info("stadiums", id_, attr) def all_matches(self): matches = [] for key in ("groups", "knockout"): for stage in self.raw_data[key].keys(): matches.extend(self.raw_data[key][stage]["matches"]) return matches def get_group_matches(self, group): return self.raw_data["groups"][group]["matches"] def get_group_members(self, group): group_matches = self.get_group_matches(group) group_teams = {match["home_team"] for match in group_matches} assert len(group_teams) == 4 return [self.get_team_info(team, "name") for team in group_teams] def calculate_group_table(self, group): table = {team: defaultdict(int) for team in self.get_group_members(group)} matches = self.get_group_matches(group) for match in filter(lambda m: m['finished'] is True, matches): home_team = self.get_team_info(match["home_team"], "name") table[home_team]['played'] += 1 table[home_team]['scored'] += match["home_result"] table[home_team]['conceded'] += match["away_result"] away_team = self.get_team_info(match["away_team"], "name") table[away_team]['played'] += 1 table[away_team]['scored'] += match["away_result"] table[away_team]['conceded'] += match["home_result"] if match["home_result"] > match["away_result"]: table[home_team]['points'] += 3 elif match["home_result"] < match["away_result"]: table[away_team]["points"] += 3 else: table[home_team]['points'] += 1 table[away_team]['points'] += 1 return table def get_nearest_match(self): systimezone = get_localzone() # System non-DST timezone now = pytz.UTC.localize(datetime.datetime.now()) nearest = None for match in self.all_matches(): match_date = iso_to_datetime(match['date']).astimezone(systimezone) time_diff = abs(now - match_date) if not nearest: nearest = (match, time_diff) elif match_date > now and time_diff < nearest[1]: nearest = (match, time_diff) return nearest[0] def match_as_str(self, match): home_team = self.get_team_info(match["home_team"]) away_team = self.get_team_info(match["away_team"]) if match['finished']: return u"Match #{}: {} {} vs {} {}\nResult: {} : {}\nDate: {}".format( match['name'], home_team['emojiString'], home_team['name'], away_team["name"], away_team["emojiString"], match['home_result'], match['away_result'], get_nice_date(match["date"]) ) else: return u"Match #{}: {} {} vs {} {}\nWhen: {}\nWhere: {}".format( match['name'], home_team['emojiString'], home_team['name'], away_team["name"], away_team["emojiString"], get_nice_date(match["date"]), self.get_stadium_info(match["stadium"], "city") ) def group_table_as_str(self, group): table = self.calculate_group_table(group) ret_str = 'GROUP {0: <20} MP GF GA PTS\n'.format(group.upper()) ret_str += '-' * 39 for team, info in sorted(table.items(), key=lambda k: (k[1]['points'], k[1]['scored'] - k[1]['conceded']), reverse=1): ret_str += "\n{0: <26} {1} {2} {3} {4}".format( team, info['played'], info['scored'], info['conceded'], info['points']) return ret_str PK!1133worldcup18/utils.py# - *- coding: utf- 8 - *- from __future__ import absolute_import import dateutil.parser from tzlocal import get_localzone def iso_to_datetime(s): return dateutil.parser.parse(s) def get_nice_date(date): return iso_to_datetime(date).astimezone(get_localzone()).strftime("%A, %d. %B %Y %I:%M%p") PK!MGGworldcup18/worldcup.py#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import sys import click from worldcup18.api_parser import WorldCupData @click.group(invoke_without_command=True) def cli(): """ CLI tool for being up to date with 2018 World Cup """ @cli.command('next', short_help='Show nearest match info') def nearest(): wc_data = WorldCupData() click.secho(wc_data.match_as_str(wc_data.get_nearest_match()), bold=1, fg="blue") @cli.command('groups', short_help='Show group info') @click.argument('group_names', nargs=-1) @click.option('--table/--no-table', default=True, help="Show group table") def groups(group_names, table): """Show info for specific group(s). If groups are not specified shows info for all of them.""" possible_groups = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') def check_args(): for g in group_names: if g.lower() not in possible_groups: click.secho("There is no group {}".format(g.upper(), fg="red", err=True)) sys.exit(1) check_args() if not len(group_names): group_names = possible_groups wc_data = WorldCupData() if table: for g in group_names: group = g.lower() click.secho(wc_data.group_table_as_str(group), fg="green") click.echo() @cli.command('knockout', short_help='Show info about knockout phase') def knockout(): # wc_data = WorldCupData() click.secho("Not supported yet", bold=1, fg="red") @cli.command('stats', short_help='Show info about specific country') @click.option('-c', '--country', help="Select country") @click.option('--table/--no-table', default=False, help="Show group table") def stats(): # wc_data = WorldCupData() click.secho("Not supported yet", bold=1, fg="red") if __name__ == '__main__': cli() PK!HjO;/)4+worldcup18-0.1.0.dist-info/entry_points.txtN+I/N.,()*/II.-1 -`LL..PK!k!L33"worldcup18-0.1.0.dist-info/LICENSEMIT License Copyright (c) 2018 Tadek Teleżyński Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!Hf'VX worldcup18-0.1.0.dist-info/WHEEL A н#Z;/" bFF]xzwK;<*mTֻhVJs)猶j>GbaPn>PK!HZ{#worldcup18-0.1.0.dist-info/METADATAUn6S"h Bsk^BKY5U1v=@}>e;'@6?>7,fyp,hS\*#[Gڢ>m9SU"/3 ڰ lB-޺`е%I+YRcJ4 F2ob9\J\''"Fp7"oxX׈2ј)#kRax?}>gbexDK13M]RrBq +b/OONh>[g1Tp̼*a:enůr*(Huqe!nOOox* ˓CQ5"sX{5L7)F/c/63XЧaN( *xD4QrX. BvOO?Z 3V_?]k(6ڋ*y +Ŋ(=ə6\~.!GdgbKBnnnwwܗTVP`L~o|vrkXe9_~ oS m%JRa %mϷ OgQHo{ȥE.M|}EnWURfsX@GKbx^ʳ\2 GEx A߹8q,+Z R;;5u˴a*`R!t%^AE\;6mPO@S'lm)8Ck~G%1<%Qr xOR] 6A 3UI4mdLLz<̾|E ]oq8YejUW\m5#B PK!H$!worldcup18-0.1.0.dist-info/RECORD}ͻ0~%8 b .AƱa!:$(4il/-R>j*$Xx% ֩/}NZ-\?+mM;w/oT''nJm:?R8i QX^}yf`ϫ3{,gC oQ:Vc3[m4߬;q$IXCĚ }E0g݆f 2^8NNBϼ#i/UلE ;B09A?rf4Iߩ *%: