-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexpressive_gui.py
More file actions
857 lines (748 loc) · 36.5 KB
/
Copy pathexpressive_gui.py
File metadata and controls
857 lines (748 loc) · 36.5 KB
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
import os
import sys
import json
import time
import logging
import asyncio
import argparse
from pathlib import Path
from collections.abc import Mapping
from os.path import splitext, basename
from logging.handlers import QueueListener
from concurrent.futures import ProcessPoolExecutor
import webview
from nicegui import ui, app, background_tasks
from utils.ui import (
blink_taskbar_window,
change_window_style,
NiceguiNativeDropArea,
WaveSurferRangeSelector,
webview_active_window,
)
from utils.monkeypatch import (
patch_runpy,
patch_tooltip_md,
patch_nicegui_json,
)
from __version__ import VERSION
from expressive import process_expressions
from utils.i18n import _, init_gettext, detect_preferred_langs
from utils.wavtool import get_wav_end_ts, validate_timestamp
from utils.worker import WorkerContext, setup_worker_context
from expressions.base import getExpressionLoader, get_registered_expressions
FORMATTER_APP = logging.Formatter("%(asctime)s %(levelname)s [%(name)s]: %(message)s", datefmt="%H:%M:%S")
FORMATTER_EXP = logging.Formatter("%(asctime)s %(levelname)s [%(expression)s]: %(message)s", datefmt="%H:%M:%S")
LOGGER_APP_NAME = splitext(basename(__file__))[0]
LOGGER_EXP_NAME = getExpressionLoader(None).__name__
LANG = detect_preferred_langs()
LOCALE_DIR = os.path.join(os.path.dirname(__file__), 'locales')
LOCALE_DOMAIN = "app"
worker_context = WorkerContext(
formatter_app = FORMATTER_APP,
formatter_exp = FORMATTER_EXP,
logger_app_name = LOGGER_APP_NAME,
logger_exp_name = LOGGER_EXP_NAME,
lang = LANG,
locale_dir = LOCALE_DIR,
domain = LOCALE_DOMAIN,
)
general_args = getExpressionLoader(None).args
class LogElementHandler(logging.Handler):
"""A logging handler that emits messages to a log element."""
def __init__(self, element: ui.log, level: int = logging.NOTSET) -> None:
self.element = element
super().__init__(level)
def emit(self, record: logging.LogRecord) -> None:
try:
msg = self.format(record)
self.element.push(msg)
time.sleep(0.1) # Avoid flooding
except Exception:
self.handleError(record)
def is_root_mode() -> bool:
"""Determine if the app is running in root mode or in script mode.
This is used to decide how to run the NiceGUI app.
"""
def is_file(path: str | Path | None) -> bool:
"""Check if the path is a file that exists.
Cited from nicegui/helpers.py @ v3.7.1 with MIT License, Copyright (c) 2021 Zauberzeug GmbH
"""
if not path:
return False
if isinstance(path, str) and path.strip().startswith('data:'):
return False # NOTE: avoid passing data URLs to Path
try:
return Path(path).is_file()
except OSError:
return False
return not sys.argv or not sys.argv[0] or not is_file(sys.argv[0])
def dict_update(d: dict, u: Mapping):
"""Recursively update a dictionary with another dictionary.
This function updates the dictionary `d` with the values from the dictionary `u`.
See: https://stackoverflow.com/a/3233356
"""
for k, v in u.items():
if isinstance(v, Mapping):
d[k] = dict_update(d.get(k, {}), v)
else:
d[k] = v
return d
@app.on_connect
def close_splash():
"""Close the splash screen when the app is connected if this script is frozen.
This is a workaround for PyInstaller, which doesn't support splash screen in the main thread
See: https://github.com/zauberzeug/nicegui/discussions/3536
https://stackoverflow.com/questions/71057636/how-can-i-solve-no-module-named-pyi-splash-after-using-pyinstaller
"""
if getattr(sys, 'frozen', False):
import pyi_splash # type: ignore
pyi_splash.close()
def build_default_state() -> dict:
"""Build the default application state from registered expression loaders."""
return {
"utau_wav" : general_args.utau_path.default,
"ref_wav" : general_args.ref_path.default,
"ustx_input" : general_args.ustx_path.default,
"ustx_output" : "",
"track_number": general_args.track_number.default,
"ref_start" : general_args.ref_start.default,
"ref_end" : general_args.ref_end.default,
"utau_start" : general_args.utau_start.default,
"utau_end" : general_args.utau_end.default,
"expressions" : {
exp_name: {
"selected": False,
**{
arg.name: arg.default
for arg in getExpressionLoader(exp_name).get_args_dict().values()
},
} for exp_name in get_registered_expressions()
},
}
def create_gui(): # noqa: C901
state = build_default_state()
def on_color_scheme_changed(event):
"""Change the window style based on the color scheme."""
color_scheme = event.args
if color_scheme == 'dark':
change_window_style(app.config.title, 'mica')
else:
change_window_style(app.config.title, 'light')
async def export_config(state=state):
file = await app.native.main_window.create_file_dialog( # type: ignore
dialog_type=webview.FileDialog.SAVE,
file_types=("JSON files (*.json)",),
save_filename="expressive_config",
)
if file and len(file) > 0:
try:
with open(file[0], "w+", encoding="utf-8-sig") as f: # type: ignore
json.dump(state, f, indent=4, ensure_ascii=False)
ui.notify(_("Config exported successfully!"), type="positive")
except Exception as e:
ui.notify(_("Failed to export config") + f": {str(e)}", type="negative")
async def import_config(state=state):
file = await app.native.main_window.create_file_dialog( # type: ignore
dialog_type=webview.FileDialog.OPEN,
file_types=("JSON files (*.json)",),
)
if file and len(file) > 0:
try:
with open(file[0], "r", encoding="utf-8-sig") as f:
cfg = json.load(f)
# Start from defaults, then overlay imported values — missing keys stay default
default_state = build_default_state()
dict_update(default_state, cfg)
dict_update(state, default_state)
ui.notify(_("Config imported successfully!"), type="positive")
ui.update()
except Exception as e:
ui.notify(_("Failed to import config") + f": {str(e)}", type="negative")
async def run_processing():
# Prepare expressions list
expressions = [
{
"expression": exp_name,
** {
arg.name: state["expressions"][exp_name][arg.name]
for arg in getExpressionLoader(exp_name).get_args_dict().values()
}
}
for exp_name in get_registered_expressions()
if state["expressions"][exp_name]["selected"]
]
with status_row:
process_button.disable()
spinner_dialog.open()
log_element.clear()
logger_app.info(_("Start Processing..."))
try:
ui_handler = LogElementHandler(log_element)
listener = QueueListener(worker_context.log_queue, ui_handler)
listener.start()
# We have to use multiprocessing with a separate process for the expression processing
# to avoid blocking the UI and to allow using more CPU cores for heavy processing.
loop = asyncio.get_event_loop()
with ProcessPoolExecutor(
max_workers=1, # ALWAYS use a single worker to avoid messing with CUDA in multiple processes
initializer=setup_worker_context,
initargs=(worker_context,),
) as executor:
await loop.run_in_executor(
executor,
process_expressions,
state["utau_wav"],
state["ref_wav"],
state["ustx_input"],
state["ustx_output"],
state["track_number"],
state["ref_start"],
state["ref_end"],
state["utau_start"],
state["utau_end"],
expressions,
)
blink_taskbar_window(app.config.title)
logger_app.info(_("Processing completed successfully!"))
ui.notify(_("Processing completed successfully!"), type="positive")
except Exception as e:
logger_app.exception(_("Error during processing") + f": {str(e)}")
ui.notify(_("Error during processing") + f": {str(e)}", type="negative")
finally:
spinner_dialog.close()
process_button.enable()
async def choose_file(field, ftypes):
file = await app.native.main_window.create_file_dialog( # type: ignore
dialog_type=webview.FileDialog.OPEN,
file_types=ftypes,
)
if file is not None and len(file) > 0:
state[field] = file[0]
file_inputs[field].set_value(state[field])
async def save_file(field, ftypes, fname):
file = await app.native.main_window.create_file_dialog( # type: ignore
dialog_type=webview.FileDialog.SAVE,
file_types=ftypes,
save_filename=fname,
)
if file is not None and len(file) > 0:
state[field] = file[0]
file_inputs[field].set_value(state[field])
def on_drag(event, input_ids: list[str]):
target_id = event['target'].get('id')
if target_id not in input_ids:
return
if event['type'] == 'dragenter':
webview_active_window().evaluate_js(f'''
document.getElementById("{target_id}").focus();
''')
elif event['type'] == 'dragleave':
webview_active_window().evaluate_js(f'''
document.getElementById("{target_id}").blur();
''')
def on_drop(event, input_ids: list[str]):
target_id = event['target'].get('id')
if target_id not in input_ids:
return
files = event['dataTransfer']['files']
if not files:
return
fpath = files[0]["pywebviewFullPath"]
# Fill the input field and trigger the NiceGUI binding propagation
webview_active_window().evaluate_js(f"""
const el = document.getElementById("{target_id}");
if (el) {{
el.value = {json.dumps(fpath)};
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}
""")
async def process_files():
# Validate inputs
if (
not state["utau_wav"]
or not state["ref_wav"]
or not state["ustx_input"]
or not state["ustx_output"]
):
ui.notify(_("Please fill all required file paths"), type="negative")
return
if not any(
[
state["expressions"][exp_name]["selected"]
for exp_name in get_registered_expressions()
]
):
ui.notify(_("Please select at least one expression to apply"), type="negative")
return
asyncio.create_task(run_processing())
def setup_loggers(log_element: ui.log):
"""Configure application and expression loggers to write to the log_element."""
def configure_logger(name: str, formatter: logging.Formatter):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
handler = LogElementHandler(log_element)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger, handler
logger_app, handler_app = configure_logger(LOGGER_APP_NAME, FORMATTER_APP)
logger_exp, handler_exp = configure_logger(LOGGER_EXP_NAME, FORMATTER_EXP)
# Clean up on disconnect
ui.context.client.on_disconnect(lambda: (
logger_app.removeHandler(handler_app),
logger_exp.removeHandler(handler_exp)
))
return logger_app, logger_exp
# Set up the UI dark mode
ui.dark_mode(None)
ui.add_head_html('''
<script>
// Emit an event when the color scheme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
const colorScheme = event.matches ? "dark" : "light";
emitEvent('color-scheme-changed', colorScheme);
});
// Initial check
window.onload = function() {
const colorScheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light";
emitEvent('color-scheme-changed', colorScheme);
};
</script>
''')
ui.on('color-scheme-changed', lambda e: on_color_scheme_changed(e))
# File inputs
file_inputs = {}
with ui.card().classes("w-full"):
ui.label(_("File Paths")).classes("text-xl font-bold")
on_drag_impl = lambda e: on_drag(e,
[ f'c{v.id}' for v in file_inputs.values() ])
on_drop_impl = lambda e: on_drop(e,
[ f'c{v.id}' for v in file_inputs.values() ])
with NiceguiNativeDropArea(
on_dragenter = on_drag_impl,
on_dragleave = on_drag_impl,
on_dragover = on_drag_impl,
on_drop = on_drop_impl,
).classes('w-full'):
# ── Reference WAV ────────────────────────────────────────────
def on_ref_change(e):
nonlocal input_ref_start, input_ref_end
ref_path = e.value
placeholder_start = _("e.g. 0:10.01 (default: beginning)")
placeholder_end = _("e.g. 1:30.00 (default: end)")
input_ref_start._props.set_optional('placeholder', placeholder_start)
input_ref_end._props.set_optional('placeholder', placeholder_end)
if ref_path and os.path.isfile(ref_path):
async def update_placeholders():
try:
end_ts = await asyncio.get_event_loop().run_in_executor(
None, get_wav_end_ts, ref_path
)
input_ref_start._props.set_optional('placeholder', "0:0.0")
input_ref_end._props.set_optional('placeholder', end_ts)
except Exception:
pass
background_tasks.create(update_placeholders(), name="ref_placeholder_update")
with ui.row().classes("w-full"):
file_inputs["ref_wav"] = (
ui.input(
label=_("Reference WAV File"),
placeholder=general_args.ref_path.help,
validation={_("Input required"): lambda v: bool(v)},
on_change=on_ref_change,
)
.bind_value(state, "ref_wav")
.classes("flex-grow")
)
ui.button(
icon="folder",
on_click=lambda: choose_file("ref_wav", ("WAV files (*.wav)",)),
).classes("self-end")
# Waveform shown only after a file is selected
with ui.card().classes("w-full no-shadow no-border").bind_visibility_from(state, "ref_wav"):
WaveSurferRangeSelector() \
.bind_wav_path_from(state, "ref_wav") \
.bind_start(state, "ref_start") \
.bind_end(state, "ref_end")
with ui.row().classes("w-full"):
input_ref_start = ui.input(
label=_("Reference Start"),
validation={_("Invalid format"): lambda v: not v or validate_timestamp(v, "ref_start")},
).bind_value(
state, "ref_start",
forward=lambda v: v or None, backward=lambda v: v or ""
).classes("flex-grow").tooltip_md(general_args.ref_start.help)
input_ref_end =ui.input(
label=_("Reference End"),
validation={_("Invalid format"): lambda v: not v or validate_timestamp(v, "ref_end")},
).bind_value(
state, "ref_end",
forward=lambda v: v or None, backward=lambda v: v or ""
).classes("flex-grow").tooltip_md(general_args.ref_end.help)
# ── UTAU WAV ─────────────────────────────────────────────────
def on_utau_change(e):
nonlocal input_utau_start, input_utau_end
utau_path = e.value
placeholder_start = _("e.g. 0:10.01 (default: beginning)")
placeholder_end = _("e.g. 1:30.00 (default: end)")
input_utau_start._props.set_optional('placeholder', placeholder_start)
input_utau_end._props.set_optional('placeholder', placeholder_end)
if utau_path and os.path.isfile(utau_path):
async def update_placeholders():
try:
end_ts = await asyncio.get_event_loop().run_in_executor(
None, get_wav_end_ts, utau_path
)
input_utau_start._props.set_optional('placeholder', "0:0.0")
input_utau_end._props.set_optional('placeholder', end_ts)
except Exception:
pass
background_tasks.create(update_placeholders(), name="utau_placeholder_update")
with ui.row().classes("w-full"):
file_inputs["utau_wav"] = (
ui.input(
label=_("UTAU WAV File"),
placeholder=general_args.utau_path.help,
validation={_("Input required"): lambda v: bool(v)},
on_change=on_utau_change,
)
.bind_value(state, "utau_wav")
.classes("flex-grow")
)
ui.button(
icon="folder",
on_click=lambda: choose_file("utau_wav", ("WAV files (*.wav)",)),
).classes("self-end")
with ui.card ().classes("w-full no-shadow no-border").bind_visibility_from(state, "utau_wav"):
WaveSurferRangeSelector() \
.bind_wav_path_from(state, "utau_wav") \
.bind_start(state, "utau_start") \
.bind_end(state, "utau_end")
with ui.row().classes("w-full"):
input_utau_start = ui.input(
label=_("UTAU Start"),
validation={_("Invalid format"): lambda v: not v or validate_timestamp(v, "utau_start")},
).bind_value(
state, "utau_start",
forward=lambda v: v or None, backward=lambda v: v or ""
).classes("flex-grow").tooltip_md(general_args.utau_start.help)
input_utau_end = ui.input(
label=_("UTAU End"),
validation={_("Invalid format"): lambda v: not v or validate_timestamp(v, "utau_end")},
).bind_value(
state, "utau_end",
forward=lambda v: v or None, backward=lambda v: v or ""
).classes("flex-grow").tooltip_md(general_args.utau_end.help)
# ── Remaining file inputs ────────────────────────────────────
with ui.row().classes("w-full"):
file_inputs["ustx_input"] = (
ui.input(
label=_("Input USTX File"),
placeholder=general_args.ustx_path.help,
validation={_("Input required"): lambda v: bool(v)},
)
.bind_value(state, "ustx_input")
.classes("flex-grow")
)
ui.button(
icon="folder",
on_click=lambda: choose_file("ustx_input", ("USTX files (*.ustx)",)),
).classes("self-end")
with ui.row().classes("w-full"):
file_inputs["ustx_output"] = (
ui.input(
label=_("Output USTX File"),
placeholder=_("Path to save the processed `.ustx` file"),
validation={_("Input required"): lambda v: bool(v)},
)
.bind_value(state, "ustx_output")
.classes("flex-grow")
)
ui.button(
icon="save",
on_click=lambda: save_file(
"ustx_output", ("USTX files (*.ustx)",), "output"
),
).classes("self-end")
ui.number(label=_("Track Number"), min=1, format="%d").bind_value(
state, "track_number",
forward=lambda v: general_args.track_number.type(v) if v is not None else None,
).classes("w-full").tooltip_md(general_args.track_number.help)
# Expression selection
with ui.card().classes("w-full"):
ui.label(_("Expression Selection")).classes("text-xl font-bold")
with ui.row():
for exp_name in get_registered_expressions():
exp_info = getExpressionLoader(exp_name).expression_info
ui.checkbox(exp_info).bind_value(
state["expressions"][exp_name], "selected"
)
# Brec parameters
brec_args = getExpressionLoader("brec").args
brec_info = getExpressionLoader("brec").expression_info
with ui.card().classes("w-full").bind_visibility_from(
state["expressions"]["brec"], "selected"
):
ui.label(brec_info).classes("text-lg font-bold")
with ui.grid(columns=2).classes("w-full"):
ui.switch(_("Spline Smoothing")).bind_value(
state["expressions"]["brec"], "spline_smoothing",
).tooltip_md(brec_args.spline_smoothing.help)
with ui.grid(columns=3).classes("w-full"):
ui.number(label=_("Align Radius"), min=1, format="%d").bind_value(
state["expressions"]["brec"], "align_radius",
forward=lambda v: brec_args.align_radius.type(v) if v is not None else None,
).tooltip_md(brec_args.align_radius.help)
ui.number(label=_("Smoothness"), min=0, format="%d").bind_value(
state["expressions"]["brec"], "smoothness",
forward=lambda v: brec_args.smoothness.type(v) if v is not None else None,
).tooltip_md(brec_args.smoothness.help)
ui.number(label=_("Scaler"), min=0.0, step=0.1, format="%.1f").bind_value(
state["expressions"]["brec"], "scaler",
forward=lambda v: brec_args.scaler.type(v) if v is not None else None,
).tooltip_md(brec_args.scaler.help)
ui.number(label=_("Bias"), format="%d").bind_value(
state["expressions"]["brec"], "bias",
forward=lambda v: brec_args.bias.type(v) if v is not None else None,
).tooltip_md(brec_args.bias.help)
# Dyn parameters
dyn_args = getExpressionLoader("dyn").args
dyn_info = getExpressionLoader("dyn").expression_info
with ui.card().classes("w-full").bind_visibility_from(
state["expressions"]["dyn"], "selected"
):
ui.label(dyn_info).classes("text-lg font-bold")
with ui.grid(columns=2).classes("w-full"):
ui.switch(_("Trim Silence")).bind_value(
state["expressions"]["dyn"], "trim_silence",
).tooltip_md(dyn_args.trim_silence.help)
ui.switch(_("Spline Smoothing")).bind_value(
state["expressions"]["dyn"], "spline_smoothing",
).tooltip_md(dyn_args.spline_smoothing.help)
with ui.grid(columns=3).classes("w-full"):
ui.number(label=_("Align Radius"), min=1, format="%d").bind_value(
state["expressions"]["dyn"], "align_radius",
forward=lambda v: dyn_args.align_radius.type(v) if v is not None else None,
).tooltip_md(dyn_args.align_radius.help)
ui.number(label=_("Smoothness"), min=0, format="%d").bind_value(
state["expressions"]["dyn"], "smoothness",
forward=lambda v: dyn_args.smoothness.type(v) if v is not None else None,
).tooltip_md(dyn_args.smoothness.help)
ui.number(label=_("Scaler"), min=0.0, step=0.1, format="%.1f").bind_value(
state["expressions"]["dyn"], "scaler",
forward=lambda v: dyn_args.scaler.type(v) if v is not None else None,
).tooltip_md(dyn_args.scaler.help)
# Pitd parameters
pitd_args = getExpressionLoader("pitd").args
pitd_info = getExpressionLoader("pitd").expression_info
with ui.card().classes("w-full").bind_visibility_from(
state["expressions"]["pitd"], "selected"
):
ui.label(pitd_info).classes("text-lg font-bold")
with ui.grid(columns=2).classes("w-full"):
with ui.row().classes("w-full items-center gap-2"):
ui.select(
label=_("mHuBERT Embedder"),
options=pitd_args.mhubert_embedder.choices,
).classes("flex-1").bind_value(
state["expressions"]["pitd"], "mhubert_embedder"
).tooltip_md(pitd_args.mhubert_embedder.help)
ui.icon("warning", color="warning").tooltip_md(
getExpressionLoader("pitd").mhubert_embedder_warning
).bind_visibility_from(
state["expressions"]["pitd"], "mhubert_embedder",
backward=lambda v: v != "disabled",
)
ui.switch(_("Spline Smoothing")).bind_value(
state["expressions"]["pitd"], "spline_smoothing",
).tooltip_md(pitd_args.spline_smoothing.help)
with ui.grid(columns=3).classes("w-full"):
def on_backend_change(e):
nonlocal ui_confidence_utau, ui_confidence_ref
backend = e.value
# Update the confidence input placeholders based on the selected backend's recommended values
# TODO: _props is an internal API of NiceGUI, may need to be updated if NiceGUI changes its implementation
ui_confidence_utau._props.set_optional(
'placeholder',
getExpressionLoader("pitd").confidence_utau_recommended[backend]
)
ui_confidence_ref._props.set_optional(
'placeholder',
getExpressionLoader("pitd").confidence_ref_recommended[backend]
)
ui_confidence_utau = ui.number(
label=_("UTAU Confidence"), min=0.0, max=1.0, step=0.01, format="%.2f"
).bind_value(state["expressions"]["pitd"], "confidence_utau",
forward=lambda v: pitd_args.confidence_utau.type(v) if v is not None else None,
).tooltip_md(pitd_args.confidence_utau.help)
ui_confidence_ref = ui.number(
label=_("Reference Confidence"), min=0.0, max=1.0, step=0.01, format="%.2f"
).bind_value(state["expressions"]["pitd"], "confidence_ref",
forward=lambda v: pitd_args.confidence_ref.type(v) if v is not None else None,
).tooltip_md(pitd_args.confidence_ref.help)
ui.select(
label=_("Backend"), options=pitd_args.backend.choices,
on_change=on_backend_change,
).bind_value(state["expressions"]["pitd"], "backend").tooltip_md(pitd_args.backend.help)
ui.number(label=_("Align Radius"), min=1, format="%d").bind_value(
state["expressions"]["pitd"], "align_radius",
forward=lambda v: pitd_args.align_radius.type(v) if v is not None else None,
).tooltip_md(pitd_args.align_radius.help)
ui.number(label=_("Semitone Shift"), step=1, format="%d",
placeholder=_("Auto Estimation")).bind_value(
state["expressions"]["pitd"], "semitone_shift",
forward=lambda v: pitd_args.semitone_shift.type(v) if v is not None else None,
).tooltip_md(pitd_args.semitone_shift.help)
ui.number(label=_("Smoothness"), min=0, format="%d").bind_value(
state["expressions"]["pitd"], "smoothness",
forward=lambda v: pitd_args.smoothness.type(v) if v is not None else None,
).tooltip_md(pitd_args.smoothness.help)
ui.number(label=_("Scaler"), min=0.0, step=0.1, format="%.1f").bind_value(
state["expressions"]["pitd"], "scaler",
forward=lambda v: pitd_args.scaler.type(v) if v is not None else None,
).tooltip_md(pitd_args.scaler.help)
# Tenc parameters
tenc_args = getExpressionLoader("tenc").args
tenc_info = getExpressionLoader("tenc").expression_info
with ui.card().classes("w-full").bind_visibility_from(
state["expressions"]["tenc"], "selected"
):
ui.label(tenc_info).classes("text-lg font-bold")
with ui.grid(columns=2).classes("w-full"):
ui.switch(_("Trim Silence")).bind_value(
state["expressions"]["tenc"], "trim_silence",
).tooltip_md(tenc_args.trim_silence.help)
ui.switch(_("Spline Smoothing")).bind_value(
state["expressions"]["tenc"], "spline_smoothing",
).tooltip_md(tenc_args.spline_smoothing.help)
with ui.grid(columns=3).classes("w-full"):
ui.number(label=_("Align Radius"), min=1, format="%d").bind_value(
state["expressions"]["tenc"], "align_radius",
forward=lambda v: tenc_args.align_radius.type(v) if v is not None else None,
).tooltip_md(tenc_args.align_radius.help)
ui.number(label=_("Smoothness"), min=0, format="%d").bind_value(
state["expressions"]["tenc"], "smoothness",
forward=lambda v: tenc_args.smoothness.type(v) if v is not None else None,
).tooltip_md(tenc_args.smoothness.help)
ui.number(label=_("Scaler"), min=0.0, step=0.1, format="%.1f").bind_value(
state["expressions"]["tenc"], "scaler",
forward=lambda v: tenc_args.scaler.type(v) if v is not None else None,
).tooltip_md(tenc_args.scaler.help)
ui.number(label=_("Bias"), format="%d").bind_value(
state["expressions"]["tenc"], "bias",
forward=lambda v: tenc_args.bias.type(v) if v is not None else None,
).tooltip_md(tenc_args.bias.help)
# Voic parameters
voic_args = getExpressionLoader("voic").args
voic_info = getExpressionLoader("voic").expression_info
with ui.card().classes("w-full").bind_visibility_from(
state["expressions"]["voic"], "selected"
):
ui.label(voic_info).classes("text-lg font-bold")
with ui.grid(columns=2).classes("w-full"):
ui.switch(_("Spline Smoothing")).bind_value(
state["expressions"]["voic"], "spline_smoothing",
).tooltip_md(voic_args.spline_smoothing.help)
with ui.grid(columns=3).classes("w-full"):
ui.number(label=_("Align Radius"), min=1, format="%d").bind_value(
state["expressions"]["voic"], "align_radius",
forward=lambda v: voic_args.align_radius.type(v) if v is not None else None,
).tooltip_md(voic_args.align_radius.help)
ui.number(label=_("Smoothness"), min=0, format="%d").bind_value(
state["expressions"]["voic"], "smoothness",
forward=lambda v: voic_args.smoothness.type(v) if v is not None else None,
).tooltip_md(voic_args.smoothness.help)
ui.number(label=_("Dynamic Range"), min=0.0, step=0.1, format="%.1f").bind_value(
state["expressions"]["voic"], "dynamic_range",
forward=lambda v: voic_args.dynamic_range.type(v) if v is not None else None,
).tooltip_md(voic_args.dynamic_range.help)
ui.number(label=_("Bias"), format="%d").bind_value(
state["expressions"]["voic"], "bias",
forward=lambda v: voic_args.bias.type(v) if v is not None else None,
).tooltip_md(voic_args.bias.help)
# Add the config buttons above the Process button
with ui.row().classes("w-full justify-between"):
ui.button(
_("Import Config"),
on_click=import_config,
color="secondary",
icon="file_download",
)
ui.button(
_("Export Config"),
on_click=export_config,
color="secondary",
icon="file_upload",
)
# Process button, spinner, and log element
with ui.row().classes("w-full") as status_row:
with ui.dialog() as spinner_dialog, ui.card():
ui.spinner(size="lg")
process_button = ui.button(
_("Process"), on_click=process_files, icon="play_arrow"
).classes("flex-grow")
with ui.element().classes("relative w-full h-60"):
log_element = ui.log().classes("w-full h-full select-text cursor-text")
# Clipboard button
ui.button("📋").props("flat dense").classes(
"absolute top-0 right-5 m-1 text-sm px-1 py-0.5 opacity-70 hover:opacity-100"
).on("click", js_handler=f"""
() => {{
const logEl = document.getElementById("c{log_element.id}");
if (logEl) {{
const text = [...logEl.children].map(el => el.textContent).join("\\n");
navigator.clipboard.writeText(text);
}}
}}
""")
logger_app, logger_exp = setup_loggers(log_element)
def main():
init_gettext(lang=LANG, locale_dir=LOCALE_DIR, domain=LOCALE_DOMAIN)
parser = argparse.ArgumentParser(
description=_("Migrate expressions from real singers to DiffSingers (GUI)"),
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--version", action="version", version=f"%(prog)s v{VERSION}")
# Parse only the known arguments for frozen script with multiprocessing
args, unknown = parser.parse_known_args()
# Patch NiceGUI's JSON serializer to handle LazyString
patch_nicegui_json()
patch_tooltip_md()
# Start the GUI
ui_params = {
"title": f"Expressive GUI v{VERSION}",
"native": True,
"reload": False,
"window_size": (600, 640),
"reconnect_timeout": 60,
"language": LANG[0].replace('_', '-') if LANG else 'en-US',
}
try:
# Deal with different running mode of this nicegui app
if is_root_mode():
# Run with root function (app installed from wheel)
ui.run(
root=create_gui,
**ui_params
)
else:
# Run in script mode (app run through this script or frozen with pyinstaller)
create_gui()
# For multiprocessing support in PyInstaller on Windows before calling ui.run()
# https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing
import multiprocessing
multiprocessing.freeze_support()
# For PyInstaller compatibility with runpy used in ui.run from nicegui 3
# https://github.com/zauberzeug/nicegui/issues/5247
with patch_runpy():
ui.run(
**ui_params
)
except KeyboardInterrupt:
if getattr(sys, 'frozen', False):
# Suppress KeyboardInterrupt error on exit
pass
else:
raise
# Run the app
if __name__ in {"__main__", "__mp_main__"}:
main()