This repository was archived by the owner on Jan 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathGAPP.py
1762 lines (1547 loc) · 80.8 KB
/
GAPP.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
import csv # For writing data to CSV files
import logging # For error handling and debugging
import os # For getting directory paths
import threading # For multi threading
from pathlib import Path # For data paths
from tkinter import BOTH, DoubleVar, E, IntVar, S, StringVar, Tk, W, ttk # To create the GUI
from tkinter.ttk import Notebook # For tabs in the GUI
from lxml import html
# Import external data
from calcs import profileCalc, setupCalc, strategyCalc, wearCalc
from funcs import *
# Logging setup
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%y-%m-%d %H:%M')
logger = logging.getLogger(__name__)
# Handlers
dataPath = str(Path.home()) + "\\Documents\\GAPP"
if not os.path.exists(dataPath):
os.makedirs(dataPath)
fLogFileName = str(Path.home()) + r"\Documents\GAPP\error.log"
gLogFileName = str(Path.home()) + r"\Documents\GAPP\logging.log"
f_handler = logging.FileHandler(fLogFileName)
g_handler = logging.FileHandler(gLogFileName)
f_handler.setLevel(logging.ERROR)
g_handler.setLevel(logging.DEBUG)
# Handler Format
f_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
g_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
# Add Handlers
logger.addHandler(f_handler)
logger.addHandler(g_handler)
class Autoresized_Notebook(Notebook):
def __init__(self, master=None, **kw):
Notebook.__init__(self, master, **kw)
self.bind("<<NotebookTabChanged>>", self._on_tab_changed)
def _on_tab_changed(self, event):
event.widget.update_idletasks()
tab = event.widget.nametowidget(event.widget.select())
event.widget.configure(height=tab.winfo_reqheight(), width=tab.winfo_reqwidth())
'''
Data Storage Setup
'''
logger.info("Getting reference to GAPP folder in Documents for storage")
dataPath = str(Path.home()) + "\\Documents\\GAPP"
if not os.path.exists(dataPath):
try:
logger.info("No GAPP folder found in documents, creating it")
os.makedirs(dataPath)
except Exception:
logger.exception("Unable to create GAPP folder in documents, GAPP may not have permissions to do so")
filename = dataPath + "\\data.dat"
try:
logger.info("Creating login data file")
open(filename, "x").close()
except:
logger.info("Login data file already exists, skipping")
pass
try:
logger.info("Opening login data file for reading")
file = open(filename, "r")
credentialCheck = int(float(file.readline()))
username = file.readline()
password = file.readline()
logger.info("Login data file read successfully")
except:
logger.info("Unable to open or read login data file, setting credential check to 0")
username = ""
password = ""
credentialCheck = 0
finally:
logger.info("Closing login data file")
file.close()
# Thread Controller - starts and manages threads as required
def calculateThreadController(*args):
logger.info("Writing user data to login data file")
checkData(filename, inputRememberCredentials.get(), inputUsername.get(), inputPassword.get())
logger.info("Getting tab information to create thread name")
threadName = notebook.tab(notebook.select(), "text")
threads = threading.enumerate()
for thread in threads:
if not threadName == thread.name:
logger.info("Starting new thread: %s", threadName)
threading.Thread(daemon=True, name=threadName, target=calculate, args=(threadName,)).start()
else:
logger.warning("Thread of same name already exists: %s", threadName)
def fillThreadController(*args):
logger.info("Writing user data to login data file")
checkData(filename, inputRememberCredentials.get(), inputUsername.get(), inputPassword.get())
logger.info("Getting tab information to create thread name")
threadName = notebook.tab(notebook.select(), "text")
threads = threading.enumerate()
for thread in threads:
if not threadName == thread.name:
logger.info("Starting new thread: %s", threadName)
if threadName == "Car Wear":
threading.Thread(daemon=True, name=threadName, target=fillWear).start()
elif threadName == "PHA":
threading.Thread(daemon=True, name=threadName, target=fillProfile).start()
else:
logger.warning("Thread of same name already exists: %s", threadName)
# Calculate the setup and others
def calculate(tab):
logger.info("Starting calculation process")
try:
logger.info("Getting user login details")
username = str(inputUsername.get())
password = str(inputPassword.get())
logger.info("Checking user login details are correct and user is in Viper team")
if (not checkLogin(username, password)):
logger.warning("Login details are incorrect")
warningLabel.set("Incorrect Login Details")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
if (tab == "Setup"):
logger.info("Starting Setup calcuation")
weather = str(inputWeather.get())
session = str(inputSession.get())
setup = setupCalc(username, password, weather, session)
logger.info("Applying calculated setup")
frontWing.set(str(setup[0]))
rearWing.set(str(setup[1]))
engine.set(str(setup[2]))
brakes.set(str(setup[3]))
gear.set(str(setup[4]))
suspension.set(str(setup[5]))
elif (tab == "Strategy"):
logger.info("Getting strategy input")
try:
wear = float(re.findall(r'\d+', inputWear.get())[0])
except:
try:
wear = float(re.findall(r'\d+.\d+', inputWear.get())[0])
except:
logger.warning("Wear input incorrect format, despite input control")
wear = 0.0
inputWear.set(0)
try:
laps = int(re.findall(r'\d+', inputLaps.get())[0])
except:
try:
laps = inputLaps.get()
except:
logger.warning("Laps input incorrect format, despite input control")
laps = 0
inputLaps.set(0)
lapsUpper.set(laps + 1)
logger.info("Starting Strategy calculation")
strategy = strategyCalc(username, password, wear, laps)
logger.info("Applying calculated strategy")
for i in range(5):
stops[i].set(strategy[0][i])
stintlaps[i].set(strategy[1][i])
fuels[i].set(strategy[2][i])
pitTimes[i].set(strategy[3][i])
TCDs[i].set(strategy[4][i])
FLDs[i].set(strategy[5][i])
pitTotals[i].set(strategy[6][i])
totals[i].set(strategy[7][i])
lapsFuelLoadLower.set(strategy[8][0])
lapsFuelLoadUpper.set(strategy[8][1])
for i in range(len(labelsTotal)):
labelsTotal[i].configure(style="Black.Label")
labelsTotal[strategy[9]].configure(style="Green.Label")
logger.info("Getting track information for stragey tab")
GPROnextTrackName.set(strategy[10])
GPROnextTrackLaps.set(strategy[11])
GPROnextTrackLapDistance.set(strategy[12])
GPROnextTrackDistance.set(strategy[13])
GPROnextTrackPitInOut.set(strategy[14])
elif (tab == "Car Wear"):
logger.info("Creating GPRO session for web scraping")
# Get user and password
username = entryUsername.get()
password = entryPassword.get()
# Logon to GPRO using the logon information provided and store that under our session
browser = mechanize.Browser()
browser.open("https://gpro.net/gb/Login.asp")
browser.select_form(id="Form1")
browser.form["textLogin"] = username
browser.form["textPassword"] = password
browser.submit()
# Get the driver details
logger.info("Getting Driver information")
browser.follow_link(url_regex=re.compile("DriverProfile"))
tree = html.fromstring(browser.response().get_data())
browser.back()
driverConcentration = int(tree.xpath("normalize-space(//td[contains(@id, 'Conc')]/text())"))
driverTalent = int(tree.xpath("normalize-space(//td[contains(@id, 'Talent')]/text())"))
driverExperience = int(tree.xpath("normalize-space(//td[contains(@id, 'Experience')]/text())"))
driverFactor = (0.998789138 ** driverConcentration) * (0.998751839 ** driverTalent) * (
0.998707677 ** driverExperience)
# Get the track details
logger.info("Getting track information")
browser.follow_link(url_regex=re.compile("TrackDetails"))
tree = html.fromstring(browser.response().get_data())
browser.back()
trackName = str(tree.xpath("normalize-space(//h1[contains(@class, 'block')]/text())"))
trackName = trackName.strip()
logger.info("Checking user input is in corret format")
for i in range(len(startWears)):
try:
int(startWears[i].get())
except:
startWears[i].set(0)
try:
int(wearlevels[i].get())
except:
wearlevels[i].set(1)
try:
int(wearClearTrackRisk.get())
except:
wearClearTrackRisk.set(0)
logger.info("Calculating and applying car wear")
for i in range(len(startWears)):
raceWears[i].set(round(float(
wearCalc(startWears[i].get(), int(wearlevels[i].get()), driverFactor, trackName,
wearClearTrackRisk.get(), i)), 2))
endWears[i].set(int(round(raceWears[i].get() + round(startWears[i].get(), 0), 0)))
if (endWears[i].get() >= 90):
endLabels[i].configure(style="Red.Label")
elif (endWears[i].get() >= 80):
endLabels[i].configure(style="Orange.Label")
else:
endLabels[i].configure(style="Black.Label")
elif (tab == "PHA"):
logger.info("Starting PHA calculation")
partNames = ["Chassis", "Engine", "Front Wing", "Rear Wing", "Underbody", "Sidepods", "Cooling", "Gearbox",
"Brakes", "Suspension", "Electronics"]
for i in range(len(PHA) - 1):
profile = profileCalc(partNames[i], profilePartLevels[i].get())
for j in range(len(PHA[i])):
PHA[i][j].set(round(profile[j], 2))
PTotal = HTotal = ATotal = 0
for i in range(len(PHA) - 1):
PTotal += PHA[i][0].get()
HTotal += PHA[i][1].get()
ATotal += PHA[i][2].get()
logger.info("Applying calculated PHA")
PParts.set(int(round(PTotal, 0)))
HParts.set(int(round(HTotal, 0)))
AParts.set(int(round(ATotal, 0)))
for i in range(3):
subTotal = 0
subTotal += PHAParts[i].get()
subTotal += profileTesting[i].get()
profileTotals[i].set(int(round(subTotal, 0)))
elif (tab == "Analysis"):
# First step is to import current data, which will allow a long running data file for the user
pastSessionData = []
try:
with open("RaceData.csv", mode="r") as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
rowData = {}
for key in row:
rowData[key] = row[key]
pastSessionData.append(rowData)
except:
logger.warning("Unable to open RaceData.csv data file - might not exist or permission is denied")
logger.info("Starting pre- and post-race analysis")
# Create the logon payload and create the session
username = entryUsername.get()
password = entryPassword.get()
browser = mechanize.Browser()
browser.open("https://gpro.net/gb/Login.asp")
browser.select_form(id="Form1")
browser.form["textLogin"] = username
browser.form["textPassword"] = password
browser.submit()
# Gather the session information for the upcoming or past race, based on input choice
logger.info("Getting ID data for season and race")
tree = html.fromstring(browser.response().get_data())
rawData = tree.xpath("normalize-space(//strong[contains(text(), 'Next race:')]/../text())")
reSearch = re.findall(r"(\d{2}),\s\w+\s(\d+)", rawData)[0]
seasonNumber = reSearch[0]
raceNumber = reSearch[1]
raceState = inputAnalysis.get()
if (raceState == "Pre-Race"):
logger.info("Calculating for Pre-Race")
# Creating raceID
if (len(raceNumber) == 1):
raceNumber = "0" + raceNumber
raceID = "S" + seasonNumber + "R" + raceNumber
# Define required URLs
Q1URL = "https://www.gpro.net/gb/Qualify.asp"
Q2URL = "https://www.gpro.net/gb/Qualify2.asp"
SetupURL = "https://www.gpro.net/gb/RaceSetup.asp"
# Get session data
browser.follow_link(url_regex=re.compile("Qualify.asp"))
Q1Result = browser.response().get_data()
browser.back()
browser.follow_link(url_regex=re.compile("Qualify2.asp"))
Q2Result = browser.response().get_data()
browser.back()
browser.follow_link(url_regex=re.compile("RaceSetup.asp"))
SetupResult = browser.response().get_data()
browser.back()
# List to store the created dictionaries, for easier looped writing
sessionDicts = []
# Process data
# Q1
try:
logger.info("Analysing for Q1")
tree = html.fromstring(Q1Result)
Q1LapData = tree.xpath(
"//img[contains(@src, 'suppliers')]/../..//*[string-length(text()) > 2]/text()")
Q1LapData += tree.xpath("//img[contains(@src, 'suppliers')]/@alt")
Q1LapData.remove(Q1LapData[0])
Q1LapData.remove(Q1LapData[1])
Q1LapDict = {
"RaceID": raceID,
"Session": "Q1",
"Fastest Lap": Q1LapData[0],
"FWing": Q1LapData[1],
"RWing": Q1LapData[2],
"Engine": Q1LapData[3],
"Brakes": Q1LapData[4],
"Gear": Q1LapData[5],
"Suspension": Q1LapData[6],
"Compound": Q1LapData[7],
"Risk O/D": Q1LapData[8],
"Supplier": Q1LapData[9]
}
sessionDicts.append(Q1LapDict)
except Exception:
logger.exception("Pre-Race analysis failed in Q1 - user probably hasn't done Q1 yet")
logger.info("Updating status label to notify user of completed calculations")
warningLabel.set("Q1 Not Done")
foregroundColour("Status.Label", "#FF0000")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
# Q2
try:
logger.info("Analysing for Q2")
tree = html.fromstring(Q2Result)
Q2LapData = tree.xpath(
"//img[contains(@src, 'suppliers')]/../..//*[string-length(text()) > 2]/text()")
Q2LapData += tree.xpath("//img[contains(@src, 'suppliers')]/@alt")
Q2LapData.remove(Q2LapData[0])
Q2LapData.remove(Q2LapData[1])
Q2LapDict = {
"RaceID": raceID,
"Session": "Q2",
"Fastest Lap": Q2LapData[0],
"FWing": Q2LapData[1],
"RWing": Q2LapData[2],
"Engine": Q2LapData[3],
"Brakes": Q2LapData[4],
"Gear": Q2LapData[5],
"Suspension": Q2LapData[6],
"Compound": Q2LapData[7],
"Risk O/D": Q2LapData[8],
"Supplier": Q2LapData[9]
}
sessionDicts.append(Q2LapDict)
except Exception:
logger.exception("Pre-Race analysis failed in Q2 - user probably hasn't done Q2 yet")
logger.info("Updating status label to notify user of completed calculations")
warningLabel.set("Q2 Not Done")
foregroundColour("Status.Label", "#FF0000")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
# Setup
try:
logger.info("Anlysing race setup")
tree = html.fromstring(SetupResult)
SetupDict = {}
# Session Information
SetupDict["RaceID"] = raceID
SetupDict["Session"] = "Setup"
# Car Setup
SetupDict["FWing"] = str(tree.xpath("//input[contains(@id, 'FWing')]/@value")[0])
SetupDict["RWing"] = str(tree.xpath("//input[contains(@id, 'RWing')]/@value")[0])
SetupDict["Engine"] = str(tree.xpath("//input[contains(@id, 'Engine')]/@value")[0])
SetupDict["Brakes"] = str(tree.xpath("//input[contains(@id, 'Brakes')]/@value")[0])
SetupDict["Gear"] = str(tree.xpath("//input[contains(@id, 'Gear')]/@value")[0])
SetupDict["Suspension"] = str(tree.xpath("//input[contains(@id, 'Suspension')]/@value")[0])
# Fuel
SetupDict["Fuel Start"] = str(tree.xpath("//input[contains(@name, 'FuelStart')]/@value")[0])
SetupDict["Stop 1 Refuel"] = str(tree.xpath("//input[contains(@name, 'FuelStop1')]/@value")[0])
SetupDict["Stop 2 Refuel"] = str(tree.xpath("//input[contains(@name, 'FuelStop2')]/@value")[0])
SetupDict["Stop 3 Refuel"] = str(tree.xpath("//input[contains(@name, 'FuelStop3')]/@value")[0])
SetupDict["Stop 4 Refuel"] = str(tree.xpath("//input[contains(@name, 'FuelStop4')]/@value")[0])
SetupDict["Stop 5 Refuel"] = str(tree.xpath("//input[contains(@name, 'FuelStop5')]/@value")[0])
# Risks
SetupDict["Risk O/D"] = str(
tree.xpath("//input[contains(@name, 'RiskOver')]/@value")[0]) + "/" + str(
tree.xpath("//input[contains(@name, 'RiskDefend')]/@value")[0])
SetupDict["Risk CT"] = str(tree.xpath("//input[@name='DriverRisk']/@value")[0]) + "/" + str(
tree.xpath("//input[contains(@name, 'RiskWet')]/@value")[0])
# Boosts
SetupDict["Boosts"] = str(
tree.xpath("//input[contains(@name, 'BoostLap1')]/@value")[0]) + "/" + str(
tree.xpath("//input[contains(@name, 'BoostLap2')]/@value")[0]) + "/" + str(
tree.xpath("//input[contains(@name, 'BoostLap3')]/@value")[0])
sessionDicts.append(SetupDict)
except Exception:
logger.exception(
"Pre-Race analysis failed in race setup - user probably hasn't done race setup yet")
logger.info("Updating status label to notify user of completed calculations")
warningLabel.set("Setup Not Done")
foregroundColour("Status.Label", "#FF0000")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
# Write the data to file
try:
logger.info("Writing pre-race analysis to CSV")
with open("RaceData.csv", "a", newline="") as csvFile:
fieldnames = [
"RaceID",
"Session",
"Fastest Lap",
"FWing",
"RWing",
"Engine",
"Brakes",
"Gear",
"Suspension",
"Compound",
"Supplier",
"Risk O/D",
"Risk CT",
"Boosts",
"Fuel Start",
"Stop 1 Lap",
"Stop 1 Tyres/Fuel",
"Stop 1 Refuel",
"Stop 1 Time",
"Stop 2 Lap",
"Stop 2 Tyres/Fuel",
"Stop 2 Refuel",
"Stop 2 Time",
"Stop 3 Lap",
"Stop 3 Tyres/Fuel",
"Stop 3 Refuel",
"Stop 3 Time",
"Stop 4 Lap",
"Stop 4 Tyres/Fuel",
"Stop 4 Refuel",
"Stop 4 Time",
"Stop 5 Lap",
"Stop 5 Tyres/Fuel",
"Stop 5 Refuel",
"Stop 5 Time",
"Fuel End",
"Tyres End",
"Finances",
"CHA Level/Start/End",
"ENG Level/Start/End",
"FWI Level/Start/End",
"RWI Level/Start/End",
"UND Level/Start/End",
"SID Level/Start/End",
"COL Level/Start/End",
"GEA Level/Start/End",
"BRA Level/Start/End",
"SUS Level/Start/End",
"ELE Level/Start/End",
"Energy Start",
"Energy End",
"Driver Stats Start",
"Driver Stats Change"
]
logger.info("Writing pre-race data to CSV file")
writer = csv.DictWriter(csvFile, fieldnames=fieldnames)
if len(pastSessionData) == 0:
writer.writeheader()
for sessionDict in sessionDicts:
if not any(session["RaceID"] == sessionDict["RaceID"] and session["Session"] == sessionDict[
"Session"] for session in pastSessionData):
try:
logger.info("Writing session to data file")
writer.writerow(sessionDict)
except Exception:
logger.exception("Unable to write session to data file")
else:
logger.warning("Session already exists in RaceData.csv")
except Exception:
logger.exception(
"Unable to open data file for analysis - file might be open in another application")
warningLabel.set("File error: permission denied")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
elif (raceState == "Post-Race"):
logger.info("Calculating for Post-Race")
# Creating raceID
if (not raceNumber == "1"):
raceNumber = str(int(raceNumber) - 1)
if (len(raceNumber) == 1):
raceNumber = "0" + raceNumber
else:
seasonNumber = str(int(seasonNumber) - 1)
raceNumber = "17"
raceID = "S" + seasonNumber + "R" + raceNumber
# Empty dictionary for the race information
raceDict = {}
# Assign values to the race dictionary - make sure not to bloat the CSV file!
raceDict["RaceID"] = raceID
raceDict["Session"] = "Race"
# Define the race URL and get page data
browser.follow_link(url_regex=re.compile("RaceAnalysis"))
tree = html.fromstring(browser.response().get_data())
browser.back()
# Find setup informaiton
raceSetupSearch = tree.xpath("//td[contains(text(), 'Race')]/../td/text()")
raceSetup = [str(element) for element in raceSetupSearch]
raceSetup.remove("Race")
raceDict["FWing"] = raceSetup[0]
raceDict["RWing"] = raceSetup[1]
raceDict["Engine"] = raceSetup[2]
raceDict["Brakes"] = raceSetup[3]
raceDict["Gear"] = raceSetup[4]
raceDict["Suspension"] = raceSetup[5]
raceDict["Compound"] = raceSetup[6]
# Find race risks
raceRiskSearch = tree.xpath("//th[contains(text(), 'Overtake')]/../../tr[7]/td/text()")
raceRisk = [str(element) for element in raceRiskSearch]
raceDict["Risk O/D"] = str(raceRisk[0]) + "/" + str(raceRisk[1])
raceDict["Risk CT"] = str(raceRisk[2] + "/" + str(raceRisk[3]))
# Tyre supplier
raceDict["Supplier"] = tree.xpath("normalize-space(//img[contains(@src, 'suppliers')]/@title)")
# Find driver stats and changes
raceDriverStatSearch = tree.xpath("//a[contains(@href, 'DriverProfile.asp')]/../../td/text()")
raceDriverChangeSearch = tree.xpath(
"//a[contains(@href, 'DriverProfile.asp')]/../../../tr[4]/td/text()")
raceDriverStats = []
raceDriverChange = []
for element in raceDriverStatSearch:
try:
raceDriverStats.append(re.findall(r"\d+", str(element))[0])
except:
pass
for element in raceDriverChangeSearch:
try:
raceDriverChange.append(re.findall(r"\d+", str(element))[0])
except:
pass
raceDict["Driver Stats Start"] = raceDriverStats
raceDict["Driver Stats Change"] = raceDriverChange
# Find driver energy
raceEnergyStartSearch = tree.xpath(
"normalize-space(//td[contains(@title, 'Before the race')]/div[contains(@class, 'barLabel')]/text())")
raceEnergyEndSearch = tree.xpath(
"normalize-space(//td[contains(@title, 'After the race')]/div[contains(@class, 'barLabel')]/text())")
raceDict["Energy Start"] = raceEnergyStartSearch
raceDict["Energy End"] = raceEnergyEndSearch
# Start and Finish positions
racePositionSearch = tree.xpath("//th[contains(text(), 'Positions')]/../../tr[3]/td/text()")
racePosition = [str(element) for element in racePositionSearch]
raceDict["Start Position"] = racePosition[0]
raceDict["End Position"] = racePosition[1]
# Fastest lap time
raceDict["Fastest Lap"] = tree.xpath(
"normalize-space(//font[contains(@color, 'lime') and contains(text(), ':')]/text())")
# Start fuel
raceFuelStartSearch = tree.xpath("normalize-space(//div[contains(text(), 'Start fuel:')]/b/text())")
raceDict["Fuel Start"] = re.findall(r"\d+", raceFuelStartSearch)[0]
# Stops
raceStopsSearch = tree.xpath("//td[starts-with(text(), 'Stop')]/..//text()")
raceStops = []
for element in raceStopsSearch:
try:
raceStops.append(re.findall(r"[a-zA-Z0-9 \u00a0]+", str(element))[0])
except:
pass
for i in range(len(raceStops) // 7):
raceDict["Stop " + str(i + 1) + " Lap"] = raceStops[(i * 7) + 1]
raceDict["Stop " + str(i + 1) + " Tyres/Fuel"] = str(raceStops[(i * 7) + 3]) + "% / " + str(
raceStops[(i * 7) + 4]) + "%"
raceDict["Stop " + str(i + 1) + " Refuel"] = raceStops[(i * 7) + 5]
raceDict["Stop " + str(i + 1) + " Time"] = raceStops[(i * 7) + 6]
# End condition
raceTyreEndSearch = tree.xpath(
"normalize-space(//p[contains(text(), 'Tyres condition after finish:')]/b//text())")
raceDict["Tyres End"] = raceTyreEndSearch
# End fuel
raceFuelEndSearch = tree.xpath(
"normalize-space(//p[contains(text(), 'Fuel left in the car after finish:')]/b/text())")
raceDict["Fuel End"] = raceFuelEndSearch
# Finances
raceFinancesTotalSearch = tree.xpath(
"normalize-space(//td[contains(text(), 'Total:')]/../td[2]/text())")
raceFinancesBalanceSearch = tree.xpath(
"normalize-space(//td[contains(text(), 'Current balance')]/../td[2]//text())")
raceDict["Finances"] = raceFinancesTotalSearch + " / " + raceFinancesBalanceSearch
# Car parts
raceCarSearch = tree.xpath("//b[contains(text(), 'Cha')]/../../../tr/td/text()")
raceCar = [str(element) for element in raceCarSearch]
raceDict["CHA Level/Start/End"] = str(raceCar[0]) + "/" + str(raceCar[11]) + "/" + str(raceCar[22])
raceDict["ENG Level/Start/End"] = str(raceCar[1]) + "/" + str(raceCar[12]) + "/" + str(raceCar[23])
raceDict["FWI Level/Start/End"] = str(raceCar[2]) + "/" + str(raceCar[13]) + "/" + str(raceCar[24])
raceDict["RWI Level/Start/End"] = str(raceCar[3]) + "/" + str(raceCar[14]) + "/" + str(raceCar[25])
raceDict["UND Level/Start/End"] = str(raceCar[4]) + "/" + str(raceCar[15]) + "/" + str(raceCar[26])
raceDict["SID Level/Start/End"] = str(raceCar[5]) + "/" + str(raceCar[16]) + "/" + str(raceCar[27])
raceDict["COL Level/Start/End"] = str(raceCar[6]) + "/" + str(raceCar[17]) + "/" + str(raceCar[28])
raceDict["GEA Level/Start/End"] = str(raceCar[7]) + "/" + str(raceCar[18]) + "/" + str(raceCar[29])
raceDict["BRA Level/Start/End"] = str(raceCar[8]) + "/" + str(raceCar[19]) + "/" + str(raceCar[30])
raceDict["SUS Level/Start/End"] = str(raceCar[9]) + "/" + str(raceCar[20]) + "/" + str(raceCar[31])
raceDict["ELE Level/Start/End"] = str(raceCar[10]) + "/" + str(raceCar[21]) + "/" + str(raceCar[32])
# Write the data to file
try:
logger.info("Writing pre-race analysis to CSV")
with open("RaceData.csv", "a", newline="") as csvFile:
fieldnames = [
"RaceID",
"Session",
"Fastest Lap",
"FWing",
"RWing",
"Engine",
"Brakes",
"Gear",
"Suspension",
"Compound",
"Supplier",
"Risk O/D",
"Risk CT",
"Boosts",
"Start Position",
"End Position",
"Fuel Start",
"Stop 1 Lap",
"Stop 1 Tyres/Fuel",
"Stop 1 Refuel",
"Stop 1 Time",
"Stop 2 Lap",
"Stop 2 Tyres/Fuel",
"Stop 2 Refuel",
"Stop 2 Time",
"Stop 3 Lap",
"Stop 3 Tyres/Fuel",
"Stop 3 Refuel",
"Stop 3 Time",
"Stop 4 Lap",
"Stop 4 Tyres/Fuel",
"Stop 4 Refuel",
"Stop 4 Time",
"Stop 5 Lap",
"Stop 5 Tyres/Fuel",
"Stop 5 Refuel",
"Stop 5 Time",
"Fuel End",
"Tyres End",
"Finances",
"CHA Level/Start/End",
"ENG Level/Start/End",
"FWI Level/Start/End",
"RWI Level/Start/End",
"UND Level/Start/End",
"SID Level/Start/End",
"COL Level/Start/End",
"GEA Level/Start/End",
"BRA Level/Start/End",
"SUS Level/Start/End",
"ELE Level/Start/End",
"Energy Start",
"Energy End",
"Driver Stats Start",
"Driver Stats Change"
]
logger.info("Writing pre-race data to CSV file")
writer = csv.DictWriter(csvFile, fieldnames=fieldnames)
if len(pastSessionData) == 0:
writer.writeheader()
if not any(session["RaceID"] == raceID and session["Session"] == "Race" for session in
pastSessionData):
try:
logger.info("Writing session to data file")
writer.writerow(raceDict)
except Exception:
logger.exception("Unable to write session to data file")
else:
logger.warning("Session already exists in RaceData.csv")
except Exception:
logger.exception(
"Unable to open data file for analysis - file might be open in another application")
warningLabel.set("File error: permission denied")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
else:
logger.error(
"Unable to get session information, so unable to perform analysis, this shouldn't be possible with radio buttons")
warningLabel.set("Error")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
logger.info("Updating status label to notify user of completed calculations")
warningLabel.set("Updated")
foregroundColour("Status.Label", "#00FF00")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
except Exception:
logger.exception("Something went wrong with calculations, see exception")
def fillWear():
logger.info("Starting fillWear() function")
try:
username = entryUsername.get()
password = entryPassword.get()
if (not checkLogin(username, password)):
logger.warning("Incorrect login details provided by user")
warningLabel.set("Incorrect Login Details")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
# Create our logon payload. 'hiddenToken' may change at a later date.
logger.info("Starting GPRO session for wear fill")
# Logon to GPRO using the logon information provided and store that under our session
browser = mechanize.Browser()
browser.open("https://gpro.net/gb/Login.asp")
browser.select_form(id="Form1")
browser.form["textLogin"] = username
browser.form["textPassword"] = password
browser.submit()
# Request the car information page and scrape the car character and part level and wear data
browser.follow_link(url_regex=re.compile("UpdateCar"))
tree = html.fromstring(browser.response().get_data())
browser.back()
wearlevelChassis.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Chassis')]/../../td[2]/text())")))
wearlevelEngine.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Engine')]/../../td[2]/text())")))
wearlevelFWing.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Front wing')]/../../td[2]/text())")))
wearlevelRWing.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Rear wing')]/../../td[2]/text())")))
wearlevelUnderbody.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Underbody')]/../../td[2]/text())")))
wearlevelSidepods.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Sidepods')]/../../td[2]/text())")))
wearlevelCooling.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Cooling')]/../../td[2]/text())")))
wearlevelGearbox.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Gearbox')]/../../td[2]/text())")))
wearlevelBrakes.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Brakes')]/../../td[2]/text())")))
wearlevelSuspension.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Suspension')]/../../td[2]/text())")))
wearlevelElectronics.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Electronics')]/../../td[2]/text())")))
carWearChassis = str(tree.xpath("normalize-space(//b[contains(text(), 'Chassis')]/../../td[4]/text())"))
if (carWearChassis == ""):
carWearChassis = str(
tree.xpath("normalize-space(//b[contains(text(), 'Chassis')]/../../td[4]/font/text())"))
wearChassis.set(int((re.findall(r"\d+", carWearChassis))[0]))
carWearEngine = str(tree.xpath("normalize-space(//b[contains(text(), 'Engine')]/../../td[4]/text())"))
if (carWearEngine == ""):
carWearEngine = str(tree.xpath("normalize-space(//b[contains(text(), 'Engine')]/../../td[4]/font/text())"))
wearEngine.set(int((re.findall(r"\d+", carWearEngine))[0]))
carWearFrontWing = str(tree.xpath("normalize-space(//b[contains(text(), 'Front wing')]/../../td[4]/text())"))
if (carWearFrontWing == ""):
carWearFrontWing = str(
tree.xpath("normalize-space(//b[contains(text(), 'Front wing')]/../../td[4]/font/text())"))
wearFWing.set(int((re.findall(r"\d+", carWearFrontWing))[0]))
carWearRearWing = str(tree.xpath("normalize-space(//b[contains(text(), 'Rear wing')]/../../td[4]/text())"))
if (carWearRearWing == ""):
carWearRearWing = str(
tree.xpath("normalize-space(//b[contains(text(), 'Rear wing')]/../../td[4]/font/text())"))
wearRWing.set(int((re.findall(r"\d+", carWearRearWing))[0]))
carWearUnderbody = str(tree.xpath("normalize-space(//b[contains(text(), 'Underbody')]/../../td[4]/text())"))
if (carWearUnderbody == ""):
carWearUnderbody = str(
tree.xpath("normalize-space(//b[contains(text(), 'Underbody')]/../../td[4]/font/text())"))
wearUnderbody.set(int((re.findall(r"\d+", carWearUnderbody))[0]))
carWearSidepod = str(tree.xpath("normalize-space(//b[contains(text(), 'Sidepods')]/../../td[4]/text())"))
if (carWearSidepod == ""):
carWearSidepod = str(
tree.xpath("normalize-space(//b[contains(text(), 'Sidepods')]/../../td[4]/font/text())"))
wearSidepods.set(int((re.findall(r"\d+", carWearSidepod))[0]))
carWearCooling = str(tree.xpath("normalize-space(//b[contains(text(), 'Cooling')]/../../td[4]/text())"))
if (carWearCooling == ""):
carWearCooling = str(
tree.xpath("normalize-space(//b[contains(text(), 'Cooling')]/../../td[4]/font/text())"))
wearCooling.set(int((re.findall(r"\d+", carWearCooling))[0]))
carWearGears = str(tree.xpath("normalize-space(//b[contains(text(), 'Gearbox')]/../../td[4]/text())"))
if (carWearGears == ""):
carWearGears = str(tree.xpath("normalize-space(//b[contains(text(), 'Gearbox')]/../../td[4]/font/text())"))
wearGearbox.set(int((re.findall(r"\d+", carWearGears))[0]))
carWearBrakes = str(tree.xpath(r"normalize-space(//b[contains(text(), 'Brakes')]/../../td[4]/text())"))
if (carWearBrakes == ""):
carWearBrakes = str(tree.xpath("normalize-space(//b[contains(text(), 'Brakes')]/../../td[4]/font/text())"))
wearBrakes.set(int((re.findall(r"\d+", carWearBrakes))[0]))
carWearSuspension = str(tree.xpath("normalize-space(//b[contains(text(), 'Suspension')]/../../td[4]/text())"))
if (carWearSuspension == ""):
carWearSuspension = str(
tree.xpath("normalize-space(//b[contains(text(), 'Suspension')]/../../td[4]/font/text())"))
wearSuspension.set(int((re.findall(r"\d+", carWearSuspension))[0]))
carWearElectronics = str(tree.xpath("normalize-space(//b[contains(text(), 'Electronics')]/../../td[4]/text())"))
if (carWearElectronics == ""):
carWearElectronics = str(
tree.xpath("normalize-space(//b[contains(text(), 'Electronics')]/../../td[4]/font/text())"))
wearElectronics.set(int((re.findall(r"\d+", carWearElectronics))[0]))
except Exception:
logger.exception("Unable to fill wear, see exception for details")
def fillProfile():
logger.info("Starting fillProfile() function")
try:
username = entryUsername.get()
password = entryPassword.get()
if (not checkLogin(username, password)):
logger.warning("Incorrect login details provided by user")
warningLabel.set("Incorrect Login Details")
foregroundColour("Status.Label", "Red")
root.after(1000, lambda: foregroundColour("Status.Label", "Black"))
return
# Logon to GPRO using the logon information provided and store that under our session
browser = mechanize.Browser()
browser.open("https://gpro.net/gb/Login.asp")
browser.select_form(id="Form1")
browser.form["textLogin"] = username
browser.form["textPassword"] = password
browser.submit()
# Request the car information page and scrape the car character and part level and wear data
browser.follow_link(url_regex=re.compile("UpdateCar"))
tree = html.fromstring(browser.response().get_data())
browser.back()
profilelevelChassis.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Chassis')]/../../td[2]/text())")))
profilelevelEngine.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Engine')]/../../td[2]/text())")))
profilelevelFWing.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Front wing')]/../../td[2]/text())")))
profilelevelRWing.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Rear wing')]/../../td[2]/text())")))
profilelevelUnderbody.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Underbody')]/../../td[2]/text())")))
profilelevelSidepods.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Sidepods')]/../../td[2]/text())")))
profilelevelCooling.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Cooling')]/../../td[2]/text())")))
profilelevelGearbox.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Gearbox')]/../../td[2]/text())")))
profilelevelBrakes.set(int(tree.xpath("normalize-space(//b[contains(text(), 'Brakes')]/../../td[2]/text())")))
profilelevelSuspension.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Suspension')]/../../td[2]/text())")))
profilelevelElectronics.set(
int(tree.xpath("normalize-space(//b[contains(text(), 'Electronics')]/../../td[2]/text())")))
profilePowerTotal.set(
int(tree.xpath("normalize-space(//td[contains(text(), 'Power')]/../../tr[3]/td[1]/text())")))
profileHandlingTotal.set(
int(tree.xpath("normalize-space(//td[contains(text(), 'Power')]/../../tr[3]/td[2]/text())")))
profileAccelerationTotal.set(
int(tree.xpath("normalize-space(//td[contains(text(), 'Power')]/../../tr[3]/td[3]/text())")))
partNames = ["Chassis", "Engine", "Front Wing", "Rear Wing", "Underbody", "Sidepods", "Cooling", "Gearbox",
"Brakes", "Suspension", "Electronics"]
for i in range(len(PHA) - 1):
profile = profileCalc(partNames[i], profilePartLevels[i].get())
for j in range(len(PHA[i])):
PHA[i][j].set(round(profile[j], 2))
PTotal = 0
HTotal = 0
ATotal = 0
for i in range(len(PHA) - 1):
PTotal += PHA[i][0].get()
HTotal += PHA[i][1].get()
ATotal += PHA[i][2].get()
PParts.set(int(round(PTotal, 0)))
HParts.set(int(round(HTotal, 0)))
AParts.set(int(round(ATotal, 0)))
profileTestingPower.set(int(profilePowerTotal.get()) - int(PParts.get()))
profileTestingHandling.set(int(profileHandlingTotal.get()) - int(HParts.get()))
profileTestingAcceleration.set(int(profileAccelerationTotal.get()) - int(AParts.get()))
except Exception:
logger.exception("Unable to fill car character profile information - see exception for details")
def validateFloat(P):
if (P == ""):
return True
else:
try:
int(P)
return True
except:
try:
float(P)
return True
except:
return False
def validateInt(P):
if (P == ""):
return True
else:
try:
int(P)
return True
except:
return False
def foregroundColour(styleName, colourName):
style.configure(styleName, foreground=colourName)
# Create the root window
root = Tk()
root.title("GAPP")
vcmdInt = root.register(validateInt)
vcmdFloat = root.register(validateFloat)
# Create the tab controller
notebook = Autoresized_Notebook(root)