From 38cc7c7672e7e06a78bc354c48c627760fc06394 Mon Sep 17 00:00:00 2001 From: Trygve Date: Mon, 27 Jun 2022 14:26:32 +0200 Subject: [PATCH] Stilforbedringer+ --- otime.py | 315 ++++++++++++++++++++++--------------------------------- 1 file changed, 125 insertions(+), 190 deletions(-) diff --git a/otime.py b/otime.py index 9458f70..8630272 100644 --- a/otime.py +++ b/otime.py @@ -10,49 +10,19 @@ from fpdf import FPDF # The event object stores all the event data. # A .otime file is more or less just a json dump of the Event object. class Event: - def __init__(self, eventid, name, **kwargs): + def __init__(self, eventid, name, start_time=None, end_time=None, + organiser=None, courses=[], o_classes=[], runners=[], + card_dumps=[], fees=[]): self.id = eventid self.name = name - - try: - self.start_time = kwargs['start_time'] - except KeyError: - self.start_time = None - - try: - self.end_time = kwargs['end_time'] - except KeyError: - self.end_time = None - - try: - self.organiser = kwargs['organiser'] - except KeyError: - self.organiser = None - - try: - self.courses = kwargs['courses'] - except KeyError: - self.courses = [] - - try: - self.o_classes = kwargs['o_classes'] - except KeyError: - self.o_classes = [] - - try: - self.runners = kwargs['runners'] - except KeyError: - self.runners = [] - - try: - self.card_dumps = kwargs['card_dumps'] - except KeyError: - self.card_dumps = [] - - try: - self.fees = kwargs['fees'] - except KeyError: - self.fees = [] + self.start_time = start_time + self.end_time = end_time + self.organiser = organiser + self.courses = courses + self.o_classes = o_classes + self.runners = runners + self.card_dumps = card_dumps + self.fees = fees def add_course(self, *args): for n in args: @@ -78,24 +48,25 @@ class Event: tree = ET.parse(xml_file) root = tree.getroot() - event_el = root.find('./{http://www.orienteering.org/datastandard/3.0}Event') - event_id = int(event_el.find('./{http://www.orienteering.org/datastandard/3.0}Id').text) - name = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text - organiser = event_el.find('./{http://www.orienteering.org/datastandard/3.0}Organiser/{http://www.orienteering.org/datastandard/3.0}Name').text + url = '{http://www.orienteering.org/datastandard/3.0}' + event_el = root.find(f'./{url}Event') + event_id = int(event_el.find(f'./{url}Id').text) + name = event_el.find(f'./{url}Name').text + organiser = event_el.find(f'./{url}Organiser/{url}Name').text - start_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Date').text - start_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}StartTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1] + start_ds = event_el.find(f'./{url}StartTime/{url}Date').text + start_ts = event_el.find(f'./{url}StartTime/{url}Time').text[:-1] start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}') - end_ds = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Date').text - end_ts = event_el.find('./{http://www.orienteering.org/datastandard/3.0}EndTime/{http://www.orienteering.org/datastandard/3.0}Time').text[:-1] + end_ds = event_el.find(f'./{url}EndTime/{url}Date').text + end_ts = event_el.find(f'./{url}EndTime/{url}Time').text[:-1] end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}') runners = runners_from_xml_entries(xml_file) fees = fees_from_xml_entries(xml_file) return Event(event_id, name, organiser=organiser, runners=runners, - fees=fees, start_time=start_time, end_time=end_time) + fees=fees, start_time=start_time, end_time=end_time) def import_ttime_cnf(self, ttime_file): self.add_course(*courses_from_ttime_conf(ttime_file)) @@ -119,6 +90,7 @@ class Event: for d in self.card_dumps: if r.card == d.card: r.card_r = d + def match_runners_o_classes(self): for r in self.runners: for c in self.o_classes: @@ -136,6 +108,7 @@ class Event: for f in self.fees: if r.fee_id == f.id: r.fee = f + def match_all(self): self.match_runners_cards() self.match_runners_o_classes() @@ -214,13 +187,10 @@ class Event: # elif n.status() == 'Disqualified': xml_child(result, 'Status', n.status()) - - controls = copy(n.card_r.controls) - splits = copy(n.card_r.splits) for code, split in zip(n.res_codes(), n.res_splits()): st = ET.SubElement(result, 'SplitTime') xml_child(st, 'ControlCode', code) - if split != None: + if split is not None: xml_child(st, 'Time', split) else: xml_child(result, 'Status', n.status()) @@ -256,6 +226,9 @@ class Event: json_data = { 'id': self.id, 'name': self.name, + 'orginser': self.organiser, + 'start_time': self.start_time.isoformat(), + 'end_time': self.end_time.isoformat(), 'runners': rdicts, 'courses': cdicts, 'o_classes': ocdicts, @@ -269,11 +242,15 @@ class Event: data = json.load(f) runners = [] for r in data['runners']: - runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'], club=r['club'], country=r['country'], card=r['card'], o_class_str=r['o_class_str'], fork=r['fork'],start_time=r['start_time'])) + runners.append(Runner(r['id'], r['first'], r['last'], club_id=r['club_id'], + club=r['club'], country=r['country'], card=r['card'], + o_class_str=r['o_class_str'], fork=r['fork'], + start_time=r['start_time'], fee_id=int(r['fee_id']))) courses = [] for c in data['courses']: - courses.append(Course(c['name'], c['codes'], forked=c['forked'], variations=c['variations'])) + courses.append(Course(c['name'], c['codes'], forked=c['forked'], + variations=c['variations'])) o_classes = [] for c in data['o_classes']: @@ -281,13 +258,22 @@ class Event: card_dumps = [] for d in data['card_dumps']: - card_dumps.append(CardDump(d['card'], d['controls'], d['splits'], datetime.datetime.fromisoformat(d['read_time']), datetime.datetime.fromisoformat(d['s_time']), datetime.datetime.fromisoformat(d['f_time']))) + card_dumps.append(CardDump(d['card'], d['controls'], d['splits'], + datetime.datetime.fromisoformat(d['read_time']), + datetime.datetime.fromisoformat(d['s_time']), + datetime.datetime.fromisoformat(d['f_time']))) fees = [] for f in data['fees']: - fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'], from_birth_date=f['from_birth_date'], to_birth_date=f['to_birth_date'])) + fees.append(Fee(f['id'], f['name'], f['currency'], f['amount'], + from_birth_date=f['from_birth_date'], + to_birth_date=f['to_birth_date'])) - return Event(data['id'], data['name'], runners=runners, courses=courses, o_classes=o_classes, card_dumps=card_dumps) + return Event(data['id'], data['name'], organiser=data['orginiser'], + start_time=datetime.datetime.fromisoformat(data['start_time']), + end_time=datetime.datetime.fromisoformat(data['end_time']), + runners=runners, courses=courses, o_classes=o_classes, + card_dumps=card_dumps, fees=fees) def create_start_list_pdf(self, file_name): pdf = FPDF() @@ -300,7 +286,7 @@ class Event: pdf.multi_cell(col_width, line_height, runner.fullname(), border=1, ln=3, max_line_height=pdf.font_size, align='L') pdf.multi_cell(col_width, line_height, runner.o_class_str, border=1, ln=3, max_line_height=pdf.font_size) pdf.multi_cell(col_width, line_height, str(runner.card), border=1, ln=3, max_line_height=pdf.font_size) - if runner.start_time != None: + if runner.start_time is not None: pdf.multi_cell(col_width, line_height, str(runner.start_time), border=1, ln=3, max_line_height=pdf.font_size) else: pdf.multi_cell(col_width, line_height, '', border=1, ln=3, max_line_height=pdf.font_size) @@ -308,7 +294,7 @@ class Event: pdf.output(file_name) def create_all_invoices(self, filename_prefix): - clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club] + clubs = [x.club for x in self.runners if x.club != self.runners[self.runners.index(x)-1].club and x.club is not None] for club in clubs: self.create_club_invoice(club, filename_prefix + club + '.pdf') @@ -318,7 +304,6 @@ class Event: payments = [x.fee.amount for x in runners_ic] subtotal = sum(payments) - # Dict of runners in each fee fee_dict = {} for fee in self.fees: @@ -333,7 +318,6 @@ class Event: pdf.set_creator('oTime 0.0.1') pdf.set_creation_date() - pdf.add_page() pdf.add_font("LiberationSans", fname="data/fonts/LiberationSans-Regular.ttf") pdf.add_font("LiberationSans-Bold", fname="data/fonts/LiberationSans-Bold.ttf") @@ -396,19 +380,19 @@ class Event: pdf.set_font("LiberationSans", size=10) # Tabell line_height = pdf.font_size * 2 - col_width = pdf.epw / 9 # distribute content evenly - #Top row + col_width = pdf.epw / 8 # distribute content evenly + # Top row pdf.set_fill_color(191, 191, 191) pdf.set_draw_color(191, 191, 191) pdf.set_font("LiberationSans-Bold", size=10) - pdf.multi_cell(col_width, line_height, 'Startnr', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width*2, line_height, 'Navn', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Klasse', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Brikke', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Resultat', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Plass', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) - pdf.multi_cell(col_width, line_height, 'Kontigent', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Startnr', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width*2, line_height, 'Navn', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Klasse', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Brikke', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + # pdf.multi_cell(col_width, line_height, 'Starttid', border=1, ln=3,max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Resultat', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Plass', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) + pdf.multi_cell(col_width, line_height, 'Kontigent', border=1, ln=3, max_line_height=pdf.font_size, align='L', fill=True) pdf.ln() pdf.set_draw_color(0, 0, 0) for runners in fee_dict.values(): @@ -418,15 +402,15 @@ class Event: line_height = pdf.font_size * 1.6 pdf.ln() for runner in runners: - pdf.multi_cell(col_width, line_height, runner.id, ln=3,max_line_height=pdf.font_size, align='L') # Start Number + pdf.multi_cell(col_width, line_height, runner.id, ln=3, max_line_height=pdf.font_size, align='L') # Start Number pdf.multi_cell(col_width*2, line_height, f'{runner.last}, {runner.first}', ln=3, max_line_height=pdf.font_size, align='L') # Name pdf.multi_cell(col_width, line_height, runner.o_class_str, ln=3, max_line_height=pdf.font_size, align='L') # Class pdf.multi_cell(col_width, line_height, str(runner.card), ln=3, max_line_height=pdf.font_size) # card # Starttime: - if runner.start_time != None: - pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size) - else: - pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size) + #if runner.start_time != None: + # pdf.multi_cell(col_width, line_height, str(runner.start_time), ln=3, max_line_height=pdf.font_size) + #else: + # pdf.multi_cell(col_width, line_height, 'Fristart', ln=3, max_line_height=pdf.font_size) # Time used: if runner.status() == 'OK': pdf.multi_cell(col_width, line_height, str(datetime.timedelta(seconds=runner.totaltime())), ln=3, max_line_height=pdf.font_size) @@ -450,7 +434,7 @@ class Event: # sum pdf.set_font("LiberationSans-Bold", size=10) pdf.set_x(col_width*8) - pdf.multi_cell(0, line_height, 'Sum ' + str(subtotal), border='TB', ln=3, max_line_height=pdf.font_size, align='R') + pdf.cell(0, line_height, 'Sum ' + str(subtotal), border='TB', align='R') pdf.set_font("LiberationSans", size=10) line_height = pdf.font_size * 1.5 @@ -486,63 +470,22 @@ class PDF(FPDF): # The runner object stores all the data specific to a runner. class Runner: - def __init__(self, runner_id, first, last, **kwargs): + def __init__(self, runner_id, first, last, club=None, club_id=None, + country=None, card=None, o_class_str=None, o_class=None, + fork=0, start_time=None, fee_id=None, fee=None): self.id = runner_id self.first = first self.last = last - try: - self.club = kwargs['club'] - except KeyError: - self.club = None - - try: - self.club_id = kwargs['club_id'] - except KeyError: - self.club_id = None - - try: - self.country = kwargs['country'] - except KeyError: - self.country = None - - try: - self.card = kwargs['card'] - except KeyError: - self.card = 0 - - try: - self.o_class_str = kwargs['o_class_str'] - except KeyError: - self.o_class = None - - try: - self.o_class = kwargs['o_class'] - except KeyError: - self.o_class = None - - try: - self.fork = kwargs['fork'] - except KeyError: - self.fork = 0 - - try: - self.start_time = kwargs['start_time'] - except KeyError: - self.start_time = None - - try: - self.fee_id = kwargs['fee_id'] - except KeyError: - self.fee_id = None - - try: - self.fee = kwargs['fee'] - self.fee_id = kwargs['fee'].id - except KeyError: - self.fee = None - - #self.o_class = o_class - #self.start_time = start_time + self.club = club + self.club_id = club_id + self.country = country + self.card = card + self.o_class_str = o_class_str + self.o_class = o_class + self.fork = fork + self.start_time = start_time + self.fee_id = fee_id + self.fee = fee def from_string(tt_line, o_classes): #https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer @@ -605,11 +548,11 @@ class Runner: return 0 def status(self): - if hasattr(self, 'card_r') == False or self.o_class == None: + if hasattr(self, 'card_r') is False or self.o_class is None: return 'Active' elif self.check_codes(): return 'OK' - elif self.check_codes() == False: + elif self.check_codes() is False: return 'Disqualified' # TODO: må forbedres @@ -621,7 +564,7 @@ class Runner: return None def res_codes(self): - if self.o_class.course.forked == False: + if self.o_class.course.forked is False: return self.o_class.course.codes else: return self.o_class.course.variations[self.fork] @@ -672,6 +615,7 @@ class Runner: 'fee_id': self.fee_id } + class CardDump: def __init__(self, card, controls, splits, read_time, s_time, f_time): self.card = card @@ -714,7 +658,7 @@ class CardDump: read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds) if len(controls) > 2: - s_time = read_time - datetime.timedelta(seconds = splits[-1]) + s_time = read_time - datetime.timedelta(seconds=splits[-1]) f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2])) else: s_time = read_time @@ -760,8 +704,8 @@ class CardDump: tl[1] = list(map(int, tl[1])) read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2]) if len(controls) > 2 and len(splits) > 2: - s_time = read_time - datetime.timedelta(seconds = splits[-1]) - f_time = read_time - (datetime.timedelta(seconds = splits[-1]) + datetime.timedelta(seconds = splits[-2])) + s_time = read_time - datetime.timedelta(seconds=splits[-1]) + f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2])) else: s_time = read_time f_time = read_time @@ -780,19 +724,11 @@ class CardDump: # Stored in Event.courses class Course: - def __init__(self, name, codes, **kwargs): + def __init__(self, name, codes, forked=False, variations=None): self.name = name self.codes = codes - - try: - self.forked = kwargs['forked'] - except KeyError: - self.forked = False - - try: - self.variations = kwargs['variations'] - except KeyError: - self.variations = None + self.forked = forked + self.variations = variations def __repr__(self): return f'name({self.name})' @@ -822,21 +758,14 @@ class OClass: } class Fee: - def __init__(self, fee_id, name, currency, amount, **kwargs): + def __init__(self, fee_id, name, currency, amount, from_birth_date=None, + to_birth_date=None): self.id = fee_id self.name = name self.currency = currency self.amount = amount - - try: - self.from_birth_date = kwargs['from_birth_date'] - except KeyError: - self.from_birth_date = None - - try: - self.to_birth_date = kwargs['to_birth_date'] - except KeyError: - self.to_birth_date = None + self.from_birth_date = from_birth_date + self.to_birth_date = to_birth_date def asdict(self): return { @@ -880,78 +809,83 @@ def classes_from_ttime_conf(ttime_file, courses): def runners_from_xml_entries(xml_file): tree = ET.parse(xml_file) root = tree.getroot() - runners = [] - person_entries = root.findall('./{http://www.orienteering.org/datastandard/3.0}PersonEntry') + url = '{http://www.orienteering.org/datastandard/3.0}' + runners = [] + person_entries = root.findall(f'./{url}PersonEntry') for p_entry in person_entries: rid = p_entry[1][0].text - person = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Person') - name = person.find('./{http://www.orienteering.org/datastandard/3.0}Name') - first = name.find('./{http://www.orienteering.org/datastandard/3.0}Given').text - last = name.find('./{http://www.orienteering.org/datastandard/3.0}Family').text + person = p_entry.find(f'./{url}Person') + name = person.find(f'./{url}Name') + first = name.find(f'./{url}Given').text + last = name.find(f'./{url}Family').text - organisation = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Organisation') + organisation = p_entry.find(f'./{url}Organisation') if organisation is not None: - club_id = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Id').text - club_name = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Name').text - club_name_short = organisation.find('./{http://www.orienteering.org/datastandard/3.0}ShortName').text - country = organisation.find('./{http://www.orienteering.org/datastandard/3.0}Country').attrib['code'] + club_id = organisation.find(f'./{url}Id').text + club_name = organisation.find(f'./{url}Name').text + club_name_short = organisation.find(f'./{url}ShortName').text + country = organisation.find(f'./{url}Country').attrib['code'] else: club_id = club_name = club_name_short = country = None - class_el = p_entry.find('./{http://www.orienteering.org/datastandard/3.0}Class') - class_str = class_el.find('./{http://www.orienteering.org/datastandard/3.0}Name').text + class_el = p_entry.find(f'./{url}Class') + class_str = class_el.find(f'./{url}Name').text - fee_id = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}AssignedFee/{http://www.orienteering.org/datastandard/3.0}Fee/{http://www.orienteering.org/datastandard/3.0}Id').text) + fee_id = int(p_entry.find(f'./{url}AssignedFee/{url}Fee/{url}Id').text) try: - card = int(p_entry.find('./{http://www.orienteering.org/datastandard/3.0}ControlCard').text) + card = int(p_entry.find(f'./{url}ControlCard').text) except AttributeError: card = None start_time = None runners.append(Runner(rid, first, last, club=club_name, club_id=club_id, - country=country,card=card, o_class_str=class_str, - start_time=start_time, fee_id=fee_id)) + country=country,card=card, o_class_str=class_str, + start_time=start_time, fee_id=fee_id)) return runners + def fees_from_xml_entries(xml_file): tree = ET.parse(xml_file) root = tree.getroot() - allfees = root.findall('.//{http://www.orienteering.org/datastandard/3.0}Fee') + url = '{http://www.orienteering.org/datastandard/3.0}' + allfees = root.findall(f'.//{url}Fee') added_ids = [] fee_objs = [] for fee in allfees: - f_id = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Id').text) + f_id = int(fee.find(f'./{url}Id').text) if f_id not in added_ids: added_ids.append(f_id) fee_id = f_id - name = fee.find('./{http://www.orienteering.org/datastandard/3.0}Name').text - currency = fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').attrib['currency'] - amount = int(fee.find('./{http://www.orienteering.org/datastandard/3.0}Amount').text) + name = fee.find(f'./{url}Name').text + currency = fee.find(f'./{url}Amount').attrib['currency'] + amount = int(fee.find(f'./{url}Amount').text) try: - from_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}FromDateOfBirth').text + from_birth_date = fee.find(f'./{url}FromDateOfBirth').text except AttributeError: from_birth_date = None try: - to_birth_date = fee.find('./{http://www.orienteering.org/datastandard/3.0}ToDateOfBirth').text + to_birth_date = fee.find(f'./{url}ToDateOfBirth').text except AttributeError: to_birth_date = None - fee_objs.append(Fee(fee_id, name, currency, amount, from_birth_date=from_birth_date, to_birth_date=to_birth_date)) + fee_objs.append(Fee(fee_id, name, currency, amount, + from_birth_date=from_birth_date, to_birth_date=to_birth_date)) return fee_objs + # Checks if small list is in big list def contains(small, big): valid = True mark = 0 map_bl = [] for i in small: - for n,control in enumerate(big[mark:]): + for n, control in enumerate(big[mark:]): if i == control: mark += n map_bl.append(mark) @@ -962,16 +896,17 @@ def contains(small, big): return map_bl else: return False - + + def get_runners_in_class(runners, o_class): # Filters out runner objects that dont have the correct o_class list_filtrd = [] for i in runners: - marker = 0 if i.o_class == o_class: list_filtrd.append(i) return list_filtrd + def rank_runners(allrunners, o_class): runners = get_runners_in_class(allrunners, o_class) runners_ranked = [] @@ -981,8 +916,8 @@ def rank_runners(allrunners, o_class): runners_ranked.sort(key=lambda x: x.totaltime()) return runners_ranked + # Used to make creating xml files easier def xml_child(parent, tag, content): e = ET.SubElement(parent, tag) e.text = str(content) -