File size: 114,579 Bytes
e527cbb
 
 
a9240b9
 
6c52bb8
e527cbb
a9240b9
a8bcc2a
e527cbb
 
a9240b9
6c52bb8
 
 
e527cbb
6c52bb8
 
 
 
 
 
e527cbb
6c52bb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e527cbb
 
 
 
6c52bb8
 
 
88d335a
6c52bb8
92a1819
6c52bb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
 
 
 
a9240b9
9baaa55
 
88d335a
9baaa55
 
 
 
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
 
c2861b3
 
9baaa55
 
c2861b3
9baaa55
 
 
c2861b3
 
9baaa55
 
 
 
 
c2861b3
9baaa55
 
 
c2861b3
 
9baaa55
 
88d335a
9baaa55
 
 
88d335a
 
9baaa55
 
88d335a
9baaa55
 
 
88d335a
 
9baaa55
 
 
 
 
88d335a
9baaa55
 
 
88d335a
 
9baaa55
 
88d335a
9baaa55
88d335a
 
9baaa55
 
88d335a
bbed340
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbed340
 
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
bbed340
 
9baaa55
 
 
 
 
 
6c52bb8
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9240b9
9baaa55
88d335a
 
a9240b9
9baaa55
88d335a
 
9baaa55
 
 
 
88d335a
 
9baaa55
88d335a
9baaa55
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
88d335a
 
9baaa55
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
88d335a
9baaa55
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
 
88d335a
 
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
88d335a
9baaa55
 
 
 
 
88d335a
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
 
88d335a
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
92a1819
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
9baaa55
88d335a
9baaa55
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
88d335a
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
 
88d335a
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
0d89ce4
9baaa55
e527cbb
9baaa55
 
 
 
 
 
0d89ce4
 
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
8e1e184
9baaa55
 
 
8e1e184
9baaa55
e527cbb
9baaa55
 
e527cbb
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
 
2cd7261
 
9baaa55
 
 
8e1e184
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
9baaa55
e527cbb
9baaa55
e527cbb
 
9baaa55
 
e527cbb
 
9baaa55
 
8e1e184
9baaa55
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
88d335a
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
88d335a
9baaa55
 
88d335a
9baaa55
 
88d335a
9baaa55
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
88d335a
9baaa55
 
 
88d335a
9baaa55
 
 
88d335a
9baaa55
 
 
88d335a
9baaa55
 
 
 
 
88d335a
9baaa55
 
 
 
 
8e1e184
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
88d335a
9baaa55
 
 
 
88d335a
 
 
9baaa55
 
 
8e1e184
9baaa55
 
 
 
 
 
8e1e184
9baaa55
88d335a
9baaa55
 
88d335a
9baaa55
 
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
8e1e184
9baaa55
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
8e1e184
9baaa55
88d335a
9baaa55
 
 
 
88d335a
9baaa55
8e1e184
9baaa55
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
88d335a
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
88d335a
9baaa55
 
88d335a
9baaa55
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
88d335a
9baaa55
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
8e1e184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9baaa55
88d335a
9baaa55
8e1e184
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
88d335a
9baaa55
 
88d335a
9baaa55
 
8e1e184
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
 
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
88d335a
8e1e184
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
6c52bb8
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
88d335a
9baaa55
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
9baaa55
 
 
88d335a
9baaa55
 
 
88d335a
 
 
9baaa55
88d335a
9baaa55
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
9baaa55
 
 
 
 
8e1e184
88d335a
 
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
 
 
9baaa55
 
 
 
 
 
88d335a
9baaa55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
 
9baaa55
 
 
 
 
88d335a
 
a187464
315aa03
 
b3f6d6c
 
 
bbed340
 
8e1e184
bbed340
 
 
 
 
 
 
 
8e1e184
bbed340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
bbed340
 
 
 
 
 
 
8e1e184
bbed340
 
 
 
 
 
 
 
8e1e184
bbed340
 
 
 
8e1e184
bbed340
 
 
 
8e1e184
bbed340
 
 
 
 
 
 
 
 
 
 
 
60cfd7a
e527cbb
 
 
8e1e184
e527cbb
 
 
 
8e1e184
e527cbb
 
 
8e1e184
e527cbb
 
 
 
 
 
 
 
 
88d335a
b3a1fdb
e527cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
c268808
88d335a
 
e161cd8
88d335a
 
 
c268808
88d335a
c268808
88d335a
 
e527cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e1e184
e527cbb
 
 
 
 
8e1e184
e527cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a1819
 
 
 
 
8e1e184
92a1819
 
 
 
 
 
 
 
8e1e184
92a1819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bdd960
92a1819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e527cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88d335a
e527cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9240b9
e527cbb
88d335a
e527cbb
8e1e184
e527cbb
 
 
88d335a
d6fbbdc
a9240b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
from __future__ import annotations

import os
import sys
from enum import IntEnum, StrEnum, auto
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING, Annotated, Any, TypedDict

import gradio as gr
import typer
from huggingface_hub import snapshot_download
from pydantic import BaseModel
from ultimate_rvc.common import AUDIO_DIR, MODELS_DIR, TEMP_DIR
from ultimate_rvc.core.generate.song_cover import get_named_song_dirs
from ultimate_rvc.core.generate.speech import get_edge_tts_voice_names
from ultimate_rvc.core.manage.audio import (
    get_audio_datasets,
    get_named_audio_datasets,
    get_saved_output_audio,
    get_saved_speech_audio,
)
from ultimate_rvc.core.manage.config import get_config_names, load_config
from ultimate_rvc.core.manage.models import (
    get_custom_embedder_model_names,
    get_custom_pretrained_model_names,
    get_training_model_names,
    get_voice_model_names,
)
from ultimate_rvc.web.common import (
    initialize_dropdowns,
    exception_harness,
    render_transfer_component,
    setup_transfer_event,
    toggle_visibility,
    toggle_visible_component,
    update_dropdowns,
    update_output_name,
    update_value,
)

from ultimate_rvc.web.config.component import (
    AnyComponentConfig,
    AudioConfig,
    CheckboxConfig,
    ComponentConfig,
    DropdownConfig,
    NumberConfig,
    RadioConfig,
    SliderConfig,
    TextboxConfig,
)
from ultimate_rvc.web.config.tab import (
    SongGenerationConfig,
    SpeechGenerationConfig,
    TrainingConfig,
)
from ultimate_rvc.web.tabs.generate.speech.multi_step_generation import (
    render as render_speech_multi_step_tab,
)
from ultimate_rvc.web.tabs.generate.speech.one_click_generation import (
    render as render_speech_one_click_tab,
)
from ultimate_rvc.web.tabs.manage.audio import render as render_audio_tab
from ultimate_rvc.web.tabs.manage.models import render as render_models_tab
from ultimate_rvc.web.tabs.manage.settings import render as render_settings_tab

if TYPE_CHECKING:
    import gradio as gr
    from typing import TYPE_CHECKING

from functools import partial

import gradio as gr
from ultimate_rvc.core.common import (
    INTERMEDIATE_AUDIO_BASE_DIR,
    OUTPUT_AUDIO_DIR,
    copy_file_safe,
    display_progress,
    get_file_hash,
    json_dump,
    json_load,
    validate_model,
    validate_url,
)
from ultimate_rvc.core.exceptions import (
    Entity,
    InvalidLocationError,
    Location,
    NotFoundError,
    NotProvidedError,
    UIMessage,
    YoutubeUrlError,
)
from ultimate_rvc.core.generate.common import (
    convert,
    get_unique_base_path,
    mix_audio,
    validate_audio_dir_exists,
    validate_audio_file_exists,
    wavify,
)
from ultimate_rvc.core.generate.song_cover import (
    get_named_song_dirs,
    get_song_cover_name,
    mix_song,
    pitch_shift,
    postprocess,
    retrieve_song,
    separate_audio,
    get_named_song_dirs,
    get_song_cover_name,
    run_pipeline,
)
from ultimate_rvc.core.generate.typing_extra import (
    EffectedVocalsMetaData,
    FileMetaData,
    MixedAudioType,
    PitchShiftMetaData,
    RVCAudioMetaData,
    SeparatedAudioMetaData,
)
from ultimate_rvc.core.manage.audio import get_saved_output_audio
from ultimate_rvc.typing_extra import EmbedderModel
from ultimate_rvc.web.common import (
    PROGRESS_BAR,
    exception_harness,
    toggle_intermediate_audio,
    toggle_visibility,
    toggle_visible_component,
    update_dropdowns,
    update_output_name,
    update_value,
)
from ultimate_rvc.web.typing_extra import ConcurrencyId

type StrPath = str | PathLike[str]

type Json = Mapping[str, Json] | Sequence[Json] | str | int | float | bool | None


class SegmentSize(IntEnum):
    """Enumeration of segment sizes for audio separation."""

    SEG_64 = 64
    SEG_128 = 128
    SEG_256 = 256
    SEG_512 = 512
    SEG_1024 = 1024
    SEG_2048 = 2048
    SEG_4096 = 4096


class F0Method(StrEnum):
    """Enumeration of pitch extraction methods."""

    RMVPE = "rmvpe"
    CREPE = "crepe"
    CREPE_TINY = "crepe-tiny"
    FCPE = "fcpe"


class RVCContentType(StrEnum):
    """Enumeration of valid content to convert with RVC."""

    VOCALS = "vocals"
    VOICE = "voice"
    SPEECH = "speech"
    AUDIO = "audio"


class SampleRate(IntEnum):
    """Enumeration of supported audio sample rates."""

    HZ_16000 = 16000
    HZ_44100 = 44100
    HZ_48000 = 48000
    HZ_96000 = 96000
    HZ_192000 = 192000


class AudioExt(StrEnum):
    """Enumeration of supported audio file formats."""

    MP3 = "mp3"
    WAV = "wav"
    FLAC = "flac"
    OGG = "ogg"


class DeviceType(StrEnum):
    """Enumeration of device types for training voice models."""

    AUTOMATIC = "Automatic"
    CPU = "CPU"
    GPU = "GPU"


class TrainingSampleRate(StrEnum):
    """Enumeration of sample rates for training voice models."""

    HZ_32K = "32000"
    HZ_40K = "40000"
    HZ_48K = "48000"


class PretrainedSampleRate(StrEnum):
    """Enumeration of valid sample rates for pretrained models."""

    HZ_32K = "32k"
    HZ_40K = "40k"
    HZ_44K = "44k"
    HZ_48K = "48k"


class TrainingF0Method(StrEnum):
    """Enumeration of pitch extraction methods for training."""

    RMVPE = "rmvpe"
    CREPE = "crepe"
    CREPE_TINY = "crepe-tiny"


class AudioSplitMethod(StrEnum):
    """
    Enumeration of methods to use for splitting audio files during
    dataset preprocessing.
    """

    SKIP = "Skip"
    SIMPLE = "Simple"
    AUTOMATIC = "Automatic"


class Vocoder(StrEnum):
    """Enumeration of vocoders for training voice models."""

    HIFI_GAN = "HiFi-GAN"
    MRF_HIFI_GAN = "MRF HiFi-GAN"
    REFINE_GAN = "RefineGAN"


class IndexAlgorithm(StrEnum):
    """Enumeration of indexing algorithms for training voice models."""

    AUTO = "Auto"
    FAISS = "Faiss"
    KMEANS = "KMeans"


class PretrainedType(StrEnum):
    """
    Enumeration of the possible types of pretrained models to finetune
    voice models on.
    """

    NONE = "None"
    DEFAULT = "Default"
    CUSTOM = "Custom"


class ConcurrencyId(StrEnum):
    """Enumeration of possible concurrency identifiers."""

    GPU = auto()


class SongSourceType(StrEnum):
    """The type of source providing the song to generate a cover of."""

    PATH = "Local or HTTP filepath"
    LOCAL_FILE = "Local file"
    CACHED_SONG = "Cached song"


class SpeechSourceType(StrEnum):
    """The type of source providing the text to generate speech from."""

    TEXT = "Text"
    LOCAL_FILE = "Local file"


class SongTransferOption(StrEnum):
    """Enumeration of possible song transfer options."""

    STEP_1_AUDIO = "Step 1: stem splitting"
    STEP_2_VOCALS = "Step 2: vocal conversion"
    STEP_3_VOCALS = "Step 3: vocal effect"
    STEP_4_INSTRUMENTALS = "Step 4: instrumentals"
    STEP_4_BACKUP_VOCALS = "Step 4: backup vocals"
    STEP_5_MAIN_VOCALS = "Step 5: main vocals"
    STEP_5_INSTRUMENTALS = "Step 5: instrumentals"
    STEP_5_BACKUP_VOCALS = "Step 5: backup vocals"


class SpeechTransferOption(StrEnum):
    """Enumeration of possible speech transfer options."""

    STEP_2_SPEECH = "Step 2: speech conversion"
    STEP_3_SPEECH = "Step 3: speech effect"


class ComponentVisibilityKwArgs(TypedDict, total=False):
    """
    Keyword arguments for setting component visibility.

    Attributes
    ----------
    visible : bool
        Whether the component should be visible.
    value : Any
        The value of the component.

    """

    visible: bool
    value: Any


