-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·2062 lines (1737 loc) · 84.6 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, Blueprint, flash, g, redirect, render_template, request, session, url_for
import werkzeug
#from flask_session.__init__ import Session
## GETTING DATE AND TIME
from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
this_year = date.today().strftime('%Y')
current_year = '2021'
from time import sleep
import cpl_main
import numpy as np
import os
import pandas as pd
import re
canpl = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
canpl.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
# get all player information and store it in one dataframe
# create a new column to allow better filtering by year
player_info_19 = pd.read_csv(f'datasets/2019/league/2019-player-info.csv')
player_info_19['year'] = '2019'
player_info_20 = pd.read_csv(f'datasets/2020/league/2020-player-info.csv')
player_info_20['year'] = '2020'
player_info_21 = pd.read_csv(f'datasets/2021/league/2021-player-info.csv')
player_info_21['year'] = '2021'
player_info = pd.concat([ player_info_19, player_info_20, player_info_21 ])
# get all player names and store these in one dataframe
# create a dictionary for better retrieval of the names
player_names_df = pd.concat([ player_info_19[['name','display']] , player_info_20[['name','display']], player_info_21[['name','display']] ])
player_names_df = player_names_df.sort_values(by='name')
player_names_df = player_names_df.drop_duplicates()
player_names = {}
for c,r in player_names_df.iterrows():
player_names[r['name']] = r['display']
player_names[r['display']] = r['display']
ccd_names = {'Atlético Ottawa' : 'Atlético Ottawa',
'Cavalry' : 'Cavalry FC',
'Edmonton' : 'FC Edmonton',
'Forge' : 'Forge FC',
'HFX Wanderers' : 'HFX Wanderers FC',
'Pacific' : 'Pacific FC',
'Valour' : 'Valour FC',
'York United' : 'York United FC',
'York United' : 'York9 FC','York9' : 'York9 FC'}
team_names = {'Atlético Ottawa' : 'ato',
'Cavalry FC' : 'cav','Cavalry' : 'cav',
'FC Edmonton' : 'fce','Edmonton' : 'fce',
'Forge FC' : 'for','Forge' : 'for',
'HFX Wanderers FC' : 'hfx','HFX Wanderers' : 'hfx',
'Pacific FC' : 'pac','Pacific' : 'pac',
'Valour FC' : 'val','Valour' : 'val',
'York United FC' : 'yor','York United' : 'yor',
'York9 FC' : 'y9','York9' : 'y9'}
team_colour = {'Atlético Ottawa' : '#fff',
'Cavalry FC' : '#fff',
'FC Edmonton' : '#fff',
'Forge FC' : '#fff',
'HFX Wanderers FC' : '#052049',
'Pacific FC' : '#fff',
'Valour FC' : '#fff',
'York United FC' : '#003b5c',
'York9 FC' : '#003b5c'}
col_check = {'overall':'O',
'Aerials':'air',
'BgChncFace':'BgChF',
'ChncOpnPl':'Ch-c',
'CleanSheet':'CS',
'Clrnce':'Clr',
'DefTouch':'defTch',
'Disposs':'dis',
'DuelLs':'DlL',
'DuelsW%':'DlW',
'ExpA':'xA',
'ExpG':'xG',
'ExpGAg':'xGc',
'FlComA3':'FlA3',
'FlSufM3':'Flsuf',
'Goal':'G',
'GoalCnIBx':'GcBox',
'GoalCncd':'Gc',
'Int':'int',
'Off':'shtTrg',
'Pass%':'Pc%',
'PsAtt':'Pat',
'PsCmpA3':'Pata',
'PsCmpM3':'Patm',
'PsOnHfFl':'Pfd',
'PsOpHfFl':'Pfa',
'PsOpHfScs':'Psuca',
'Recovery':'Rec',
'Saves':'SV',
'SucflDuels':'sDl',
'SucflTkls':'sTkl',
'SvClct':'SVc',
'SvDive':'dvS',
'SvHands':'hdS',
'SvInBox':'SVi',
'SvOutBox':'SVo',
'SvPrdSaf':'SVps',
'SvStand':'SVstn',
'TchsA3':'Tcha',
'TchsM3':'Tchm',
'TouchOpBox':'TchoB',
'Touches':'Tch'}
tooltip = {'O':'Overall Score',
'air':'Aerials Duels Won',
'BgChF':'Big Chances Faced',
'Ch-c':'Chances Created from Open Play',
'CS':'Clean Sheets',
'Clr':'Clearances',
'defTch':'Defensive Touches',
'dis':'Dispossed',
'DlL':'Duels Lost',
'DlW':'Successful Duels',
'xA':'Expected Assists',
'xG':'Expected Goals',
'xGc':'Expected Goals Conceded',
'FlA3':'Fouls Committed in the Attacking Third',
'Flsuf':'Fouls Suffered in the Middle Third',
'G':'Goals',
'GcBox':'Goals Condeded from Inside the Box',
'Gc':'Goals Conceded',
'int':'Interceptions',
'shtTrg':'Shots Off Target',
'Pc%':'Pass Completion Percentage',
'Pat':'Passes Attempted',
'Pata':'Passes Completed from the Attacking Third',
'Patm':'Passes Completed from the Middle Third',
'Pfd':'Failed Passed in Own Half',
'Pfa':'Failed Passes in Opponents Half',
'Psuca':'Successful Passes in Opponents Half',
'Rec':'Recoveries',
'SV':'Saves',
'sDl':'Successful Duels',
'sTkl':'Successful Tackles',
'SVc':'Saves Collected',
'dvS':'Diving Saves',
'hdS':'Saves with the Hands',
'SVi':'Saves from shots Inside the Box',
'SVo':'Saves from shots Outside the Boix',
'SVps':'Saves Parried into Safety',
'SVstn':'Saves while Standing',
'Tcha':'Touches in the Attacking Third',
'Tchm':'Touches in the Middle Third',
'TchoB':'Touches in the Opponents Box',
'Tch':'Touches',
'Min':'Minutes Played',}
contributors = {
'tam':'Todd McCullough',
'bot':'Match Bot',
'lab':'The Cook Book',
}
geegle = ['#000000','#ffffff','#ffd700','#ff00ff','#4a86e8','#0000ff','#9900ff','#ff00ff']
def new_col(data):#,chart=''
for col in data.columns:
try:
data[col_check[col]] = data[col]
if col_check[col]:
data.pop(col)
except:
pass
for col in data.columns:
try:
if col in ['display','number']:
temp = data.pop(col)
data[col] = temp
except:
pass
return data
def convert_num_str(num):
num = str(num*100)
return num[0:4]
def get_year():
'''try:
session['year'] = request.form['year']
return session.get('year'), ''
except KeyError as error:
session['year'] = '2020'
return session.get('year'), error # if "year" hasn't been set yet, return None'''
error = None
if request.method == 'POST':
try:
print('REQUESTING YEAR: ')
print(request.form['year'])
return request.form['year'], error
except Exception as error:
print(error)
return '2021' , error
else:
return '2021' , error
def load_main_files(year):
results = pd.read_csv(f'datasets/{year}/league/{year}-results.csv')
try:
week = results[results['hr'] == 'E']['w'].head(1).values[0]
schedule = results[results['w'] == week].copy()
schedule = schedule.fillna(0)
except:
week = results['w'].tail(1).values[0]
schedule = results[results['w'] == week].copy()
stats = pd.read_csv(f'datasets/{year}/playerstats/{year}-stats.csv')
stats_seed = pd.read_csv(f'datasets/{year}/playerstats/{year}-stats-seed.csv')
team_ref = pd.read_csv('datasets/teams.csv')
team_ref = team_ref[team_ref['year'] == int(year)]
player_info = pd.read_csv(f'datasets/{year}/league/{year}-player-info.csv')
results_old = results[results['hr'] != 'E'].copy()
results_diff = pd.concat([results, results_old]).drop_duplicates()
if results_diff.empty:
results_diff = results_old.tail(1)
colours = team_ref['colour']
results_brief = cpl_main.get_results_brief(results,year)
return results, team_ref, player_info, results_old, results_diff, schedule, results_brief
def check_dataframe(data,file,column,year):
## check to see if there is stats available for the season
if data.at[0,column] == 'tbd':
last_year = str(int(year)-1)
data = pd.read_csv(f'datasets/{last_year}/playerstats/{last_year}-{file}.csv')
if data.at[0,column] == 'tbd':
data
return data
def load_player_files(year,check=1):
# get all rated player information based on position and calculate and overall score for the individual player
rated_assists = pd.read_csv(f'datasets/{year}/playerstats/{year}-assists.csv')
rated_assists = check_dataframe(rated_assists,'assists','name',year)
rated_goalscorers = pd.read_csv(f'datasets/{year}/playerstats/{year}-goalscorers.csv')
rated_goalscorers = check_dataframe(rated_goalscorers,'goalscorers','name',year)
rated_offenders = pd.read_csv(f'datasets/{year}/playerstats/{year}-discipline.csv')
stats = {'goals' : rated_goalscorers['Goal'].sum(),'assists' : rated_assists['Ast'].sum(),'yellow' : rated_offenders['Yellow'].sum(),'red' : rated_offenders['Red'].sum()}
if check == 0:
return stats
rated_forwards = pd.read_csv(f'datasets/{year}/playerstats/{year}-forwards.csv')
rated_forwards = check_dataframe(rated_forwards,'forwards','name',year)
rated_midfielders = pd.read_csv(f'datasets/{year}/playerstats/{year}-midfielders.csv')
rated_midfielders = check_dataframe(rated_midfielders,'midfielders','name',year)
rated_defenders = pd.read_csv(f'datasets/{year}/playerstats/{year}-defenders.csv')
rated_defenders = check_dataframe(rated_defenders,'defenders','name',year)
rated_keepers = pd.read_csv(f'datasets/{year}/playerstats/{year}-keepers.csv')
rated_keepers = check_dataframe(rated_keepers,'keepers','name',year)
return rated_forwards, rated_midfielders, rated_defenders, rated_keepers, rated_offenders, rated_goalscorers, rated_assists, stats
# get current day and set time variables
month, day, weekday = cpl_main.get_weekday()
games_played = {1:28,2:7}
# set the year - which will change based on user choice
year = '2021'
error = ''
@canpl.context_processor
def inject_user():
return dict(today = today, day = day, weekday = weekday, month = month, theme = 'mono', current_year = current_year, error = error)
@canpl.route('/setsession')
def setsession():
session['Username'] = 'Admin'
return f"The session has been Set"
@canpl.route('/getsession')
def getsession():
if 'Username' in session:
Username = session['Username']
return f"Welcome {Username}"
else:
return "Welcome Anonymous"
@canpl.route('/popsession')
def popsession():
session.pop('Username',None)
return "Session Deleted"
@canpl.route('/', methods=['GET','POST'])
def index():
na = 'TBD'
session['year'] = '2021'
year, error = get_year()
results, team_ref, player_info, results_old, results_diff, schedule, results_brief = load_main_files(year)
stats = load_player_files(year,check=0)
championship = pd.read_csv(f'datasets/{year}/league/{year}-championship.csv')
playoffs = pd.read_csv(f'datasets/{year}/league/{year}-playoffs.csv')
standings = pd.read_csv(f'datasets/{year}/league/{year}-regular-standings.csv')
standings_old = pd.read_csv(f'datasets/{year}/league/{year}-regular-standings-prev.csv')
rankings = pd.read_csv(f'datasets/{year}/league/{year}-power_rankings.csv')
rankings = rankings.sort_values(by='rank')
if championship.at[0,'team'] == 'TBD':
top_team = standings.iloc[0]['team']
top_team_info = team_ref[team_ref['team'].str.contains(top_team)]
first_colour = top_team_info.iloc[0]['colour']
first_crest = top_team_info.iloc[0]['crest']
top_mover = rankings.iloc[0]['team']
top_crest = team_ref[team_ref['team'].str.contains(top_mover)]
top_crest = top_crest.iloc[0]['crest']
top_dropper = rankings.iloc[-1]['team']
bot_crest = team_ref[team_ref['team'].str.contains(top_dropper)]
bot_crest = bot_crest.iloc[0]['crest']
if standings.at[0,'matches'] == 0:
headline = f'{year} Season Starts June 26th'
else:
headline = f'{year} Season'
else:
top_team = championship.iloc[0]['team']
top_team_info = team_ref[team_ref['team'].str.contains(top_team)]
first_colour = top_team_info.iloc[0]['colour']
first_crest = top_team_info.iloc[0]['crest']
top_mover = standings.iloc[0]['team']
top_crest = team_ref[team_ref['team'].str.contains(top_mover)]
top_crest = top_crest.iloc[0]['crest']
if year == '2019':
top_dropper = playoffs.iloc[-1]['team']
else:
top_dropper = standings.iloc[-1]['team']
bot_crest = team_ref[team_ref['team'].str.contains(top_dropper)]
bot_crest = bot_crest.iloc[0]['crest']
if championship.at[0,'matches'] == 0:
headline = f'{year} Playoffs'
else:
headline = f'{year} Season Completed'
#game_week, goals, big_win, top_team, low_team, other_team, assists, yellows, reds
game_week, goals, big_win, top_result, low_result, other_result, assists, yellows, reds = cpl_main.get_weeks_results(year,results,standings,stats,team_ref,team_names)
# set the headlines to dynamically change based on what year is being viewed
if year != '2021':
timeframe = 1
results_headline = 'Top Results of the Season'
players_headline = 'Top Players of the Season'
else:
if standings.iloc[0]['matches'] == 0:
timeframe = 0
results_headline = 'Season Yet to Start'
players_headline = f'Top Players of {int(year)-1}'
else:
timeframe = 1
results_headline = 'Top Results of the Week'
players_headline = 'Top Players of the Week'
top_scorer = player_info[player_info['gl'] == 1 ][['name','overall']].copy().reset_index(drop=True)
top_assist = player_info[player_info['al'] == 1 ][['name','overall']].copy().reset_index(drop=True)
top_forward = player_info[player_info['p'] == 4 ][['name','overall']].copy().reset_index(drop=True)
top_midfielder = player_info[player_info['p'] == 3 ][['name','overall']].copy().reset_index(drop=True)
top_defender = player_info[player_info['p'] == 2 ][['name','overall']].copy().reset_index(drop=True)
top_keeper = player_info[player_info['p'] == 1 ][['name','overall']].copy().reset_index(drop=True)
top_offender = player_info[player_info['ol'] == 1 ][['name','overall']].copy().reset_index(drop=True)
if results.iloc[0]['hr'] == 'E':
top_team, top_mover, top_dropper, first_crest, top_crest, bot_crest, first_colour = na, na, na, 'CPL-Crest-White.png', 'oneSoccer_nav.png', 'canNat_icon.png', 'w3-indigo'
suspended = ['none']
return render_template('index.html', year = year, top_mover = top_mover, top_dropper = top_dropper,
goals = goals, assists = assists, yellows = yellows, reds = reds,
big_win = big_win, top_result = top_result, low_result = low_result, other_result = other_result,
top_team = top_team, top_keeper = top_keeper,top_forward = top_forward,
top_midfielder = top_midfielder, top_defender = top_defender,
top_scorer = top_scorer, top_assist = top_assist, top_offender = top_offender, suspended = suspended,
first_crest = first_crest, first_colour = first_colour, top_crest = top_crest, bot_crest = bot_crest,
headline = headline, timeframe = timeframe,results_headline = results_headline, players_headline = players_headline)
@canpl.route('/todate', methods=['GET','POST'])
def todate():
season_tables = {}
for yr in range(2019,int(year)+1):
try:
season_tables[yr] = pd.read_csv(f'datasets/{yr}/league/{yr}-season_totals.csv')
except:
pass
team_ref = pd.read_csv(f'datasets/teams.csv')
def get_crest(data,yr):
data['crest'] = '-'
team_check = team_ref[team_ref['year'] == yr]
for c,r in data.iterrows():
data.at[c,'crest'] = team_check[team_check['team'] == r['team']]['crest'].values[0]
return data
yeartodate_season_total = pd.DataFrame()
for k in season_tables.keys():
yeartodate_season_total = pd.concat([season_tables[k],yeartodate_season_total])
season_tables[k] = season_tables[k].sort_values(by=['points','gd','win'],ascending = False)
season_tables[k] = season_tables[k].reset_index(drop=True)
season_tables[k] = get_crest(season_tables[k],k)
yeartodate_season_total = yeartodate_season_total.groupby('team').sum()
yeartodate_season_total = yeartodate_season_total.reset_index()
yeartodate_season_total = yeartodate_season_total.sort_values(by=['points','gd','win'],ascending = False)
yeartodate_season_total = yeartodate_season_total.reset_index(drop=True)
# clean out old team names
for c,r in yeartodate_season_total.iterrows():
if r['team'] == 'York9 FC':
yeartodate_season_total.at[c,'team'] = 'York United FC'
yeartodate_season_total = get_crest(yeartodate_season_total,int(year))
columns = yeartodate_season_total.columns
return render_template('todate.html',columns = columns,
yeartodate_table = yeartodate_season_total, season_tables = season_tables,
year = this_year,
headline = 'Year to Date')
@canpl.route('/standings', methods=['GET','POST'])
def standings():
year, error = get_year()
standings = pd.read_csv(f'datasets/{year}/league/{year}-regular-standings.csv')
headline = 'Top 10 Goals / Assists for '
if standings.at[0,'matches'] == 0:
check = 1
last_year = str(int(year)-1)
standings = pd.read_csv(f'datasets/{last_year}/league/{last_year}-regular-standings.csv')
championship = pd.read_csv(f'datasets/{last_year}/league/{last_year}-championship.csv')
playoffs = pd.read_csv(f'datasets/{last_year}/league/{last_year}-playoffs.csv')
headline = 'Previous Season Standings for '
year = last_year
else:
championship = pd.read_csv(f'datasets/{year}/league/{year}-championship.csv')
playoffs = pd.read_csv(f'datasets/{year}/league/{year}-playoffs.csv')
headline = 'Standings'
championship = championship.sort_values(by=['points','gd','win'],ascending = False)
championship = championship.reset_index(drop=True)
playoffs = playoffs.sort_values(by=['points','gd','win'],ascending = False)
playoffs = playoffs.reset_index(drop=True)
standings = standings.sort_values(by=['points','gd','win'],ascending = False)
standings = standings.reset_index(drop=True)
team_form_results = pd.read_csv(f'datasets/{year}/league/{year}-team_form.csv')
team_ref = pd.read_csv(f'datasets/teams.csv')
team_ref = team_ref[team_ref['year'] == int(year)]
def get_crest(data,column):
data['crest'] = '-'
for i in range(data.shape[0]):
data.at[i,'crest'] = team_ref[team_ref['team'] == data.at[i,column]]['crest'].values[0]
return data
if championship.at[0,'team'] == 'TBD':
print(f'\n{standings}\n')
standings = get_crest(standings,'team')
team_form_results = get_crest(team_form_results,'index')
columns = standings.columns
return render_template('standings.html',columns = columns,
standings_table = standings,
form_table = team_form_results, year = year,
headline = 'Standings')
else:
championship = get_crest(championship,'team')
playoffs = get_crest(playoffs,'team')
standings = get_crest(standings,'team')
team_form_results = get_crest(team_form_results,'index')
columns = standings.columns
return render_template('standings.html',columns = columns,
championship_table = championship, standings_table = standings, playoffs_table = playoffs,
form_table = team_form_results, year = year,
headline = headline)
@canpl.route('/eleven', methods=['GET','POST'])
def eleven():
year, error = get_year()
best_eleven_t = pd.DataFrame()
for pos in ['keepers','defenders','forwards','midfielders']:
best_eleven_t = pd.concat([pd.read_csv(f'datasets/{year}/playerstats/{year}-{pos}.csv'),best_eleven_t])
best_eleven_t = best_eleven_t.reset_index(drop=True)
player_info = pd.read_csv(f'datasets/{year}/league/{year}-player-info.csv')
headline = 'Best Eleven'
if best_eleven_t.at[0,'name'] == 'tbd':
headline = f'Previous Season Best Eleven of '
best_eleven_t = pd.DataFrame()
last_year = str(int(year)-1)
player_info = pd.read_csv(f'datasets/{last_year}/league/{last_year}-player-info.csv')
for pos in ['keepers','defenders','forwards','midfielders']:
best_eleven_t = pd.concat([pd.read_csv(f'datasets/{last_year}/playerstats/{last_year}-{pos}.csv'),best_eleven_t])
best_eleven_t = best_eleven_t.sort_values(by=['overall'],ascending=False)
best_eleven_t = best_eleven_t.reset_index(drop=True)
best_eleven_t['tp'] = 0
for c,r in best_eleven_t.iterrows():
try:
best_eleven_t.at[c,'tp'] = player_info[player_info['name'] == r['name']]['tp'].values[0]
except:
try:
best_eleven_t.at[c,'tp'] = player_info[player_info['display'] == r['name']]['tp'].values[0]
except:
try:
best_eleven_t.at[c,'tp'] = player_info[player_info['name'].str.contains(r['name'].split(' ')[-1])]['tp'].values[0]
except:
try:
best_eleven_t.at[c,'tp'] = player_info[player_info['display'].str.contains(r['name'].split(' ')[-1])]['tp'].values[0]
except:
print(f"{r['name']} missing info")
best_eleven = pd.DataFrame()
pos_dict= {
1:'Keeper',2:'Right Back',3:'Left Back',4:'Rt Center Back',
5:'Lt Center Back',6:'Defensive Mid',7:'Right Winger',
8:'Box-to-Box Mid',9:'Striker',10:'Playmaker',11:'Left Winger',
}
num_list = [4,1,5,2,6,8,3,7,10,9,11]
team_colour = {'Atlético Ottawa' : 'cpl-ato',
'Cavalry FC' : 'cpl-cfc',
'FC Edmonton' : 'cpl-fce',
'Forge FC' : 'cpl-ffc',
'HFX Wanderers FC' : 'cpl-hfx',
'Pacific FC' : 'cpl-pfc',
'Valour FC' : 'cpl-vfc',
'York United FC' : 'cpl-yor',
'York9 FC' : 'cpl-y9'}
for i in num_list:
try:
name = best_eleven_t[best_eleven_t['tp'] == i].head(1)['name'].values[0]
except:
name = best_eleven_t[best_eleven_t['tp'] == 4].head(2)['name'].values[1]
db = player_info[player_info['name'] == name][['team','image','name','display','number','flag','overall','position','link','tp']].copy().reset_index(drop=True)
db['colour'] = team_colour[db['team'].values[0]]
db['pos#'] = pos_dict[i]
best_eleven = pd.concat([db,best_eleven])
return render_template('eleven.html',
html_table = best_eleven, headline = headline, year = year)
@canpl.route('/power', methods=['GET','POST'])
def power():
year, error = get_year()
print(year)
team_ref = pd.read_csv('datasets/teams.csv')
power = pd.read_csv(f'datasets/{year}/league/{year}-power_rankings.csv')
standings = pd.read_csv(f'datasets/{year}/league/{year}-regular-standings.csv')
if power['move'].max() == 0 and standings.at[0,'matches'] == 0:
print("BROKEN",standings.at[0,'matches'])
year = str(int(year)-1)
team_ref = team_ref[team_ref['year'] == int(year)]
headline = f'Previous Season Power Rankings of '
power = pd.read_csv(f'datasets/{year}/league/{year}-power_rankings.csv')
else:
if year != this_year:
headline = f'Final Power Rankings for '
else:
headline = 'Power Rankings '
team_ref = team_ref[team_ref['year'] == int(year)]
for i in range(power.shape[0]):
power.at[i,'crest'] = team_ref[team_ref['team'] == power.at[i,'team']]['crest'].values[0]
power.at[i,'colour'] = team_ref[team_ref['team'] == power.at[i,'team']]['colour'].values[0]
return render_template('power.html', year = year, html_table = power, headline = headline)
@canpl.route('/versus', methods=['GET','POST'])
def versus():
year = current_year
matches_predictions = pd.read_csv(f'datasets/{year}/league/{year}-match_predictions.csv')
if matches_predictions.empty:
year = str(int(year)-1)
matches_predictions = pd.read_csv(f'datasets/{year}/cpl-{year}-match_predictions.csv')
game_form = pd.read_csv(f'datasets/{year}/league/{year}-game_form.csv')
else:
game_form = pd.read_csv(f'datasets/{year}/league/{year}-game_form.csv')
results, team_ref, player_info, results_old, results_diff, schedule, results_brief = load_main_files(year)
player_info = pd.read_csv(f'datasets/{year}/league/{year}-player-info.csv')
schedule = pd.read_csv(f'datasets/{year}/league/{year}-results.csv')
schedule = schedule[schedule['hr']=='E']
results_old, stats_old = pd.DataFrame(), pd.DataFrame()
for yr in range(2019,int(year)+1):
prev_results = pd.read_csv(f'datasets/{year}/league/{year}-results.csv')
prev_stats = pd.read_csv(f'datasets/{year}/playerstats/{year}-stats.csv')
results_old = pd.concat([prev_results,results_old])
stats_old = pd.concat([prev_stats,stats_old])
team_colours_dict = {}
print(matches_predictions)
team_names = {
'Atlético Ottawa' : 'ato',
'Cavalry FC' : 'cav',
'FC Edmonton' : 'fce',
'Forge FC' : 'for',
'HFX Wanderers FC' : 'hfx',
'Pacific FC' : 'pac',
'Valour FC' : 'val',
'York United FC' : 'yor',
}
try:
request_team_name = request.form['home'][:3]
for long_name,short_name in team_names.items():
if short_name == request_team_name:
q1 = long_name
print(f'retrieved {q1}')
except:
q1 = matches_predictions.iloc[0]['home']
print(f'default {q1}')
# home side
home_team_info = team_ref[team_ref['team'] == q1]
home_colour = home_team_info.iloc[0]['colour']
home_fill = home_team_info.iloc[0]['colour2']
home_text = team_colour[q1]
home_crest = home_team_info.iloc[0]['crest']
game_info = schedule[schedule['home'] == q1]
game = game_info.iloc[0]['game']
# away side
q2 = game_info.iloc[0]['away']
away_team_info = team_ref[team_ref['team'] == q2]
away_colour = away_team_info.iloc[0]['colour']
away_fill = away_team_info.iloc[0]['colour2']
away_text = team_colour[q2]
away_crest = away_team_info.iloc[0]['crest']
home_win = matches_predictions[(matches_predictions['home'] == q1) & (matches_predictions['away'] == q2)]['home_p'].values[0]
draw = matches_predictions[(matches_predictions['home'] == q1) & (matches_predictions['away'] == q2)]['draw_p'].values[0]
away_win = matches_predictions[(matches_predictions['home'] == q1) & (matches_predictions['away'] == q2)]['away_p'].values[0]
home_form = game_form[q1]
away_form = game_form[q2]
home_roster = cpl_main.best_roster(q1, player_info)
away_roster = cpl_main.best_roster(q2, player_info)
home_score = matches_predictions[(matches_predictions['home'] == q1) & (matches_predictions['away'] == q2)]['hs'].values[0]
away_score = matches_predictions[(matches_predictions['home'] == q1) & (matches_predictions['away'] == q2)]['as'].values[0]
# get previous results
results_19 = pd.read_csv(f'datasets/2019/league/2019-results.csv')
results_20 = pd.read_csv(f'datasets/2020/league/2020-results.csv')
if results.empty:
results_todate = pd.concat([results_19,results_20])
else:
results_todate = pd.concat([results_19,results_20,results])
results_todate['home'] = results_todate['home'].apply(lambda x: 'York United FC' if x == 'York9 FC' else x)
results_todate['away'] = results_todate['away'].apply(lambda x: 'York United FC' if x == 'York9 FC' else x)
compare = cpl_main.get_team_comparison(results_todate,q1,q2)
q1_r = cpl_main.get_match_history(compare,q1)
q2_r = cpl_main.get_match_history(compare,q2)
print(q1_r,q2_r)
team1, team2, team3, team4, team5, team6, team7, team8 = cpl_main.get_team_files(schedule,team_ref)
print(team1, team2, team3, team4, team5, team6, team7, team8)
if (home_win < draw) and (away_win < draw):
home_win, away_win = draw, draw
home_win = round(round(home_win,3)*100,3)
away_win = round(round(away_win,3)*100,3)
draw = round(round(draw,3)*100,3)
group1 = team1 + '-' + team2
if team3 == 1:
group2 = 1
group3 = 1
group4 = 1
else:
group2 = team3 + '-' + team4
if team5 == 1:
group3 = 1
group4 = 1
else:
group3 = team5 + '-' + team6
group4 = team7 + '-' + team8
radar = pd.read_csv(f'datasets/{year}/league/{year}-radar.csv')
homet = max(q1.split(' '), key=len)
awayt = max(q2.split(' '), key=len)
home_radar = radar[radar['team'].str.contains(homet)]
home_radar = home_radar.reset_index(drop=True)
away_radar = radar[radar['team'].str.contains(awayt)]
away_radar = away_radar.reset_index(drop=True)
home_sum = home_roster['overall'].sum()
away_sum = away_roster['overall'].sum()
# get the week that the matches will be played and display the value
try:
week = results[results['hr'] == 'E']['w'].head(1).values[0]
except:
week = results['w'].tail(1).values[0]
if results.iloc[-2]['hr'] != 'E':
headline = f'{year} Finals: {q1} vs {q2}'
else:
headline = f'{year} Season: Week {week} Matches:'
return render_template('versus.html',
home_team = q1, home_table = home_roster.head(11), home_win = home_win, home_history = q1_r,
home_crest = home_crest, home_colour = home_colour, home_fill = home_fill, home_radar = home_radar, home_text = home_text,
away_team = q2, away_table = away_roster.head(11), away_win = away_win, away_history = q2_r,
away_crest = away_crest, away_colour = away_colour, away_fill = away_fill, away_radar = away_radar, away_text = away_text,
draw = draw, home_form = home_form, away_form = away_form,
headline = headline, year = year,
home_score = home_score, away_score = away_score,
team1 = team1, team2 = team2, team3 = team3, team4 = team4, team5 = team5, team6 = team6, team7 = team7, team8 = team8,
group1 = group1, group2 = group2, group3 = group3, group4 = group4)
@canpl.route('/teams', methods=['GET','POST'])
def teams():
year, error = get_year()
team_ref = pd.read_csv('datasets/teams.csv')
team_ref = team_ref[team_ref['year'] == int(year)]
columns = team_ref.columns
return render_template('teams.html', year = year, columns = columns, headline = 'Club Information',
html_table = team_ref, roster = roster)
@canpl.route('/charts', methods=['GET','POST'])
def charts():
year, error = get_year()
team_standings = pd.read_csv(f'datasets/{year}/league/{year}-regular-standings.csv')
if team_standings.at[0,'matches'] == 0:
team_standings = pd.read_csv(f'datasets/{int(year)-1}/league/{int(year)-1}-regular-standings.csv')
radar = pd.read_csv(f'datasets/{year}/league/{year}-radar.csv')
team_standings = team_standings.sort_values(by='team')
team_standings['xg'] = round((team_standings['Goal'] / team_standings['matches'])*7,2)
team_standings['xp'] = round(team_standings['points'] / team_standings['matches'],2)
print(team_standings)
team_standings['xt'] = team_standings['xp'] * 7
team_standings['xg'] = team_standings['xg'].astype('int')
team_standings['xt'] = team_standings['xt'].astype('int')
team_standings = team_standings.reset_index(drop=True)
team_ref = pd.read_csv('datasets/teams.csv')
team_ref = team_ref[team_ref['year'] == int(year)]
team_list = sorted([x for x in team_ref['team'].unique()])
### GET TEAM LINE CHARTS
team_dict = {}
team_stats = {}
for team in team_ref['team'].unique():
team_stats[team] = []
team_dict[team] = pd.read_csv(f'datasets/{year}/league/{year}-{team}-line.csv')
team_stats[team].append(team_dict[team].loc[team_dict[team].shape[0]-1]['ExpG'])
team_stats[team].append(team_dict[team].loc[team_dict[team].shape[0]-1]['ExpA'])
team_stats[team].append(round( team_dict[team]['Goal'].sum() / team_dict[team].shape[0],2))
team_dict[team] = team_dict[team][team_dict[team].columns[2:]].T
team_dict[team] = cpl_main.index_reset(team_dict[team]).values.tolist()
columns = team_ref.columns
stat_cols = ['ExpG','ExpA','Goal','BgChnc','Chance','CleanSheet','GoalCncd','BgChncFace']
return render_template('charts.html',columns = columns, html_table = team_ref, stat_cols = stat_cols[2:],
team_list = team_list, team_dict = team_dict, team_stats = team_stats, year = year, geegle = geegle,
stats = team_standings, radar = radar, headline = 'Radar & Line Charts')
@canpl.route('/roster', methods=['GET','POST'])
def roster():
year, error = get_year()
try:
team = request.form['team']
except:
team = session['team']
if year != '2021' and team == 'York United FC':
team = 'York9 FC'
if team == 'York9 FC' and year == '2021':
team = 'York United FC'
radar = pd.read_csv(f'datasets/{year}/league/{year}-radar.csv')
radar = radar[radar['team'] == team]
radar = cpl_main.index_reset(radar)
player_info = pd.read_csv(f'datasets/{year}/league/{year}-player-info.csv')
roster = player_info[player_info['team'] == team][['name','image','position','number','flag','overall','link']]
team_ref = pd.read_csv('datasets/teams.csv')
team_ref = team_ref[team_ref['year'] == int(year)]
coach = team_ref[team_ref['team'] == team][['cw','cl','cd','coach','country','image','w','l','d','year']]
roster_team_info = team_ref[team_ref['team'] == team].copy()
roster_team_info = roster_team_info.reset_index(drop=True)
roster_colour = roster_team_info.iloc[0]['colour']
crest = roster_team_info.iloc[0]['crest']
colour1 = roster_team_info.iloc[0]['colour1']
colour2 = roster_team_info.iloc[0]['colour2']
team_stats = []
team_line = pd.read_csv(f'datasets/{year}/league/{year}-{team}-line.csv')
team_stats.append(team_line.loc[team_line.shape[0]-1]['ExpG'])
team_stats.append(team_line.loc[team_line.shape[0]-1]['ExpA'])
team_stats.append(round( team_line['Goal'].sum() / team_line.shape[0],2))
team_line = team_line[team_line.columns[2:]].T
team_line = cpl_main.index_reset(team_line).values.tolist()
session['team'] = team
return render_template('roster.html', year = year, team_name = team, coach = coach, radar = radar, team_line = team_line, team_stats = team_stats,
crest = crest, colour1 = colour1, colour2 = colour2, html_table = roster, team_colour = roster_colour, headline = 'Roster Info')
@canpl.route('/team-compare', methods=['GET','POST'])
def teamcompare():
headline = f'Team Comparison'
variable_list = ['team1','team1YR','team2','team2YR']
default_values = {}
for x in variable_list:
try:
default_values[x] = session[x]
except:
session[x] = ''
default_values[x] = session[x]
print(default_values[x])
## request ALL values in request.form create BLANKS if not received
###############################################################
stat_values = {}
refresh_check = 0
for x in variable_list:
try:
stat_values[x] = request.form[x]
refresh_check+=1
except:
refresh_check=0
print(x,' exception')
stat_values[x] = ''
# Get the selected year for the first choice
if stat_values['team1YR']:
pass
else:
if refresh_check == 0:
stat_values['team1YR'] = '2021'
session['team1YR'] = stat_values['team1YR']
elif default_values['team1YR']:
stat_values['team1YR'] = default_values['team1YR']
else:
stat_values['team1YR'] = '2021'
# Get the selected year for the team 2 choice
if stat_values['team2YR']:
if refresh_check == 0:
stat_values['team2YR'] = '2021'
session['team2YR'] = stat_values['team2YR']
else:
pass
else:
if refresh_check == 0:
stat_values['team2YR'] = '2021'
session['team2YR'] = stat_values['team2YR']
elif default_values['team1YR']:
stat_values['team2YR'] = default_values['team2YR']
else:
stat_values['team2YR'] = '2021'
year1 = stat_values['team1YR']
year2 = stat_values['team2YR']
# ENSURE that if ATO is selected, 2019 is not selected
year_correct = {'Atlético Ottawa':'2020','York United FC':'2021'}
if (default_values['team1'] == 'Atlético Ottawa') & (year1 == '2019'):
year1 = year_correct['Atlético Ottawa']
if (default_values['team2'] == 'Atlético Ottawa') & (year2 == '2019'):
year2 = year_correct['Atlético Ottawa']
if (default_values['team1'] == 'York United FC') & (year1 in ['2019','2020']):
stat_values['team1'] = 'York9 FC'
if (default_values['team2'] == 'York United FC') & (year2 in ['2019','2020']):
stat_values['team2'] = 'York9 FC'
if (default_values['team1'] == 'York9 FC') & (int(year1) > 2020):
stat_values['team1'] = 'York United FC'
if (default_values['team2'] == 'York9 FC') & (int(year2) > 2020):
stat_values['team2'] = 'York United FC'
standings = pd.read_csv(f'datasets/{current_year}/league/{current_year}-regular-standings.csv')
team_ref = pd.read_csv('datasets/teams.csv')
team_ref1 = team_ref[team_ref['year'] == int(year1)].copy()
team_ref1 = team_ref1.reset_index(drop=True)
team_ref2 = team_ref[team_ref['year'] == int(year2)].copy()
team_ref2 = team_ref2.reset_index(drop=True)
team1_select_list = team_ref1.team.unique().tolist()
team2_select_list = team_ref2.team.unique().tolist()
if year1 == '2020':
try:
team1_select_list.remove('York United FC')
except:
pass
if year2 == '2020':
try:
team2_select_list.remove('York United FC')
except:
pass
if year1 == '2019':
try:
team1_select_list.remove('Atlético Ottawa')
except:
pass
if year2 == '2019':
try:
team2_select_list.remove('Atlético Ottawa')
except:
pass
# Get the selected team for the first choice
duplicate = 0
if stat_values['team1']:
if refresh_check == 0:
stat_values['team1'] = standings.at[0,'team']
session['team1'] = stat_values['team1']
else:
pass
else:
if refresh_check == 0:
stat_values['team1'] = standings.at[0,'team']
session['team1'] = stat_values['team1']
elif (default_values['team1'] != '') & (stat_values['team1YR'] != ''):
stat_values['team1'] = default_values['team1']
elif default_values['team1'] == stat_values['team2']:
duplicate = 1
stat_values['team1'] == stat_values['team2']
elif (default_values['team1'] != '') & (stat_values['team2'] != ''):
stat_values['team1'] == default_values['team1']
else:
stat_values['team1'] = team_ref1.at[0,'team']
# Get the selected team for the team 2 choice
if stat_values['team2']:
if duplicate:
stat_values['team2'] = stat_values['team1']
if refresh_check == 0:
stat_values['team2'] = team_ref1.at[1,'team']
session['team2'] = stat_values['team2']
else:
if refresh_check == 0:
stat_values['team2'] = standings.at[1,'team']
session['team2'] = stat_values['team2']
elif (default_values['team2'] != '') & (stat_values['team2YR'] != ''):
stat_values['team2'] = default_values['team2']