-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki.py
executable file
·6012 lines (4776 loc) · 202 KB
/
wiki.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
#!/usr/bin/env python
import pytz
from league import League
import api as fpl_api
import plot
from collections import Counter
import mout
from player import Player
from manager import Manager
import json as js
from web import (
html_page,
player_summary_cell_modal,
get_style_from_event_score,
md2html,
get_player_history_table,
get_style_from_minutes_played,
get_style_from_expected_return,
get_style_from_bonus,
)
from squad import Squad
import time
from pprint import pprint
from sys import argv
import mrich
# https://stackoverflow.com/questions/60598837/html-to-image-using-python
from datetime import datetime
timestamp = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
# deployment configuration
DEPLOY_ROOT = "mwinokan.github.io/ToiletFPL"
JSON_PATH = "data_wiki_2425.json" # store the award data in this JSON
TAGLINE = "Home of the RBS Diamond Invitational and Tesco Bean Value Toilet League"
# run options
run_push_changes = False # push changes to github
test = False # only run the 'run_test' function
offline = False # use cached request data
### other options
force_generate_kits = False # force the generation of manager's kits
scrape_kits = False # scrape latest PL team jerseys and exit
fetch_latest = False # pull latest changes from github before running
force_go_graphs = True # force update of Assets graph
# gamestate options (to be automated)
halfway_awards = True # generate half-season / christmas awards
season_awards = False # generate full-season awards
cup_active = False # activate the cup
christmas_gw = 17
if "--push" in argv:
run_push_changes = True
if "--offline" in argv:
offline = True
if "--kits" in argv:
scrape_kits = True
if "--test" in argv:
test = True
# configure the leagues
# 23/24
league_codes = [352961, 241682, 1678697, 352258]
league_icons = ["💎", "🚽", "🧭", "🍝"]
league_shortnames = ["Diamond", "Toilet", "SOLENT", "Dinner"]
league_colours = ["aqua", "dark-grey", "indigo", "dark-grey"]
award_flavourtext = dict(
king="👑 King",
cock="🐓 Cock",
goals="⚽️ Massive Goal FC",
boner="🦴 Boner",
scientist="🧑🔬 Scientist",
smooth_brain="🧠 Smooth Brain",
chair="🪑 Chair",
minutes="👹 Minutes Monster",
asbo="🥊 ASBO",
nerd="🤓 Nerd",
hot_stuff="🥵 Hot Stuff",
soggy_biscuit="🍪 Soggy Biscuit",
innovator="🎓 Innovator",
fortune="🔮 Fortune Teller",
clown="🤡 Clown",
oligarch="🛢 Oligarch",
iceman="🥶 Iceman",
peasant="🏚 Peasant",
glow_up="💡 Glow-Up",
has_been="👨🦳 Has-Been",
kneejerker="🔨 Kneejerker",
rocket="🚀 Rocket",
flushed="🚽 #DownTheToilet",
wc1_best="Best Wildcard 1",
wc1_worst="Worst Wildcard 1",
wc2_best="Best Wildcard 2",
wc2_worst="Worst Wildcard 2",
tc_best="Best Triple Captain",
tc_worst="Worst Triple Captain",
bb_best="Best Bench Boost",
bb_worst="Worst Bench Boost",
fh_best="Best Free Hit",
fh_worst="Worst Free Hit",
zombie="Best Dead Team",
)
award_unittext = dict(
king="points",
cock="points",
goals="goals",
boner="points",
scientist="points",
smooth_brain="points on the bench",
chair="'",
minutes="'",
asbo="cards",
nerd="%",
innovator="%",
rocket="%",
flushed="%",
fortune="points gained",
clown="points lost",
hot_stuff="points overperformed",
soggy_biscuit="points underperformed",
zombie="th place",
)
award_colour = dict(
king="amber",
cock="red",
goals="indigo",
scientist="green",
boner="grey",
smooth_brain="pale-red",
chair="light-blue",
minutes="deep-orange",
asbo="yellow",
fortune="purple",
clown="pink",
nerd="pale-yellow",
innovator="grey",
oligarch="black",
iceman="aqua",
peasant="brown",
glow_up="pale-yellow",
has_been="grey",
kneejerker="deep-orange",
wc1_best="red",
wc1_worst="red",
wc2_best="red",
wc2_worst="red",
tc_best="yellow",
tc_worst="yellow",
bb_best="blue",
bb_worst="blue",
fh_best="green",
fh_worst="green",
hot_stuff="orange",
soggy_biscuit="teal",
rocket="lime",
flushed="brown",
zombie="teal",
)
_league_table_html = {}
brk = "</p><p>"
league_halfway_text = {
352961: f"PLACEHOLDER DIAMOND CHRISTMAS REVIEW",
241682: f"PLACEHOLDER TOILET CHRISTMAS REVIEW",
}
league_season_text = {
352961: f"PLACEHOLDER DIAMOND SEASON REVIEW",
241682: f"PLACEHOLDER TOILET SEASON REVIEW",
}
preseason = False
completed_playerpages = []
mout.showDebug()
api = None
json = {}
def main():
mout.debugOut("main()")
import os
if offline:
os.system(
f"terminal-notifier -title 'ToiletFPL' -message 'Started Wiki Update [OFFLINE]' -open 'index.html'"
)
else:
os.system(
f"terminal-notifier -title 'ToiletFPL' -message 'Started Wiki Update' -open 'index.html'"
)
if fetch_latest:
pull_changes()
global api
api = fpl_api.FPL_API(
offline=offline,
quick=False,
force_generate_kits=force_generate_kits,
write_offline_data=True,
)
global halfway_awards
if api._current_gw == 18 and not api._live_gw:
halfway_awards = True
global preseason
preseason = api._current_gw < 1
api._skip_kits = False
global json
json = load_json()
if len(json) == 0:
json = {}
if test:
run_test()
if scrape_kits:
api.scrape_team_kits()
exit()
extra_managers = None
leagues = []
for icon, code, colour, shortname in zip(
league_icons, league_codes, league_colours, league_shortnames
):
try:
leagues.append(League(code, api))
leagues[-1]._icon = icon
leagues[-1]._shortname = shortname
leagues[-1]._colour_str = colour
except fpl_api.Request404:
mout.error(f"Could not init League({code},{shortname})")
leagues[1]._skip_awards.append(3900121)
if api._current_gw < 38:
create_comparison_page(api, leagues)
navbar = create_navbar(leagues, path_root="html/")
create_homepage(navbar)
navbar = create_navbar(leagues)
for i, l in enumerate(leagues):
create_leaguepage(l, leagues, i)
if cup_active:
create_cup_page(api, leagues[1], leagues)
if not api._live_gw or any(
[f["started"] for f in api.get_gw_fixtures(api._current_gw)]
):
generate_summary_template(api, leagues[1])
create_teampage(api, leagues)
if halfway_awards:
# create_christmaspage(leagues)
pass
if season_awards:
create_seasonpage(leagues)
json["timestamp"] = timestamp
dump_json(json)
json = load_json()
get_manager_json_awards(api, leagues)
count = 0
mout.debugOut("main()::ManagerPages")
mout.hideDebug()
maximum = len(api._managers)
for i, m in enumerate(api._managers.values()):
mout.progress(i, maximum)
if m.valid:
create_managerpage(api, m, leagues)
mout.progress(maximum, maximum)
mout.showDebug()
count = 0
mout.debugOut("main()::PlayerPages")
mout.hideDebug()
maximum = len(api._loaded_players)
for pid in api._loaded_players:
mout.progress(count, maximum, append=f" {count}/{maximum}")
pid = int(pid)
create_playerpage(
api, Player(None, index=api.get_player_index(pid), api=api), leagues
)
count += 1
mout.progress(maximum, maximum)
mout.showDebug()
create_assetpage(leagues)
api.finish()
if run_push_changes:
push_changes()
def test_christmas():
leagues = []
for icon, code, colour, shortname in zip(
league_icons, league_codes, league_colours, league_shortnames
):
try:
leagues.append(League(code, api))
leagues[-1]._icon = icon
leagues[-1]._shortname = shortname
leagues[-1]._colour_str = colour
except fpl_api.Request404:
mout.error(f"Could not init League({code},{shortname})")
for i, l in enumerate(leagues):
create_leaguepage(l, leagues, i)
create_christmaspage(leagues)
def run_test():
# push_changes()
# test_christmas()
# print(api.fixtures.columns)
# print(api.get_gw_fixtures(6))
# print(api.elements_by_team['MCI'])
# print(api.get_player_team_obj(15))
# print(api.get_player_team_obj(17))
# print(api.elements.columns)
# print(api.get_player_index(664))
# pprint(api.elements['web_name'][api.get_player_index(664)])
# p = Player('Maddison',api)
# s = p.get_event_score(8,debug=True)
# print(p,s)
p = Player("Iraola", api)
s = p.get_event_score(23, debug=True)
s2 = p.get_event_summary(23, html_highlight=False)
create_playerpage(api, p, [])
print(p, s)
print(s2)
# create_comparison_page(api,[])
# l = League(352961, api)
# print(l.last_gw_position_dict)
# create_leaguepage(l,[],0)
# p = Player('Havertz',api)
# create_playerpage(api,p,[])
# leagues = []
# for icon,code,colour,shortname in zip(league_icons,league_codes,league_colours,league_shortnames):
# try:
# leagues.append(League(code,api))
# leagues[-1]._icon = icon
# leagues[-1]._shortname = shortname
# leagues[-1]._colour_str = colour
# except fpl_api.Request404:
# mout.error(f'Could not init League({code},{shortname})')
# # p.expected_points(gw=2,use_official=True,debug=True)
# # p.new_expected_points(gw=2,use_official=False,debug=True,force=True)
# man = Manager("Max Winokan", 1327451, api, team_name="Diamond Diogo's", authenticate=False)
# man = Manager("Max Winokan", 264578, api, team_name="Diamond Diogo's", authenticate=False)
# create_managerpage(api, man, leagues)
api.finish()
exit()
def create_comparison_page(api, leagues, prev_gw_count=5, next_gw_count=5):
mout.debug(f"create_comparison_page()")
# instantiate all the player objects
players = []
for pid in api._elements["id"]:
index = api.get_player_index(pid)
p = Player(None, api, index=index)
players.append(p)
players = sorted(players, key=lambda x: x.selected_by, reverse=True)
html_buffer = ""
### SEARCH BOX
html_buffer += '<div class="w3-col s12 m12 l12">\n'
html_buffer += '<div class="w3-panel w3-black shadow89 w3-padding" style="padding:0px;padding-bottom:3px;">\n'
html_buffer += (
f'<h3><i class="fa fa-search"></i> Search for and click to add players: </h3>\n'
)
html_buffer += f'<h4><input class="w3-input w3-white shadow25" onkeyup="searchFunction()" id="searchInput" type="text" placeholder="Search players by name..."></h4>\n'
html_buffer += f"</div>\n"
html_buffer += f"</div>\n"
html_buffer += f'<div class="w3-padding w3-center" id="searchTable">\n'
for p in players:
team_bg_color = p.team_obj.get_style()["background-color"]
team_text_color = p.team_obj.get_style()["color"]
team_style_str = f'"background-color:{team_bg_color};color:{team_text_color};margin-bottom:5px;"'
html_buffer += f'<span style="display:none;">\n'
html_buffer += f'<button class="w3-button" onclick="addPlayer({p.id})" style={team_style_str}>\n'
html_buffer += f'<img class="w3-image" src="{p.team_obj._badge_url}" alt="{p.team_obj.shortname}" width="20" height="20">\n'
html_buffer += f" {p.full_name}</button>\n"
html_buffer += f"</span>\n"
html_buffer += f"</div>\n"
### ADD PLAYER SCRIPTING
html_buffer += "<script>\n"
html_buffer += "function addPlayer(id) {\n"
html_buffer += " var id;\n"
html_buffer += ' tr = document.getElementById("statRow"+id);\n'
html_buffer += ' tr.style.display = "";\n'
html_buffer += ' tr = document.getElementById("graphDiv");\n'
html_buffer += ' tr.style.display = "";\n'
html_buffer += " showPlayerTrace(id);\n"
html_buffer += "};\n"
html_buffer += "</script>\n"
### REMOVE PLAYER SCRIPTING
html_buffer += "<script>\n"
html_buffer += "function removePlayer(id) {\n"
html_buffer += " var id;\n"
html_buffer += ' tr = document.getElementById("statRow"+id);\n'
html_buffer += ' tr.style.display = "none";\n'
html_buffer += " hidePlayerTrace(id);\n"
html_buffer += "};\n"
html_buffer += "</script>\n"
### SEARCH SCRIPTING (SPANS)
html_buffer += "<script>\n"
html_buffer += "function searchFunction() {\n"
html_buffer += " var input, filter, table, tr, td, i, txtValue;\n"
html_buffer += ' input = document.getElementById("searchInput");\n'
html_buffer += " filter = input.value.toUpperCase();\n"
html_buffer += ' table = document.getElementById("searchTable");\n'
html_buffer += ' tr = table.getElementsByTagName("span");\n'
html_buffer += "\n"
html_buffer += " if (filter.length < 1) {\n"
html_buffer += " for (i = 0; i < tr.length; i++) {\n"
html_buffer += ' td = tr[i].getElementsByTagName("button")[0];\n'
html_buffer += " if (td) {\n"
html_buffer += ' tr[i].style.display = "none";\n'
html_buffer += " } \n"
html_buffer += " }\n"
html_buffer += " } else {\n"
html_buffer += " for (i = 0; i < tr.length; i++) {\n"
html_buffer += ' td = tr[i].getElementsByTagName("button")[0];\n'
html_buffer += " if (td) {\n"
html_buffer += " txtValue = td.textContent || td.innerText;\n"
html_buffer += " if (txtValue.toUpperCase().indexOf(filter) > -1) {\n"
html_buffer += ' tr[i].style.display = "";\n'
html_buffer += " } else {\n"
html_buffer += ' tr[i].style.display = "none";\n'
html_buffer += " }\n"
html_buffer += " } \n"
html_buffer += " }\n"
html_buffer += " }\n"
html_buffer += "}\n"
html_buffer += "</script>\n"
### STATS DATA
html_buffer += '<div class="w3-col s12 m12 l12">\n'
html_buffer += '<div class="w3-panel w3-white shadow89 w3-responsive" style="padding:0px;padding-bottom:3px;">\n'
html_buffer += f'<table class="w3-table responsive-text" id="statTable">\n'
now_gw = api._current_gw
start_gw = max(1, now_gw - prev_gw_count)
end_gw = min(37, now_gw + next_gw_count)
### HEADERS
html_buffer += f"<tr>\n"
html_buffer += f"<th></th>\n"
html_buffer += f"<th>Name</th>\n"
html_buffer += f'<th style="text-align:center;">Price</th>\n'
html_buffer += f'<th style="text-align:center;">ΣPts</th>\n'
html_buffer += f'<th style="text-align:center;">Trans.</th>\n'
html_buffer += f'<th style="text-align:center;">xM</th>\n'
html_buffer += f'<th style="text-align:center;">xG</th>\n'
html_buffer += f'<th style="text-align:center;">xA</th>\n'
html_buffer += f'<th style="text-align:center;">xC</th>\n'
html_buffer += f'<th style="text-align:center;">xB</th>\n'
for i in range(start_gw, now_gw + 1):
html_buffer += f'<th style="text-align:center;">GW{i}</th>\n'
html_buffer += f'<th style="text-align:center;">Form</th>\n'
for i in range(now_gw + 1, end_gw + 1):
html_buffer += f'<th style="text-align:center;">GW{i}</th>\n'
html_buffer += f"</tr>\n"
n = len(players)
### PLAYER ROWS
for i, p in enumerate(players):
mout.progress(i, n)
html_buffer += f'<tr id="statRow{p.id}" style="display:none;">\n'
html_buffer += f'<td class="w3-center w3-button w3-black" onclick="removePlayer({p.id})"><i class="fa fa-close"></i></td>\n'
# name
bg_color = p.team_obj.get_style()["background-color"]
text_color = p.team_obj.get_style()["color"]
style_str = (
f'"background-color:{bg_color};color:{text_color};vertical-align:middle;"'
)
html_buffer += f"<td style={style_str}>\n"
html_buffer += f'<img class="w3-image" src="{p.team_obj._badge_url}" alt="{p.team_obj.shortname}" width="20" height="20">\n'
html_buffer += f'<a href="player_{p.id}.html"><b> {p.name}</a>\n'
if p.is_yellow_flagged:
html_buffer += f" ⚠️"
elif p.is_red_flagged:
html_buffer += f" ⛔️"
html_buffer += f"</b></td>\n"
html_buffer += (
f'<td style="text-align:center;vertical-align:middle;">£{p.price}</td>\n'
)
# total points
if p.appearances < 1:
score = 0
else:
score = p.total_points / p.appearances
style_str = (
get_style_from_event_score(score).rstrip('"') + ';vertical-align:middle;"'
)
html_buffer += (
f'<td class="w3-center" style={style_str}>{p.total_points}</td>\n'
)
# transfer percent
value = p.transfer_percent
text = f"{p.transfer_percent:.1f}%"
if abs(value) > 10:
if text.startswith("-"):
style_str = '"color:darkred;vertical-align:middle;"'
else:
style_str = '"color:darkgreen;vertical-align:middle;"'
html_buffer += (
f'<td class="w3-center" style={style_str}><b>{text}</b></td>\n'
)
else:
if text.startswith("-"):
style_str = '"color:red;vertical-align:middle;"'
else:
style_str = '"color:green;vertical-align:middle;"'
html_buffer += f'<td class="w3-center" style={style_str}>{text}</td>\n'
# minutes
style_str = (
get_style_from_minutes_played(p.expected_minutes()).rstrip('"')
+ ';vertical-align:middle;text-align:right;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>'
if p.xG_no_opponent is None:
html_buffer += f"-"
else:
html_buffer += f"{p.expected_minutes():.0f}"
html_buffer += "</td>\n"
# xG
style_str = (
get_style_from_expected_return(p.xG_no_opponent).rstrip('"')
+ ';vertical-align:middle;text-align:right;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>'
if p.xG_no_opponent is None:
html_buffer += f"-"
else:
html_buffer += f"{p.xG_no_opponent:.2f}"
html_buffer += "</td>\n"
# xA
style_str = (
get_style_from_expected_return(p.xA_no_opponent).rstrip('"')
+ ';vertical-align:middle;text-align:right;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>'
if p.xA_no_opponent is None:
html_buffer += f"-"
else:
html_buffer += f"{p.xA_no_opponent:.2f}"
html_buffer += "</td>\n"
# xCS
style_str = (
get_style_from_expected_return(p.xC_no_opponent).rstrip('"')
+ ';vertical-align:middle;text-align:right;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>'
if p.xC_no_opponent is None:
html_buffer += f"-"
else:
html_buffer += f"{p.xC_no_opponent:.0%}"
html_buffer += "</td>\n"
# xB
style_str = (
get_style_from_bonus(p.xBpts).rstrip('"')
+ ';vertical-align:middle;text-align:right;border-right: 4px solid white;border-collapse:collapse;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>'
if p.xBpts is None:
html_buffer += f"-"
else:
html_buffer += f"{p.xBpts:.2f}"
html_buffer += "</td>\n"
# previous GWs
for i in range(start_gw, now_gw + 1):
html_buffer += player_summary_cell_modal(p, i)
# form
form = p.form
style_str = (
get_style_from_event_score(form).rstrip('"')
+ ';vertical-align:middle;border-right:4px solid white;border-left:4px solid white;border-collapse:collapse;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>{form}</td>\n'
# upcoming GWs
for i in range(now_gw + 1, end_gw + 1):
exp = p.expected_points(gw=i, debug=False)
style_str = (
get_style_from_event_score(exp).rstrip('"') + ';vertical-align:middle;"'
)
html_buffer += f'<td class="w3-center" style={style_str}>{p.get_fixture_str(i,short=True,lower_away=True)}</td>\n'
html_buffer += f"</tr>\n"
mout.finish()
html_buffer += f"</table>"
html_buffer += f"</div>"
html_buffer += f"</div>"
### GRAPH
html_buffer += '<div class="w3-col s12 m12 l12">\n'
html_buffer += '<div class="w3-panel w3-white shadow89 w3-responsive w3-padding" id="graphDiv" style="display:none;">\n'
# html_buffer += f'<h3>Expected Points Graph</h3>\n'
html_buffer += f'<div id="comparisonGraph" style="width:100%;height:500px">\n'
html_buffer += f"</div>\n"
### BUILD THE PLOTTING DATA
gw_indices = [i + 1 for i in range(now_gw, end_gw + 1)]
gw_strs = [f"GW{i+1}" for i in range(now_gw, end_gw + 1)]
plot_data = []
player_id_to_trace_id = {}
for i, p in enumerate(players):
player_id_to_trace_id[p.id] = i
plot_y = [round(p.expected_points(gw=i), 1) for i in gw_indices]
plot_data.append(
dict(
name=p.name,
x=gw_strs,
y=plot_y,
visible=False,
mode="lines+markers",
)
)
### CREATE THE GRAPH
html_buffer += "<script>\n"
html_buffer += ' GRAPH = document.getElementById("comparisonGraph");\n'
html_buffer += f" Plotly.newPlot( GRAPH, {js.dumps(plot_data)}"
html_buffer += ', { title: "Expected Points", margin: { r:0 }, font: {size: 14}} , {responsive: true});\n'
html_buffer += "</script>\n"
### SHOW TRACE SCRIPTING
html_buffer += "<script>\n"
html_buffer += "function showPlayerTrace(id) {\n"
html_buffer += " var id, player_id_to_trace_id, trace_id;\n"
html_buffer += f" player_id_to_trace_id = {js.dumps(player_id_to_trace_id)};\n"
html_buffer += f" trace_id = player_id_to_trace_id[id];\n"
html_buffer += ' Plotly.update(GRAPH, {"visible":true}, {}, [trace_id]);\n'
html_buffer += "};\n"
html_buffer += "</script>\n"
### HIDE TRACE SCRIPTING
html_buffer += "<script>\n"
html_buffer += "function hidePlayerTrace(id) {\n"
html_buffer += " var id, player_id_to_trace_id, trace_id;\n"
html_buffer += f" player_id_to_trace_id = {js.dumps(player_id_to_trace_id)};\n"
html_buffer += f" trace_id = player_id_to_trace_id[id];\n"
html_buffer += ' Plotly.update(GRAPH, {"visible":false}, {}, [trace_id]);\n'
html_buffer += "};\n"
html_buffer += "</script>\n"
html_buffer += f"</div>\n"
html_buffer += f"</div>\n"
### Help/Explainer
html_buffer += '<div class="w3-col s12 m6 l6">\n'
html_buffer += '<div class="w3-panel w3-blue shadow89 w3-responsive w3-padding">\n'
html_buffer += f"<h3>Legend</h3>"
html_buffer += f'<span class="w3-tag">T%</span> Net transfer percentage <br><br>\n'
html_buffer += f'<span class="w3-tag"><sup>1</sup></span> Recent results are weighted higher <br><br>\n'
html_buffer += (
f'<span class="w3-tag"><sup>2</sup></span> Not adjusted for opponent <br><br>\n'
)
html_buffer += (
f'<span class="w3-tag">xM</span> Expected Minutes <sup>1</sup><br><br>\n'
)
html_buffer += (
f'<span class="w3-tag">xG</span> Expected Goals <sup>1,2</sup><br><br>\n'
)
html_buffer += (
f'<span class="w3-tag">xA</span> Expected Assists <sup>1,2</sup><br><br>\n'
)
html_buffer += (
f'<span class="w3-tag">xC</span> Expected Clean Sheets <sup>1,2</sup><br><br>\n'
)
html_buffer += (
f'<span class="w3-tag">xB</span> Expected Bonus Points <sup>1,2</sup>\n'
)
html_buffer += f"</div>\n"
html_buffer += f"</div>\n"
navbar = create_navbar(leagues, colour="black")
html_page(
"html/comparison.html",
None,
title=f"Comparison Tool",
gw=api._current_gw,
html=html_buffer,
showtitle=True,
bar_html=navbar,
colour="aqua",
plotly=True,
)
def create_cup_page(api, league, leagues):
# try and get data pertaining to the cups
# the page should be a bunch of tables separating by gameweek
# each table row should contain:
"""
Team Name | Points | vs. | Points | Team Name
Manager Name | Fixtures/Total | | Fixtures/Total | Manager Name
"""
all_matches = []
mout.debugOut(f"Getting all cup matches in {league.name}...")
for i, manager in enumerate(league.managers):
mout.progress(i, league.num_managers, width=50)
matches = manager.get_cup_matches(league)
# print(i,manager.name,len(matches))
all_matches += manager.get_cup_matches(league)
mout.progress(league.num_managers, league.num_managers, width=50)
# go by gameweek
gws = list(set([m["gw"] for m in all_matches]))
# gws = [gw for gw in gws if gw < 36]
create_key(json[str(league.id)], "cup")
total_buffer = ""
if api._current_gw > 35:
# total_buffer += floating_subtitle(f'Top 8 brackets',pad=0)
print("brackets!")
from cup import process_matches, bracket_table
final = process_matches(api, [m for m in all_matches if m["gw"] == 38])
semi_finals = process_matches(api, [m for m in all_matches if m["gw"] == 37])
quarter_finals = process_matches(api, [m for m in all_matches if m["gw"] == 36])
### testing ##########
# def man(id):
# return api.get_manager(id=id)
# final=(man(264578), man(660251))
# semi_finals=[
# (man(264578), man(5983)),
# (man(660251), man(566))
# ]
######################
total_buffer += bracket_table(
final=final, semis=semi_finals, quarters=quarter_finals
)
# prog_step = (50/len(gws))
for i, gw in enumerate(sorted(gws, reverse=True)):
html_buffer = ""
create_key(json[str(league.id)]["cup"], gw)
json[str(league.id)]["cup"][gw]["n_diamond_winners"] = 0
json[str(league.id)]["cup"][gw]["n_diamond_losers"] = 0
json[str(league.id)]["cup"][gw]["lowest_winner_rank"] = (None, -1)
json[str(league.id)]["cup"][gw]["highest_winner_rank"] = (None, 1_000_000_000)
json[str(league.id)]["cup"][gw]["lowest_loser_rank"] = (None, -1)
json[str(league.id)]["cup"][gw]["highest_loser_rank"] = (None, 1_000_000_000)
json[str(league.id)]["cup"][gw]["lowest_winner_score"] = (None, 1_000_000_000)
json[str(league.id)]["cup"][gw]["highest_winner_score"] = (None, -1_000_000_000)
json[str(league.id)]["cup"][gw]["lowest_loser_score"] = (None, 1_000_000_000)
json[str(league.id)]["cup"][gw]["highest_loser_score"] = (None, -1_000_000_000)
matches = [m for m in all_matches if m["gw"] == gw]
processed = []
html_buffer += floating_subtitle(f'GW{gw}: {matches[0]["title"]}', pad=0)
html_buffer += '<div class="w3-col s12 m12 l12">\n'
html_buffer += '<div class="w3-panel w3-white shadow89" style="padding:0px;padding-bottom:4px;">\n'
html_buffer += '<div class="w3-responsive">\n'
html_buffer += '<table class="w3-table responsive-text w3-striped">\n'
# html_buffer += f'<h2>GW{gw} Cup Matches: {matches[0]["title"]}</h2>\n'
# html_buffer += '<table class="w3-table-all w3-responsive">\n'
html_buffer += "<tr>\n"
html_buffer += f'<th class="w3-right">\n'
html_buffer += f"Player 1\n"
html_buffer += f"</th>\n"
html_buffer += f"<th>\n"
html_buffer += f"</th>\n"
html_buffer += f"<th>\n"
html_buffer += f"</th>\n"
html_buffer += f'<th class="w3-center">\n'
html_buffer += f"</th>\n"
html_buffer += f"<th>\n"
html_buffer += f"</th>\n"
html_buffer += f"<th>\n"
html_buffer += f"</th>\n"
html_buffer += f'<th class="w3-left">\n'
html_buffer += f"Player 2\n"
html_buffer += f"</th>\n"
html_buffer += "</tr>\n"
for j, match in enumerate(matches):
# mout.progress(i*prog_step + j*prog_step/len(matches),50,width=50)
man1 = match["self"]
man1_score = man1.get_event_score(gw)
processed.append(man1.id)
is_bye = match["bye"]
if not is_bye:
man2 = match["opponent"]
if man2.id in processed:
continue
man2_score = man2.get_event_score(gw)
if match["winner"]:
if man1.id == match["winner"]:
winner = 1
else:
winner = 2
else:
if man1_score > man2_score:
winner = 1
elif man1_score == man2_score:
winner = 0
else:
winner = 2
else:
man2 = None
winner = 1
html_buffer += "<tr>\n"
html_buffer += f'<td class="w3-right">\n'
html_buffer += f'<a href="{man1.gui_url}">{man1.name}</a>'
if man1.is_diamond:
html_buffer += "💎"
if winner == 1:
json[str(league.id)]["cup"][gw]["n_diamond_winners"] += 1
else:
json[str(league.id)]["cup"][gw]["n_diamond_losers"] += 1
html_buffer += f'<br><a href="{man1.gui_url}">{man1.team_name}</a>\n'
html_buffer += "</td>\n"
html_buffer += f'<td class="w3-center" style="vertical-align:middle;"><img class="w3-image" src="{man1._kit_path}" alt="Kit Icon" width="22" height="29"></td>\n'
if winner == 1:
html_buffer += f'<td class="w3-green w3-center">\n'
if (r := man1.overall_rank) > json[str(league.id)]["cup"][gw][
"lowest_winner_rank"
][1]:
json[str(league.id)]["cup"][gw]["lowest_winner_rank"] = (
man1.id,
r,
man2.id if man2 else None,
)
if (r := man1.overall_rank) < json[str(league.id)]["cup"][gw][
"highest_winner_rank"
][1]:
json[str(league.id)]["cup"][gw]["highest_winner_rank"] = (
man1.id,
r,
man2.id if man2 else None,
)
if (s := man1.livescore) < json[str(league.id)]["cup"][gw][
"lowest_winner_score"
][1]:
json[str(league.id)]["cup"][gw]["lowest_winner_score"] = (
man1.id,
s,
man2.id if man2 else None,
)