class UpdateDropdownKwArgs(TypedDict, total=False):
    """
    Keyword arguments for updating a dropdown component.

    Attributes
    ----------
    choices : DropdownChoices
        The updated choices for the dropdown component.
    value : DropdownValue
        The updated value for the dropdown component.

    """

    choices: DropdownChoices
    value: DropdownValue


class TextBoxKwArgs(TypedDict, total=False):
    """
    Keyword arguments for updating a textbox component.

    Attributes
    ----------
    value : str | None
        The updated value for the textbox component.
    placeholder : str | None
        The updated placeholder for the textbox component.

    """

    value: str | None
    placeholder: str | None


class UpdateAudioKwArgs(TypedDict, total=False):
    """
    Keyword arguments for updating an audio component.

    Attributes
    ----------
    value : str | None
        The updated value for the audio component.

    """

    value: str | None


class DatasetType(StrEnum):
    """The type of dataset to train a voice model."""

    NEW_DATASET = "Create new dataset"
    EXISTING_DATASET = "Use existing dataset"


class EmbedderModel(StrEnum):
    """Enumeration of audio embedding models."""

    CONTENTVEC = "contentvec"
    CRUSTY = "Crusty"
    CUSTOM = "custom"


class SeparationModel(StrEnum):
    """Enumeration of audio separation models."""

    UVR_MDX_NET_VOC_FT = "UVR-MDX-NET-Voc_FT.onnx"
    UVR_MDX_NET_KARA_2 = "UVR_MDXNET_KARA_2.onnx"
    REVERB_HQ_BY_FOXJOY = "Reverb_HQ_By_FoxJoy.onnx"
    UVR_MDX_NET_Inst_HQ_3 = "UVR-MDX-NET-Inst_HQ_3.onnx"
    Kim_Vocal_1 = "Kim_Vocal_1.onnx"
    Kim_Vocal_2 = "Kim_Vocal_2.onnx"
    Kim_Inst = "Kim_Inst.onnx"
    UVR_MDX_NET_Inst_HQ_4 = "UVR-MDX-NET-Inst_HQ_4.onnx"
    kuielab_a_vocals = "kuielab_a_vocals.onnx"
    kuielab_b_vocals = "kuielab_b_vocals.onnx"
    kuielab_a_drums = "kuielab_a_drums.onnx"
    kuielab_b_drums = "kuielab_b_drums.onnx"
    kuielab_a_bass = "kuielab_a_bass.onnx"
    kuielab_b_bass = "kuielab_b_bass.onnx"
    kuielab_a_other = "kuielab_a_other.onnx"
    kuielab_b_other = "kuielab_b_other.onnx"
    MDX23C_8KFFT_InstVoc_HQ_2 = "MDX23C-8KFFT-InstVoc_HQ_2.ckpt"
    UVR_DeNoise = "UVR-DeNoise.pth"
    UVR_DeEcho_DeReverb = "UVR-DeEcho-DeReverb.pth"


now_dir = os.getcwd()

sys.path.append(now_dir)
models_dir = "models"

dump_path = os.path.join(now_dir, models_dir)

repo_id = "lainlives/voice"

hf_token = os.environ.get("HF_TOKEN")
snapshot_download(repo_id=repo_id, local_dir=dump_path, token=hf_token)

# if __name__ == "__main__":
#    start_app(share=False, ssr_mode = True)


config_name = "default"  # os.environ.get("URVC_CONFIG")
cookiefile = os.environ.get("YT_COOKIEFILE")


"""
Module defining models for representing configuration settings for
UI tabs.
"""


class SongIntermediateAudioConfig(BaseModel):
    """
    Configuration settings for intermediate audio components in the
    one-click song generation tab.

    Attributes
    ----------
    song : AudioConfig
        Configuration settings for the input song audio component.
    vocals : AudioConfig
        Configuration settings for the vocals audio component.
    instrumentals : AudioConfig
        Configuration settings for the instrumentals audio component.
    main_vocals : AudioConfig
        Configuration settings for the main vocals audio component.
    backup_vocals : AudioConfig
        Configuration settings for the backup vocals audio component.
    main_vocals_dereverbed : AudioConfig
        Configuration settings for the main vocals de-reverbed audio
        component.
    main_vocals_reverb : AudioConfig
        Configuration settings for the main vocals reverb audio
        component.
    converted_vocals : AudioConfig
        Configuration settings for the converted vocals audio
        component.
    postprocessed_vocals : AudioConfig
        Configuration settings for the postprocessed vocals audio
        component.
    instrumentals_shifted : AudioConfig
        Configuration settings for the shifted instrumentals audio
        component.
    backup_vocals_shifted : AudioConfig
        Configuration settings for the shifted backup vocals audio
        component.
    all : list[gr.Audio]
        List of instances of all intermediate audio components.

    """

    song: AudioConfig = AudioConfig.intermediate(label="Song")
    vocals: AudioConfig = AudioConfig.intermediate(label="Vocals")
    instrumentals: AudioConfig = AudioConfig.intermediate(
        label="Instrumentals",
    )
    main_vocals: AudioConfig = AudioConfig.intermediate(
        label="Main vocals",
    )
    backup_vocals: AudioConfig = AudioConfig.intermediate(
        label="Backup vocals",
    )
    main_vocals_dereverbed: AudioConfig = AudioConfig.intermediate(
        label="De-reverbed main vocals",
    )
    main_vocals_reverb: AudioConfig = AudioConfig.intermediate(
        label="Main vocals with reverb",
    )
    converted_vocals: AudioConfig = AudioConfig.intermediate(
        label="Converted vocals",
    )
    postprocessed_vocals: AudioConfig = AudioConfig.intermediate(
        label="Postprocessed vocals",
    )
    instrumentals_shifted: AudioConfig = AudioConfig.intermediate(
        label="Pitch-shifted instrumentals",
    )
    backup_vocals_shifted: AudioConfig = AudioConfig.intermediate(
        label="Pitch-shifted backup vocals",
    )

    @property
    def all(self) -> list[gr.Audio]:
        """
        Retrieve instances of all intermediate audio components
        in the one-click song generation tab.

        Returns
        -------
        list[gr.Audio]
            List of instances of all intermediate audio components in
            the one-click song generation tab.

        """
        # NOTE we are using self.__annotations__ to get the fields in
        # the order they are defined in the class
        return [getattr(self, field).instance for field in self.__annotations__]


class OneClickSongGenerationConfig(SongGenerationConfig):
    """
    Configuration settings for the one-click song generation tab.

    Attributes
    ----------
    n_octaves : SliderConfig
        Configuration settings for an octave pitch shift slider
        component.
    n_semitones : SliderConfig
        Configuration settings for a semitone pitch shift slider
        component.
    show_intermediate_audio : CheckboxConfig
        Configuration settings for a show intermediate audio checkbox
        component.
    intermediate_audio : SongIntermediateAudioConfig
        Configuration settings for intermediate audio components.

    See Also
    --------
    SongGenerationConfig
        Parent model defining common component configuration settings
        for song generation tabs.

    """

    n_octaves: SliderConfig = SliderConfig.octave_shift(
        label="Vocal pitch shift",
        info=(
            "The number of octaves to shift the pitch of the converted vocals by. Use 1"
            " for male-to-female and -1 for vice-versa."
        ),
    )

    n_semitones: SliderConfig = SliderConfig.semitone_shift(
        label="Overall pitch shift",
        info=(
            "The number of semi-tones to shift the pitch of the converted vocals,"
            " instrumentals and backup vocals by."
        ),
    )
    show_intermediate_audio: CheckboxConfig = CheckboxConfig(
        label="Show intermediate audio",
        info="Show intermediate audio tracks produced during song cover generation.",
        value=False,
        exclude_value=True,
    )
    intermediate_audio: SongIntermediateAudioConfig = SongIntermediateAudioConfig()


class SongInputAudioConfig(BaseModel):
    """
    Configuration settings for input audio components in the multi-step
    song generation tab.

    Attributes
    ----------
    audio : AudioConfig
        Configuration settings for the input audio component.
    vocals : AudioConfig
        Configuration settings for the vocals audio component.
    converted_vocals : AudioConfig
        Configuration settings for the converted vocals audio
        component.
    instrumentals : AudioConfig
        Configuration settings for the instrumentals audio
        component.
    backup_vocals : AudioConfig
        Configuration settings for the backup vocals audio
        component.
    main_vocals : AudioConfig
        Configuration settings for the main vocals audio
        component.
    shifted_instrumentals : AudioConfig
        Configuration settings for the shifted instrumentals audio
        component.
    shifted_backup_vocals : AudioConfig
        Configuration settings for the shifted backup vocals audio
        component.
    all : list[AudioConfig]
        List of configuration settings for all input audio
        components in the multi-step song generation tab.

    """

    audio: AudioConfig = AudioConfig.input(label="Audio")
    vocals: AudioConfig = AudioConfig.input(label="Vocals")
    converted_vocals: AudioConfig = AudioConfig.input(label="Vocals")
    instrumentals: AudioConfig = AudioConfig.input(label="Instrumentals")
    backup_vocals: AudioConfig = AudioConfig.input(label="Backup vocals")
    main_vocals: AudioConfig = AudioConfig.input(label="Main vocals")
    shifted_instrumentals: AudioConfig = AudioConfig.input(label="Instrumentals")
    shifted_backup_vocals: AudioConfig = AudioConfig.input(label="Backup vocals")

    @property
    def all(self) -> list[AudioConfig]:
        """
        Retrieve configuration settings for all input audio components
        in the multi-step song generation tab.

        Returns
        -------
        list[AudioConfig]
            List of configuration settings for all input audio
            components in the multi-step song generation tab.

        """
        return [getattr(self, field) for field in self.__annotations__]


class SongDirsConfig(BaseModel):
    """
    Configuration settings for song directory components in the
    multi-step song generation tab.

    Attributes
    ----------
    separate_audio : DropdownConfig
        Configuration settings for the song directory component
        for separating audio.
    convert_vocals : DropdownConfig
        Configuration settings for the song directory component
        for converting vocals.
    postprocess_vocals : DropdownConfig
        Configuration settings for the song directory component
        for postprocessing vocals.
    pitch_shift_background : DropdownConfig
        Configuration settings for the song directory component
        for pitch-shifting background audio.
    mix : DropdownConfig
        Configuration settings for the song directory component
        for mixing audio.
    all : list[gr.Dropdown]
        List of instances of all song directory components in the
        multi-step song generation tab.

    """

    separate_audio: DropdownConfig = DropdownConfig.song_dir()
    convert_vocals: DropdownConfig = DropdownConfig.song_dir()
    postprocess_vocals: DropdownConfig = DropdownConfig.song_dir()
    pitch_shift_background: DropdownConfig = DropdownConfig.song_dir()
    mix: DropdownConfig = DropdownConfig.song_dir()

    @property
    def all(self) -> list[gr.Dropdown]:
        """
        Retrieve instances of all song directory components in the
        multi-step song generation tab.

        Returns
        -------
        list[gr.Dropdown]
            List of instances of all song directory components in
            the multi-step song generation tab.

        """
        return [getattr(self, field).instance for field in self.__annotations__]


class MultiStepSongGenerationConfig(SongGenerationConfig):
    """
    Configuration settings for multi-step song generation tab.

    Attributes
    ----------
    separation_model : DropdownConfig
        Configuration settings for a separation model dropdown
        component.
    segment_size : RadioConfig
        Configuration settings for a segment size radio component.
    n_octaves : SliderConfig
        Configuration settings for an octave pitch shift slider
        component.
    n_semitones : SliderConfig
        Configuration settings for a semitone pitch shift slider
        component.
    n_semitones_instrumentals : SliderConfig
        Configuration settings for an instrumentals pitch shift slider
        component.
    n_semitones_backup_vocals : SliderConfig
        Configuration settings for a backup vocals pitch shift slider
        component.
    input_audio : SongInputAudioConfig
        Configuration settings for input audio components.
    song_dirs : SongDirsConfig
        Configuration settings for song directory components.

    See Also
    --------
    SongGenerationConfig
        Parent model defining common component configuration settings
        for song generation tabs.

    """

    separation_model: DropdownConfig = DropdownConfig(
        label="Separation model",
        info="The model to use for audio separation.",
        value=SeparationModel.MDX23C_8KFFT_InstVoc_HQ_2,
        choices=list(SeparationModel),
    )
    segment_size: RadioConfig = RadioConfig(
        label="Segment size",
        info=(
            "The size of the segments into which the audio is split. Using a larger"
            " size consumes more resources, but may give better results."
        ),
        value=SegmentSize.SEG_2048,
        choices=list(SegmentSize),
    )
    n_octaves: SliderConfig = SliderConfig.octave_shift(
        label="Pitch shift (octaves)",
        info=(
            "The number of octaves to pitch-shift the converted voice by. Use 1 for"
            " male-to-female and -1 for vice-versa."
        ),
    )
    n_semitones: SliderConfig = SliderConfig.semitone_shift(
        label="Pitch shift (semi-tones)",
        info=(
            "The number of semi-tones to pitch-shift the converted vocals by. Altering"
            " this slightly reduces sound quality."
        ),
    )
    n_semitones_instrumentals: SliderConfig = SliderConfig.semitone_shift(
        label="Instrumental pitch shift",
        info="The number of semi-tones to pitch-shift the instrumentals by.",
    )
    n_semitones_backup_vocals: SliderConfig = SliderConfig.semitone_shift(
        label="Backup vocal pitch shift",
        info="The number of semi-tones to pitch-shift the backup vocals by.",
    )
    input_audio: SongInputAudioConfig = SongInputAudioConfig()
    song_dirs: SongDirsConfig = SongDirsConfig()


