forked from Project-Babble/ProjectBabble
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbabbleapp.py
343 lines (304 loc) · 13.9 KB
/
babbleapp.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
"""
-------------------------------------------------------------------------------------------------------------
██████╗ ██████╗ ██████╗ ██╗███████╗ ██████╗████████╗ ██████╗ █████╗ ██████╗ ██████╗ ██╗ ███████╗
██╔══██╗██╔══██╗██╔═══██╗ ██║██╔════╝██╔════╝╚══██╔══╝ ██╔══██╗██╔══██╗██╔══██╗██╔══██╗██║ ██╔════╝
██████╔╝██████╔╝██║ ██║ ██║█████╗ ██║ ██║ ██████╔╝███████║██████╔╝██████╔╝██║ █████╗
██╔═══╝ ██╔══██╗██║ ██║██ ██║██╔══╝ ██║ ██║ ██╔══██╗██╔══██║██╔══██╗██╔══██╗██║ ██╔══╝
██║ ██║ ██║╚██████╔╝╚█████╔╝███████╗╚██████╗ ██║ ██████╔╝██║ ██║██████╔╝██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚══════╝╚══════╝
--------------------------------------------------------------------------------------------------------------
GUI by: Prohurtz, qdot
Model by: Summer
App model implementation: Prohurtz, Summer
Additional contributors: RamesTheGeneric (dataset synthesizer), dfgHiatus (locale, some other stuff)
Copyright (c) 2023 Project Babble <3
"""
import os
import PySimpleGUI as sg
import queue
import requests
import threading
import asyncio
import logging
from ctypes import c_int
from babble_model_loader import *
from camera_widget import CameraWidget
from config import BabbleConfig
from tab import Tab
from osc import VRChatOSCReceiver, VRChatOSC
from general_settings_widget import SettingsWidget
from algo_settings_widget import AlgoSettingsWidget
from calib_settings_widget import CalibSettingsWidget
from notification_manager import NotificationManager
from utils.misc_utils import EnsurePath, is_nt, bg_color_highlight, bg_color_clear
from lang_manager import LocaleStringManager as lang
winmm = None
if is_nt:
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')
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"
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')
else:
winmm.timeEndPeriod(1)
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"
)
latestversion = response.json()["name"]
if appversion == latestversion:
print(
f'\033[92m[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.latestVersion")}! [{latestversion}]\033[0m'
)
else:
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)
except Exception as e:
print(
f'[{lang._instance.get_string("log.info")}] {lang._instance.get_string("babble.noInternet")}. Error: {e}'
)
async def async_main():
EnsurePath()
# Get Configuration
config: BabbleConfig = BabbleConfig.load()
# Init locale manager
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)
cancellation_event = threading.Event()
ROSC = False
timerResolution(True)
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()
cams = [
CameraWidget(Tab.CAM, config, osc_queue),
]
settings = [
SettingsWidget(Tab.SETTINGS, config, osc_queue),
AlgoSettingsWidget(Tab.ALGOSETTINGS, config, osc_queue),
CalibSettingsWidget(Tab.CALIBRATION, config, osc_queue),
]
layout = [
[
sg.Radio(
lang._instance.get_string("babble.camPage"),
"TABSELECTRADIO",
background_color=bg_color_clear,
default=(config.cam_display_id == Tab.CAM),
key=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,
),
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,
),
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,
),
],
[
sg.Column(
cams[0].widget_layout,
vertical_alignment="top",
key=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,
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,
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,
visible=(config.cam_display_id in [Tab.CALIBRATION]),
background_color=bg_color_highlight,
),
],
# 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)],
]
if config.cam_display_id in [Tab.CAM]:
cams[0].start()
if config.cam_display_id in [Tab.SETTINGS]:
settings[0].start()
if config.cam_display_id in [Tab.ALGOSETTINGS]:
settings[1].start()
if config.cam_display_id in [Tab.CALIBRATION]:
settings[2].start()
# 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)
osc_receiver_thread.start()
ROSC = True
# Create the window
window = sg.Window(
f"{appversion}", layout, icon="Images/logo.ico", background_color=bg_color_clear
)
tint = 33
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
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()
window.refresh()
else:
if not fs:
fs = True
tint = 100
window["-WINFOCUS-"].update(visible=True)
window["-WINFOCUS-"].unhide_row()
continue
except KeyError:
pass
if values[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)
config.cam_display_id = Tab.CAM
config.save()
elif values[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)
config.cam_display_id = Tab.SETTINGS
config.save()
elif (
values[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)
config.cam_display_id = Tab.ALGOSETTINGS
config.save()
elif (
values[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)
config.cam_display_id = Tab.CALIBRATION
config.save()
# Otherwise, render all
for cam in cams:
if cam.started():
cam.render(window, event, values)
for setting in settings:
if setting.started():
setting.render(window, event, values)
# Does adding this help?
# await asyncio.sleep(0)
def main():
asyncio.run(async_main())
if __name__ == "__main__":
main()