From e4d572965d1b8b97adba6c48564f84a1bf47d957 Mon Sep 17 00:00:00 2001 From: Stefan Date: Tue, 25 Feb 2025 21:18:25 +0200 Subject: [PATCH 1/7] thread handling improvements, seperate file for constants, async improvements, better error handling --- BabbleApp/babbleapp.py | 100 +++++++++++++++++++++++-------------- BabbleApp/camera_widget.py | 4 ++ BabbleApp/constants.py | 19 +++++++ BabbleApp/requirements.txt | 4 +- 4 files changed, 88 insertions(+), 39 deletions(-) create mode 100644 BabbleApp/constants.py diff --git a/BabbleApp/babbleapp.py b/BabbleApp/babbleapp.py index 883a48a..637085f 100644 --- a/BabbleApp/babbleapp.py +++ b/BabbleApp/babbleapp.py @@ -36,6 +36,7 @@ from notification_manager import NotificationManager from utils.misc_utils import ensurePath, os_type, bg_color_highlight, bg_color_clear from lang_manager import LocaleStringManager as lang from logger import setup_logging +from constants import UIConstants, AppConstants winmm = None @@ -80,9 +81,17 @@ async def check_for_updates(config, notification_manager): if config.settings.gui_update_check: try: response = requests.get( - "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest" + "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest", + timeout=10 # Add timeout ) - latestversion = response.json()["name"] + response.raise_for_status() # Will raise exception for HTTP errors + + data = response.json() + latestversion = data.get("name") + + if not latestversion: + print(f'[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("babble.invalidVersionFormat")}') + return if appversion == latestversion: print( @@ -93,10 +102,30 @@ async def check_for_updates(config, notification_manager): f'\033[93m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.needUpdateOne")} [{appversion}] {lang._instance.get_string("babble.needUpdateTwo")} [{latestversion}] {lang._instance.get_string("babble.needUpdateThree")}.\033[0m' ) await notification_manager.show_notification(appversion, latestversion, page_url) + except requests.exceptions.Timeout: + print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateTimeout")}') + except requests.exceptions.HTTPError as e: + print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateHttpError")}: {e}') + except requests.exceptions.ConnectionError: + print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}') except Exception as e: - print( - f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}. Error: {e}' - ) + print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}') +class ThreadManager: + def __init__(self): + self.threads = [] + + def add_thread(self, thread): + self.threads.append(thread) + thread.start() + + def shutdown_all(self): + for thread in self.threads: + if hasattr(thread, 'shutdown') and callable(thread.shutdown): + thread.shutdown() + + for thread in self.threads: + if thread.is_alive(): + thread.join() async def async_main(): ensurePath() @@ -124,10 +153,12 @@ async def async_main(): timerResolution(True) + thread_manager = ThreadManager() + osc_queue: queue.Queue[tuple[bool, int, int]] = queue.Queue(maxsize=10) osc = VRChatOSC(cancellation_event, osc_queue, config) osc_thread = threading.Thread(target=osc.run) - osc_thread.start() + thread_manager.add_thread(osc_thread) cams = [ CameraWidget(Tab.CAM, config, osc_queue), @@ -217,59 +248,50 @@ async def async_main(): if config.settings.gui_ROSC: osc_receiver = VRChatOSCReceiver(cancellation_event, config, cams) osc_receiver_thread = threading.Thread(target=osc_receiver.run) - osc_receiver_thread.start() + thread_manager.add_thread(osc_receiver_thread) ROSC = True # Create the window window = sg.Window( - f"{appversion}", layout, icon="Images/logo.ico", background_color=bg_color_clear + f"{AppConstants.VERSION}", layout, icon="Images/logo.ico", background_color=bg_color_clear ) + + # Run the main loop + await main_loop(window, config, cams, settings, cancellation_event) + + # Cleanup after main loop exits + timerResolution(False) + print(f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m') - tint = 33 +async def main_loop(window, config, cams, settings, cancellation_event): + tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH fs = False + while True: - # First off, check for any events from the GUI event, values = window.read(timeout=tint) - - # If we're in either mode and someone hits q, quit immediately + if event in ("Exit", sg.WIN_CLOSED): - for ( - cam - ) in ( - cams - ): # yes we only have one cam page but im just gonna leave this incase + # Exit code here + for cam in cams: cam.stop() cancellation_event.set() - # shut down worker threads - osc_thread.join() - # TODO: find a way to have this function run on join maybe?? - # threading.Event() wont work because pythonosc spawns its own thread. - # only way i can see to get around this is an ugly while loop that only checks if a threading event is triggered - # and then call the pythonosc shutdown function - if ROSC: - osc_receiver.shutdown() - osc_receiver_thread.join() - timerResolution(False) - print( - f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m' - ) return - + try: # If window isn't in focus increase timeout and stop loop early if window.TKroot.focus_get(): if fs: fs = False - tint = 33 - window["-WINFOCUS-"].update(visible=False) - window["-WINFOCUS-"].hide_row() + tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH + window[UIConstants.WINDOW_FOCUS_KEY].update(visible=False) + window[UIConstants.WINDOW_FOCUS_KEY].hide_row() window.refresh() else: if not fs: fs = True - tint = 100 - window["-WINFOCUS-"].update(visible=True) - window["-WINFOCUS-"].unhide_row() + tint = AppConstants.UNFOCUSED_WINDOW_REFRESH + window[UIConstants.WINDOW_FOCUS_KEY].update(visible=True) + window[UIConstants.WINDOW_FOCUS_KEY].unhide_row() continue except KeyError: pass @@ -336,6 +358,10 @@ async def async_main(): if setting.started(): setting.render(window, event, values) + # Rather than await asyncio.sleep(0), yield control periodically + await asyncio.sleep(0.001) # Small sleep to allow other tasks to rundef main(): + asyncio.run(async_main()) + def main(): asyncio.run(async_main()) diff --git a/BabbleApp/camera_widget.py b/BabbleApp/camera_widget.py index 82be261..1d8f833 100644 --- a/BabbleApp/camera_widget.py +++ b/BabbleApp/camera_widget.py @@ -419,6 +419,10 @@ class CameraWidget: if event == self.gui_autoroi: print(lang._instance.get_string("info.setROI")) + if self.maybe_image is None: + # Skip rendering or use a default/placeholder image + return # Or handle appropriately + output = self.maybe_image[0].shape self.config.roi_window_x = 0 self.config.roi_window_y = 0 diff --git a/BabbleApp/constants.py b/BabbleApp/constants.py new file mode 100644 index 0000000..7cf79bc --- /dev/null +++ b/BabbleApp/constants.py @@ -0,0 +1,19 @@ +# New file with constants +class UIConstants: + WINDOW_NAME = "Babble App" + CAM_NAME = "-CAMWIDGET-" + SETTINGS_NAME = "-SETTINGSWIDGET-" + ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-" + CALIB_SETTINGS_NAME = "-CALIBSETTINGSWIDGET-" + CAM_RADIO_NAME = "-CAMRADIO-" + SETTINGS_RADIO_NAME = "-SETTINGSRADIO-" + ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-" + CALIB_SETTINGS_RADIO_NAME = "-CALIBSETTINGSRADIO-" + WINDOW_FOCUS_KEY = "-WINFOCUS-" + +class AppConstants: + VERSION = "Babble v2.0.7" + GITHUB_REPO_URL = "https://github.com/Project-Babble/ProjectBabble/releases/latest" + GITHUB_API_URL = "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest" + DEFAULT_WINDOW_FOCUS_REFRESH = 33 + UNFOCUSED_WINDOW_REFRESH = 100 \ No newline at end of file diff --git a/BabbleApp/requirements.txt b/BabbleApp/requirements.txt index 514038f..26a69c1 100644 --- a/BabbleApp/requirements.txt +++ b/BabbleApp/requirements.txt @@ -1,6 +1,6 @@ -onnxruntime==1.19.2; +onnxruntime==1.20.1; onnxruntime-directml==1.19.2; platform_system == "Windows" -onnxruntime-gpu==1.19.2; platform_system == "Linux" +onnxruntime-gpu==1.20.1; platform_system == "Linux" torch==2.6.0; torchvision==0.21.0; opencv_python==4.11.0.86; From 3dc0d098b3dd0243ab66d68d2b9ac90ddea09a5e Mon Sep 17 00:00:00 2001 From: Stefan Date: Wed, 26 Feb 2025 14:02:43 +0200 Subject: [PATCH 2/7] Fix #98: fixed onnxruntime versions and error messages. --- BabbleApp/Locale/Afrikaans/locale.json | 4 ++++ BabbleApp/Locale/Dansk/locale.json | 4 ++++ BabbleApp/Locale/Deutsch/locale.json | 4 ++++ BabbleApp/Locale/English/locale.json | 4 ++++ BabbleApp/Locale/Español/locale.json | 4 ++++ BabbleApp/Locale/Française/locale.json | 4 ++++ BabbleApp/Locale/Indonesian/locale.json | 4 ++++ BabbleApp/Locale/Italiano/locale.json | 4 ++++ BabbleApp/Locale/Nederlands/locale.json | 4 ++++ BabbleApp/Locale/OwO/locale.json | 4 ++++ BabbleApp/Locale/Pirate Speak/locale.json | 4 ++++ BabbleApp/Locale/Polski/locale.json | 4 ++++ BabbleApp/Locale/Pусский/locale.json | 4 ++++ BabbleApp/Locale/Svenska/locale.json | 4 ++++ BabbleApp/Locale/简体中文/locale.json | 4 ++++ BabbleApp/Locale/繁體中文/locale.json | 4 ++++ BabbleApp/babbleapp.py | 3 +-- "BabbleApp/eval \"$(ssh-agent -s)\"" | 8 ++++++++ "BabbleApp/eval \"$(ssh-agent -s)\".pub" | 1 + BabbleApp/requirements.txt | 4 ++-- 20 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\"" create mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\".pub" diff --git a/BabbleApp/Locale/Afrikaans/locale.json b/BabbleApp/Locale/Afrikaans/locale.json index 7b14763..578ab31 100644 --- a/BabbleApp/Locale/Afrikaans/locale.json +++ b/BabbleApp/Locale/Afrikaans/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo Settings", "babble.calibrationPage": "Calibration", "babble.exit": "Exiting Babble App", + "babble.invalidVersionFormat": "Invalid version format received from GitHub API.", + "babble.updateTimeout": "Timeout occurred while checking for updates.", + "babble.updateHttpError": "HTTP error occurred while checking for updates.", + "babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.", "calibration.header": "Calibration Settings", "calibration.mode": "Calibration Mode", "calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.", diff --git a/BabbleApp/Locale/Dansk/locale.json b/BabbleApp/Locale/Dansk/locale.json index b3021ba..42ae38a 100644 --- a/BabbleApp/Locale/Dansk/locale.json +++ b/BabbleApp/Locale/Dansk/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo Settings", "babble.calibrationPage": "Calibration", "babble.exit": "Exiting Babble App", + "babble.invalidVersionFormat": "Invalid version format received from GitHub API.", + "babble.updateTimeout": "Timeout occurred while checking for updates.", + "babble.updateHttpError": "HTTP error occurred while checking for updates.", + "babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.", "calibration.header": "Calibration Settings", "calibration.mode": "Calibration Mode", "calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.", diff --git a/BabbleApp/Locale/Deutsch/locale.json b/BabbleApp/Locale/Deutsch/locale.json index 1446985..82db9c6 100644 --- a/BabbleApp/Locale/Deutsch/locale.json +++ b/BabbleApp/Locale/Deutsch/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo-Einstellungen", "babble.calibrationPage": "Kalibrierung", "babble.exit": "Babble-App wird beendet", + "babble.invalidVersionFormat": "Ungültiges Versionsformat von der GitHub API empfangen.", + "babble.updateTimeout": "Timeout aufgetreten beim Prüfen auf Updates.", + "babble.updateHttpError": "HTTP-Fehler aufgetreten beim Prüfen auf Updates.", + "babble.updateCheckFailed": "Fehler beim Prüfen auf Updates wegen eines unerwarteten Fehlers.", "calibration.header": "Kalibrierung", "calibration.mode": "Kalibrierungs-Modus", "calibration.modeTooltip": "Neutral = Beim Starten und Stoppen der Kalibrierung werden nur Mindestwerte festgelegt. Voll = Beim Starten der Kalibrierung werden Mindest- und Höchstwerte basierend auf den aufgezeichneten Werten festgelegt.", diff --git a/BabbleApp/Locale/English/locale.json b/BabbleApp/Locale/English/locale.json index 1740732..d1f452c 100644 --- a/BabbleApp/Locale/English/locale.json +++ b/BabbleApp/Locale/English/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Also Settings", "babble.calibrationPage": "Calibration", "babble.exit": "Exiting Babble App", + "babble.invalidVersionFormat": "Invalid version format received from GitHub API.", + "babble.updateTimeout": "Timeout occurred while checking for updates.", + "babble.updateHttpError": "HTTP error occurred while checking for updates.", + "babble.updateCheckFailed": "Failed to check for updates due to an unexpected error.", "calibration.header": "Calibration Settings", "calibration.mode": "Calibration Mode", "calibration.modeTooltip": "Neutral = Only Min values are set when starting and stopping calibration. Full = Min and Max values are set based on recorded values when starting calibration.", diff --git a/BabbleApp/Locale/Español/locale.json b/BabbleApp/Locale/Español/locale.json index 763d95e..a8eb782 100644 --- a/BabbleApp/Locale/Español/locale.json +++ b/BabbleApp/Locale/Español/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Ajustes de Algoritmo", "babble.calibrationPage": "Calibración", "babble.exit": "Saliendo de la App Babble", + "babble.invalidVersionFormat": "Formato de versión inválido recibido de la API de GitHub.", + "babble.updateTimeout": "Se produjo un timeout al verificar actualizaciones.", + "babble.updateHttpError": "Se produjo un error HTTP al verificar actualizaciones.", + "babble.updateCheckFailed": "No se pudieron verificar las actualizaciones debido a un error inesperado.", "calibration.header": "Configuración de Calibración", "calibration.mode": "Modo de Calibración", "calibration.modeTooltip": "Neutral = Solo se establecen los valores mínimos al iniciar y detener la calibración. Completa = Se establecen los valores Mín y Máx en base a los valores registrados al iniciar la calibración.", diff --git a/BabbleApp/Locale/Française/locale.json b/BabbleApp/Locale/Française/locale.json index b7342b5..c2a4744 100644 --- a/BabbleApp/Locale/Française/locale.json +++ b/BabbleApp/Locale/Française/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Paramètres d'algorithme", "babble.calibrationPage": "Calibration", "babble.exit": "Sortie de l'application Babble", + "babble.invalidVersionFormat": "Format de version invalide reçu de l'API GitHub.", + "babble.updateTimeout": "Délai d'attente dépassé lors de la vérification des mises à jour.", + "babble.updateHttpError": "Erreur HTTP lors de la vérification des mises à jour.", + "babble.updateCheckFailed": "Échec de la vérification des mises à jour en raison d'une erreur inattendue.", "calibration.header": "Paramètres de calibration", "calibration.mode": "Mode de calibration", "calibration.modeTooltip": "Neutre = Seulement les valeurs minimales sont appliquées au démarrage et à l'arrêt de la calibration. Entière = Les valeurs minimales et maximales sont appliquées en fonction des valeurs enregistrées au début de la calibration.", diff --git a/BabbleApp/Locale/Indonesian/locale.json b/BabbleApp/Locale/Indonesian/locale.json index 32139ce..7db87a5 100644 --- a/BabbleApp/Locale/Indonesian/locale.json +++ b/BabbleApp/Locale/Indonesian/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Pengaturan Algo", "babble.calibrationPage": "Kalibrasi", "babble.exit": "Tutup App Babble", + "babble.invalidVersionFormat": "Format versi tidak valid diterima dari API GitHub.", + "babble.updateTimeout": "Waktu tunggu habis saat memeriksa pembaruan.", + "babble.updateHttpError": "Kesalahan HTTP saat memeriksa pembaruan.", + "babble.updateCheckFailed": "Pemeriksaan pembaruan gagal karena kesalahan yang tidak terduga.", "calibration.header": "Pengaturan Kalibrasi", "calibration.mode": "Mode Kalibrasi", "calibration.modeTooltip": "Neutral = Hanya nilai Min ditentukan ketika mulai dan berhenti kalibrasi. Full = Nilai Min dan Maks menjadi dasar nilai yang terekam ketika memulai kalibrasi.", diff --git a/BabbleApp/Locale/Italiano/locale.json b/BabbleApp/Locale/Italiano/locale.json index c7308fd..0299a18 100644 --- a/BabbleApp/Locale/Italiano/locale.json +++ b/BabbleApp/Locale/Italiano/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Impostazioni Algoritmo", "babble.calibrationPage": "Calibrazione", "babble.exit": "Uscendo Dall'App Babble", + "babble.invalidVersionFormat": "Formato versione non valido ricevuto dall'API GitHub.", + "babble.updateTimeout": "Timeout superato durante la verifica degli aggiornamenti.", + "babble.updateHttpError": "Errore HTTP durante la verifica degli aggiornamenti.", + "babble.updateCheckFailed": "Verifica degli aggiornamenti non riuscita a causa di un errore imprevisto.", "calibration.header": "Impostazioni Calibrazione", "calibration.mode": "Modalità Calibrazione", "calibration.modeTooltip": "Neutrale = Vengono impostati solo i valori minimi all'avvio e all'arresto della calibrazione. Completo = Valori minimi e massimi sono impostati in base ai valori registrati quando si inizia la calibrazione.", diff --git a/BabbleApp/Locale/Nederlands/locale.json b/BabbleApp/Locale/Nederlands/locale.json index 8c891f2..7a75833 100644 --- a/BabbleApp/Locale/Nederlands/locale.json +++ b/BabbleApp/Locale/Nederlands/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo Instellingen", "babble.calibrationPage": "Kalibratie", "babble.exit": "Babble App Verlaten", + "babble.invalidVersionFormat": "Ongeldig versieformaat ontvangen van de GitHub API.", + "babble.updateTimeout": "Time-out opgetreden bij het controleren op updates.", + "babble.updateHttpError": "HTTP-fout bij het controleren op updates.", + "babble.updateCheckFailed": "Controleren op updates mislukt vanwege een onverwachte fout.", "calibration.header": "Kalibratie-Instellingen", "calibration.mode": "Kalibratie-Modus", "calibration.modeTooltip": "Neutraal = Alleen Min waardes zijn ingesteld bij het starten en stoppen van de kalibratie. Volledig = Min en Max waardes zijn ingesteld d.m.v opgenomen waardes bij het starten van de kalibratie", diff --git a/BabbleApp/Locale/OwO/locale.json b/BabbleApp/Locale/OwO/locale.json index ca97dec..109c698 100644 --- a/BabbleApp/Locale/OwO/locale.json +++ b/BabbleApp/Locale/OwO/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "awgo settings :3", "babble.calibrationPage": "cawibwation OwO", "babble.exit": "Qwiting Babble App~ Nyaa~", + "babble.invalidVersionFormat": "Invawid vewsion fowmat weceived fwom the GitHub API nya~", + "babble.updateTimeout": "Timeout occuwwed while checking fow updates UwU", + "babble.updateHttpError": "HTTP ewwow occuwwed while checking fow updates >w<", + "babble.updateCheckFailed": "Fwailed to check fow updates due to an unexpected ewwow :3", "calibration.header": "cawibwation Settings >w<", "calibration.mode": "cawibwation Mode nya~", "calibration.modeTooltip": "neutwaw = onwy min vawues awe set when stawting and stopping cawibwation. fuww = min and max vawues awe set based on wecowded vawues when stawting cawibwation. :3", diff --git a/BabbleApp/Locale/Pirate Speak/locale.json b/BabbleApp/Locale/Pirate Speak/locale.json index cbac74d..5db64c3 100644 --- a/BabbleApp/Locale/Pirate Speak/locale.json +++ b/BabbleApp/Locale/Pirate Speak/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo Riggin's", "babble.calibrationPage": "Calibration", "babble.exit": "Exiting Babble App", + "babble.invalidVersionFormat": "Arrr! GitHub API's sent us a crooked version map that makes no sense.", + "babble.updateTimeout": "Blast! Our hunt fer booty updates ran out o' time on the high seas.", + "babble.updateHttpError": "Shiver me timbers! An HTTP error struck while scoutin' fer fresh booty.", + "babble.updateCheckFailed": "Yo-ho-ho! The update check be marooned by an unexpected squall.", "calibration.header": "Calibration Riggin's", "calibration.mode": "Calibration Mode", "calibration.modeTooltip": "Neutral = Only Min values be set when startin' and stoppin' calibration. Full = Min and Max values be set based on recorded values when startin' calibration.", diff --git a/BabbleApp/Locale/Polski/locale.json b/BabbleApp/Locale/Polski/locale.json index 601dd44..2ad6644 100644 --- a/BabbleApp/Locale/Polski/locale.json +++ b/BabbleApp/Locale/Polski/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Ustawienia algorytmu", "babble.calibrationPage": "Kalibracja", "babble.exit": "Wychodzenie z aplikacji", + "babble.invalidVersionFormat": "Nieprawidłowy format wersji otrzymany z GitHub API.", + "babble.updateTimeout": "Przekroczono limit czasu podczas sprawdzania aktualizacji.", + "babble.updateHttpError": "Wystąpił błąd HTTP podczas sprawdzania aktualizacji.", + "babble.updateCheckFailed": "Nie udało się sprawdzić aktualizacji z powodu nieoczekiwanego błędu.", "calibration.header": "Ustawienia kalibracji", "calibration.mode": "Tryb kalibracji", "calibration.modeTooltip": "Neutralna = Tylko Minimalne wartości są ustawiane podczas rozpoczynania i zakańczania kalibracji. Pełna = Minimalne I maksymalne wartości są ustawione na podstawie zapisanych wartości podczas kalibracji.", diff --git a/BabbleApp/Locale/Pусский/locale.json b/BabbleApp/Locale/Pусский/locale.json index aa63406..f51248c 100644 --- a/BabbleApp/Locale/Pусский/locale.json +++ b/BabbleApp/Locale/Pусский/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Настройки алгоритма", "babble.calibrationPage": "Калибровка", "babble.exit": "Выход из приложения Babble", + "babble.invalidVersionFormat": "Получен недопустимый формат версии от GitHub API.", + "babble.updateTimeout": "Произошло превышение времени ожидания при проверке обновлений.", + "babble.updateHttpError": "При проверке обновлений произошла HTTP-ошибка.", + "babble.updateCheckFailed": "Не удалось проверить обновления из-за непредвиденной ошибки.", "calibration.header": "Настройки калибровки", "calibration.mode": "Режим калибровки", "calibration.modeTooltip": "Нейтральный = Устанавливаются только минимальные значения при начале и завершении калибровки. Полный = Устанавливаются минимальные и максимальные значения на основе записанных данных при начале калибровки.", diff --git a/BabbleApp/Locale/Svenska/locale.json b/BabbleApp/Locale/Svenska/locale.json index 8bf1857..f922f57 100644 --- a/BabbleApp/Locale/Svenska/locale.json +++ b/BabbleApp/Locale/Svenska/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "Algo Inställningar", "babble.calibrationPage": "Kalibrering", "babble.exit": "Babble Avslutas", + "babble.invalidVersionFormat": "Ogiltigt versionsformat mottaget från GitHub API.", + "babble.updateTimeout": "Tidsgräns överskreds vid sökning efter uppdateringar.", + "babble.updateHttpError": "HTTP-fel inträffade vid sökning efter uppdateringar.", + "babble.updateCheckFailed": "Misslyckades med att söka efter uppdateringar på grund av ett oväntat fel.", "calibration.header": "Kalibreringsinställningar", "calibration.mode": "Kalibreringsläge", "calibration.modeTooltip": "Neutralt = Endast Min värden är inställda vid kalibrering. Full = Min och Max värden är inställda baserat på tidigare sparade värden vid kalibrering.", diff --git a/BabbleApp/Locale/简体中文/locale.json b/BabbleApp/Locale/简体中文/locale.json index b63884f..3731e3b 100644 --- a/BabbleApp/Locale/简体中文/locale.json +++ b/BabbleApp/Locale/简体中文/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "算法设定", "babble.calibrationPage": "校准", "babble.exit": "退出Babble", + "babble.invalidVersionFormat": "从 GitHub API 接收到的版本格式无效。", + "babble.updateTimeout": "检查更新时发生了超时。", + "babble.updateHttpError": "检查更新时发生了 HTTP 错误。", + "babble.updateCheckFailed": "由于意外错误,检查更新失败。", "calibration.header": "校准设定", "calibration.mode": "校准模式", "calibration.modeTooltip": "中性:开始和停止校准时仅设置最小值。\n完整:开始校准时根据记录值设置最小值和最大值", diff --git a/BabbleApp/Locale/繁體中文/locale.json b/BabbleApp/Locale/繁體中文/locale.json index 5d1427a..c15db25 100644 --- a/BabbleApp/Locale/繁體中文/locale.json +++ b/BabbleApp/Locale/繁體中文/locale.json @@ -130,6 +130,10 @@ "babble.algoSettingsPage": "演算法設定", "babble.calibrationPage": "校正", "babble.exit": "結束 Babble App", + "babble.invalidVersionFormat": "從 GitHub API 接收到的版本格式無效。", + "babble.updateTimeout": "檢查更新時發生超時。", + "babble.updateHttpError": "檢查更新時發生 HTTP 錯誤。", + "babble.updateCheckFailed": "由於意外錯誤,無法檢查更新。", "calibration.header": "校正設定", "calibration.mode": "校正模式", "calibration.modeTooltip": "自然校正 = 僅在開始和停止校正時設定最小值。完整校正 = 根據開始校正時記錄的數值設定最小值和最大值。", diff --git a/BabbleApp/babbleapp.py b/BabbleApp/babbleapp.py index 637085f..10a25d8 100644 --- a/BabbleApp/babbleapp.py +++ b/BabbleApp/babbleapp.py @@ -253,8 +253,7 @@ async def async_main(): # Create the window window = sg.Window( - f"{AppConstants.VERSION}", layout, icon="Images/logo.ico", background_color=bg_color_clear - ) + f"{AppConstants.VERSION}", layout, icon=os.path.join('Images', 'logo.ico'), background_color=bg_color_clear ) # Run the main loop await main_loop(window, config, cams, settings, cancellation_event) diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\"" "b/BabbleApp/eval \"$(ssh-agent -s)\"" new file mode 100644 index 0000000..0529181 --- /dev/null +++ "b/BabbleApp/eval \"$(ssh-agent -s)\"" @@ -0,0 +1,8 @@ +-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQAAAKh2VWFWdlVh +VgAAAAtzc2gtZWQyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQ +AAAEAqGnMaqJSLYiFu1OaDjA54UuZHOtyDLJzm2wXqcE2WCEvRT99R7ddDn3KYxXS6A9Fa +JlnOzjp7/BTLbBaI2wI1AAAAIHN0ZWZhbi5lYXN0bWFuLmdpbmRpbGFAZ21haWwuY29tAQ +IDBAU= +-----END OPENSSH PRIVATE KEY----- diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\".pub" "b/BabbleApp/eval \"$(ssh-agent -s)\".pub" new file mode 100644 index 0000000..ddc27eb --- /dev/null +++ "b/BabbleApp/eval \"$(ssh-agent -s)\".pub" @@ -0,0 +1 @@ +ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEvRT99R7ddDn3KYxXS6A9FaJlnOzjp7/BTLbBaI2wI1 stefan.eastman.gindila@gmail.com diff --git a/BabbleApp/requirements.txt b/BabbleApp/requirements.txt index 26a69c1..514038f 100644 --- a/BabbleApp/requirements.txt +++ b/BabbleApp/requirements.txt @@ -1,6 +1,6 @@ -onnxruntime==1.20.1; +onnxruntime==1.19.2; onnxruntime-directml==1.19.2; platform_system == "Windows" -onnxruntime-gpu==1.20.1; platform_system == "Linux" +onnxruntime-gpu==1.19.2; platform_system == "Linux" torch==2.6.0; torchvision==0.21.0; opencv_python==4.11.0.86; From 5bb5b0b396ed5c0a27f581b6e972a7d25515300c Mon Sep 17 00:00:00 2001 From: Stefan Date: Wed, 26 Feb 2025 14:13:46 +0200 Subject: [PATCH 3/7] Add sensitive files to .gitignore --- BabbleApp/.gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/BabbleApp/.gitignore b/BabbleApp/.gitignore index 397b4a7..fb801e1 100644 --- a/BabbleApp/.gitignore +++ b/BabbleApp/.gitignore @@ -1 +1,3 @@ *.log +eval/id_rsa +eval/id_rsa.pub From 0d96b7880ac80967b6045384c6e9874971cb0814 Mon Sep 17 00:00:00 2001 From: Stefan Eastman <78572090+BigMrLemon@users.noreply.github.com> Date: Wed, 26 Feb 2025 14:15:50 +0200 Subject: [PATCH 4/7] Delete BabbleApp/eval "$(ssh-agent -s)" --- "BabbleApp/eval \"$(ssh-agent -s)\"" | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\"" diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\"" "b/BabbleApp/eval \"$(ssh-agent -s)\"" deleted file mode 100644 index 0529181..0000000 --- "a/BabbleApp/eval \"$(ssh-agent -s)\"" +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW -QyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQAAAKh2VWFWdlVh -VgAAAAtzc2gtZWQyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQ -AAAEAqGnMaqJSLYiFu1OaDjA54UuZHOtyDLJzm2wXqcE2WCEvRT99R7ddDn3KYxXS6A9Fa -JlnOzjp7/BTLbBaI2wI1AAAAIHN0ZWZhbi5lYXN0bWFuLmdpbmRpbGFAZ21haWwuY29tAQ -IDBAU= ------END OPENSSH PRIVATE KEY----- From 799ebf705cc0c4033dd84df806964ab18a1ce527 Mon Sep 17 00:00:00 2001 From: Stefan Eastman <78572090+BigMrLemon@users.noreply.github.com> Date: Wed, 26 Feb 2025 14:16:04 +0200 Subject: [PATCH 5/7] Delete BabbleApp/eval "$(ssh-agent -s)".pub --- "BabbleApp/eval \"$(ssh-agent -s)\".pub" | 1 - 1 file changed, 1 deletion(-) delete mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\".pub" diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\".pub" "b/BabbleApp/eval \"$(ssh-agent -s)\".pub" deleted file mode 100644 index ddc27eb..0000000 --- "a/BabbleApp/eval \"$(ssh-agent -s)\".pub" +++ /dev/null @@ -1 +0,0 @@ -ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEvRT99R7ddDn3KYxXS6A9FaJlnOzjp7/BTLbBaI2wI1 stefan.eastman.gindila@gmail.com From 810aec1ce5d58036f083b45e8cfa3856710b0bc1 Mon Sep 17 00:00:00 2001 From: Stefan Date: Thu, 27 Feb 2025 15:09:58 +0200 Subject: [PATCH 6/7] Fix Project-Babble#98: Remove duplicate constants and update references to UIConstants/AppConstants + Improve thread management for better stability and shutdown handling --- BabbleApp/babbleapp.py | 139 +++++++++++++---------- "BabbleApp/eval \"$(ssh-agent -s)\"" | 8 -- "BabbleApp/eval \"$(ssh-agent -s)\".pub" | 1 - 3 files changed, 77 insertions(+), 71 deletions(-) delete mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\"" delete mode 100644 "BabbleApp/eval \"$(ssh-agent -s)\".pub" diff --git a/BabbleApp/babbleapp.py b/BabbleApp/babbleapp.py index 10a25d8..1bcb9e5 100644 --- a/BabbleApp/babbleapp.py +++ b/BabbleApp/babbleapp.py @@ -52,17 +52,6 @@ os.system("color") # init ANSI color # Random environment variable to speed up webcam opening on the MSMF backend. # https://github.com/opencv/opencv/issues/17687 os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0" - -WINDOW_NAME = "Babble App" -CAM_NAME = "-CAMWIDGET-" -SETTINGS_NAME = "-SETTINGSWIDGET-" -ALGO_SETTINGS_NAME = "-ALGOSETTINGSWIDGET-" -CALIB_SETTINGS_NAME = "-CALIBSETTINGSWIDGET-" -CAM_RADIO_NAME = "-CAMRADIO-" -SETTINGS_RADIO_NAME = "-SETTINGSRADIO-" -ALGO_SETTINGS_RADIO_NAME = "-ALGOSETTINGSRADIO-" -CALIB_SETTINGS_RADIO_NAME = "-CALIBSETTINGSRADIO-" - page_url = "https://github.com/Project-Babble/ProjectBabble/releases/latest" appversion = "Babble v2.0.7" @@ -102,6 +91,7 @@ async def check_for_updates(config, notification_manager): f'\033[93m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.needUpdateOne")} [{appversion}] {lang._instance.get_string("babble.needUpdateTwo")} [{latestversion}] {lang._instance.get_string("babble.needUpdateThree")}.\033[0m' ) await notification_manager.show_notification(appversion, latestversion, page_url) + except requests.exceptions.Timeout: print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateTimeout")}') except requests.exceptions.HTTPError as e: @@ -109,23 +99,48 @@ async def check_for_updates(config, notification_manager): except requests.exceptions.ConnectionError: print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}') except Exception as e: - print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}') + print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}') + class ThreadManager: - def __init__(self): - self.threads = [] - - def add_thread(self, thread): - self.threads.append(thread) + def __init__(self, cancellation_event): + """Initialize ThreadManager with a cancellation event for signaling threads.""" + self.threads = [] # List of (thread, shutdown_obj) tuples + self.cancellation_event = cancellation_event + self.logger = logging.getLogger("ThreadManager") + + def add_thread(self, thread, shutdown_obj=None): + """Add a thread and its optional shutdown object to the manager.""" + self.threads.append((thread, shutdown_obj)) thread.start() - - def shutdown_all(self): - for thread in self.threads: - if hasattr(thread, 'shutdown') and callable(thread.shutdown): - thread.shutdown() - - for thread in self.threads: + self.logger.debug(f"Started thread: {thread.name}") + + def shutdown_all(self, timeout=5.0): + """Shutdown all managed threads with a configurable timeout.""" + self.logger.info("Initiiating shutdown of all threads") + self.cancellation_event.set() # Signal all threads to stop + + # Call shutdown methods on associated objects if available + for thread, shutdown_obj in self.threads: + if shutdown_obj and hasattr(shutdown_obj, 'shutdown') and callable(shutdown_obj.shutdown): + try: + self.logger.debug(f"Calling shutdown on {shutdown_obj}") + shutdown_obj.shutdown() + except Exception as e: + self.logger.error(f"Error shutting down {shutdown_obj}: {e}") + + # Join threads with the specified timeout + for thread, _ in self.threads: if thread.is_alive(): - thread.join() + self.logger.debug(f"Joining thread: {thread.name} with timeout {timeout}s") + thread.join(timeout=timeout) + + # Remove terminated threads from the list + self.threads = [(t, s) for t, s in self.threads if t.is_alive()] + + if self.threads: + self.logger.warning(f"{len(self.threads)} threads still alive: {[t.name for t, _ in self.threads]}") + else: + self.logger.info("All threads terminated successfully") async def async_main(): ensurePath() @@ -153,13 +168,12 @@ async def async_main(): timerResolution(True) - thread_manager = ThreadManager() + thread_manager = ThreadManager(cancellation_event) osc_queue: queue.Queue[tuple[bool, int, int]] = queue.Queue(maxsize=10) osc = VRChatOSC(cancellation_event, osc_queue, config) - osc_thread = threading.Thread(target=osc.run) - thread_manager.add_thread(osc_thread) - + osc_thread = threading.Thread(target=osc.run, name="OSCThread") + thread_manager.add_thread(osc_thread, shutdown_obj=osc) cams = [ CameraWidget(Tab.CAM, config, osc_queue), ] @@ -177,56 +191,56 @@ async def async_main(): "TABSELECTRADIO", background_color=bg_color_clear, default=(config.cam_display_id == Tab.CAM), - key=CAM_RADIO_NAME, + key=UIConstants.CAM_RADIO_NAME, ), sg.Radio( lang._instance.get_string("babble.settingsPage"), "TABSELECTRADIO", background_color=bg_color_clear, default=(config.cam_display_id == Tab.SETTINGS), - key=SETTINGS_RADIO_NAME, + key=UIConstants.SETTINGS_RADIO_NAME, ), sg.Radio( lang._instance.get_string("babble.algoSettingsPage"), "TABSELECTRADIO", background_color=bg_color_clear, default=(config.cam_display_id == Tab.ALGOSETTINGS), - key=ALGO_SETTINGS_RADIO_NAME, + key=UIConstants.ALGO_SETTINGS_RADIO_NAME, ), sg.Radio( lang._instance.get_string("babble.calibrationPage"), "TABSELECTRADIO", background_color=bg_color_clear, default=(config.cam_display_id == Tab.CALIBRATION), - key=CALIB_SETTINGS_RADIO_NAME, + key=UIConstants.CALIB_SETTINGS_RADIO_NAME, ), ], [ sg.Column( cams[0].widget_layout, vertical_alignment="top", - key=CAM_NAME, + key=UIConstants.CAM_NAME, visible=(config.cam_display_id in [Tab.CAM]), background_color=bg_color_highlight, ), sg.Column( settings[0].widget_layout, vertical_alignment="top", - key=SETTINGS_NAME, + key=UIConstants.SETTINGS_NAME, visible=(config.cam_display_id in [Tab.SETTINGS]), background_color=bg_color_highlight, ), sg.Column( settings[1].widget_layout, vertical_alignment="top", - key=ALGO_SETTINGS_NAME, + key=UIConstants.ALGO_SETTINGS_NAME, visible=(config.cam_display_id in [Tab.ALGOSETTINGS]), background_color=bg_color_highlight, ), sg.Column( settings[2].widget_layout, vertical_alignment="top", - key=CALIB_SETTINGS_NAME, + key=UIConstants.CALIB_SETTINGS_NAME, visible=(config.cam_display_id in [Tab.CALIBRATION]), background_color=bg_color_highlight, ), @@ -247,8 +261,8 @@ async def async_main(): # the cam needs to be running before it is passed to the OSC if config.settings.gui_ROSC: osc_receiver = VRChatOSCReceiver(cancellation_event, config, cams) - osc_receiver_thread = threading.Thread(target=osc_receiver.run) - thread_manager.add_thread(osc_receiver_thread) + osc_receiver_thread = threading.Thread(target=osc_receiver.run, name="OSCReceiverThread") + thread_manager.add_thread(osc_receiver_thread, shutdown_obj=osc_receiver) ROSC = True # Create the window @@ -256,13 +270,13 @@ async def async_main(): f"{AppConstants.VERSION}", layout, icon=os.path.join('Images', 'logo.ico'), background_color=bg_color_clear ) # Run the main loop - await main_loop(window, config, cams, settings, cancellation_event) + await main_loop(window, config, cams, settings, thread_manager) # Cleanup after main loop exits timerResolution(False) print(f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m') -async def main_loop(window, config, cams, settings, cancellation_event): +async def main_loop(window, config, cams, settings, thread_manager): tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH fs = False @@ -273,7 +287,8 @@ async def main_loop(window, config, cams, settings, cancellation_event): # Exit code here for cam in cams: cam.stop() - cancellation_event.set() + thread_manager.shutdown_all() + window.close() return try: @@ -295,57 +310,57 @@ async def main_loop(window, config, cams, settings, cancellation_event): except KeyError: pass - if values[CAM_RADIO_NAME] and config.cam_display_id != Tab.CAM: + if values[UIConstants.CAM_RADIO_NAME] and config.cam_display_id != Tab.CAM: cams[0].start() settings[0].stop() settings[1].stop() settings[2].stop() - window[CAM_NAME].update(visible=True) - window[SETTINGS_NAME].update(visible=False) - window[ALGO_SETTINGS_NAME].update(visible=False) - window[CALIB_SETTINGS_NAME].update(visible=False) + window[UIConstants.CAM_NAME].update(visible=True) + window[UIConstants.SETTINGS_NAME].update(visible=False) + window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False) + window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False) config.cam_display_id = Tab.CAM config.save() - elif values[SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.SETTINGS: + elif values[UIConstants.SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.SETTINGS: cams[0].stop() settings[1].stop() settings[2].stop() settings[0].start() - window[CAM_NAME].update(visible=False) - window[SETTINGS_NAME].update(visible=True) - window[ALGO_SETTINGS_NAME].update(visible=False) - window[CALIB_SETTINGS_NAME].update(visible=False) + window[UIConstants.CAM_NAME].update(visible=False) + window[UIConstants.SETTINGS_NAME].update(visible=True) + window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False) + window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False) config.cam_display_id = Tab.SETTINGS config.save() elif ( - values[ALGO_SETTINGS_RADIO_NAME] + values[UIConstants.ALGO_SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.ALGOSETTINGS ): cams[0].stop() settings[0].stop() settings[2].stop() settings[1].start() - window[CAM_NAME].update(visible=False) - window[SETTINGS_NAME].update(visible=False) - window[ALGO_SETTINGS_NAME].update(visible=True) - window[CALIB_SETTINGS_NAME].update(visible=False) + window[UIConstants.CAM_NAME].update(visible=False) + window[UIConstants.SETTINGS_NAME].update(visible=False) + window[UIConstants.ALGO_SETTINGS_NAME].update(visible=True) + window[UIConstants.CALIB_SETTINGS_NAME].update(visible=False) config.cam_display_id = Tab.ALGOSETTINGS config.save() elif ( - values[CALIB_SETTINGS_RADIO_NAME] + values[UIConstants.CALIB_SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.CALIBRATION ): cams[0].start() # Allow tracking to continue in calibration tab settings[0].stop() settings[1].stop() settings[2].start() - window[CAM_NAME].update(visible=False) - window[SETTINGS_NAME].update(visible=False) - window[ALGO_SETTINGS_NAME].update(visible=False) - window[CALIB_SETTINGS_NAME].update(visible=True) + window[UIConstants.CAM_NAME].update(visible=False) + window[UIConstants.SETTINGS_NAME].update(visible=False) + window[UIConstants.ALGO_SETTINGS_NAME].update(visible=False) + window[UIConstants.CALIB_SETTINGS_NAME].update(visible=True) config.cam_display_id = Tab.CALIBRATION config.save() diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\"" "b/BabbleApp/eval \"$(ssh-agent -s)\"" deleted file mode 100644 index 0529181..0000000 --- "a/BabbleApp/eval \"$(ssh-agent -s)\"" +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN OPENSSH PRIVATE KEY----- -b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW -QyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQAAAKh2VWFWdlVh -VgAAAAtzc2gtZWQyNTUxOQAAACBL0U/fUe3XQ59ymMV0ugPRWiZZzs46e/wUy2wWiNsCNQ -AAAEAqGnMaqJSLYiFu1OaDjA54UuZHOtyDLJzm2wXqcE2WCEvRT99R7ddDn3KYxXS6A9Fa -JlnOzjp7/BTLbBaI2wI1AAAAIHN0ZWZhbi5lYXN0bWFuLmdpbmRpbGFAZ21haWwuY29tAQ -IDBAU= ------END OPENSSH PRIVATE KEY----- diff --git "a/BabbleApp/eval \"$(ssh-agent -s)\".pub" "b/BabbleApp/eval \"$(ssh-agent -s)\".pub" deleted file mode 100644 index ddc27eb..0000000 --- "a/BabbleApp/eval \"$(ssh-agent -s)\".pub" +++ /dev/null @@ -1 +0,0 @@ -ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEvRT99R7ddDn3KYxXS6A9FaJlnOzjp7/BTLbBaI2wI1 stefan.eastman.gindila@gmail.com From 7a67eccf91016b1839ccd7a668a25869660895f9 Mon Sep 17 00:00:00 2001 From: Stefan Date: Thu, 27 Feb 2025 15:25:23 +0200 Subject: [PATCH 7/7] ran it through a formater --- BabbleApp/babbleapp.py | 116 +++++++++++++++++++++++++++++------------ BabbleApp/constants.py | 7 ++- 2 files changed, 89 insertions(+), 34 deletions(-) diff --git a/BabbleApp/babbleapp.py b/BabbleApp/babbleapp.py index 1bcb9e5..157420f 100644 --- a/BabbleApp/babbleapp.py +++ b/BabbleApp/babbleapp.py @@ -40,13 +40,16 @@ from constants import UIConstants, AppConstants winmm = None -if os_type == 'Windows': +if os_type == "Windows": try: from ctypes import windll + winmm = windll.winmm except OSError: - print(f'\033[91m[{lang._instance.get_string("log.error")}] {lang._instance.get_string("error.winmm")}.\033[0m') - + print( + f'\033[91m[{lang._instance.get_string("log.error")}] {lang._instance.get_string("error.winmm")}.\033[0m' + ) + os.system("color") # init ANSI color # Random environment variable to speed up webcam opening on the MSMF backend. @@ -55,13 +58,16 @@ os.environ["OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS"] = "0" page_url = "https://github.com/Project-Babble/ProjectBabble/releases/latest" appversion = "Babble v2.0.7" + def timerResolution(toggle): if winmm != None: if toggle: rc = c_int(winmm.timeBeginPeriod(1)) if rc.value != 0: # TIMEERR_NOCANDO = 97 - print(f'\033[93m[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("warn.timerRes")} {rc.value}\033[0m') + print( + f'\033[93m[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("warn.timerRes")} {rc.value}\033[0m' + ) else: winmm.timeEndPeriod(1) @@ -71,15 +77,17 @@ async def check_for_updates(config, notification_manager): try: response = requests.get( "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest", - timeout=10 # Add timeout + timeout=10, # Add timeout ) response.raise_for_status() # Will raise exception for HTTP errors - + data = response.json() latestversion = data.get("name") - + if not latestversion: - print(f'[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("babble.invalidVersionFormat")}') + print( + f'[{lang._instance.get_string("log.warn")}] {lang._instance.get_string("babble.invalidVersionFormat")}' + ) return if appversion == latestversion: @@ -90,16 +98,27 @@ async def check_for_updates(config, notification_manager): print( f'\033[93m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.needUpdateOne")} [{appversion}] {lang._instance.get_string("babble.needUpdateTwo")} [{latestversion}] {lang._instance.get_string("babble.needUpdateThree")}.\033[0m' ) - await notification_manager.show_notification(appversion, latestversion, page_url) - + await notification_manager.show_notification( + appversion, latestversion, page_url + ) + except requests.exceptions.Timeout: - print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateTimeout")}') + print( + f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateTimeout")}' + ) except requests.exceptions.HTTPError as e: - print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateHttpError")}: {e}') + print( + f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateHttpError")}: {e}' + ) except requests.exceptions.ConnectionError: - print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}') + print( + f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}' + ) except Exception as e: - print(f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}') + print( + f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.updateCheckFailed")}: {e}' + ) + class ThreadManager: def __init__(self, cancellation_event): @@ -121,7 +140,11 @@ class ThreadManager: # Call shutdown methods on associated objects if available for thread, shutdown_obj in self.threads: - if shutdown_obj and hasattr(shutdown_obj, 'shutdown') and callable(shutdown_obj.shutdown): + if ( + shutdown_obj + and hasattr(shutdown_obj, "shutdown") + and callable(shutdown_obj.shutdown) + ): try: self.logger.debug(f"Calling shutdown on {shutdown_obj}") shutdown_obj.shutdown() @@ -131,16 +154,21 @@ class ThreadManager: # Join threads with the specified timeout for thread, _ in self.threads: if thread.is_alive(): - self.logger.debug(f"Joining thread: {thread.name} with timeout {timeout}s") + self.logger.debug( + f"Joining thread: {thread.name} with timeout {timeout}s" + ) thread.join(timeout=timeout) # Remove terminated threads from the list self.threads = [(t, s) for t, s in self.threads if t.is_alive()] if self.threads: - self.logger.warning(f"{len(self.threads)} threads still alive: {[t.name for t, _ in self.threads]}") + self.logger.warning( + f"{len(self.threads)} threads still alive: {[t.name for t, _ in self.threads]}" + ) else: - self.logger.info("All threads terminated successfully") + self.logger.info("All threads terminated successfully") + async def async_main(): ensurePath() @@ -153,13 +181,13 @@ async def async_main(): lang("Locale", config.settings.gui_language) config.save() - + notification_manager = NotificationManager() await notification_manager.initialize() - + # Run the update check await check_for_updates(config, notification_manager) - + # Uncomment for low-level Vive Facial Tracker logging # logging.basicConfig(filename='BabbleApp.log', filemode='w', encoding='utf-8', level=logging.INFO) @@ -246,7 +274,17 @@ async def async_main(): ), ], # Keep at bottom! - [sg.Text(f'- - - {lang._instance.get_string("general.windowFocus")} - - -', key="-WINFOCUS-", background_color=bg_color_clear, text_color="#F0F0F0", justification="center", expand_x=True, visible=False)], + [ + sg.Text( + f'- - - {lang._instance.get_string("general.windowFocus")} - - -', + key="-WINFOCUS-", + background_color=bg_color_clear, + text_color="#F0F0F0", + justification="center", + expand_x=True, + visible=False, + ) + ], ] if config.cam_display_id in [Tab.CAM]: @@ -261,28 +299,37 @@ async def async_main(): # the cam needs to be running before it is passed to the OSC if config.settings.gui_ROSC: osc_receiver = VRChatOSCReceiver(cancellation_event, config, cams) - osc_receiver_thread = threading.Thread(target=osc_receiver.run, name="OSCReceiverThread") + osc_receiver_thread = threading.Thread( + target=osc_receiver.run, name="OSCReceiverThread" + ) thread_manager.add_thread(osc_receiver_thread, shutdown_obj=osc_receiver) ROSC = True # Create the window window = sg.Window( - f"{AppConstants.VERSION}", layout, icon=os.path.join('Images', 'logo.ico'), background_color=bg_color_clear ) - + f"{AppConstants.VERSION}", + layout, + icon=os.path.join("Images", "logo.ico"), + background_color=bg_color_clear, + ) + # Run the main loop await main_loop(window, config, cams, settings, thread_manager) - + # Cleanup after main loop exits timerResolution(False) - print(f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m') + print( + f'\033[94m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.exit")}\033[0m' + ) + async def main_loop(window, config, cams, settings, thread_manager): tint = AppConstants.DEFAULT_WINDOW_FOCUS_REFRESH fs = False - + while True: event, values = window.read(timeout=tint) - + if event in ("Exit", sg.WIN_CLOSED): # Exit code here for cam in cams: @@ -290,7 +337,7 @@ async def main_loop(window, config, cams, settings, thread_manager): thread_manager.shutdown_all() window.close() return - + try: # If window isn't in focus increase timeout and stop loop early if window.TKroot.focus_get(): @@ -322,7 +369,10 @@ async def main_loop(window, config, cams, settings, thread_manager): config.cam_display_id = Tab.CAM config.save() - elif values[UIConstants.SETTINGS_RADIO_NAME] and config.cam_display_id != Tab.SETTINGS: + elif ( + values[UIConstants.SETTINGS_RADIO_NAME] + and config.cam_display_id != Tab.SETTINGS + ): cams[0].stop() settings[1].stop() settings[2].stop() @@ -371,13 +421,15 @@ async def main_loop(window, config, cams, settings, thread_manager): for setting in settings: if setting.started(): setting.render(window, event, values) - + # Rather than await asyncio.sleep(0), yield control periodically await asyncio.sleep(0.001) # Small sleep to allow other tasks to rundef main(): asyncio.run(async_main()) + def main(): asyncio.run(async_main()) + if __name__ == "__main__": main() diff --git a/BabbleApp/constants.py b/BabbleApp/constants.py index 7cf79bc..71c6a60 100644 --- a/BabbleApp/constants.py +++ b/BabbleApp/constants.py @@ -11,9 +11,12 @@ class UIConstants: CALIB_SETTINGS_RADIO_NAME = "-CALIBSETTINGSRADIO-" WINDOW_FOCUS_KEY = "-WINFOCUS-" + class AppConstants: VERSION = "Babble v2.0.7" GITHUB_REPO_URL = "https://github.com/Project-Babble/ProjectBabble/releases/latest" - GITHUB_API_URL = "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest" + GITHUB_API_URL = ( + "https://api.github.com/repos/Project-Babble/ProjectBabble/releases/latest" + ) DEFAULT_WINDOW_FOCUS_REFRESH = 33 - UNFOCUSED_WINDOW_REFRESH = 100 \ No newline at end of file + UNFOCUSED_WINDOW_REFRESH = 100