class SpeechIntermediateAudioConfig(BaseModel):
    """
    Configuration settings for intermediate audio components in the
    one-click speech generation tab.

    Attributes
    ----------
    speech : AudioConfig
        Configuration settings for the input speech audio component.
    converted_speech : AudioConfig
        Configuration settings for the converted speech audio component.
    all : list[gr.Audio]
        List of instances of all intermediate audio components in the
        speech generation tab.

    """

    speech: AudioConfig = AudioConfig.intermediate(label="Speech")
    converted_speech: AudioConfig = AudioConfig.intermediate(label="Converted speech")

    @property
    def all(self) -> list[gr.Audio]:
        """
        Retrieve instances of all intermediate audio components in the
        speech generation tab.

        Returns
        -------
        list[gr.Audio]
            List of instances of all intermediate audio components in
            the speech generation tab.

        """
        return [getattr(self, field).instance for field in self.__annotations__]


class OneClickSpeechGenerationConfig(SpeechGenerationConfig):
    """
    Configuration settings for one-click speech generation tab.

    Attributes
    ----------
    intermediate_audio : SpeechIntermediateAudioConfig
        Configuration settings for intermediate audio components.
    show_intermediate_audio : CheckboxConfig
        Configuration settings for a show intermediate audio checkbox
        component.

    See Also
    --------
    SpeechGenerationConfig
        Parent model defining common component configuration settings
        for speech generation tabs.

    """

    intermediate_audio: SpeechIntermediateAudioConfig = SpeechIntermediateAudioConfig()

    show_intermediate_audio: CheckboxConfig = CheckboxConfig(
        label="Show intermediate audio",
        info="Show intermediate audio tracks produced during speech generation.",
        value=False,
        exclude_value=True,
    )


class SpeechInputAudioConfig(BaseModel):
    """
    Configuration settings for input audio components in the multi-step
    speech generation tab.

    Attributes
    ----------
    speech : AudioConfig
        Configuration settings for the input speech audio component.
    converted_speech : AudioConfig
        Configuration settings for the converted speech audio component.

    all : list[AudioConfig]
        List of configuration settings for all input audio components in
        the multi-step speech generation tab.

    """

    speech: AudioConfig = AudioConfig.input("Speech")
    converted_speech: AudioConfig = AudioConfig.input("Converted speech")

    @property
    def all(self) -> list[AudioConfig]:
        """
        Retrieve configuration settings for all input audio components
        in the multi-step speech generation tab.

        Returns
        -------
        list[AudioConfig]
            List of configuration settings for all input audio
            components in the multi-step speech generation tab.

        """
        return [getattr(self, field) for field in self.__annotations__]


class MultiStepSpeechGenerationConfig(SpeechGenerationConfig):
    """
    Configuration settings for the multi-step speech generation tab.

    Attributes
    ----------
    input_audio : SpeechInputAudioConfig
        Configuration settings for input audio components.

    See Also
    --------
    SpeechGenerationConfig
        Parent model defining common component configuration settings
        for speech generation tabs.

    """

    input_audio: SpeechInputAudioConfig = SpeechInputAudioConfig()


class MultiStepTrainingConfig(TrainingConfig):
    """Configuration settings for multi-step training tab."""


class ModelManagementConfig(BaseModel):
    """

    Configuration settings for model management tab.

    Attributes
    ----------
    voices : DropdownConfig
        Configuration settings for delete voice models dropdown
        component.
    embedders : DropdownConfig
        Configuration settings for delete embedder models dropdown
        component.
    pretraineds : DropdownConfig
        Configuration settings for delete pretrained models dropdown
        component.
    traineds : DropdownConfig
        Configuration settings for delete training models dropdown
        component.
    dummy_checkbox : CheckboxConfig
        Configuration settings for a dummy checkbox component.

    """

    voices: DropdownConfig = DropdownConfig.multi_delete(
        label="Voice models",
        info="Select one or more voice models to delete.",
    )
    embedders: DropdownConfig = DropdownConfig.multi_delete(
        label="Custom embedder models",
        info="Select one or more embedder models to delete.",
    )
    pretraineds: DropdownConfig = DropdownConfig.multi_delete(
        label="Custom pretrained models",
        info="Select one or more pretrained models to delete.",
    )
    traineds: DropdownConfig = DropdownConfig.multi_delete(
        label="Training models",
        info="Select one or more training models to delete.",
    )

    dummy_checkbox: CheckboxConfig = CheckboxConfig(
        value=False,
        visible=False,
        exclude_value=True,
    )


class AudioManagementConfig(BaseModel):
    """
    Configuration settings for audio management tab.

    Attributes
    ----------
    intermediate : DropdownConfig
        Configuration settings for delete intermediate audio files
        dropdown component
    speech : DropdownConfig
        Configuration settings for delete speech audio files dropdown
        component.
    output : DropdownConfig
        Configuration settings for delete output audio files dropdown
        component.
    dataset : DropdownConfig
        Configuration settings for delete dataset audio files dropdown
        component.
    dummy_checkbox : CheckboxConfig
        Configuration settings for a dummy checkbox component.

    """

    intermediate: DropdownConfig = DropdownConfig.multi_delete(
        label="Song directories",
        info=(
            "Select one or more song directories containing intermediate audio files to"
            " delete."
        ),
    )
    speech: DropdownConfig = DropdownConfig.multi_delete(
        label="Speech audio files",
        info="Select one or more speech audio files to delete.",
    )
    output: DropdownConfig = DropdownConfig.multi_delete(
        label="Output audio files",
        info="Select one or more output audio files to delete.",
    )
    dataset: DropdownConfig = DropdownConfig.multi_delete(
        label="Dataset audio files",
        info="Select one or more datasets containing audio files to delete.",
    )

    dummy_checkbox: CheckboxConfig = CheckboxConfig(
        value=False,
        visible=False,
        exclude_value=True,
    )


class SettingsManagementConfig(BaseModel):
    """
    Configuration settings for settings management tab.

    Attributes
    ----------
    dummy_checkbox : CheckboxConfig
        Configuration settings for a dummy checkbox component.

    """

    load_config_name: DropdownConfig = DropdownConfig(
        label="Configuration name",
        info="The name of a configuration to load UI settings from",
        value=None,
        render=False,
        exclude_value=True,
    )
    delete_config_names: DropdownConfig = DropdownConfig.multi_delete(
        label="Configuration names",
        info="Select the name of one or more configurations to delete",
    )
    dummy_checkbox: CheckboxConfig = CheckboxConfig(
        value=False,
        visible=False,
        exclude_value=True,
    )


class TotalSongGenerationConfig(BaseModel):
    """
    All configuration settings for song generation tabs.

    Attributes
    ----------
    one_click : OneClickSongGenerationConfig
        Configuration settings for the one-click song generation tab.
    multi_step : MultiStepSongGenerationConfig
        Configuration settings for the multi-step song generation tab.

    """

    one_click: OneClickSongGenerationConfig = OneClickSongGenerationConfig()
    multi_step: MultiStepSongGenerationConfig = MultiStepSongGenerationConfig()


class TotalSpeechGenerationConfig(BaseModel):
    """
    All configuration settings for speech generation tabs.

    Attributes
    ----------
    one_click : OneClickSpeechGenerationConfig
        Configuration settings for the one-click speech generation tab.
    multi_step : MultiStepSpeechGenerationConfig
        Configuration settings for the multi-step speech generation tab.

    """

    one_click: OneClickSpeechGenerationConfig = OneClickSpeechGenerationConfig()
    multi_step: MultiStepSpeechGenerationConfig = MultiStepSpeechGenerationConfig()


class TotalTrainingConfig(BaseModel):
    """
    All configuration settings for training tabs.

    Attributes
    ----------
    training : TrainingConfig
        Configuration settings for the multi-step training tab.

    """

    multi_step: MultiStepTrainingConfig = MultiStepTrainingConfig()


class TotalManagementConfig(BaseModel):
    """
    All configuration settings for management tabs.

    Attributes
    ----------
    model : ModelManagementConfig
        Configuration settings for the model management tab.
    audio : AudioManagementConfig
        Configuration settings for the audio management tab.
    settings : SettingsManagementConfig
        Configuration settings for the settings management tab.

    """

    model: ModelManagementConfig = ModelManagementConfig()
    audio: AudioManagementConfig = AudioManagementConfig()
    settings: SettingsManagementConfig = SettingsManagementConfig()


class TotalConfig(BaseModel):
    """
    All configuration settings for the Ultimate RVC app.

    Attributes
    ----------
    song : TotalSongGenerationConfig
        Configuration settings for song generation tabs.
    speech : TotalSpeechGenerationConfig
        Configuration settings for speech generation tabs.
    training : TotalTrainingConfig
        Configuration settings for training tabs.
    management : TotalManagementConfig
        Configuration settings for management tabs.

    """

    song: TotalSongGenerationConfig = TotalSongGenerationConfig()
    speech: TotalSpeechGenerationConfig = TotalSpeechGenerationConfig()
    training: TotalTrainingConfig = TotalTrainingConfig()
    management: TotalManagementConfig = TotalManagementConfig()

    @cached_property
    def all(self) -> list[AnyComponentConfig]:
        """
        Recursively collect those component configuration models nested
        within the current model instance, which have values that are
        not excluded.

        Returns
        -------
        list[AnyComponentConfig]
            A list of component configuration models found within the
            current model instance, which have values that are not
            excluded.

        """

        def _collect(model: BaseModel) -> list[AnyComponentConfig]:
            component_configs: list[Any] = []
            for _, value in model:
                if isinstance(value, ComponentConfig):
                    if not value.exclude_value:
                        component_configs.append(value)
                elif isinstance(value, BaseModel):
                    component_configs.extend(_collect(value))
            return component_configs

        return _collect(self)


class BaseTabConfig(BaseModel):
    """
    Base model defining common component configuration settings for
    UI tabs.

    Attributes
    ----------
    embedder_model : DropdownConfig
        Configuration settings for an embedder model dropdown component.
    custom_embedder_model : DropdownConfig
        Configuration settings for a custom embedder model dropdown
        component.

    """

    embedder_model: DropdownConfig = DropdownConfig(
        label="Embedder model",
        info="The model to use for generating speaker embeddings.",
        value=EmbedderModel.CONTENTVEC,
        choices=list(EmbedderModel),
        exclude_value=True,
    )
    custom_embedder_model: DropdownConfig = DropdownConfig(
        label="Custom embedder model",
        info="Select a custom embedder model from the dropdown.",
        value=None,
        visible=False,
        render=False,
        exclude_value=True,
    )


