-
Notifications
You must be signed in to change notification settings - Fork 2
/
compy_data.py
1456 lines (1361 loc) · 58.3 KB
/
compy_data.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
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# ━━━━━━━━━━━━━
# ┏┓┏┓┳┳┓┏┓┓┏
# ┃ ┃┃┃┃┃┃┃┗┫
# ┗┛┗┛┛ ┗┣┛┗┛
# ━━━━━━━━━━━━━
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# Competition organization tool
# for freediving competitions.
#
# Copyright 2023 - Arno Mayrhofer
#
# Licensed under the GNU AGPL
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# Authors:
#
# - Arno Mayrhofer
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
try:
import pandas as pd
except ImportError:
print("Could not find pandas. Install with 'pip3 install pandas'")
exit(-1)
import logging
from collections import Counter, namedtuple
try:
import requests
except ImportError:
print("Could not find requests. Install with 'pip3 install requests'")
exit(-1)
import re
import math
from packaging.version import Version
try:
import country_converter
assert Version(country_converter.version.__version__) >= Version("1.2")
except ImportError:
print("Could not find country_converter. Install with 'pip3 install country_converter'")
exit(-1)
except AssertionError:
print("country_converter found with version", country_converter.version.__version__, "but version >= 1.2 required, please update it.")
exit(-1)
import os
import json
import glob
from datetime import datetime, timedelta, time
import flask
try:
import weasyprint as wp
except ImportError:
print("Could not find weasyprint. Install with 'pip3 install weasyprint'")
exit(-1)
import base64
from PIL import Image
from io import BytesIO
import numpy as np
import regex
import sys
import athlete
from compy_config import CompyConfig
INVALID_DATE="0000-00-00"
INVALID_TIME="99:99"
DISCIPLINES=["FIM", "CNF", "CWT", "CWTB", "STA", "DNF", "DYN", "DYNB"]
class CompyData:
def __init__(self, db, app):
self.id_ = None
self.db_ = db
self.app_ = app
self.name_ = "undefined"
self.special_ranking_name_ = "Newcomer"
self.config_ = CompyConfig()
self.version_ = None
self.lane_style_ = "numeric"
self.comp_type_ = "aida"
self.comp_file_ = ''
self.start_date_ = None
self.end_date_ = None
self.nrs_ = None
self.sponsor_img_ = None
self.disciplines_ = 0
self.selected_country_ = None
self.NR = namedtuple("NR", ["federation", "country", "cls", "gender", "discipline"])
self.name_ = "undefined"
with self.app_.app_context():
#self.updateNationalRecords();
# try and find it first
c_id = self.db_.execute("SELECT id FROM competition WHERE name=?", self.name_)
if c_id is not None:
self.load(c_id[0][0])
else:
self.save()
@property
def version(self):
if self.version_ is None:
with open('VERSION', 'r') as f:
self.version_ = str(f.read().strip())
return self.version_
@property
def name(self):
return self.name_
@property
def special_ranking_name(self):
return self.special_ranking_name_
@property
def config(self):
return self.config_
@property
def lane_style(self):
return self.lane_style_
def changeLaneStyle(self, lane_style):
allowed_lane_styles = ["numeric", "alphabetic"]
if lane_style not in allowed_lane_styles:
return 1
self.lane_style_ = lane_style
self.save()
return 0
@property
def comp_type(self):
return self.comp_type_
def changeCompType(self, comp_type):
allowed_comp_types = ["aida", "cmas"]
if comp_type not in allowed_comp_types:
return 1
self.comp_type_ = comp_type
self.save()
return 0
def laneStyleConverter(self, lane, invert=False):
if invert:
if self.lane_style_ == "alphabetic":
return ord(lane) - 64
else: # numeric
return int(lane)
else:
if self.lane_style_ == "alphabetic":
return chr(lane + 64)
else: # numeric
return str(lane)
@property
def comp_file(self):
return self.comp_file_
@property
def number_of_athletes(self):
db_out = self.db_.execute("SELECT COUNT(*) FROM competition_athlete WHERE competition_id=?", self.id_)
if db_out is None:
return 0
else:
return db_out[0][0]
@property
def start_date(self):
return self.start_date_
@property
def end_date(self):
return self.end_date_
@property
def disciplines(self):
dis = []
for bit, d in enumerate(DISCIPLINES):
if self.disciplines_ & 1<<bit:
dis.append(d)
return dis
@property
def sponsor_img_data(self):
if self.sponsor_img_ is None:
return ""
else:
return self.sponsor_img_["data"]
@property
def countries(self):
if self.id_ is None:
return None
c_data = self.db_.execute('''SELECT DISTINCT athlete.country FROM athlete
INNER JOIN competition_athlete
ON athlete.id==competition_athlete.athlete_id
WHERE competition_athlete.competition_id==?''',
self.id_)
if c_data is None:
return []
return [c[0] for c in c_data]
@property
def sponsor_img_width(self):
if self.sponsor_img_ is None:
return 0
else:
aspect_ratio = self.sponsor_img_["aspect_ratio"]
if aspect_ratio < 1:
return 19.*self.sponsor_img_["aspect_ratio"]
else:
return 19.
@property
def sponsor_img_height(self):
if self.sponsor_img_ is None:
return 0
else:
aspect_ratio = self.sponsor_img_["aspect_ratio"]
if aspect_ratio > 1:
return 5./self.sponsor_img_["aspect_ratio"]
else:
return 5.
@property
def selected_country(self):
if self.selected_country_ is None:
return "none"
else:
return self.selected_country_
@property
def nr(self):
if self.nrs_ is None:
nrs = self.db_.execute('''SELECT country, class, gender, discipline, value
FROM records
WHERE federation=?''',
self.comp_type)
if nrs is None:
return None
self.nrs_ = {}
for nr in nrs:
self.nrs_[self.NR(self.comp_type, nr[0], nr[1], nr[2], nr[3])] = nr[4]
return self.nrs_
def changeSponsorImage(self, img_content):
self.sponsor_img_ = {}
img_base64 = base64.b64encode(img_content).decode('utf-8')
self.sponsor_img_["data"] = 'data:image/png;base64,' + img_base64
img = Image.open(BytesIO(img_content))
width, height = img.size # in pixels
self.sponsor_img_["aspect_ratio"] = float(width)*5./float(height)/19. # < 1 if too high, > 1 if too wide
self.save()
def compFileChange(self, comp_file):
self.comp_file_ = comp_file
self.refresh()
def refresh(self):
# special ranking ids of athletes
srd_ids = None
if self.id_ is not None:
sr_ids = self.db_.execute(
'''SELECT a.id FROM athlete a
INNER JOIN competition_athlete ca ON a.id == ca.athlete_id
WHERE ca.special_ranking AND ca.competition_id==?''',
self.id_)
self.db_.execute('''DELETE FROM start
WHERE competition_athlete_id IN (
SELECT competition_athlete_id FROM start
INNER JOIN competition_athlete
ON start.competition_athlete_id == competition_athlete.id
WHERE competition_athlete.competition_id == ?)''',
self.id_)
self.db_.execute("DELETE FROM competition_athlete WHERE competition_id=?", self.id_)
# read first sheet (start & end date)
if not os.path.exists(self.comp_file_):
logging.error("File '%s' does not exist", self.comp_file_)
return
df = pd.read_excel(self.comp_file_, sheet_name="Event")
i = 0
for l in df[df.keys()[0]]:
if l == "Starts:":
self.start_date_ = df[df.keys()[1]][i]
if l == "Ends:":
self.end_date_ = df[df.keys()[1]][i]
if l == "Disciplines:":
print([1<<DISCIPLINES.index(d) for d in df[df.keys()[1]][i].split(",")], df[df.keys()[1]][i].split(","))
self.disciplines_ = sum([1<<DISCIPLINES.index(d) for d in df[df.keys()[1]][i].split(",")])
i += 1
logging.debug("Start date: %s. End date: %s", self.start_date_, self.end_date_)
# read second sheet (list of athletes)
df = pd.read_excel(self.comp_file_, sheet_name="Athletes and Judges", skiprows=1)
for i,r in df.iterrows():
a = athlete.Athlete.fromArgs(r['Id'], r['FirstName'], r['LastName'], r['Gender'], r['Country'], r['Club'] if 'club' in r else "", self.db_)
logging.debug("Athlete: %s %s %s %s %s", r['Id'], r['FirstName'], r['LastName'], r['Gender'], r['Country'])
a.associateWithComp(self.id_)
logging.debug("Number of athletes: %d", self.number_of_athletes)
if sr_ids is not None:
for sr in sr_ids:
self.setSpecialRanking(sr[0], True, False)
self.save()
ap_lambda = lambda x, y, d, self: None if math.isnan(x) else (int(x)*60+float(y) if d=="STA" else float(x))
for day in self.getDays():
df = pd.read_excel(self.comp_file_, sheet_name=day, skiprows=1)
for i,r in df.iterrows():
aida_id = r['Diver Id']
ca_id = self.db_.execute('''SELECT competition_athlete.id FROM competition_athlete
INNER JOIN athlete
ON competition_athlete.athlete_id == athlete.id
WHERE athlete.aida_id=? AND competition_athlete.competition_id == ?''',
(aida_id, self.id_))
dis = r['Discipline']
ap = ap_lambda(r['Meters or Min'], r['Sec(STA only)'], dis, self)
ot = self.parseTime(r['OT'])
lane = int(r['Zone'])
rp = ap_lambda(r['Meters or Min.1'], r['Sec(STA only).1'], dis, self)
card = r['Card']
pen_other = float(r['Pen(other)']) if not math.isnan(r['Pen(other)']) else 0.
penalty = float(r['Pen(UNDER AP)']) + pen_other
remarks = r['Remarks']
if remarks == "DNS":
rp = float('nan')
card = "nan"
penalty = "nan"
if rp is not None:
self.db_.execute('''INSERT INTO start
(competition_athlete_id, discipline, lane, OT, AP, day,
rp, card, penalty, remarks)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(ca_id[0][0], dis, lane, ot, ap, day, rp, card, penalty, remarks))
else:
self.db_.execute('''INSERT INTO start
(competition_athlete_id, discipline, lane, OT, AP, day)
VALUES (?, ?, ?, ?, ?, ?)''',
(ca_id[0][0], dis, lane, ot, ap, day))
def getNationalRecordsAida(self):
empty_req = requests.post('https://www.aidainternational.org/public_pages/all_national_records.php', data={})
html = empty_req.text
start = html.find('id="nationality"')
start = html.find('<option', start)
end = html.find('</select>', start)
nationalities = str.splitlines(html[start:end])
p = re.compile("<option.*value=\"([0-9]+)\">(.*)</option>")
country_value_map = {}
cc = country_converter.CountryConverter()
for n in nationalities:
result = p.search(n)
if result:
country_value_map[cc.convert(result.group(2), to = 'IOC')] = result.group(1)
nrs = {}
for c_ioc, c_str in country_value_map.items():
data = {
'nationality': str(c_str),
'discipline': '',
'gender': '',
'apply': ''
}
req = requests.post('https://www.aidainternational.org/public_pages/all_national_records.php', data=data)
html = req.text
start = html.find('<tbody>')
start = html.find('<tr>', start)
end = html.find('</tbody>', start)
entries = str.splitlines(html[start:end])[:-1]
p = re.compile("<td>(.*)</td>")
for i in range(int(len(entries)/10)):
gender = p.search(entries[i*10 + 2]).group(1)
dis = p.search(entries[i*10 + 3]).group(1)
res_str = p.search(entries[i*10 + 4]).group(1)
result = 0.
if dis == "STA":
p_dis = re.compile("([0-9]+):([0-9][0-9])")
res_re = p_dis.search(res_str)
result = float(res_re.group(1))*60.0 + float(res_re.group(2))
else:
p_dis = re.compile("[0-9]+")
result = float(p_dis.search(res_str).group(0))
points = float(p.search(entries[i*10 + 6]).group(1))
nrs[self.NR(federation="aida", country=c_ioc, cls="", gender=gender, discipline=dis)] = result
logging.debug("National records:")
logging.debug("Country | Gender | Discipline | Result | Points")
for key, val in nrs.items():
logging.debug("%s | %s | %s | %s | %d", key.country, key.gender, key.discipline, val)
logging.debug("-----------------")
return nrs
def setSpecialRanking(self, athlete_id, special_ranking, warn=True):
found = False
if self.number_of_athletes == 0:
logging.warning("Data not initialized yet in setSpecialRanking")
return 1
try:
self.db_.execute(
'''UPDATE competition_athlete SET special_ranking=?
WHERE competition_id==? AND athlete_id==?''',
(special_ranking, self.id_, athlete_id))
return 0
except sqlite3.Error as e:
if warn:
logging.warning("Tried setting special_ranking (" + str(special_ranking) + ") to athlete with id '" + athlete_id + "' but this id could not be found")
return 1
def getSavedCompetitions(self):
os.chdir(self.config.storage_folder)
saved_comp_info = []
comps = self.db_.execute("SELECT id, name, save_date FROM competition")
if comps is None:
return None
for comp in comps:
saved_comp_info.append({"comp_id": comp[0], "name": comp[1], "save_date": comp[2]})
return sorted(saved_comp_info, key=lambda ci: ci["save_date"], reverse=True)
def changeName(self, new_name, overwrite):
comp_id = self.db_.execute("SELECT id FROM competition WHERE name=?", new_name)
if not comp_id is None and not overwrite:
return [1, self.name_]
else:
self.name_ = new_name
if comp_id is None:
self.id_ = None
else:
self.id_ = comp_id[0][0]
self.save()
return [0, self.name_]
def save(self):
if self.id_ is None:
self.db_.execute('''INSERT INTO competition
(name, save_date, version, lane_style, comp_type, comp_file, start_date,
end_date, disciplines)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(self.name_, datetime.now().isoformat(), self.version,
self.lane_style, self.comp_type, self.comp_file,
self.start_date_, self.end_date_, self.disciplines_))
self.id_ = self.db_.last_index
sponsor_img_data = ""
if self.sponsor_img_ is not None:
sponsor_img_data = self.sponsor_img_["data"]
self.db_.execute('''UPDATE competition
SET name=?, save_date=?, version=?, lane_style=?, comp_type=?, comp_file=?,
start_date=?, end_date=?, sponsor_img=?, selected_country=?,
special_ranking_name=?, disciplines=? WHERE id=?''',
(self.name_, datetime.now().isoformat(), self.version, self.lane_style, self.comp_type,
self.comp_file, self.start_date_, self.end_date_, sponsor_img_data,
self.selected_country_, self.special_ranking_name, self.disciplines_,
self.id_))
logging.debug("Saved competition: " + self.name)
def load(self, comp_id):
#TODO on load find self.id_ if not, reset to None
load_data = self.db_.execute('''SELECT name, version, lane_style, comp_type, comp_file,
start_date, end_date, sponsor_img, selected_country,
special_ranking_name, disciplines
FROM competition WHERE id=?''',
comp_id)
if load_data is None:
logging.error("Could not find save file with id '" + id + "'")
return ""
else:
self.id_ = comp_id
comp_data = load_data[0]
self.name_ = comp_data[0]
self.version_ = comp_data[1]
self.lane_style_ = comp_data[2]
self.comp_type_ = comp_data[3]
self.comp_file_ = comp_data[4]
self.start_date_ = comp_data[5]
self.end_date_ = comp_data[6]
self.sponsor_img_ = {"data": comp_data[7], "aspect_ratio": 1} # TODO
self.selected_country_ = comp_data[8]
self.special_ranking_name_ = comp_data[9]
self.disciplines_ = comp_data[10]
#self.getResultPDF('all', 'all', 'all', False, True)
return self.name_
def getDays(self):
if self.start_date is None:
return
days = []
d0 = datetime.strptime(self.start_date, '%Y-%m-%d')
d1 = datetime.strptime(self.end_date, '%Y-%m-%d')
delta = d1 - d0
for i in range(delta.days + 1):
yield (d0 + timedelta(days=i)).strftime('%Y-%m-%d')
def getDaysWithDisciplinesLanes(self, internal=False):
dwd = {}
for day in self.getDays():
db_out = self.db_.execute('''SELECT DISTINCT discipline, lane FROM start s
INNER JOIN competition_athlete ca
ON s.competition_athlete_id == ca.id
WHERE (ca.competition_id==? AND s.day==?)''',
(self.id_, day))
if db_out is None:
continue
disciplines_on_day = list({d[0] for d in db_out})
disciplines_w_lanes = {}
for dis in disciplines_on_day:
disciplines_w_lanes[dis] = [d[1] if internal else self.laneStyleConverter(d[1]) for d in db_out if d[0]==dis]
dwd[day] = disciplines_w_lanes
logging.debug("dwd:" + str(dwd))
return dwd
def getDisciplines(self):
if self.disciplines is None:
return []
dwc = []
# only aida has Overall and SpecialRanking
if self.comp_type == "aida":
dwc.append("Overall")
# only add special_ranking result if we have at least one special_ranking
has_special_ranking = self.db_.execute(
'''SELECT id FROM competition_athlete
WHERE competition_id==? AND special_ranking''',
self.id_)
if has_special_ranking is not None:
dwc.append(self.special_ranking_name)
dwc += self.disciplines
return dwc
def getCountries(self, for_result=False):
countries = []
if self.countries is None:
return []
if self.selected_country != "none":
countries.append(self.selected_country)
countries.append("International")
if for_result:
if self.comp_type == "cmas":
# only add special_ranking result if we have at least one special_ranking
has_special_ranking = self.db_.execute(
'''SELECT id FROM competition_athlete
WHERE competition_id==? AND special_ranking''',
self.id_)
if has_special_ranking is not None:
countries.append(self.special_ranking_name)
else:
countries += self.countries
return countries
def getStartList(self, day, discipline):
if self.comp_file is None:
return None
db_out = self.db_.execute('''
SELECT a.first_name, a.last_name, a.country, s.AP, s.OT, s.lane, s.id
FROM start s
INNER JOIN competition_athlete ca ON s.competition_athlete_id == ca.id
INNER JOIN athlete a ON ca.athlete_id == a.id
WHERE ca.competition_id==? AND s.discipline==? AND s.day==?''',
(self.id_, discipline, day))
if db_out is None:
return []
startlist = [{'Name': r[0] + " " + r[1],
'Nationality': r[2],
'AP': self.convertPerformance(r[3], discipline),
'Warmup': self.getWTfromOT(r[4]),
'OT': r[4],
'Lane': self.laneStyleConverter(r[5]),
'Discipline': discipline,
'Id': r[6]}
for r in db_out]
startlist.sort(key=lambda r: (self.getMinFromTime(r['OT']), int(self.laneStyleConverter(r['Lane'], True))))
br_out = self.db_.execute('''
SELECT duration, idx
FROM break
WHERE competition_id == ? AND discipline == ? AND day == ?''',
(self.id_, discipline, day))
if br_out is not None:
for br in br_out:
idx = int(br[1])
if idx >= len(startlist):
continue
br_time = str(int(br[0]/60)) + ":" + str(br[0]%60).zfill(2)
startlist.insert(idx, {'Name': "Break", 'Nationality': "", 'AP': br_time, 'Warmup': "",
'OT': "", 'Lane': "", 'Discipline': discipline, 'Id': -1})
return startlist
def updateStartList(self, day, discipline, to_remove, startlist):
day = self.cleanDay(day)
if discipline not in DISCIPLINES or day == INVALID_DATE:
return -1
to_remove = [int(tr) for tr in to_remove]
# remove all starts from the start list that were removed and make sure they belong to this comp
if len(to_remove) > 0:
if len(to_remove) == 1:
self.db_.execute(
'''DELETE FROM start WHERE id IN
(SELECT s.id FROM start s
INNER JOIN competition_athlete ca ON ca.id == s.competition_athlete_id
WHERE s.id == ? AND ca.competition_id == ?''',
(to_remove[0], self.id_))
else:
rlist = str(tuple(to_remove))
self.db_.execute(
'''DELETE FROM start WHERE id IN
(SELECT s.id FROM start s
INNER JOIN competition_athlete ca ON ca.id == s.competition_athlete_id
WHERE s.id IN ? AND ca.competition_id == ?''',
(rlist, self.id_))
# remove all breaks
self.db_.execute("DELETE FROM break WHERE competition_id == ? AND discipline == ? AND day == ?",
(self.id_, discipline, day))
for i in range(len(startlist)):
if startlist[i]["Name"] == "Break":
duration = self.getMinFromTime(self.cleanTime(startlist[i]["AP"]))
self.db_.execute(
'''INSERT INTO break
(competition_id, discipline, day, duration, idx) VALUES (?, ?, ?, ?, ?)''',
(self.id_, discipline, day, duration, i))
else: # start
ca_id = int(startlist[i]["Id"])
if ca_id < 0: # new start, in this case ca_id = - athlete_id
ca_id = self.db_.execute(
'''SELECT id FROM competition_athlete
WHERE athlete_id == ? AND competition_id == ?''',
(-ca_id, self.id_))
else: # old start in this case ca_id = start_id
ca_id = self.db_.execute(
'''SELECT s.id FROM competition_athlete ca
INNER JOIN start s ON ca.id == s.competition_athlete_id
WHERE s.id == ? AND ca.competition_id == ?''',
(ca_id, self.id_))
if ca_id is None:
log.warning("Invalid athlete not added to competition")
continue
ot = self.cleanTime(startlist[i]["OT"])
ap = self.cleanPerf(startlist[i]["AP"], discipline)
lane = self.cleanNumber(self.laneStyleConverter(startlist[i]["Lane"], true)) # TODO min/max
if int(startlist[i]["Id"]) < 0: # new s["art
self.db_.execute(
'''INSERT INTO start
(competition_athlete_id, discipline, lane, day, OT, AP)
VALUES (?, ?, ?, ?, ?, ?)''',
(ca_id[0][0], discipline, lane, day, ot, ap));
else: #update start
self.db_.execute(
'''UPDATE start SET
discipline=?, lane=?, day=?, OT=?, AP=?
WHERE id == ?''',
(discipline, lane, day, ot, ap, ca_id[0][0]));
return 0
def convertPerformance(self, val, dis):
if val is None:
return ""
if dis == "STA":
m = math.floor(val/60)
s = val - m*60
out = str(int(m)) + ":"
if self.comp_type == "aida":
out += str(int(s)).zfill(2)
else:
out += "%05.2f" % round(s, 2)
return out
else:
return str(val)
def getWTfromOT(self, ot):
otf = self.getMinFromTime(ot)
wtf = otf-45 # does not work if ot is close to midnight, but seriously?
wt = str(math.floor(wtf/60)) + ":" + str(wtf%60).zfill(2)
return wt
def getStartListPDF(self, day="all", discipline="all", in_memory=False):
if day=="all" and discipline=="all":
dwd = self.getDaysWithDisciplinesLanes()
files = []
for d in dwd:
for dis in dwd[d].keys():
files.append(self.getStartListPDF(d, dis, True))
pages = []
for doc in files:
for page in doc.pages:
pages.append(page)
merged_pdf = files[0].copy(pages)
fname = os.path.join(self.config.download_folder, self.name + "_start_lists.pdf")
merged_pdf.write_pdf(fname)
return fname
start_df = pd.DataFrame(self.getStartList(day, discipline))
start_df.drop("Id", axis=1, inplace=True)
html_string = start_df.to_html(index=False, justify="left", classes="df_table")
day_obj = datetime.strptime(day, "%Y-%m-%d")
human_day = day_obj.strftime("%d. %m. %Y")
html_string = """
<html>
<head>
<style>
table {{
margin-left: 2cm;
}}
tr th:first-child {{
padding-left:0px;
text-align: left;
}}
tr td:first-child {{
padding-left:0;
text-align: left;
}}
th, td {{
padding:5px 0px 2px 20px;
text-align: center;
border-bottom: 1px solid #ddd;
font-size: 12px;
}}
@page {{
margin: 4cm 1cm 6cm 1cm;
size: A4;
@top-right {{
content: counter(page) "/" counter(pages);
}}
}}
header, footer {{
position: fixed;
left: 0;
right: 0;
}}
header {{
/* subtract @page margin */
top: -4cm;
height: 4cm;
text-align: center;
vertical-align: center;
}}
footer {{
/* subtract @page margin */
bottom: -6cm;
height: 6cm;
text-align: center;
vertical-align: center;
}}
</style>
</head>
<body>
<header>
<h1>{}</h1>
<h2>Start list {} - {}</h2>
</header>
{}
<footer><img src="{}" style="width:{}cm; height:{}cm;"></footer>
</body>
</html>
""".format(self.name, discipline, human_day, html_string, self.sponsor_img_data, self.sponsor_img_width, self.sponsor_img_height)
html = wp.HTML(string=html_string, base_url="/")
#fname = os.path.join(self.config.download_folder, "test.html")
#with open(fname, "w") as f:
# f.write(html_string)
if in_memory:
return html.render()
else:
fname = os.path.join(self.config.download_folder, self.name + "_start_list_" + day + "_" + discipline + ".pdf")
html.write_pdf(fname)
return fname
def getLaneList(self, day, discipline, lane):
lane_db = self.laneStyleConverter(lane, True)
db_out = self.db_.execute('''SELECT a.first_name, a.last_name, s.AP, s.OT, a.country, a.gender
FROM athlete a
INNER JOIN competition_athlete ca ON a.id == ca.athlete_id
INNER JOIN start s ON s.competition_athlete_id == ca.id
WHERE s.discipline == ? AND s.lane == ? AND s.day == ? AND ca.competition_id == ?
''',
(discipline, lane_db, day, self.id_))
if db_out is None:
return None
lane_list = [{'OT': r[3],
'Name': r[0] + " " + r[1],
'Nat': r[4],
'AP': self.convertPerformance(r[2], discipline),
'NR': self.convertPerformance(self.nr.get(self.NR(self.comp_type, r[4], "", r[5], discipline)), discipline)}
for r in db_out]
lane_list.sort(key=lambda r: self.getMinFromTime(r['OT']))
return lane_list
def getLaneListPDF(self, day="all", discipline="all", lane="all", in_memory=False):
if day=="all" and discipline=="all":
dwd = self.getDaysWithDisciplinesLanes()
files = []
for d in dwd:
for dis in dwd[d].keys():
for l in dwd[d][dis]:
files.append(self.getLaneListPDF(d, dis, l, True))
pages = []
for doc in files:
for page in doc.pages:
pages.append(page)
merged_pdf = files[0].copy(pages)
fname = os.path.join(self.config.download_folder, self.name + "_lane_lists.pdf")
merged_pdf.write_pdf(fname)
return fname
lane_df = pd.DataFrame(self.getLaneList(day, discipline, lane))
lane_df["RP"] = ""
lane_df["Card"] = ""
lane_df["Remarks"] = ""
cols = lane_df.columns.tolist()
cols = cols[0:4] + cols[5:] + [cols[4]]
lane_df = lane_df[cols]
html_string = lane_df.to_html(index=False, justify="left", classes="df_table")
day_obj = datetime.strptime(day, "%Y-%m-%d")
human_day = day_obj.strftime("%d. %m. %Y")
html_string = """
<html>
<head>
<style>
table {{
width: 100%;
}}
tr th:first-child {{
padding-left:0px;
}}
tr td:first-child {{
padding-left:0px;
}}
th, td {{
padding:10px 0px 10px 20px;
text-align: center;
border-bottom: 1px solid #ddd;
}}
table th:nth-child(1) {{
width: 5%;
}}
table th:nth-child(2) {{
width: 21%;
text-align: left;
}}
table td:nth-child(2) {{
text-align: left;
}}
table th:nth-child(3) {{
width: 5%;
}}
table th:nth-child(4) {{
width: 5%;
}}
table th:nth-child(5) {{
width: 10%;
}}
table th:nth-child(6) {{
width: 10%;
}}
table th:nth-child(7) {{
width: 39%;
}}
table th:nth-child(8) {{
width: 5%;
}}
@page {{
margin: 4cm 1cm 1.5cm 2.5cm;
size: A4 landscape;
@top-right {{
content: counter(page) "/" counter(pages);
}}
}}
header, footer {{
position: fixed;
left: 0;
right: 0;
}}
header {{
/* subtract @page margin */
top: -4cm;
height: 4cm;
text-align: center;
vertical-align: center;
}}
footer {{
/* subtract @page margin */
bottom: -1.5cm;
height: 1.5cm;
text-align: left;
vertical-align: center;
}}
</style>
</head>
<body>
<header>
<h1>{}</h1>
<h2>Lane list {} - lane {} - {}</h2>
</header>
{}
<footer><span style="margin-left:3mm">Judge Name:</span><span style="margin-left:8cm">Signature:</span></footer>
</body>
</html>
""".format(self.name, discipline, lane, human_day, html_string, self.sponsor_img_data, self.sponsor_img_width, self.sponsor_img_height)
html = wp.HTML(string=html_string, base_url="/")
fname = os.path.join(self.config.download_folder, "test.html")
with open(fname, "w") as f:
f.write(html_string)
if in_memory:
return html.render()
else:
fname = os.path.join(self.config.download_folder, self.name + "_lane_list_" + day + "_" + discipline + "_" + lane + ".pdf")
html.write_pdf(fname)
return fname
def getResult(self, discipline, gender, country, with_empty=False):
if self.comp_file is None:
return None, None
result = []
result_keys = ['Rank', 'Name', 'Country']
if self.comp_type == "cmas":
result_keys.append('Club')
if discipline == "Overall" or discipline == self.special_ranking_name:
if self.comp_type == "cmas":
logging.error("Attempted to get " + discipline + " ranking for cmas competition")
return None, None
cmd = '''SELECT ca.id, a.first_name, a.last_name, a.country, a.club,
s.rp, s.penalty, s.card, s.remarks, s.discipline
FROM start s
INNER JOIN competition_athlete ca ON s.competition_athlete_id == ca.id
INNER JOIN athlete a ON ca.athlete_id == a.id
WHERE a.gender == ? AND s.remarks IS NOT NULL AND ca.competition_id == ?'''
args = (gender, self.id_)
if country != 'International':
cmd += " AND a.country = ?"
args += (country, )
if discipline == self.special_ranking_name:
cmd += " AND ca.special_ranking"
db_out = self.db_.execute(cmd, args)
if db_out is None:
return None, None
res = {}
for r in db_out:
if not r[0] in res:
res[r[0]] = {'Rank': 0, 'Name': r[1] + " " + r[2], 'Country': r[3], 'Points': 0.}
for d in self.disciplines:
res[r[0]][d] = ''
if self.comp_type == "cmas":
res[r[0]]['Club'] = r[4]
res[r[0]][r[9]] = 0 if r[7] == "RED" else self.convertPerformance(r[5], r[9])
res[r[0]]['Points'] += self.computePoints(r[5], r[6], r[7], r[8], r[9])
# remove all 0 points and format points to two decimals after comma
to_remove = []
for r in res:
if res[r]['Points'] == 0.:
to_remove.append(r)
else:
res[r]['Points'] = "%.2f" % res[r]['Points']
for tr in to_remove:
res.pop(tr)
res_list = sorted(list(res.values()), key=lambda r: -float(r['Points']))
# set ranks
res_list[0]['Rank'] = 1
for i in range(len(res_list)-1):
if res_list[i]['Points'] != res_list[i+1]['Points']:
res_list[i+1]['Rank'] = i+2
else:
res_list[i+1]['Rank'] = ""
result_keys += self.disciplines + ["Points"]
return res_list, result_keys
else:
cmd = '''SELECT a.first_name, a.last_name, a.country, a.club,
s.AP, s.RP, s.penalty, s.card, s.remarks, s.id, s.OT, a.gender
FROM start s
INNER JOIN competition_athlete ca ON s.competition_athlete_id == ca.id
INNER JOIN athlete a ON ca.athlete_id == a.id
WHERE s.discipline == ? AND a.gender == ? and ca.competition_id == ?'''
if not with_empty: # remove unset results if requested
cmd += " AND s.remarks IS NOT NULL"
args = (discipline, gender, self.id_)
if country != 'International' and country != self.special_ranking_name:
cmd += " AND a.country = ?"
args += (country, )
if self.comp_type == "cmas" and country == self.special_ranking_name:
cmd += " AND a.country = ? AND ca.special_ranking"
args += (self.selected_country, )
db_out = self.db_.execute(cmd, args)
if db_out is None:
return [], []
def check_nr(country, gender, rp, card):
if rp is None and card != "WHITE":
return ""
this_nr = self.nr.get(self.NR(self.comp_type, country, "", gender, discipline))
return ", <b>NR</b>" if this_nr is not None and this_nr < rp else ""
if self.comp_type == "aida":
result = [{'Rank': i,