-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmain.py
923 lines (792 loc) · 33.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
'''
The main file that runs the programs loop.
'''
# Uncomment for debugging (main function includes a count for how many startup took)
# import sys
# calls = 0
# def trace(frame, event, arg):
# global calls
# if event == "call":
# filename = frame.f_code.co_filename
# if "Python" not in filename and "frozen" not in filename and "string" not in filename:
# lineno = frame.f_lineno
# # Here I'm printing the file and line number,
# # but you can examine the frame, locals, etc too.
# print("%s @ %s" % (filename, lineno))
# calls += 1
# return trace
#
# sys.settrace(trace)
# Check if the user is using python 3.12 or over
import sys
if sys.version_info[0] == 3 and sys.version_info[1] >= 12:
print(f"Python 3.12 or over detected ({sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}). This version is not supported yet. Please use Python 3.11 or lower.")
print("\n! To uninstall Python 3.12.x go to the windows apps and features page and search for python. ! ")
print("\nYou can download python 3.11.8 from this link: https://www.python.org/downloads/release/python-3118/ -> Scroll Down -> Windows installer (64-bit)")
input("\nPress enter to exit the app...")
sys.exit()
# Change from tkwebview2 to our custom version
import os
import threading
doRestart = False
def CheckTkWebview2InstallVersion():
global doRestart
def ChangeVer():
global doRestart
print(" -- Changing tkwebview2 version -- ")
os.system("pip uninstall -y tkwebview2")
os.system("pip install git+https://github.com/Tumppi066/tkwebview2.git")
print(" -- Restarting -- ")
input("Press enter to exit the app, please restart after...")
doRestart = True
try:
try:
import pkg_resources
except ImportError:
os.system("pip install pkg_resources")
ver = pkg_resources.get_distribution('tkwebview2').version
if ver != "0.1":
ChangeVer()
except:
ChangeVer()
import time
from src.logger import print
import src.variables as variables
def CheckAnomalousFrames():
try:
size_limit = 50 * 1024 * 1024 # 50 MB
path = os.path.join(variables.PATH, "anomalousFrames")
if os.path.exists(path):
remove_files = 0
total_size = 0
files = sorted(os.listdir(path), key=lambda x: os.path.getmtime(os.path.join(path, x)))
for file in files:
file_path = os.path.join(path, file)
file_size = os.path.getsize(file_path)
if total_size > size_limit:
os.remove(file_path)
remove_files += 1
total_size += file_size
freed_space_mb = round(total_size / 1048576, 2)
print(f"Removed {remove_files} anomalous frame logs. ({freed_space_mb}MB)")
except:
print(f"Unable to delete anomalous frame logs. Please delete them manually from the folder: {path}")
threading.Thread(target=CheckAnomalousFrames, daemon=True).start()
def CheckUltralyticsPackage():
try:
print(f"Checking the version of the 'ultralytics' package...")
import subprocess
RED = "\033[91m"
NORMAL = "\033[0m"
PATH = variables.PATH
if PATH.endswith("\\") or PATH.endswith("/"):
PATH = PATH[:-1]
PATH = os.path.dirname(PATH) + "\\"
result = subprocess.run("cd " + PATH + "venv/Scripts & .\\activate.bat & cd " + PATH + " & pip list", shell=True, capture_output=True, text=True)
modules = result.stdout
for module in modules.splitlines():
if "ultralytics " in module:
version = str(module.replace(" ", "").replace("ultralytics", ""))
if version in "8.3.41 8.3.42 8.3.45 8.3.46":
print(RED + f"Your installed version of the 'ultralytics' package contains a crypto miner! Trying to remove it... (Package Version: {version})" + NORMAL)
subprocess.run("cd " + PATH + "venv\\Scripts & " + PATH + "venv\\Scripts\\activate.bat & cd " + PATH + " & pip uninstall ultralytics -y & pip cache purge & pip install ultralytics", shell=True)
SendCrashReport("Successfully updated the 'ultralytics' package. (Crypto miner problem!)", "Successfull!")
else:
print(f"No problems with your installed version of the 'ultralytics' package. (Package Version: {version})")
except:
SendCrashReport("Update Ultralytics package error. (Crypto miner problem!)", traceback.format_exc())
print(RED + f"Unable to check the version of the 'ultralytics' package. Please update your 'ultralytics' package manually if you have one of these versions installed: 8.3.41, 8.3.42, 8.3.45, 8.3.46" + NORMAL)
CheckUltralyticsPackage()
thread = threading.Thread(target=CheckTkWebview2InstallVersion)
thread.start()
thread.join()
if doRestart:
sys.exit()
# hide pygame welcome message before importing pygame
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
try:
import cv2
except:
# Numpy is 2.0.0 and not compatible with opencv-python
print("Detected numpy 2... Installing numpy 1.26.4...")
os.system("pip install numpy==1.26.4 --force-reinstall")
print("Installed numpy 1.26.4. Please restart the app.")
import hashlib
import keyboard
import importlib
import traceback
import tkinter as tk
from tkinter import ttk
import progress.bar as Bar
import src.mainUI as mainUI
import src.logger as logger
import src.updater as updater
import src.console as console
import src.helpers as helpers
from tkinter import messagebox
import src.controls as controls
import src.settings as settings
import src.translator as translator
import src.scsLogReader as LogReader
from src.server import SendCrashReport, Ping
import plugins.MSSScreenCapture.main as MSSScreenCapture
try:
import importlib_metadata
except:
os.system("pip install importlib_metadata")
import importlib_metadata
if settings.GetSettings("User Interface", "hide_console", False) == True:
console.HideConsole()
# Check tkinter tcl version
tcl = tk.Tcl()
acceptedVersions = ["8.6.11", "8.6.12", "8.6.13"]
version = str(tcl.call('info', 'patchlevel'))
if version not in acceptedVersions:
messagebox.showwarning("Warning", f"Your tkinter version ({version} is not >= 8.6.11) is too old. Windows scaling will be broken with this version.")
print(f"Your tkinter version ({version} is not >= 8.6.11) is too old. Windows scaling will be broken with this version.")
# Load the UI framework
mainUI.CreateRoot()
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
mainUI.root.update()
try:
if "DXCamScreenCapture" in settings.GetSettings("Plugins", "Enabled"):
settings.RemoveFromList("Plugins", "Enabled", "DXCamScreenCapture")
settings.AddToList("Plugins", "Enabled", "BetterCamScreenCapture")
except: pass
listOfRequirementsAddedLater = ["colorama", "bettercam", "matplotlib", "pywebview", "vdf", "deep-translator", "Babel"]
listOfRequirementsAddedLater = [i.replace("-", "_") for i in listOfRequirementsAddedLater]
# Get list of installed modules using importlib
installed = [i.name for i in importlib_metadata.distributions()]
installed = [i.replace("-", "_") for i in installed]
installed = [i.split("==")[0] for i in installed]
requirementsset = set(listOfRequirementsAddedLater)
installedset = set(installed)
missing = requirementsset - installedset
if missing:
for modules in missing:
print("installing" + " " + modules)
os.system("pip install" + " " + modules)
# Check that all requirements from requirements.txt are installed
versions = {}
with open(variables.PATH + r"\requirements.txt") as f:
requirements = f.read().splitlines()
requirements = [i.replace("-", "_") for i in requirements]
for requirement in requirements:
if "==" in requirement:
name, version = requirement.split("==")
versions[name] = version
requirements[requirements.index(requirement)] = name
installed = [i.name for i in importlib_metadata.distributions()]
installed = [i.replace("-", "_") for i in installed]
installed = [i.split("==")[0] for i in installed]
requirementsset = set(requirements)
installedset = set(installed)
missing = requirementsset - installedset
if missing:
for module in missing:
if "--upgrade --no-cache-dir gdown" in module:
pass
elif "sv_ttk" in module:
pass
elif "playsound2" in module:
os.system("pip uninstall -y playsound")
os.system("pip install playsound2")
else:
if module in versions:
print("installing" + " " + module + "==" + versions[module])
os.system("pip install" + " " + module + "==" + versions[module])
else:
print("installing" + " " + module)
os.system("pip install" + " " + module)
else:
pass
# Ping server
helpers.RunEvery(60, lambda: Ping())
logger.printDebug = settings.GetSettings("logger", "debug")
if logger.printDebug == None:
logger.printDebug = False
settings.CreateSettings("logger", "debug", False)
def GetEnabledPlugins():
global enabledPlugins
enabledPlugins = settings.GetSettings("Plugins", "Enabled")
if enabledPlugins == None:
enabledPlugins = [""]
panels = []
def FindPlugins(reloadFully=False):
global plugins
global panels
global pluginObjects
global pluginNames
global splash
try:
mainUI.root.update()
hasRoot = True
except:
hasRoot = False
closeAfter = False
if hasRoot:
try:
if splash == None:
closeAfter = True
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
closeAfter = True
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
# Update the list of plugins and panels for the hash check
pluginNames = GetListOfAllPluginAndPanelNames()
# Find plugins
path = os.path.join(variables.PATH, "plugins")
plugins = []
panels = []
count = len(os.listdir(path))
index = 0
for file in os.listdir(path):
if hasRoot:
splash.updateProgress(text=f"Loading plugins... {count-index} remaining.", step=2 + (index / count))
mainUI.root.update()
index += 1
if os.path.isdir(os.path.join(path, file)):
# Check for main.py
if "main.py" in os.listdir(os.path.join(path, file)):
# Check for PluginInformation class
try:
pluginPath = "plugins." + file + ".main"
plugin = __import__(pluginPath, fromlist=["PluginInformation"])
if plugin.PluginInfo.type == "dynamic":
if plugin.PluginInfo.name in enabledPlugins:
plugins.append(plugin.PluginInfo)
else:
panels.append(__import__("plugins." + plugin.PluginInfo.name + ".main", fromlist=["UI", "PluginInfo"]))
except Exception as ex:
print(str(ex.args) + f" [{file}]")
pass
pluginObjects = []
for plugin in plugins:
pluginObjects.append(__import__("plugins." + plugin.name + ".main", fromlist=["plugin", "UI", "PluginInfo", "onEnable"]))
pluginObjects[-1].onEnable()
if closeAfter and hasRoot:
splash.close()
del splash
def ReloadPluginCode():
keybinds = controls.ReadKeybindsVariable()
FindPlugins()
controls.WriteKeybindsVariable(keybinds)
# Use the inbuilt python modules to reload the code of the plugins
with Bar.PixelBar("Reloading plugins...", max=len(pluginObjects)) as progressBar:
for plugin in pluginObjects:
try:
importlib.reload(plugin)
except Exception as ex:
print(ex.args)
pass
progressBar.next()
with Bar.PixelBar("Reloading panels...", max=len(panels)) as progressBar:
for panel in panels:
try:
importlib.reload(panel)
except Exception as ex:
print(ex.args)
pass
progressBar.next()
print("Reloading UI root code...")
try:
mainUI.DeleteRoot()
importlib.reload(mainUI)
mainUI.CreateRoot()
mainUI.drawButtons()
except Exception as ex:
print(ex.args)
pass
MSSScreenCapture.CreateCamera()
MSSScreenCapture.monitor = None
print("Reloaded UI root code.")
def RunOnEnable():
for plugin in pluginObjects:
try:
plugin.onEnable()
except Exception as ex:
print(ex.args)
pass
def UpdatePlugins(dynamicOrder, data):
for plugin in pluginObjects:
try:
if plugin.PluginInfo.dynamicOrder == dynamicOrder:
startTime = time.time()
pluginData = plugin.plugin(data)
if pluginData != None:
data = pluginData
else:
print(f"Plugin '{plugin.PluginInfo.name}' returned NoneType instead of a the data variable. Please make sure that you return the data variable.")
endTime = time.time()
data["executionTimes"][plugin.PluginInfo.name] = endTime - startTime
except Exception as ex:
print(ex.args[0] + f"[{plugin.PluginInfo.name}]")
pass
return data
def GetListOfAllPluginAndPanelNames():
# Find plugins
path = os.path.join(variables.PATH, "plugins")
plugins = []
for file in os.listdir(path):
if os.path.isdir(os.path.join(path, file)):
# Check for main.py
if "main.py" in os.listdir(os.path.join(path, file)):
# Check for PluginInformation class
try:
pluginName = file
plugins.append(pluginName)
except Exception as ex:
print(ex.args)
pass
return plugins
pluginNames = GetListOfAllPluginAndPanelNames()
def InstallPlugins():
global startInstall
global splash
list = settings.GetSettings("Plugins", "Installed")
if list == None:
settings.CreateSettings("Plugins", "Installed", [])
# Find plugins
path = os.path.join(variables.PATH, "plugins")
installers = []
pluginNames = []
for file in os.listdir(path):
if os.path.isdir(os.path.join(path, file)):
# Check for main.py
if "main.py" in os.listdir(os.path.join(path, file)):
# Check for PluginInformation class
try:
# Get installers for plugins that are not installed
if file not in settings.GetSettings("Plugins", "Installed"):
pluginPath = "plugins." + file + ".install"
try:
pluginNames.append(f"{file}")
installers.append(__import__(pluginPath, fromlist=["install"]))
except: # No installer
pass
except Exception as ex:
print(ex.args)
pass
if installers == []:
return
wasSplash = False
try:
splash.close()
del splash
wasSplash = True
except:
pass
# Create a new tab for the installer
installFrame = ttk.Frame(mainUI.pluginNotebook, width=600, height=520)
installFrame.pack(anchor=tk.CENTER, expand=True, fill=tk.BOTH)
mainUI.pluginNotebook.add(installFrame, text="Plugin Installer")
mainUI.pluginNotebook.select(mainUI.pluginNotebook.tabs()[-1])
ttk.Label(installFrame, text="The app has detected plugins that have not yet been installed.").pack()
ttk.Label(installFrame, text="Please install them before continuing.").pack()
ttk.Label(installFrame, text="").pack()
ttk.Label(installFrame, text="WARNING: Make sure you trust the authors of the plugins.").pack()
ttk.Label(installFrame, text="If you are at all skeptical then you can see the install script at").pack()
ttk.Label(installFrame, text="app/plugins/<plugin name>/installer.py").pack()
ttk.Label(installFrame, text="").pack()
startInstall = False
def SetInstallToTrue():
global startInstall
startInstall = True
ttk.Button(installFrame, text="Install plugins", command=lambda: SetInstallToTrue()).pack()
ttk.Label(installFrame, text="").pack()
ttk.Label(installFrame, text="The following plugins require installation: ").pack()
# Make tk list object
listbox = tk.Listbox(installFrame, width=75, height=30)
listbox.pack()
# Add the plugins there
for plugin in pluginNames:
listbox.insert(tk.END, plugin)
# Center the listbox text
listbox.config(justify=tk.CENTER)
while not startInstall:
try:
mainUI.root.update()
except:
mainUI.CreateRoot()
mainUI.drawButtons()
mainUI.root.update()
# Destroy all the widgets
for child in installFrame.winfo_children():
child.destroy()
# Create the progress indicators
ttk.Label(installFrame, text="\n\n\n\n\n\n\n").pack()
currentPlugin = tk.StringVar(installFrame)
currentPlugin.set("Installing plugins...")
ttk.Label(installFrame, textvariable=currentPlugin).pack()
bar = ttk.Progressbar(installFrame, orient=tk.HORIZONTAL, length=200, mode='determinate')
bar.pack(pady=15)
percentage = tk.StringVar(installFrame)
ttk.Label(installFrame, textvariable=percentage).pack()
ttk.Label(installFrame, text="").pack()
ttk.Label(installFrame, text="This may take a while...").pack()
ttk.Label(installFrame, text="For more information check the console.").pack()
mainUI.root.update()
index = 0
with Bar.PixelBar("Installing plugins...", max=len(installers)) as progressBar:
for installer, name in zip(installers, pluginNames):
sys.stdout.write(f"\nInstalling '{name}'...\n")
currentPlugin.set(f"Installing '{name}'...")
bar.config(value=(index / len(installers)) * 100)
percentage.set(f"{round((index / len(installers)) * 100)}%")
mainUI.root.update()
try:
installer.install()
settings.AddToList("Plugins", "Installed", name.split(" - ")[0])
except:
print(f"Warning. Failed to install '{name}' fully! The plugin might still work though.")
pass
index += 1
os.system("cls")
progressBar.next()
# Destroy all the widgets
for child in installFrame.winfo_children():
child.destroy()
# Remove the tab
settings.RemoveFromList("Plugins", "OpenTabs", "Plugin Installer")
variables.RELOADPLUGINS = True
if wasSplash:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
InstallPlugins()
def CheckForONNXRuntimeChange():
global splash
change = settings.GetSettings("SwitchLaneDetectionDevice", "switchTo")
if change != None:
try:
if not splash or splash == None:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
try:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
pass
if change == "GPU":
try: splash.updateProgress(text="Uninstalling ONNX...")
except: pass
os.system("pip uninstall onnxruntime -y")
try: splash.updateProgress(text="Installing ONNX GPU...")
except: pass
os.system("pip install onnxruntime-gpu")
else:
try: splash.updateProgress(text="Uninstalling ONNX GPU...")
except: pass
os.system("pip uninstall onnxruntime-gpu -y")
try: splash.updateProgress(text="Installing ONNX...")
except: pass
os.system("pip install onnxruntime")
settings.CreateSettings("SwitchLaneDetectionDevice", "switchTo", None)
def CheckLastKnownVersion():
lastVersion = settings.GetSettings("User Interface", "version")
if lastVersion == None:
settings.UpdateSettings("User Interface", "version", variables.VERSION)
mainUI.switchSelectedPlugin("plugins.Changelog.main")
return
if lastVersion != variables.VERSION:
settings.UpdateSettings("User Interface", "version", variables.VERSION)
mainUI.switchSelectedPlugin("plugins.Changelog.main")
return
def CloseAllPlugins():
for plugin in pluginObjects:
plugin.onDisable()
del plugin
timesLoaded = 0
def LoadApplication():
global mainUI
global uiUpdateRate
global timesLoaded
global splash
if timesLoaded > 0:
try:
mainUI.DeleteRoot()
del mainUI
import src.mainUI as mainUI
mainUI.CreateRoot()
except:
pass
try:
if splash == None:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
pass
try:
mainUI.root.update()
except:
mainUI.CreateRoot()
timesLoaded += 1
CheckForONNXRuntimeChange()
# Check for new plugin installs
InstallPlugins()
useSplash = True
try:
if splash == None:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
try:
splash = helpers.SplashScreen(mainUI.root, totalSteps=4)
splash.updateProgress(text="Initializing...", step=1)
except:
useSplash = False
# Load all plugins
if useSplash: splash.updateProgress(text="Loading plugins...", step=2)
GetEnabledPlugins()
FindPlugins()
if useSplash: splash.updateProgress(text="Initializing plugins...", step=3)
RunOnEnable()
if useSplash: splash.updateProgress(text="Finishing...", step=4)
logger.printDebug = settings.GetSettings("logger", "debug")
if logger.printDebug == None:
logger.printDebug = False
settings.CreateSettings("logger", "debug", False)
# We've loaded all necessary modules
showCopyrightInTitlebar = settings.GetSettings("User Interface", "TitleCopyright")
if showCopyrightInTitlebar == None:
settings.CreateSettings("User Interface", "TitleCopyright", True)
showCopyrightInTitlebar = True
mainUI.titlePath = "- " + open(settings.currentProfile, "r").readline().replace("\n", "") + " "
mainUI.UpdateTitle()
mainUI.root.update()
mainUI.drawButtons()
if useSplash: splash.close()
if useSplash: del splash
uiUpdateRate = settings.GetSettings("User Interface", "updateRate")
if uiUpdateRate == None:
uiUpdateRate = 0
settings.CreateSettings("User Interface", "updateRate", 0)
CheckLastKnownVersion()
# Show the root window
mainUI.root.deiconify()
helpers.ShowPopup("\nFound " + str(len(GetListOfAllPluginAndPanelNames())) + " plugins!", "Backend", timeout=3)
LoadApplication()
lastChecksums = {}
def CheckForFileChanges():
"""Will check the plugin main files for changes and reload them if they've changed."""
global lastChecksums
# Check if it's the first time running this function
if lastChecksums == {}:
for plugin in pluginNames:
try:
checksum = hashlib.md5(open(os.path.join(variables.PATH, "plugins", plugin, "main.py"), "rb").read()).hexdigest()
lastChecksums[plugin] = checksum
except:
pass
return
# Check for changes in the plugins
for plugin in pluginNames:
try:
checksum = hashlib.md5(open(os.path.join(variables.PATH, "plugins", plugin, "main.py"), "rb").read()).hexdigest()
if checksum != lastChecksums[plugin]:
print(f"Detected changes in {plugin}...")
ReloadPluginCode()
RunOnEnable()
variables.RELOADPLUGINS = False
variables.RELOAD = False # Already reloaded
lastChecksums[plugin] = checksum
break
except:
pass
# Check for updates
updater.UpdateChecker()
data = {}
uiFrameTimer = 0
pluginChangeTimer = time.time()
lastEnableValue = False
if __name__ == "__main__":
# print(f"Starting took {calls} calls.") # Uncomment for debugging along with the one at the top of the file
while True:
# Main Application Loop
try:
allStart = time.time()
# Remove "last" from the data and set it as this frame's "last"
try:
data.pop("last")
data = {
"last": data,
"executionTimes": {}
}
except Exception as ex:
data = {
"last": {},
"executionTimes": {}
}
if variables.RELOADPLUGINS:
print("Reloading plugins...")
ReloadPluginCode()
RunOnEnable()
variables.RELOADPLUGINS = False
variables.RELOAD = False # Already reloaded
if variables.RELOAD:
print("Reloading application...")
# Reset the open tabs
settings.UpdateSettings("User Interface", "OpenTabs", [])
LoadApplication()
variables.RELOAD = False
# Update the input manager.
controlsStartTime = time.time()
data = controls.plugin(data)
controlsEndTime = time.time()
data["executionTimes"]["Control callbacks"] = controlsEndTime - controlsStartTime
# Check for plugin changes (every second)
pluginChangeTime = time.time()
if time.time() - pluginChangeTimer > 1:
pluginChangeTimer = time.time()
CheckForFileChanges()
pluginChangeEndTime = time.time()
data["executionTimes"]["Filesystem Check"] = pluginChangeEndTime - pluginChangeTime
# Check for log file changes
logCheckTime = time.time()
data = LogReader.plugin(data)
logCheckEndTime = time.time()
data["executionTimes"]["Log Check"] = logCheckEndTime - logCheckTime
try:
if variables.APPENDDATANEXTFRAME != None or variables.APPENDDATANEXTFRAME != [] or variables.APPENDDATANEXTFRAME != {} or variables.APPENDDATANEXTFRAME != "":
# Merge the two dictionaries
data.update(variables.APPENDDATANEXTFRAME)
variables.APPENDDATANEXTFRAME = None
except: pass
if variables.UPDATEPLUGINS:
GetEnabledPlugins()
FindPlugins()
variables.UPDATEPLUGINS = False
for runner in helpers.runners:
# [duration, function, time.time(), args, kwargs]
duration, function, lastRun, args, kwargs = runner
if time.time() - lastRun > duration:
try:
function(*args, **kwargs)
except Exception as ex:
print(ex.args)
helpers.runners.remove(runner)
start = time.time()
popupCount = 0
for popup in helpers.popups:
try:
popup.update(popupCount)
popupCount += 1
except:
try:
popup.destroy()
except:
pass
helpers.popups.remove(popup)
popupCount = 0
for popup in helpers.timeoutlessPopups:
try:
popup.update(popupCount)
popupCount += 1
except:
try:
popup.destroy()
except:
pass
helpers.timeoutlessPopups.remove(popup)
end = time.time()
data["executionTimes"]["Popups"] = end - start
if variables.ENABLELOOP != lastEnableValue:
lastEnableValue = variables.ENABLELOOP
helpers.ShowPopup("\nThe main loop is now " + ("enabled" if variables.ENABLELOOP else "disabled") + "!", "Backend", timeout=2)
# Enable / Disable the main loop
if variables.ENABLELOOP == False:
start = time.time()
mainUI.update(data)
end = time.time()
data["executionTimes"]["UI"] = end - start
data = UpdatePlugins("last", data)
allEnd = time.time()
data["executionTimes"]["all"] = allEnd - allStart
try:
cv2.destroyWindow("Lane Assist")
except:
pass
try:
cv2.destroyWindow('Traffic Light Detection - Final')
except:
pass
try:
cv2.destroyWindow('Traffic Light Detection - B/W')
except:
pass
try:
cv2.destroyWindow('Traffic Light Detection - Position Estimation')
except:
pass
try:
cv2.destroyWindow('TruckStats')
except:
pass
variables.FRAMECOUNTER += 1
continue
data = UpdatePlugins("before image capture", data)
data = UpdatePlugins("image capture", data)
data = UpdatePlugins("before lane detection", data)
data = UpdatePlugins("lane detection", data)
data = UpdatePlugins("before controller", data)
data = UpdatePlugins("controller", data)
data = UpdatePlugins("before game", data)
data = UpdatePlugins("game", data)
data = UpdatePlugins("before UI", data)
# Calculate the execution time of the UI
start = time.time()
uiFrameTimer += 1
if uiFrameTimer > uiUpdateRate:
mainUI.update(data)
uiFrameTimer = 0
end = time.time()
data["executionTimes"]["UI"] = end - start
data = UpdatePlugins("last", data)
# And then the entire app
allEnd = time.time()
data["executionTimes"]["all"] = allEnd - allStart
# Check if the frame took more than 200ms (5fps)
if (allEnd - allStart) - data["executionTimes"]["UI"] > 0.2:
print(f"Frame took {round((allEnd - allStart) * 1000)}ms to execute!")
# Check if the anomalousFrames folder exists
if not os.path.exists(os.path.join(variables.PATH, "anomalousFrames")):
os.mkdir(os.path.join(variables.PATH, "anomalousFrames"))
# Save a new text file with the data
with open(os.path.join(variables.PATH, "anomalousFrames", f"{time.time()}.txt"), "w") as f:
# Go throught each key and try and write it
for key in data:
try:
f.write(f"{key}: {data[key]}\n")
except:
pass
variables.FRAMECOUNTER += 1
except Exception as ex:
try:
if settings.GetSettings("User Interface", "hide_console") == True:
console.RestoreConsole()
except:
pass
if ex.args != ('The main window has been closed.', 'If you closed the app this is normal.'):
# Press the F1 key to pause the game
keyboard.press_and_release("F1")
exc = traceback.format_exc()
traceback.print_exc()
# Get the user name
username = os.getlogin()
# Send a crash report
SendCrashReport("Main loop crash.", exc.replace(username, "censored"))
if not messagebox.askretrycancel("Error", translator.Translate("The application has encountered an error in the main thread!\nPlease either retry execution or close the application (cancel)!\n\n") + exc):
break
else:
pass
else:
CloseAllPlugins()
try:
if settings.GetSettings("User Interface", "hide_console") == True:
console.CloseConsole()
except:
pass
break