class TrainingConfig(BaseTabConfig):
    """
    Common component configuration settings for training tabs.

    Attributes
    ----------
    dataset_type : DropdownConfig
        Configuration settings for a dataset type dropdown component.
    dataset : DropdownConfig
        Configuration settings for a dataset dropdown component.
    dataset_name : TextboxConfig
        Configuration settings for a dataset name textbox component.
    preprocess_model : DropdownConfig
        Configuration settings for a model name dropdown component
        for audio preprocessing.
    sample_rate : DropdownConfig
        Configuration settings for a sample rate dropdown component.
    filter_audio : CheckboxConfig
        Configuration settings for a filter audio checkbox component.
    clean_audio : CheckboxConfig
        Configuration settings for a clean audio checkbox component.
    clean_strength : SliderConfig
        Configuration settings for a clean strength slider component.
    split_method : DropdownConfig
        Configuration settings for an audio splitting method dropdown
        component.
    chunk_len : SliderConfig
        Configuration settings for a chunk length slider component.
    overlap_len : SliderConfig
        Configuration settings for an overlap length slider component.
    preprocess_cores : SliderConfig
        Configuration settings for a CPU cores slider component for
        preprocessing.
    extract_model : DropdownConfig
        Configuration settings for a model name dropdown component for
        feature extraction.
    f0_method : DropdownConfig
        Configuration settings for an F0 method dropdown component.
    hop_length : SliderConfig
        Configuration settings for a hop length slider component.
    include_mutes : SliderConfig
        Configuration settings for an include mutes slider component.
    extract_cores : SliderConfig
        Configuration settings for a CPU cores slider component for
        feature extraction.
    extraction_acceleration : HardwareAccelerationConfig
        Configuration settings for a hardware acceleration component for
        feature extraction.
    extraction_gpus : DropdownConfig
        Configuration settings for a GPU dropdown compoennt for feature
        extraction.
    train_model : DropdownConfig
        Configuration settings for a model name dropdown component for
        training.
    num_epochs : SliderConfig
        Configuration settings for a number of epochs slider component.
    batch_size : SliderConfig
        Configuration settings for a batch size slider component.
    detect_overtraining : CheckboxConfig
        Configuration settings for a detect overtraining checkbox
        component.
    overtraining_threshold : SliderConfig
        Configuration settings for an overtraining threshold slider
        component.
    vocoder : DropdownConfig
        Configuration settings for a vocoder dropdown component.
    index_algorithm : DropdownConfig
        Configuration settings for an index algorithm dropdown
        component.
    pretrained_type : DropdownConfig
        Configuration settings for a pretrained model type dropdown
        component.
    custom_pretrained_model : DropdownConfig
        Configuration settings for a custom pretrained model dropdown
        component.
    save_interval : SliderConfig
        Configuration settings for a save-interval slider component.
    save_all_checkpoints : CheckboxConfig
        Configuration settings for a save-all-checkpoints checkbox
        component.
    save_all_weights : CheckboxConfig
        Configuration settings for a save-all-weights checkbox
        component.
    clear_saved_data : CheckboxConfig
        Configuration settings for a clear-saved-data checkbox
        component.
    upload_model : CheckboxConfig
        Configuration settings for an upload voice model checkbox
        component.
    upload_name : TextboxConfig
        Configuration settings for an upload name textbox component.
    training_acceleration : HardwareAccelerationConfig
        Configuration settings for a hardware acceleration component for
        training.
    training_gpus : DropdownConfig
        Configuration settings for a GPU dropdown component for
        training.
    preload_dataset : CheckboxConfig
        Configuration settings for a preload dataset checkbox component.
    reduce_memory_usage : CheckboxConfig
        Configuration settings for a reduce-memory-usage checkbox
        component.

    See Also
    --------
    BaseTabConfig
        Parent model defining common component configuration settings
        for UI tabs.

    """

    dataset_type: DropdownConfig = DropdownConfig(
        label="Dataset type",
        info="Select the type of dataset to preprocess.",
        value=DatasetType.NEW_DATASET,
        choices=list(DatasetType),
        exclude_value=True,
    )
    dataset: DropdownConfig = DropdownConfig(
        label="Dataset path",
        info=(
            "The path to an existing dataset. Either select a path to a previously"
            " created dataset or provide a path to an external dataset."
        ),
        value=None,
        allow_custom_value=True,
        visible=False,
        render=False,
        exclude_value=True,
    )
    dataset_name: TextboxConfig = TextboxConfig(
        label="Dataset name",
        info=(
            "The name of the new dataset. If the dataset already exists, the provided"
            " audio files will be added to it."
        ),
        value="My dataset",
        exclude_value=True,
    )
    preprocess_model: DropdownConfig = DropdownConfig(
        label="Model name",
        info=(
            "Name of the model to preprocess the given dataset for. Either select an"
            " existing model from the dropdown or provide the name of a new model."
        ),
        value="My model",
        allow_custom_value=True,
        render=False,
        exclude_value=True,
    )
    sample_rate: DropdownConfig = DropdownConfig(
        label="Sample rate",
        info="Target sample rate for the audio files in the provided dataset.",
        value=TrainingSampleRate.HZ_40K,
        choices=list(TrainingSampleRate),
    )
    filter_audio: CheckboxConfig = CheckboxConfig(
        label="Filter audio",
        info=(
            "Whether to remove low-frequency sounds from the audio files in the"
            " provided dataset by applying a high-pass butterworth filter.<br><br>"
        ),
        value=True,
    )
    clean_audio: CheckboxConfig = CheckboxConfig(
        label="Clean audio",
        info=(
            "Whether to clean the audio files in the provided dataset using noise"
            " reduction algorithms.<br><br><br>"
        ),
        value=False,
        exclude_value=True,
    )
    clean_strength: SliderConfig = SliderConfig.clean_strength(visible=False)
    split_method: DropdownConfig = DropdownConfig(
        label="Audio splitting method",
        info=(
            "The method to use for splitting the audio files in the provided dataset."
            " Use the `Skip` method to skip splitting if the audio files are already"
            " split. Use the `Simple` method if excessive silence has already been"
            " removed from the audio files. Use the `Automatic` method for automatic"
            " silence detection and splitting around it."
        ),
        value=AudioSplitMethod.AUTOMATIC,
        choices=list(AudioSplitMethod),
        exclude_value=True,
    )
    chunk_len: SliderConfig = SliderConfig(
        label="Chunk length",
        info="Length of split audio chunks.",
        value=3.0,
        minimum=0.5,
        maximum=5.0,
        step=0.1,
        visible=False,
    )
    overlap_len: SliderConfig = SliderConfig(
        label="Overlap length",
        info="Length of overlap between split audio chunks.",
        value=0.3,
        minimum=0.0,
        maximum=0.4,
        step=0.1,
        visible=False,
    )
    preprocess_cores: SliderConfig = SliderConfig.cpu_cores()

    extract_model: DropdownConfig = DropdownConfig(
        label="Model name",
        info=(
            "Name of the model with an associated preprocessed dataset to extract"
            " training features from. When a new dataset is preprocessed, its"
            " associated model is selected by default."
        ),
        value=None,
        render=False,
        exclude_value=True,
    )
    f0_method: DropdownConfig = DropdownConfig(
        label="F0 method",
        info="The method to use for extracting pitch features.",
        value=TrainingF0Method.RMVPE,
        choices=list(TrainingF0Method),
        exclude_value=True,
    )

    hop_length: SliderConfig = SliderConfig.hop_length(
        label="Hop length",
        info="The hop length to use for extracting pitch features.<br><br>",
        visible=False,
    )
    include_mutes: SliderConfig = SliderConfig(
        label="Include mutes",
        info=(
            "The number of mute audio files to include in the generated training file"
            " list. Adding silent files enables the training model to handle pure"
            " silence in inferred audio files. If the preprocessed audio dataset"
            " already contains segments of pure silence, set this to 0."
        ),
        value=0,
        minimum=0,
        maximum=10,
        step=1,
    )
    extraction_cores: SliderConfig = SliderConfig.cpu_cores()
    extraction_acceleration: DropdownConfig = DropdownConfig.hardware_acceleration()
    extraction_gpus: DropdownConfig = DropdownConfig.gpu()

    train_model: DropdownConfig = DropdownConfig(
        label="Model name",
        info=(
            "Name of the model to train. When training features are extracted for a new"
            " model, its name is selected by default."
        ),
        value=None,
        render=False,
        exclude_value=True,
    )
    num_epochs: SliderConfig = SliderConfig(
        label="Number of epochs",
        info=(
            "The number of epochs to train the voice model. A higher number can improve"
            " voice model performance but may lead to overtraining."
        ),
        value=500,
        minimum=1,
        maximum=5000,
        step=1,
    )
    batch_size: SliderConfig = SliderConfig(
        label="Batch size",
        info=(
            "The number of samples in each training batch. It is advisable to align"
            " this value with the available VRAM of your GPU."
        ),
        value=16,
        minimum=1,
        maximum=128,
        step=1,
    )
    detect_overtraining: CheckboxConfig = CheckboxConfig(
        label="Detect overtraining",
        info=(
            "Whether to detect overtraining to prevent the voice model from learning"
            " the training data too well and losing the ability to generalize to new"
            " data."
        ),
        value=True,
        exclude_value=True,
    )
    overtraining_threshold: SliderConfig = SliderConfig(
        label="Overtraining threshold",
        info=(
            "The maximum number of epochs to continue training without any observed"
            " improvement in voice model performance."
        ),
        value=500,
        minimum=1,
        maximum=1000,
        visible=False,
    )
    vocoder: DropdownConfig = DropdownConfig(
        label="Vocoder",
        info=(
            "The vocoder to use for audio synthesis during training. HiFi-GAN provides"
            " basic audio fidelity, while RefineGAN provides the highest audio"
            " fidelity."
        ),
        value=Vocoder.HIFI_GAN,
        choices=list(Vocoder),
    )
    index_algorithm: DropdownConfig = DropdownConfig(
        label="Index algorithm",
        info=(
            "The method to use for generating an index file for the trained voice"
            " model. `KMeans` is particularly useful for large datasets."
        ),
        value=IndexAlgorithm.AUTO,
        choices=list(IndexAlgorithm),
    )
    pretrained_type: DropdownConfig = DropdownConfig(
        label="Pretrained model type",
        info=(
            "The type of pretrained model to finetune the voice model on. `None` will"
            " train the voice model from scratch, while `Default` will use a pretrained"
            " model tailored to the specific voice model architecture. `Custom` will"
            " use a custom pretrained that you provide."
        ),
        value=PretrainedType.DEFAULT,
        choices=list(PretrainedType),
        exclude_value=True,
    )
    custom_pretrained_model: DropdownConfig = DropdownConfig(
        label="Custom pretrained model",
        info="Select a custom pretrained model to finetune from the dropdown.",
        value=None,
        visible=False,
        render=False,
        exclude_value=True,
    )
    save_interval: SliderConfig = SliderConfig(
        label="Save interval",
        info=(
            "The epoch interval at which to to save voice model weights and"
            " checkpoints. The best model weights are always saved regardless of this"
            " setting."
        ),
        value=10,
        minimum=1,
        maximum=100,
        step=1,
    )
    save_all_checkpoints: CheckboxConfig = CheckboxConfig(
        label="Save all checkpoints",
        info=(
            "Whether to save a unique checkpoint at each save interval. If not enabled,"
            " only the latest checkpoint will be saved at each interval."
        ),
        value=True,
    )
    save_all_weights: CheckboxConfig = CheckboxConfig(
        label="Save all weights",
        info=(
            "Whether to save unique voice model weights at each save interval. If not"
            " enabled, only the best voice model weights will be saved."
        ),
        value=True,
    )
    clear_saved_data: CheckboxConfig = CheckboxConfig(
        label="Clear saved data",
        info=(
            "Whether to delete any existing training data associated with the voice"
            " model before training commences. Enable this setting only if you are"
            " training a new voice model from scratch or restarting training."
        ),
        value=False,
    )
    upload_model: CheckboxConfig = CheckboxConfig(
        label="Upload voice model",
        info=(
            "Whether to automatically upload the trained voice model so that it can be"
            " used for generation tasks within the Ultimate RVC app."
        ),
        value=False,
        exclude_value=True,
    )
    upload_name: TextboxConfig = TextboxConfig(
        label="Upload name",
        info="The name to give the uploaded voice model.",
        value=None,
        visible=False,
        exclude_value=True,
    )
    training_acceleration: DropdownConfig = DropdownConfig.hardware_acceleration()
    training_gpus: DropdownConfig = DropdownConfig.gpu()
    preload_dataset: CheckboxConfig = CheckboxConfig(
        label="Preload dataset",
        info=(
            "Whether to preload all training data into GPU memory. This can improve"
            " training speed but requires a lot of VRAM.<br><br>"
        ),
        value=True,
    )
    reduce_memory_usage: CheckboxConfig = CheckboxConfig(
        label="Reduce memory usage",
        info=(
            "Whether to reduce VRAM usage at the cost of slower training speed by"
            " enabling activation checkpointing. This is useful for GPUs with limited"
            " memory (e.g., <6GB VRAM) or when training with a batch size larger than"
            " what your GPU can normally accommodate."
        ),
        value=False,
    )


class GenerationConfig(BaseTabConfig):
    """
    Common component configuration settings for generation tabs.

    voice_model : DropdownConfig
        Configuration settings for a voice model dropdown component.
    f0_methods : DropdownConfig
        Configuration settings for a pitch extraction algorithms
        dropdown component.
    index_rate : SliderConfig
        Configuration settings for an index rate slider component.
    rms_mix_rate : SliderConfig
        Configuration settings for a RMS mix rate slider component.
    protect_rate : SliderConfig
        Configuration settings for a protect rate slider component.
    split_voice : CheckboxConfig
        Configuration settings for a split voice checkbox component.
    autotune_voice: CheckboxConfig
        Configuration settings for an autotune voice checkbox component.
    autotune_strength: SliderConfig
        Configuration settings for an autotune strength slider
        component.
    sid : NumberConfig
        Configuration settings for a speaker ID number component.
    output_sr : DropdownConfig
        Configuration settings for an output sample rate dropdown
        component.
    output_format : DropdownConfig
        Configuration settings for an output format dropdown
        component.
    output_name : TextboxConfig
        Configuration settings for an output name textbox component.

    See Also
    --------
    BaseTabConfig
        Parent model defining common component configuration settings
        for UI tabs.

    """

    voice_model: DropdownConfig = DropdownConfig(
        label="Voice model",
        info="Select a model to use for voice conversion.",
        value=None,
        render=False,
        exclude_value=True,
    )
    f0_methods: DropdownConfig = DropdownConfig(
        label="Pitch extraction algorithm(s)",
        info=(
            "If more than one method is selected, then the median of the pitch values"
            " extracted by each method is used. RMVPE is recommended for most cases and"
            " is the default when no method is selected."
        ),
        value=[F0Method.RMVPE],
        choices=list(F0Method),
        multiselect=True,
    )
    index_rate: SliderConfig = SliderConfig(
        label="Index rate",
        info=(
            "Increase to bias the conversion towards the accent of the voice model."
            " Decrease to potentially reduce artifacts coming from the voice"
            " model.<br><br><br>"
        ),
        value=0.3,
        minimum=0.0,
        maximum=1.0,
    )
    rms_mix_rate: SliderConfig = SliderConfig(
        label="RMS mix rate",
        info=(
            "How much to mimic the loudness (0) of the input voice or a fixed loudness"
            " (1). A value of 1 is recommended for most cases.<br><br>"
        ),
        value=1.0,
        minimum=0.0,
        maximum=1.0,
    )
    protect_rate: SliderConfig = SliderConfig(
        label="Protect rate",
        info=(
            "Controls the extent to which consonants and breathing sounds are protected"
            " from artifacts. A higher value offers more protection but may worsen the"
            " indexing effect.<br><br>"
        ),
        value=0.33,
        minimum=0.0,
        maximum=0.5,
    )

    hop_length: SliderConfig = SliderConfig.hop_length(
        label="Hop length",
        info=(
            "How often the CREPE-based pitch extraction method checks for pitch changes"
            " measured in milliseconds. Lower values lead to longer conversion times"
            " and a higher risk of voice cracks, but better pitch accuracy."
        ),
        visible=True,
    )

    split_voice: CheckboxConfig = CheckboxConfig(
        label="Split input voice",
        info=(
            "Whether to split the input voice track into smaller segments before"
            " converting it. This can improve output quality for longer voice tracks."
        ),
        value=False,
    )
    autotune_voice: CheckboxConfig = CheckboxConfig(
        label="Autotune converted voice",
        info="Whether to apply autotune to the converted voice.<br><br>",
        value=False,
        exclude_value=True,
    )
    autotune_strength: SliderConfig = SliderConfig(
        label="Autotune intensity",
        info=(
            "Higher values result in stronger snapping to the chromatic grid and"
            " artifacting."
        ),
        value=1.0,
        minimum=0.0,
        maximum=1.0,
        visible=False,
    )
    sid: NumberConfig = NumberConfig(
        label="Speaker ID",
        info="Speaker ID for multi-speaker-models.",
        value=0,
        precision=0,
    )
    output_sr: DropdownConfig = DropdownConfig(
        label="Output sample rate",
        info="The sample rate of the mixed output track.",
        value=SampleRate.HZ_44100,
        choices=list(SampleRate),
    )
    output_format: DropdownConfig = DropdownConfig(
        label="Output format",
        info="The audio format of the mixed output track.",
        value=AudioExt.MP3,
        choices=list(AudioExt),
    )
    output_name: TextboxConfig = TextboxConfig(
        label="Output name",
        info="If no name is provided, a suitable name will be generated automatically.",
        value=None,
        placeholder="Ultimate RVC output",
        exclude_value=True,
    )


class SongGenerationConfig(GenerationConfig):
    """
    Common component configuration settings for song generation tabs.

    Attributes
    ----------
    source_type : DropdownConfig
        Configuration settings for a source type dropdown component.
    source : TextboxConfig
        Configuration settings for an input source textbox component.
    cached_song : DropdownConfig
        Configuration settings for a cached song dropdown component.
    clean_strength : SliderConfig
        Configuration settings for a clean strength slider component.
    clean_voice : CheckboxConfig
        Configuration settings for a clean voice checkbox component.
    room_size : SliderConfig
        Configuration settings for a room size slider component.
    wet_level : SliderConfig
        Configuration settings for a wetness level slider component.
    dry_level : SliderConfig
        Configuration settings for a dryness level slider component.
    damping : SliderConfig
        Configuration settings for a damping level slider component.
    main_gain : SliderConfig
        Configuration settings for a main gain slider component.
    inst_gain : SliderConfig
        Configuration settings for an instrumentals gain slider
        component.
    backup_gain : SliderConfig
        Configuration settings for a backup vocals gain slider
        component.

    See Also
    --------
    GenerationConfig
        Parent model defining common component configuration settings
        for song generation tabs.

    """

    source_type: DropdownConfig = DropdownConfig(
        label="Source type",
        info="The type of source to retrieve a song from.",
        value=SongSourceType.LOCAL_FILE,
        choices=list(SongSourceType),
        type="index",
        exclude_value=True,
    )
    source: TextboxConfig = TextboxConfig(
        label="Source",
        info="Local (to the server) filepath or http link.  Youtube probably wont work but most other sites still do.",
        value=None,
        exclude_value=True,
    )
    cached_song: DropdownConfig = DropdownConfig(
        label="Source",
        info="Select a song from the list of cached songs.",
        value=None,
        visible=False,
        render=False,
        exclude_value=True,
    )
    clean_voice: CheckboxConfig = CheckboxConfig(
        label="Clean converted voice",
        info=(
            "Whether to clean the converted voice using noise reduction"
            " algorithms.<br><br>"
        ),
        value=False,
        exclude_value=True,
    )
    clean_strength: SliderConfig = SliderConfig.clean_strength(visible=False)
    room_size: SliderConfig = SliderConfig(
        label="Room size",
        info=(
            "Size of the room which reverb effect simulates. Increase for longer reverb"
            " time."
        ),
        value=0.15,
        minimum=0.0,
        maximum=1.0,
    )
    wet_level: SliderConfig = SliderConfig(
        label="Wetness level",
        info="Loudness of converted vocals with reverb effect applied.",
        value=0.2,
        minimum=0.0,
        maximum=1.0,
    )
    dry_level: SliderConfig = SliderConfig(
        label="Dryness level",
        info="Loudness of converted vocals without reverb effect applied.",
        value=0.8,
        minimum=0.0,
        maximum=1.0,
    )
    damping: SliderConfig = SliderConfig(
        label="Damping level",
        info="Absorption of high frequencies in reverb effect.",
        value=0.7,
        minimum=0.0,
        maximum=1.0,
    )
    main_gain: SliderConfig = SliderConfig.gain(
        label="Main gain",
        info="The gain to apply to the main vocals.",
    )
    inst_gain: SliderConfig = SliderConfig.gain(
        label="Instrumentals gain",
        info="The gain to apply to the instrumentals.",
    )
    backup_gain: SliderConfig = SliderConfig.gain(
        label="Backup gain",
        info="The gain to apply to the backup vocals.",
    )


class SpeechGenerationConfig(GenerationConfig):
    """
    Common component configuration settings for speech generation tabs.

    Attributes
    ----------
    source_type : DropdownConfig
        Configuration settings for a source type dropdown component.
    source : TextboxConfig
        Configuration settings for an input source textbox component.
    edge_tts_voice : DropdownConfig
        Configuration settings for an Edge TTS voice dropdown
        component.
    n_octaves : SliderConfig
        Configuration settings for an octave pitch shift slider
        component.
    n_semitones : SliderConfig
        Configuration settings for a semitone pitch shift slider
        component.
    tts_pitch_shift : SliderConfig
        Configuration settings for a TTS pitch shift slider
        component.
    tts_speed_change : SliderConfig
        Configuration settings for a TTS speed change slider
        component.
    tts_volume_change : SliderConfig
        Configuration settings for a TTS volume change slider
        component.
    clean_voice : CheckboxConfig
        Configuration settings for a clean voice checkbox
        component.
    clean_strength : SliderConfig
        Configuration settings for a clean strength slider
        component.
    output_gain : GainSliderConfig
        Configuration settings for an output gain slider component.

    See Also
    --------
    GenerationConfig
        Parent model defining common component configuration settings
        for generation tabs.

    """

    source_type: DropdownConfig = DropdownConfig(
        label="Source type",
        info="The type of source to generate speech from.",
        value=SpeechSourceType.TEXT,
        choices=list(SpeechSourceType),
        type="index",
        exclude_value=True,
    )
    source: TextboxConfig = TextboxConfig(
        label="Source",
        info="Text to generate speech from",
        value=None,
        exclude_value=True,
    )
    edge_tts_voice: DropdownConfig = DropdownConfig(
        label="Edge TTS voice",
        info="Select a voice to use for text to speech conversion.",
        value=None,
        render=False,
        exclude_value=True,
    )
    n_octaves: SliderConfig = SliderConfig.octave_shift(
        label="Octave shift",
        info=(
            "The number of octaves to pitch-shift the converted speech by. Use 1 for"
            " male-to-female and -1 for vice-versa."
        ),
    )
    n_semitones: SliderConfig = SliderConfig.semitone_shift(
        label="Semitone shift",
        info="The number of semi-tones to pitch-shift the converted speech by.",
    )
    tts_pitch_shift: SliderConfig = SliderConfig(
        label="Edge TTS pitch shift",
        info=(
            "The number of hertz to shift the pitch of the speech generated by Edge"
            " TTS."
        ),
        value=0,
        minimum=-100,
        maximum=100,
        step=1,
    )
    tts_speed_change: SliderConfig = SliderConfig(
        label="TTS speed change",
        info="The percentual change to the speed of the speech generated by Edge TTS.",
        value=0,
        minimum=-50,
        maximum=100,
        step=1,
    )
    tts_volume_change: SliderConfig = SliderConfig(
        label="TTS volume change",
        info="The percentual change to the volume of the speech generated by Edge TTS.",
        value=0,
        minimum=-100,
        maximum=100,
        step=1,
    )
    clean_voice: CheckboxConfig = CheckboxConfig(
        label="Clean converted voice",
        info=(
            "Whether to clean the converted voice using noise reduction"
            " algorithms.<br><br>"
        ),
        value=True,
        exclude_value=True,
    )
    clean_strength: SliderConfig = SliderConfig.clean_strength(visible=True)
    output_gain: SliderConfig = SliderConfig.gain(
        label="Output gain",
        info="The gain to apply to the converted speech.<br><br>",
    )


total_config = load_config(config_name, TotalConfig) if config_name else TotalConfig()


def render_song_cover_multi_step_tab(
    total_config: TotalConfig, cookiefile: str | None = None
) -> None:
    """
    Render "Generate song cover - multi-step generation" tab.

    Parameters
    ----------
    total_config : TotalConfig
        Model containing all component configuration settings for the
        Ultimate RVC web UI.
    cookiefile : str, optional
        The path to a file containing cookies to use when downloading
        audio from Youtube.

    """
    tab_config = total_config.song.multi_step
    for input_track in tab_config.input_audio.all:
        input_track.instantiate()
    with gr.Tab("Multi-step"):
        _render_step_0(total_config, cookiefile=cookiefile)
        _render_step_1(tab_config)
        _render_step_2(tab_config)
        _render_step_3(tab_config)
        _render_step_4(tab_config)
        _render_step_5(total_config, tab_config)


def _render_step_0(total_config: TotalConfig, cookiefile: str | None) -> None:
    tab_config = total_config.song.multi_step

    current_song_dir = gr.State(None)
    with gr.Accordion("Step 0: song retrieval", open=True):
        gr.Markdown("")
        with gr.Row():
            with gr.Column():
                tab_config.source_type.instantiate()
            with gr.Column():
                tab_config.source.instantiate()
                local_file = gr.Audio(
                    label="Source",
                    type="filepath",
                    visible=False,
                    waveform_options=gr.WaveformOptions(show_recording_waveform=True),
                )
                tab_config.cached_song.instance.render()

            tab_config.source_type.instance.input(
                partial(toggle_visible_component, 3),
                inputs=tab_config.source_type.instance,
                outputs=[
                    tab_config.source.instance,
                    local_file,
                    tab_config.cached_song.instance,
                ],
                show_progress="hidden",
            )

            local_file.change(
                update_value,
                inputs=local_file,
                outputs=tab_config.source.instance,
                show_progress="hidden",
            )
            tab_config.cached_song.instance.input(
                update_value,
                inputs=tab_config.cached_song.instance,
                outputs=tab_config.source.instance,
                show_progress="hidden",
            )
        with gr.Accordion("Options", open=False):
            song_transfer = _render_song_transfer(
                [SongTransferOption.STEP_1_AUDIO],
                "Song",
            )
        with gr.Row():
            retrieve_song_reset_btn = gr.Button("Reset options")
            retrieve_song_btn = gr.Button("Retrieve song", variant="primary")
        song_transfer_btn = gr.Button("Transfer song")
        song_output = gr.Audio(
            label="Song",
            type="filepath",
            interactive=False,
            waveform_options=gr.WaveformOptions(show_recording_waveform=True),
        )

        retrieve_song_reset_btn.click(
            lambda: gr.Dropdown(value=[SongTransferOption.STEP_1_AUDIO]),
            outputs=song_transfer,
            show_progress="hidden",
        )

        retrieve_song_btn.click(
            partial(
                exception_harness(
                    retrieve_song,
                    info_msg="Song retrieved successfully!",
                ),
                cookiefile=cookiefile,
            ),
            inputs=tab_config.source.instance,
            outputs=[song_output, current_song_dir],
        ).then(
            partial(
                update_dropdowns,
                get_named_song_dirs,
                len(tab_config.song_dirs.all) + 2,
                value_indices=range(len(tab_config.song_dirs.all)),
            ),
            inputs=current_song_dir,
            outputs=[
                *tab_config.song_dirs.all,
                tab_config.cached_song.instance,
                total_config.song.one_click.cached_song.instance,
            ],
            show_progress="hidden",
        ).then(
            partial(update_dropdowns, get_named_song_dirs, 1, [], [0]),
            outputs=total_config.management.audio.intermediate.instance,
            show_progress="hidden",
        )
        setup_transfer_event(
            song_transfer_btn,
            song_transfer,
            song_output,
            tab_config.input_audio.all,
        )


def _render_step_1(tab_config: MultiStepSongGenerationConfig) -> None:
    with gr.Accordion("Step 1: vocal separation", open=False):
        tab_config.input_audio.audio.instance.render()
        tab_config.song_dirs.separate_audio.instance.render()
        with gr.Accordion("Options", open=False):
            with gr.Row():
                tab_config.separation_model.instantiate()
                tab_config.segment_size.instantiate()
            with gr.Row():
                primary_stem_transfer = _render_song_transfer(
                    [SongTransferOption.STEP_2_VOCALS],
                    "Primary stem",
                )
                secondary_stem_transfer = _render_song_transfer(
                    [SongTransferOption.STEP_4_INSTRUMENTALS],
                    "Secondary stem",
                )
        with gr.Row():
            separate_audio_reset_btn = gr.Button("Reset options")
            separate_vocals_btn = gr.Button("Separate vocals", variant="primary")
        with gr.Row():
            primary_stem_transfer_btn = gr.Button("Transfer primary stem")
            secondary_stem_transfer_btn = gr.Button("Transfer secondary stem")

        with gr.Row():
            primary_stem_output = gr.Audio(
                label="Primary stem",
                type="filepath",
                interactive=False,
                waveform_options=gr.WaveformOptions(show_recording_waveform=True),
            )
            secondary_stem_output = gr.Audio(
                label="Secondary stem",
                type="filepath",
                interactive=False,
                waveform_options=gr.WaveformOptions(show_recording_waveform=True),
            )

        separate_audio_reset_btn.click(
            lambda: [
                tab_config.separation_model.value,
                tab_config.segment_size.value,
                gr.Dropdown(value=[SongTransferOption.STEP_2_VOCALS]),
                gr.Dropdown(value=[SongTransferOption.STEP_4_INSTRUMENTALS]),
            ],
            outputs=[
                tab_config.separation_model.instance,
                tab_config.segment_size.instance,
                primary_stem_transfer,
                secondary_stem_transfer,
            ],
            show_progress="hidden",
        )
        separate_vocals_btn.click(
            exception_harness(
                separate_audio,
                info_msg="Vocals separated successfully!",
            ),
            inputs=[
                tab_config.input_audio.audio.instance,
                tab_config.song_dirs.separate_audio.instance,
                tab_config.separation_model.instance,
                tab_config.segment_size.instance,
            ],
            outputs=[primary_stem_output, secondary_stem_output],
            concurrency_limit=1,
            concurrency_id=ConcurrencyId.GPU,
        )
        for btn, transfer, output in [
            (primary_stem_transfer_btn, primary_stem_transfer, primary_stem_output),
            (
                secondary_stem_transfer_btn,
                secondary_stem_transfer,
                secondary_stem_output,
            ),
        ]:
            setup_transfer_event(
                btn,
                transfer,
                output,
                tab_config.input_audio.all,
            )


def _render_step_2(tab_config: MultiStepSongGenerationConfig) -> None:
    with gr.Accordion("Step 2: vocal conversion", open=False):
        tab_config.input_audio.vocals.instance.render()
        tab_config.voice_model.instance.render()
        tab_config.song_dirs.convert_vocals.instance.render()
        with gr.Accordion("Options", open=False):
            with gr.Row():
                tab_config.n_octaves.instantiate()
                tab_config.n_semitones.instantiate()

            converted_vocals_transfer = _render_song_transfer(
                [SongTransferOption.STEP_3_VOCALS],
                "Converted vocals",
            )
            with gr.Accordion("Advanced", open=False):
                with gr.Accordion("Voice synthesis", open=False):
                    with gr.Row():
                        tab_config.f0_methods.instantiate()
                        tab_config.index_rate.instantiate()
                    with gr.Row():
                        tab_config.rms_mix_rate.instantiate()
                        tab_config.protect_rate.instantiate()
                        tab_config.hop_length.instantiate()
                with gr.Accordion("Vocal enrichment", open=False), gr.Row():
                    with gr.Column():
                        tab_config.split_voice.instantiate()
                    with gr.Column():
                        tab_config.autotune_voice.instantiate()
                        tab_config.autotune_strength.instantiate()
                    with gr.Column():
                        tab_config.clean_voice.instantiate()
                        tab_config.clean_strength.instantiate()
                tab_config.autotune_voice.instance.change(
                    partial(toggle_visibility, targets={True}),
                    inputs=tab_config.autotune_voice.instance,
                    outputs=tab_config.autotune_strength.instance,
                    show_progress="hidden",
                )
                tab_config.clean_voice.instance.change(
                    partial(toggle_visibility, targets={True}),
                    inputs=tab_config.clean_voice.instance,
                    outputs=tab_config.clean_strength.instance,
                    show_progress="hidden",
                )
                with gr.Accordion("Speaker embeddings", open=False), gr.Row():
                    with gr.Column():
                        tab_config.embedder_model.instantiate()
                        tab_config.custom_embedder_model.instance.render()
                    tab_config.sid.instantiate()
                tab_config.embedder_model.instance.change(
                    partial(toggle_visibility, targets={EmbedderModel.CUSTOM}),
                    inputs=tab_config.embedder_model.instance,
                    outputs=tab_config.custom_embedder_model.instance,
                    show_progress="hidden",
                )
        with gr.Row():
            convert_vocals_reset_btn = gr.Button("Reset options")
            convert_vocals_btn = gr.Button("Convert vocals", variant="primary")
        converted_vocals_transfer_btn = gr.Button("Transfer converted vocals")
        converted_vocals_track_output = gr.Audio(
            label="Converted vocals",
            type="filepath",
            interactive=False,
            waveform_options=gr.WaveformOptions(show_recording_waveform=True),
        )

        convert_vocals_reset_btn.click(
            lambda: [
                tab_config.n_octaves.value,
                tab_config.n_semitones.value,
                tab_config.f0_methods.value,
                tab_config.index_rate.value,
                tab_config.rms_mix_rate.value,
                tab_config.protect_rate.value,
                tab_config.hop_length.value,
                tab_config.split_voice.value,
                tab_config.autotune_voice.value,
                tab_config.autotune_strength.value,
                tab_config.clean_voice.value,
                tab_config.clean_strength.value,
                tab_config.embedder_model.value,
                tab_config.sid.value,
                gr.Dropdown(value=[SongTransferOption.STEP_3_VOCALS]),
            ],
            outputs=[
                tab_config.n_octaves.instance,
                tab_config.n_semitones.instance,
                tab_config.f0_methods.instance,
                tab_config.index_rate.instance,
                tab_config.rms_mix_rate.instance,
                tab_config.protect_rate.instance,
                tab_config.hop_length.instance,
                tab_config.split_voice.instance,
                tab_config.autotune_voice.instance,
                tab_config.autotune_strength.instance,
                tab_config.clean_voice.instance,
                tab_config.clean_strength.instance,
                tab_config.embedder_model.instance,
                tab_config.sid.instance,
                converted_vocals_transfer,
            ],
            show_progress="hidden",
        )
        convert_vocals_btn.click(
            partial(
                exception_harness(convert, info_msg="Vocals converted successfully!"),
                content_type=RVCContentType.VOCALS,
            ),
            inputs=[
                tab_config.input_audio.vocals.instance,
                tab_config.song_dirs.convert_vocals.instance,
                tab_config.voice_model.instance,
                tab_config.n_octaves.instance,
                tab_config.n_semitones.instance,
                tab_config.f0_methods.instance,
                tab_config.index_rate.instance,
                tab_config.rms_mix_rate.instance,
                tab_config.protect_rate.instance,
                tab_config.hop_length.instance,
                tab_config.split_voice.instance,
                tab_config.autotune_voice.instance,
                tab_config.autotune_strength.instance,
                tab_config.clean_voice.instance,
                tab_config.clean_strength.instance,
                tab_config.embedder_model.instance,
                tab_config.custom_embedder_model.instance,
                tab_config.sid.instance,
            ],
            outputs=converted_vocals_track_output,
            concurrency_id=ConcurrencyId.GPU,
            concurrency_limit=1,
        )
        setup_transfer_event(
            converted_vocals_transfer_btn,
            converted_vocals_transfer,
            converted_vocals_track_output,
            tab_config.input_audio.all,
        )


def _render_step_3(tab_config: MultiStepSongGenerationConfig) -> None:
    with gr.Accordion("Step 3: vocal post-processing", open=False):
        tab_config.input_audio.converted_vocals.instance.render()
        tab_config.song_dirs.postprocess_vocals.instance.render()
        with gr.Accordion("Options", open=False):
            tab_config.room_size.instantiate()
            with gr.Row():
                tab_config.wet_level.instantiate()
                tab_config.dry_level.instantiate()
                tab_config.damping.instantiate()
            effected_vocals_transfer = _render_song_transfer(
                [SongTransferOption.STEP_5_MAIN_VOCALS],
                "Effected vocals",
            )
        with gr.Row():
            postprocess_vocals_reset_btn = gr.Button("Reset options")
            postprocess_vocals_btn = gr.Button("Post-process vocals", variant="primary")
        effected_vocals_transfer_btn = gr.Button("Transfer effected vocals")

        effected_vocals_track_output = gr.Audio(
            label="Effected vocals",
            type="filepath",
            interactive=False,
            waveform_options=gr.WaveformOptions(show_recording_waveform=True),
        )

        postprocess_vocals_reset_btn.click(
            lambda: [
                tab_config.room_size.value,
                tab_config.wet_level.value,
                tab_config.dry_level.value,
                tab_config.damping.value,
                gr.Dropdown(value=[SongTransferOption.STEP_5_MAIN_VOCALS]),
            ],
            outputs=[
                tab_config.room_size.instance,
                tab_config.wet_level.instance,
                tab_config.dry_level.instance,
                tab_config.damping.instance,
                effected_vocals_transfer,
            ],
            show_progress="hidden",
        )
        postprocess_vocals_btn.click(
            exception_harness(
                postprocess,
                info_msg="Vocals post-processed successfully!",
            ),
            inputs=[
                tab_config.input_audio.converted_vocals.instance,
                tab_config.song_dirs.postprocess_vocals.instance,
                tab_config.room_size.instance,
                tab_config.wet_level.instance,
                tab_config.dry_level.instance,
                tab_config.damping.instance,
            ],
            outputs=effected_vocals_track_output,
        )
        setup_transfer_event(
            effected_vocals_transfer_btn,
            effected_vocals_transfer,
            effected_vocals_track_output,
            tab_config.input_audio.all,
        )


def _render_step_4(tab_config: MultiStepSongGenerationConfig) -> None:
    with gr.Accordion("Step 4: pitch shift of background audio", open=False):
        with gr.Row():
            tab_config.input_audio.instrumentals.instance.render()
            tab_config.input_audio.backup_vocals.instance.render()
        with gr.Row():
            tab_config.n_semitones_instrumentals.instantiate()
            tab_config.n_semitones_backup_vocals.instantiate()
        tab_config.song_dirs.pitch_shift_background.instance.render()
        with gr.Accordion("Options", open=False), gr.Row():
            shifted_instrumentals_transfer = _render_song_transfer(
                [SongTransferOption.STEP_5_INSTRUMENTALS],
                "Pitch-shifted instrumentals",
            )
            shifted_backup_vocals_transfer = _render_song_transfer(
                [SongTransferOption.STEP_5_BACKUP_VOCALS],
                "Pitch-shifted backup vocals",
            )
        with gr.Row():
            pitch_shift_instrumentals_btn = gr.Button(
                "Pitch shift instrumentals",
                variant="primary",
            )
            pitch_shift_backup_vocals_btn = gr.Button(
                "Pitch shift backup vocals",
                variant="primary",
            )
        with gr.Row():
            shifted_instrumentals_transfer_btn = gr.Button(
                "Transfer shifted instrumentals",
            )
            shifted_backup_vocals_transfer_btn = gr.Button(
                "Transfer shifted backup vocals",
            )
        pitch_shift_background_reset_btn = gr.Button("Reset options")
        with gr.Row():
            shifted_instrumentals_track_output = gr.Audio(
                label="Pitch-shifted instrumentals",
                type="filepath",
                interactive=False,
                waveform_options=gr.WaveformOptions(show_recording_waveform=True),
            )
            shifted_backup_vocals_track_output = gr.Audio(
                label="Pitch-shifted backup vocals",
                type="filepath",
                interactive=False,
                waveform_options=gr.WaveformOptions(show_recording_waveform=True),
            )

        pitch_shift_background_reset_btn.click(
            lambda: [
                tab_config.n_semitones_instrumentals.value,
                tab_config.n_semitones_backup_vocals.value,
                gr.Dropdown(value=[SongTransferOption.STEP_5_INSTRUMENTALS]),
                gr.Dropdown(value=[SongTransferOption.STEP_5_BACKUP_VOCALS]),
            ],
            outputs=[
                tab_config.n_semitones_instrumentals.instance,
                tab_config.n_semitones_backup_vocals.instance,
                shifted_instrumentals_transfer,
                shifted_backup_vocals_transfer,
            ],
            show_progress="hidden",
        )
        pitch_shift_instrumentals_btn.click(
            exception_harness(
                pitch_shift,
                info_msg="Instrumentals pitch-shifted successfully!",
            ),
            inputs=[
                tab_config.input_audio.instrumentals.instance,
                tab_config.song_dirs.pitch_shift_background.instance,
                tab_config.n_semitones_instrumentals.instance,
            ],
            outputs=shifted_instrumentals_track_output,
        )
        pitch_shift_backup_vocals_btn.click(
            exception_harness(
                pitch_shift,
                info_msg="Backup vocals pitch-shifted successfully!",
            ),
            inputs=[
                tab_config.input_audio.backup_vocals.instance,
                tab_config.song_dirs.pitch_shift_background.instance,
                tab_config.n_semitones_backup_vocals.instance,
            ],
            outputs=shifted_backup_vocals_track_output,
        )
        for btn, transfer, output in [
            (
                shifted_instrumentals_transfer_btn,
                shifted_instrumentals_transfer,
                shifted_instrumentals_track_output,
            ),
            (
                shifted_backup_vocals_transfer_btn,
                shifted_backup_vocals_transfer,
                shifted_backup_vocals_track_output,
            ),
        ]:
            setup_transfer_event(
                btn,
                transfer,
                output,
                tab_config.input_audio.all,
            )


def _render_step_5(
    total_config: TotalConfig,
    tab_config: MultiStepSongGenerationConfig,
) -> None:
    with gr.Accordion("Step 5: song mixing", open=False):
        with gr.Row():
            tab_config.input_audio.main_vocals.instance.render()
            tab_config.input_audio.shifted_instrumentals.instance.render()
            tab_config.input_audio.shifted_backup_vocals.instance.render()
        tab_config.song_dirs.mix.instance.render()
        with gr.Accordion("Options", open=False):
            with gr.Row():
                tab_config.main_gain.instantiate()
                tab_config.inst_gain.instantiate()
                tab_config.backup_gain.instantiate()
            with gr.Row():
                tab_config.output_name.instantiate(
                    value=partial(
                        update_output_name,
                        get_song_cover_name,
                        False,  # noqa: FBT003,
                    ),
                    inputs=[
                        tab_config.input_audio.main_vocals.instance,
                        tab_config.song_dirs.mix.instance,
                    ],
                )
                tab_config.output_sr.instantiate()
                tab_config.output_format.instantiate()
            song_cover_transfer = _render_song_transfer([], "Song cover")
        with gr.Row():
            mix_reset_btn = gr.Button("Reset options")
            mix_btn = gr.Button("Mix song cover", variant="primary")
        song_cover_transfer_btn = gr.Button("Transfer song cover")
        song_cover_output = gr.Audio(
            label="Song cover",
            type="filepath",
            interactive=False,
            waveform_options=gr.WaveformOptions(show_recording_waveform=True),
        )
        mix_reset_btn.click(
            lambda: [
                tab_config.main_gain.value,
                tab_config.inst_gain.value,
                tab_config.backup_gain.value,
                tab_config.output_sr.value,
                tab_config.output_format.value,
                gr.Dropdown(value=[]),
            ],
            outputs=[
                tab_config.main_gain.instance,
                tab_config.inst_gain.instance,
                tab_config.backup_gain.instance,
                tab_config.output_sr.instance,
                tab_config.output_format.instance,
                song_cover_transfer,
            ],
            show_progress="hidden",
        )
        temp_audio_gains = gr.State()
        mix_btn.click(
            partial(
                _pair_audio_tracks_and_gain,
                [
                    tab_config.input_audio.main_vocals.instance,
                    tab_config.input_audio.shifted_instrumentals.instance,
                    tab_config.input_audio.shifted_backup_vocals.instance,
                ],
                [
                    tab_config.main_gain.instance,
                    tab_config.inst_gain.instance,
                    tab_config.backup_gain.instance,
                ],
            ),
            inputs={
                tab_config.input_audio.main_vocals.instance,
                tab_config.input_audio.shifted_instrumentals.instance,
                tab_config.input_audio.shifted_backup_vocals.instance,
                tab_config.main_gain.instance,
                tab_config.inst_gain.instance,
                tab_config.backup_gain.instance,
            },
            outputs=temp_audio_gains,
        ).then(
            exception_harness(mix_song, info_msg="Song cover succesfully generated."),
            inputs=[
                temp_audio_gains,
                tab_config.song_dirs.mix.instance,
                tab_config.output_sr.instance,
                tab_config.output_format.instance,
                tab_config.output_name.instance,
            ],
            outputs=song_cover_output,
        ).then(
            partial(update_dropdowns, get_saved_output_audio, 1, [], [0]),
            outputs=total_config.management.audio.output.instance,
            show_progress="hidden",
        )
        setup_transfer_event(
            song_cover_transfer_btn,
            song_cover_transfer,
            song_cover_output,
            tab_config.input_audio.all,
        )


def _render_song_transfer(
    value: list[SongTransferOption],
    label_prefix: str,
) -> gr.Dropdown:
    return render_transfer_component(value, label_prefix, SongTransferOption)


def _pair_audio_tracks_and_gain(
    audio_components: Sequence[gr.Audio],
    gain_components: Sequence[gr.Slider],
    data: dict[gr.Audio | gr.Slider, Any],
) -> list[tuple[str, int]]:
    """
    Pair audio tracks and gain levels stored in separate gradio
    components.

    This function is meant to first be partially applied to the sequence
    of audio components and the sequence of slider components containing
    the values that should be combined. The resulting function can then
    be called by an event listener whose inputs is a set containing
    those audio and slider components. The `data` parameter in that case
    will contain a mapping from each of those components to the value
    that the component stores.

    Parameters
    ----------
    audio_components : Sequence[gr.Audio]
        Audio components to pair with gain levels.
    gain_components : Sequence[gr.Slider]
        Gain level components to pair with audio tracks.
    data : dict[gr.Audio | gr.Slider, Any]
        Data from the audio and gain components.

    Returns
    -------
    list[tuple[str, int]]
        Paired audio tracks and gain levels.

    Raises
    ------
    ValueError
        If the number of audio tracks and gain levels are not the same.

    """
    audio_tracks = [data[component] for component in audio_components]
    gain_levels = [data[component] for component in gain_components]
    if len(audio_tracks) != len(gain_levels):
        err_msg = "Number of audio tracks and gain levels must be the same."
        raise ValueError(err_msg)
    return [
        (audio_track, gain_level)
        for audio_track, gain_level in zip(audio_tracks, gain_levels, strict=True)
        if audio_track
    ]


def render_app() -> gr.Blocks:
    """
    Render the Ultimate RVC web application.

    Returns
    -------
    gr.Blocks
        The rendered web application.

    """
    css = """
    h1 { text-align: center; margin-top: 20px; margin-bottom: 20px; }

    #generate-tab-button { font-weight: bold !important;}
    #manage-tab-button { font-weight: bold !important;}
    #audio-tab-button { font-weight: bold !important;}
    #settings-tab-button { font-weight: bold !important;}
    """
    cache_delete_frequency = 86400  # every 24 hours check for files to delete
    cache_delete_cutoff = 86400  # and delete files older than 24 hours

    with gr.Blocks(
        title="Redzone-6 Audio Playground",
        theme=gr.Theme.load(str(Path(__file__).parent / "config/theme.json")),
        css=css,
        delete_cache=(cache_delete_frequency, cache_delete_cutoff),
    ) as app:
        for component_config in [
            total_config.song.one_click.voice_model,
            total_config.song.one_click.cached_song,
            total_config.song.one_click.custom_embedder_model,
            total_config.song.multi_step.voice_model,
            total_config.song.multi_step.cached_song,
            total_config.song.multi_step.custom_embedder_model,
            total_config.song.multi_step.song_dirs.separate_audio,
            total_config.song.multi_step.song_dirs.convert_vocals,
            total_config.song.multi_step.song_dirs.postprocess_vocals,
            total_config.song.multi_step.song_dirs.pitch_shift_background,
            total_config.song.multi_step.song_dirs.mix,
            total_config.speech.one_click.edge_tts_voice,
            total_config.speech.one_click.voice_model,
            total_config.speech.one_click.custom_embedder_model,
            total_config.speech.multi_step.edge_tts_voice,
            total_config.speech.multi_step.voice_model,
            total_config.speech.multi_step.custom_embedder_model,
            total_config.training.multi_step.dataset,
            total_config.training.multi_step.preprocess_model,
            total_config.training.multi_step.extract_model,
            total_config.training.multi_step.train_model,
            total_config.training.multi_step.custom_embedder_model,
            total_config.training.multi_step.custom_pretrained_model,
            total_config.management.audio.intermediate,
            total_config.management.audio.speech,
            total_config.management.audio.output,
            total_config.management.audio.dataset,
            total_config.management.model.voices,
            total_config.management.model.embedders,
            total_config.management.model.pretraineds,
            total_config.management.model.traineds,
            total_config.management.settings.load_config_name,
            total_config.management.settings.delete_config_names,
        ]:
            component_config.instantiate()
        # main tab
        # with gr.Tab("Generate", elem_id="generate-tab"):
        with gr.Tab("Music", elem_id="generate-tab"):
            render_song_cover_one_click_tab(total_config, cookiefile)
            render_song_cover_multi_step_tab(total_config, cookiefile)
        with gr.Tab("Speech", elem_id="generate-tab"):
            render_speech_one_click_tab(total_config)
            render_speech_multi_step_tab(total_config)
        with gr.Tab("Configuration", elem_id="settings-tab"):
            with gr.Tab("Models"):
                render_models_tab(total_config)
            with gr.Tab("Settings"):
                render_settings_tab(total_config)
                render_audio_tab(total_config)

        app.load(
            _init_dropdowns,
            outputs=[
                total_config.speech.one_click.edge_tts_voice.instance,
                total_config.speech.multi_step.edge_tts_voice.instance,
                total_config.song.one_click.voice_model.instance,
                total_config.song.multi_step.voice_model.instance,
                total_config.speech.one_click.voice_model.instance,
                total_config.speech.multi_step.voice_model.instance,
                total_config.management.model.voices.instance,
                total_config.song.one_click.custom_embedder_model.instance,
                total_config.song.multi_step.custom_embedder_model.instance,
                total_config.speech.one_click.custom_embedder_model.instance,
                total_config.speech.multi_step.custom_embedder_model.instance,
                total_config.training.multi_step.custom_embedder_model.instance,
                total_config.management.model.embedders.instance,
                total_config.training.multi_step.custom_pretrained_model.instance,
                total_config.management.model.pretraineds.instance,
                total_config.training.multi_step.extract_model.instance,
                total_config.training.multi_step.train_model.instance,
                total_config.training.multi_step.preprocess_model.instance,
                total_config.management.model.traineds.instance,
                total_config.song.one_click.cached_song.instance,
                total_config.song.multi_step.cached_song.instance,
                total_config.song.multi_step.song_dirs.separate_audio.instance,
                total_config.song.multi_step.song_dirs.convert_vocals.instance,
                total_config.song.multi_step.song_dirs.postprocess_vocals.instance,
                total_config.song.multi_step.song_dirs.pitch_shift_background.instance,
                total_config.song.multi_step.song_dirs.mix.instance,
                total_config.management.audio.intermediate.instance,
                total_config.training.multi_step.dataset.instance,
                total_config.management.audio.speech.instance,
                total_config.management.audio.output.instance,
                total_config.management.audio.dataset.instance,
                total_config.management.settings.load_config_name.instance,
                total_config.management.settings.delete_config_names.instance,
            ],
            show_progress="hidden",
        )
    return app


def _init_dropdowns() -> list[gr.Dropdown]:
    """
    Initialize the Ultimate RVC web application by updating the choices
    and default values of non-static dropdown components.

    Returns
    -------
    tuple[gr.Dropdown, ...]
        A tuple of gr.Dropdown components with updated choices and
        default values.

    """
    # Initialize model dropdowns
    edge_tts_models = initialize_dropdowns(
        get_edge_tts_voice_names,
        2,
        "en-US-ChristopherNeural",
        range(2),
    )
    voice_models = initialize_dropdowns(
        get_voice_model_names,
        5,
        value_indices=range(4),
    )
    custom_embedder_models = initialize_dropdowns(
        get_custom_embedder_model_names,
        6,
        value_indices=range(5),
    )
    custom_pretrained_models = initialize_dropdowns(
        get_custom_pretrained_model_names,
        2,
        value_indices=range(1),
    )
    training_models = initialize_dropdowns(
        get_training_model_names,
        4,
        value_indices=range(2),
    )
    song_dirs = initialize_dropdowns(
        get_named_song_dirs,
        8,
        value_indices=range(7),
    )
    dataset = gr.Dropdown(get_audio_datasets())
    speech_delete = gr.Dropdown(get_saved_speech_audio())
    output_delete = gr.Dropdown(get_saved_output_audio())
    dataset_delete = gr.Dropdown(get_named_audio_datasets())
    configs = initialize_dropdowns(get_config_names, 2, value_indices=range(1))
    return [
        *edge_tts_models,
        *voice_models,
        *custom_embedder_models,
        *custom_pretrained_models,
        *training_models,
        *song_dirs,
        dataset,
        speech_delete,
        output_delete,
        dataset_delete,
        *configs,
    ]


def render_song_cover_one_click_tab(
    total_config: TotalConfig, cookiefile: str | None = None
) -> None:
    """
    Render "Generate song covers - One-click generation" tab.

    Parameters
    ----------
    total_config : TotalConfig
        Model containing all component configuration settings for the
        Ultimate RVC web UI.
    cookiefile : str, optional
        The path to a file containing cookies to use when downloading
        audio from Youtube.

    """
    with gr.Tab("One-click"):
        tab_config = total_config.song.one_click
        _render_input(tab_config)
        with gr.Accordion("Options", open=False):
            _render_main_options(tab_config)
            _render_conversion_options(tab_config)
            _render_mixing_options(tab_config)
            _render_output_options(tab_config)
            _render_intermediate_audio(tab_config)

        with gr.Row(equal_height=True):
            reset_btn = gr.Button(value="Reset options", scale=2)
            generate_btn = gr.Button("Generate", scale=2, variant="primary")
        song_cover = gr.Audio(
            label="Song cover",
            scale=3,
            waveform_options=gr.WaveformOptions(show_recording_waveform=False),
        )
        song_dirs = total_config.song.multi_step.song_dirs.all
        generate_btn.click(
            partial(
                exception_harness(
                    run_pipeline,
                    info_msg="Song cover generated successfully!",
                ),
                cookiefile=cookiefile,
                progress_bar=PROGRESS_BAR,
            ),
            inputs=[
                tab_config.source.instance,
                tab_config.voice_model.instance,
                tab_config.n_octaves.instance,
                tab_config.n_semitones.instance,
                tab_config.f0_methods.instance,
                tab_config.index_rate.instance,
                tab_config.rms_mix_rate.instance,
                tab_config.protect_rate.instance,
                tab_config.hop_length.instance,
                tab_config.split_voice.instance,
                tab_config.autotune_voice.instance,
                tab_config.autotune_strength.instance,
                tab_config.clean_voice.instance,
                tab_config.clean_strength.instance,
                tab_config.embedder_model.instance,
                tab_config.custom_embedder_model.instance,
                tab_config.sid.instance,
                tab_config.room_size.instance,
                tab_config.wet_level.instance,
                tab_config.dry_level.instance,
                tab_config.damping.instance,
                tab_config.main_gain.instance,
                tab_config.inst_gain.instance,
                tab_config.backup_gain.instance,
                tab_config.output_sr.instance,
                tab_config.output_format.instance,
                tab_config.output_name.instance,
            ],
            outputs=[song_cover, *tab_config.intermediate_audio.all],
            concurrency_limit=4,
            concurrency_id=ConcurrencyId.GPU,
        ).success(
            partial(update_dropdowns, get_named_song_dirs, 3 + len(song_dirs), [], [2]),
            outputs=[
                total_config.song.one_click.cached_song.instance,
                total_config.song.multi_step.cached_song.instance,
                total_config.management.audio.intermediate.instance,
                *song_dirs,
            ],
            show_progress="hidden",
        ).then(
            partial(update_dropdowns, get_saved_output_audio, 1, [], [0]),
            outputs=total_config.management.audio.output.instance,
            show_progress="hidden",
        )
        reset_btn.click(
            lambda: [
                tab_config.n_octaves.value,
                tab_config.n_semitones.value,
                tab_config.f0_methods.value,
                tab_config.index_rate.value,
                tab_config.rms_mix_rate.value,
                tab_config.protect_rate.value,
                tab_config.hop_length.value,
                tab_config.split_voice.value,
                tab_config.autotune_voice.value,
                tab_config.autotune_strength.value,
                tab_config.clean_voice.value,
                tab_config.clean_strength.value,
                tab_config.embedder_model.value,
                tab_config.sid.value,
                tab_config.room_size.value,
                tab_config.wet_level.value,
                tab_config.dry_level.value,
                tab_config.damping.value,
                tab_config.main_gain.value,
                tab_config.inst_gain.value,
                tab_config.backup_gain.value,
                tab_config.output_sr.value,
                tab_config.output_format.value,
                tab_config.show_intermediate_audio.value,
            ],
            outputs=[
                tab_config.n_octaves.instance,
                tab_config.n_semitones.instance,
                tab_config.f0_methods.instance,
                tab_config.index_rate.instance,
                tab_config.rms_mix_rate.instance,
                tab_config.protect_rate.instance,
                tab_config.hop_length.instance,
                tab_config.split_voice.instance,
                tab_config.autotune_voice.instance,
                tab_config.autotune_strength.instance,
                tab_config.clean_voice.instance,
                tab_config.clean_strength.instance,
                tab_config.embedder_model.instance,
                tab_config.sid.instance,
                tab_config.room_size.instance,
                tab_config.wet_level.instance,
                tab_config.dry_level.instance,
                tab_config.damping.instance,
                tab_config.main_gain.instance,
                tab_config.inst_gain.instance,
                tab_config.backup_gain.instance,
                tab_config.output_sr.instance,
                tab_config.output_format.instance,
                tab_config.show_intermediate_audio.instance,
            ],
            show_progress="hidden",
        )


def _render_input(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Row():
        with gr.Column():
            tab_config.source_type.instantiate()
        with gr.Column():
            tab_config.source.instantiate()
            local_file = gr.Audio(
                label="Source",
                type="filepath",
                visible=False,
                waveform_options=gr.WaveformOptions(show_recording_waveform=False),
            )
            tab_config.cached_song.instance.render()
        tab_config.source_type.instance.input(
            partial(toggle_visible_component, 3),
            inputs=tab_config.source_type.instance,
            outputs=[
                tab_config.source.instance,
                local_file,
                tab_config.cached_song.instance,
            ],
            show_progress="hidden",
        )

        local_file.change(
            update_value,
            inputs=local_file,
            outputs=tab_config.source.instance,
            show_progress="hidden",
        )
        tab_config.cached_song.instance.input(
            update_value,
            inputs=tab_config.cached_song.instance,
            outputs=tab_config.source.instance,
            show_progress="hidden",
        )

    with gr.Row():
        tab_config.voice_model.instance.render()


def _render_main_options(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Row():
        tab_config.n_octaves.instantiate()
        tab_config.n_semitones.instantiate()


def _render_conversion_options(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Accordion("Vocal conversion", open=True):
        gr.Markdown("")
        with gr.Accordion("Voice synthesis", open=True):
            with gr.Row():
                tab_config.f0_methods.instantiate()
                tab_config.index_rate.instantiate()
            with gr.Row():
                tab_config.rms_mix_rate.instantiate()
                tab_config.protect_rate.instantiate()
                tab_config.hop_length.instantiate()
        with gr.Accordion("Vocal enrichment", open=True):
            with gr.Row():
                with gr.Column():
                    tab_config.split_voice.instantiate()
                with gr.Column():
                    tab_config.autotune_voice.instantiate()
                    tab_config.autotune_strength.instantiate()
                with gr.Column():
                    tab_config.clean_voice.instantiate()
                    tab_config.clean_strength.instantiate()
            tab_config.autotune_voice.instance.change(
                partial(toggle_visibility, targets={True}),
                inputs=tab_config.autotune_voice.instance,
                outputs=tab_config.autotune_strength.instance,
                show_progress="hidden",
            )
            tab_config.clean_voice.instance.change(
                partial(toggle_visibility, targets={True}),
                inputs=tab_config.clean_voice.instance,
                outputs=tab_config.clean_strength.instance,
                show_progress="hidden",
            )
        with gr.Accordion("Speaker embedding", open=True):
            with gr.Row():
                with gr.Column():
                    tab_config.embedder_model.instantiate()
                    tab_config.custom_embedder_model.instance.render()
                tab_config.sid.instantiate()
            tab_config.embedder_model.instance.change(
                partial(toggle_visibility, targets={EmbedderModel.CUSTOM}),
                inputs=tab_config.embedder_model.instance,
                outputs=tab_config.custom_embedder_model.instance,
                show_progress="hidden",
            )


def _render_mixing_options(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Accordion("Audio mixing", open=True):
        gr.Markdown("")
        with gr.Accordion("Reverb control on converted vocals", open=True):
            with gr.Row():
                tab_config.room_size.instantiate()
            with gr.Row():
                tab_config.wet_level.instantiate()
                tab_config.dry_level.instantiate()
                tab_config.damping.instantiate()

        with gr.Accordion("Volume controls (dB)", open=True), gr.Row():
            tab_config.main_gain.instantiate()
            tab_config.inst_gain.instantiate()
            tab_config.backup_gain.instantiate()


def _render_output_options(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Accordion("Audio output", open=True):
        with gr.Row():
            tab_config.output_name.instantiate(
                value=partial(
                    update_output_name,
                    get_song_cover_name,
                    True,  # noqa: FBT003
                ),
                inputs=[
                    gr.State(None),
                    tab_config.cached_song.instance,
                    tab_config.voice_model.instance,
                ],
            )
            tab_config.output_sr.instantiate()
            tab_config.output_format.instantiate()
        with gr.Row():
            tab_config.show_intermediate_audio.instantiate()


def _render_intermediate_audio(tab_config: OneClickSongGenerationConfig) -> None:
    with gr.Accordion(
        "Intermediate audio tracks",
        open=False,
        visible=False,
    ) as intermediate_audio_accordion:
        with gr.Accordion(
            "Step 0: song retrieval",
            open=False,
        ) as song_retrieval_accordion:
            tab_config.intermediate_audio.song.instantiate()
        with (
            gr.Accordion(
                "Step 1a: vocals/instrumentals separation",
                open=False,
            ) as vocals_separation_accordion,
            gr.Row(),
        ):
            tab_config.intermediate_audio.vocals.instantiate()
            tab_config.intermediate_audio.instrumentals.instantiate()
        with (
            gr.Accordion(
                "Step 1b: main vocals/ backup vocals separation",
                open=False,
            ) as main_vocals_separation_accordion,
            gr.Row(),
        ):
            tab_config.intermediate_audio.main_vocals.instantiate()
            tab_config.intermediate_audio.backup_vocals.instantiate()
        with (
            gr.Accordion(
                "Step 1c: main vocals cleanup",
                open=False,
            ) as vocal_cleanup_accordion,
            gr.Row(),
        ):
            tab_config.intermediate_audio.main_vocals_dereverbed.instantiate()
            tab_config.intermediate_audio.main_vocals_reverb.instantiate()
        with gr.Accordion(
            "Step 2: conversion of main vocals",
            open=False,
        ) as vocal_conversion_accordion:
            tab_config.intermediate_audio.converted_vocals.instantiate()
        with gr.Accordion(
            "Step 3: post-processing of converted vocals",
            open=False,
        ) as vocals_postprocessing_accordion:
            tab_config.intermediate_audio.postprocessed_vocals.instantiate()
        with (
            gr.Accordion(
                "Step 4: pitch shift of background tracks",
                open=False,
            ) as pitch_shift_accordion,
            gr.Row(),
        ):
            tab_config.intermediate_audio.instrumentals_shifted.instantiate()
            tab_config.intermediate_audio.backup_vocals_shifted.instantiate()

    tab_config.show_intermediate_audio.instance.change(
        partial(toggle_intermediate_audio, num_components=7),
        inputs=tab_config.show_intermediate_audio.instance,
        outputs=[
            intermediate_audio_accordion,
            song_retrieval_accordion,
            vocals_separation_accordion,
            main_vocals_separation_accordion,
            vocal_cleanup_accordion,
            vocal_conversion_accordion,
            vocals_postprocessing_accordion,
            pitch_shift_accordion,
        ],
        show_progress="hidden",
    )


app = render_app()
app_wrapper = typer.Typer()


@app_wrapper.command()
def start_app(
    share: Annotated[
        bool,
        typer.Option("--share", "-s", help="Enable sharing"),
    ] = False,
    listen: Annotated[
        bool,
        typer.Option(
            "--listen",
            "-l",
            help="Make the web application reachable from your local network.",
        ),
    ] = False,
    listen_host: Annotated[
        str | None,
        typer.Option(
            "--listen-host",
            "-h",
            help="The hostname that the server will use.",
        ),
    ] = "0.0.0.0",
    listen_port: Annotated[
        int | None,
        typer.Option(
            "--listen-port",
            "-p",
            help="The listening port that the server will use.",
        ),
    ] = None,
    ssr_mode: Annotated[
        bool,
        typer.Option(
            "--ssr-mode",
            help="Enable server-side rendering mode.",
        ),
    ] = False,
) -> None:
    """Run the Ultimate RVC web application."""
    os.environ["GRADIO_TEMP_DIR"] = str(TEMP_DIR)
    gr.set_static_paths([MODELS_DIR, AUDIO_DIR])
    #    app.queue()
    app.launch(
        server_name=listen_host,
        server_port=listen_port,
        ssr_mode=ssr_mode,
    )


load_config("default", TotalConfig)
if __name__ == "__main__":
    app_wrapper()