File size: 166,339 Bytes
3978e51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os

os.chdir('/content/Music-Source-Separation-Training')
import torch
import yaml
import gradio as gr
import subprocess
import threading
import random
import time
import shutil
import librosa
import soundfile as sf
import numpy as np
import requests
import json
import locale
import shutil
from datetime import datetime
import glob
import yt_dlp
import validators
from pytube import YouTube
from google.colab import auth
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io
import math
import hashlib
import re
import gc
import psutil
import concurrent.futures
from tqdm import tqdm
from google.oauth2.credentials import Credentials
import tempfile
from urllib.parse import urlparse
from urllib.parse import quote
import gdown


os.makedirs('/content/Music-Source-Separation-Training/input', exist_ok=True)
os.makedirs('/content/Music-Source-Separation-Training/output', exist_ok=True)
os.makedirs('/content/drive/MyDrive/output', exist_ok=True)
os.makedirs('/content/drive/MyDrive/ensemble_folder', exist_ok=True)
os.makedirs('/content/Music-Source-Separation-Training/old_output', exist_ok=True)
os.makedirs('/content/Music-Source-Separation-Training/auto_ensemble_temp', exist_ok=True)
os.makedirs('/content/Music-Source-Separation-Training/wav_folder', exist_ok=True)
shutil.rmtree('/content/Music-Source-Separation-Training/ensemble', ignore_errors=True)
shutil.rmtree('/content/Music-Source-Separation-Training/auto_ensemble_temp', ignore_errors=True)


def clear_old_output():
    old_output_folder = os.path.join(BASE_PATH, 'old_output')
    try:
        if not os.path.exists(old_output_folder):
            return "❌ Old output folder does not exist"
        
        # Tüm dosya ve alt klasörleri sil
        shutil.rmtree(old_output_folder)
        os.makedirs(old_output_folder, exist_ok=True)
        
        return "✅ Old outputs successfully cleared!"
    
    except Exception as e:
        error_msg = f"🔥 Error: {str(e)}"
        print(error_msg)
        return error_msg
    
    print("All files in old_output have been deleted.")


def shorten_filename(filename, max_length=30):
    """
    Shortens a filename to a specified maximum length
    
    Args:
        filename (str): The filename to be shortened
        max_length (int): Maximum allowed length for the filename
    
    Returns:
        str: Shortened filename
    """
    base, ext = os.path.splitext(filename)
    if len(base) <= max_length:
        return filename
    
    # Take first 15 and last 10 characters
    shortened = base[:15] + "..." + base[-10:] + ext
    return shortened

def update_progress(progress=gr.Progress()):
    def track_progress(percent):
        progress
        (percent/100)
    return track_progress

# Özel karakterleri temizlemek için
def clean_filename(title):
    return re.sub(r'[^\w\-_\. ]', '', title).strip()

def download_callback(url, download_type='direct', cookie_file=None):
    try:
        # 1. TEMİZLİK VE KLASÖR HAZIRLIĞI
        BASE_PATH = "/content/Music-Source-Separation-Training"
        INPUT_DIR = os.path.join(BASE_PATH, "input")
        COOKIE_PATH = os.path.join(BASE_PATH, "cookies.txt")
        
        # Input klasörünü temizle ve yeniden oluştur
        clear_temp_folder(
            "/tmp",
            exclude_items=["gradio", "config.json"]
        )
        clear_directory(INPUT_DIR)
        os.makedirs(INPUT_DIR, exist_ok=True)

        # 2. URL DOĞRULAMA
        if not validators.url(url):
            return None, "❌ Invalid URL", None, None, None, None

        # 3. COOKIE YÖNETİMİ
        if cookie_file is not None:
            try:
                with open(cookie_file.name, "rb") as f:
                    cookie_content = f.read()
                with open(COOKIE_PATH, "wb") as f:
                    f.write(cookie_content)
                print("✅ Cookie file updated!")
            except Exception as e:
                print(f"⚠️ Cookie installation error: {str(e)}")

        wav_path = None
        download_success = False

        # 4. İNDİRME TÜRÜNE GÖRE İŞLEM
        if download_type == 'drive':
            # GOOGLE DRIVE İNDİRME
            try:
                file_id = re.search(r'/d/([^/]+)', url).group(1) if '/d/' in url else url.split('id=')[-1]
                original_filename = "drive_download.wav"
                
                # Gdown ile indirme
                output_path = os.path.join(INPUT_DIR, original_filename)
                gdown.download(
                    f'https://drive.google.com/uc?id={file_id}',
                    output_path,
                    quiet=True,
                    fuzzy=True
                )
                
                if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
                    wav_path = output_path
                    download_success = True
                    print(f"✅ Downloaded from Google Drive: {wav_path}")
                else:
                    raise Exception("File size zero or file not created")

            except Exception as e:
                error_msg = f"❌ Google Drive download error: {str(e)}"
                print(error_msg)
                return None, error_msg, None, None, None, None

        else:
            # YOUTUBE/DİREKT LİNK İNDİRME
            ydl_opts = {
                'format': 'bestaudio/best',
                'outtmpl': os.path.join(INPUT_DIR, '%(title)s.%(ext)s'),
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'wav',
                    'preferredquality': '0'
                }],
                'cookiefile': COOKIE_PATH if os.path.exists(COOKIE_PATH) else None,
                'nocheckcertificate': True,
                'ignoreerrors': True,
                'retries': 3
            }

            try:
                with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                    info_dict = ydl.extract_info(url, download=True)
                    temp_path = ydl.prepare_filename(info_dict)
                    wav_path = os.path.splitext(temp_path)[0] + '.wav'
                    
                    if os.path.exists(wav_path):
                        download_success = True
                        print(f"✅ Downloaded successfully: {wav_path}")
                    else:
                        raise Exception("WAV conversion failed")

            except Exception as e:
                error_msg = f"❌ Download error: {str(e)}"
                print(error_msg)
                return None, error_msg, None, None, None, None

        # 5. SON KONTROLLER VE TEMİZLİK
        if download_success and wav_path:
            # Input klasöründeki gereksiz dosyaları temizle
            for f in os.listdir(INPUT_DIR):
                if f != os.path.basename(wav_path):
                    os.remove(os.path.join(INPUT_DIR, f))
            
            return (
                gr.File(value=wav_path),
                "🎉 Downloaded successfully!",
                gr.File(value=wav_path),
                gr.File(value=wav_path),
                gr.Audio(value=wav_path),
                gr.Audio(value=wav_path)
            )

        return None, "❌ Download failed", None, None, None, None

    except Exception as e:
        error_msg = f"🔥 Critical Error: {str(e)}"
        print(error_msg)
        return None, error_msg, None, None, None, None

        
# Hook function to track download progress
def download_progress_hook(d):
    if d['status'] == 'finished':
        print('Download complete, conversion in progress...')
    elif d['status'] == 'downloading':
        downloaded_bytes = d.get('downloaded_bytes', 0)
        total_bytes = d.get('total_bytes') or d.get('total_bytes_estimate', 0)
        if total_bytes > 0:
            percent = downloaded_bytes * 100. / total_bytes
            print(f'Downloading: {percent:.1f}%')

# Define the global variable at the top
INPUT_DIR = "/content/Music-Source-Separation-Training/input"

def download_file(url):
    # Encode the URL to handle spaces and special characters
    encoded_url = quote(url, safe=':/')

    path = 'ckpts'
    os.makedirs(path, exist_ok=True)
    filename = os.path.basename(encoded_url)
    file_path = os.path.join(path, filename)

    if os.path.exists(file_path):
        print(f"File '{filename}' already exists at '{path}'.")
        return

    try:
        response = torch.hub.download_url_to_file(encoded_url, file_path)
        print(f"File '{filename}' downloaded successfully")
    except Exception as e:
        print(f"Error downloading file '{filename}' from '{url}': {e}")
        


def generate_random_port():
    return random.randint(1000, 9000)

    clear_memory()

# Markdown annotations
markdown_intro = """
# Voice Parsing Tool

This tool is used to parse audio files.
"""

class IndentDumper(yaml.Dumper):
    def increase_indent(self, flow=False, indentless=False):
        return super(IndentDumper, self).increase_indent(flow, False)


def tuple_constructor(loader, node):
    # Load the sequence of values from the YAML node
    values = loader.construct_sequence(node)
    # Return a tuple constructed from the sequence
    return tuple(values)

# Register the constructor with PyYAML
yaml.SafeLoader.add_constructor('tag:yaml.org,2002:python/tuple',
tuple_constructor)



def conf_edit(config_path, chunk_size, overlap):
    with open(config_path, 'r') as f:
        data = yaml.load(f, Loader=yaml.SafeLoader)

    # handle cases where 'use_amp' is missing from config:
    if 'use_amp' not in data.keys():
      data['training']['use_amp'] = True

    data['audio']['chunk_size'] = chunk_size
    data['inference']['num_overlap'] = overlap

    if data['inference']['batch_size'] == 1:
      data['inference']['batch_size'] = 2

    print("Using custom overlap and chunk_size values:")
    print(f"overlap = {data['inference']['num_overlap']}")
    print(f"chunk_size = {data['audio']['chunk_size']}")
    print(f"batch_size = {data['inference']['batch_size']}")


    with open(config_path, 'w') as f:
        yaml.dump(data, f, default_flow_style=False, sort_keys=False, Dumper=IndentDumper, allow_unicode=True)
        
def save_uploaded_file(uploaded_file, is_input=False, target_dir=None):
    try:
        # Medya dosya uzantıları
        media_extensions = ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a', '.mp4']
        
        # Hedef dizini belirle
        if target_dir is None:
            target_dir = INPUT_DIR if is_input else VİDEO_TEMP
        
        # Zaman damgası pattern'leri
        timestamp_patterns = [
            r'_\d{8}_\d{6}_\d{6}$',  # _20231215_123456_123456
            r'_\d{14}$',             # _20231215123456
            r'_\d{10}$',             # _1702658400
            r'_\d+$'                 # Herhangi bir sayı
        ]
        
        # Dosya adını al
        if hasattr(uploaded_file, 'name'):
            original_filename = os.path.basename(uploaded_file.name)
        else:
            original_filename = os.path.basename(str(uploaded_file))
        
        # Dosya adını temizle (sadece input'lar için)
        if is_input:
            base_filename = original_filename
            # Zaman damgalarını sil
            for pattern in timestamp_patterns:
                base_filename = re.sub(pattern, '', base_filename)
            # Çoklu uzantıları sil
            for ext in media_extensions:
                base_filename = base_filename.replace(ext, '')
            
            # Dosya uzantısını belirle
            file_ext = next(
                (ext for ext in media_extensions if original_filename.lower().endswith(ext)),
                '.wav'
            )
            clean_filename = f"{base_filename.strip('_- ')}{file_ext}"
        else:
            clean_filename = original_filename

        # Hedef dizini belirle (DÜZELTME BURADA)
        target_directory = INPUT_DIR if is_input else OUTPUT_DIR
        target_path = os.path.join(target_dir, clean_filename)
        
        # Dizini oluştur (yoksa)
        os.makedirs(target_directory, exist_ok=True)
        
        # Dizindeki TÜM önceki dosyaları sil
        for filename in os.listdir(target_directory):
            file_path = os.path.join(target_directory, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f"{file_path} Not deleted: {e}")

        # Yeni dosyayı kaydet
        if hasattr(uploaded_file, 'read'):
            with open(target_path, "wb") as f:
                f.write(uploaded_file.read())
        else:
            shutil.copy(uploaded_file, target_path)
            
        print(f"File saved successfully: {os.path.basename(target_path)}")
        return target_path
    
    except Exception as e:
        print(f"File save error: {e}")
        return None

        clear_memory()

def save_uploaded_file(uploaded_file, is_input=False, target_dir=None):
    try:
        # Medya dosya uzantıları
        media_extensions = ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a', '.mp4']
        
        # Hedef dizini belirle
        if target_dir is None:
            target_dir = INPUT_DIR if is_input else OUTPUT_DIR
        
        # Zaman damgası pattern'leri
        timestamp_patterns = [
            r'_\d{8}_\d{6}_\d{6}$',  # _20231215_123456_123456
            r'_\d{14}$',             # _20231215123456
            r'_\d{10}$',             # _1702658400
            r'_\d+$'                 # Herhangi bir sayı
        ]
        
        # Dosya adını al
        if hasattr(uploaded_file, 'name'):
            original_filename = os.path.basename(uploaded_file.name)
        else:
            original_filename = os.path.basename(str(uploaded_file))
        
        # Dosya adını temizle (sadece input'lar için)
        if is_input:
            base_filename = original_filename
            # Zaman damgalarını sil
            for pattern in timestamp_patterns:
                base_filename = re.sub(pattern, '', base_filename)
            # Çoklu uzantıları sil
            for ext in media_extensions:
                base_filename = base_filename.replace(ext, '')
            
            # Dosya uzantısını belirle
            file_ext = next(
                (ext for ext in media_extensions if original_filename.lower().endswith(ext)),
                '.wav'
            )
            clean_filename = f"{base_filename.strip('_- ')}{file_ext}"
        else:
            clean_filename = original_filename

        # Hedef dizini belirle
        target_directory = INPUT_DIR if is_input else OUTPUT_DIR
        target_path = os.path.join(target_directory, clean_filename)
        
        # Dizini oluştur (yoksa)
        os.makedirs(target_directory, exist_ok=True)
        
        # Eğer dosya zaten varsa, sil
        if os.path.exists(target_path):
            os.remove(target_path)

        # Yeni dosyayı kaydet
        if hasattr(uploaded_file, 'read'):
            with open(target_path, "wb") as f:
                f.write(uploaded_file.read())
        else:
            shutil.copy(uploaded_file, target_path)
            
        print(f"File saved successfully: {os.path.basename(target_path)}")
        return target_path
    
    except Exception as e:
        print(f"File save error: {e}")
        return None


def clear_temp_folder(folder_path, exclude_items=None):
    """
    Safely clears contents of a directory while preserving specified items
    
    Args:
        folder_path (str): Path to directory to clean
        exclude_items (list): Items to preserve (e.g., ['gradio', 'important.log'])
        
    Returns:
        bool: True if successful, False if failed
    """
    try:
        # Validate directory existence
        if not os.path.exists(folder_path):
            print(f"⚠️ Directory does not exist: {folder_path}")
            return False
            
        if not os.path.isdir(folder_path):
            print(f"⚠️ Path is not a directory: {folder_path}")
            return False

        # Initialize exclusion list
        exclude_items = exclude_items or []
        preserved_items = []

        # Process directory contents
        for item_name in os.listdir(folder_path):
            item_path = os.path.join(folder_path, item_name)
            
            # Skip excluded items
            if item_name in exclude_items:
                preserved_items.append(item_path)
                continue
                
            try:
                # Delete files and symlinks
                if os.path.isfile(item_path) or os.path.islink(item_path):
                    os.unlink(item_path)
                    print(f"🗑️ File removed: {item_path}")
                    
                # Delete directories
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
                    print(f"🗂️ Directory removed: {item_path}")
                    
            except PermissionError as pe:
                print(f"🔒 Permission denied: {item_path} ({str(pe)})")
                continue
                
            except Exception as e:
                print(f"⚠️ Error deleting {item_path}: {str(e)}")
                continue

        # Print summary
        print(f"\n✅ Cleaning completed: {folder_path}")
        print(f"Total preserved items: {len(preserved_items)}")
        if preserved_items:
            print("Preserved items:")
            for item in preserved_items:
                print(f"  - {item}")
                
        return True

    except Exception as e:
        print(f"❌ Critical error: {str(e)}")
        return False


def handle_file_upload(file_obj, file_path_input, is_auto_ensemble=False):
    try:
        BASE_PATH = "/content/Music-Source-Separation-Training"
        INPUT_DIR = os.path.join(BASE_PATH, "input")
        
        # Yeni: Önceki dosyaları kontrol et
        existing_files = os.listdir(INPUT_DIR)
        new_file = None

        # Dosya yolu girilmişse
        if file_path_input and os.path.exists(file_path_input):
            new_file = file_path_input
        # Dosya yüklenmişse
        elif file_obj:
            new_file = file_obj.name  # Gradio'nun geçici dosya yolu

        # Yeni dosya yoksa mevcut dosyayı koru
        if not new_file and existing_files:
            kept_file = os.path.join(INPUT_DIR, existing_files[0])
            return [
                gr.File(value=kept_file),
                gr.Audio(value=kept_file)
            ]

        # Yeni dosya varsa temizle ve yükle
        if new_file:
            clear_directory(INPUT_DIR)  # Sadece yeni dosya geldiğinde temizle
            saved_path = save_uploaded_file(new_file, is_input=True)
            return [
                gr.File(value=saved_path),
                gr.Audio(value=saved_path)
            ]

        return [None, None]
    
    except Exception as e:
        print(f"Error: {str(e)}")
        return [None, None]
        
def move_old_files(output_folder):
    old_output_folder = os.path.join(BASE_PATH, 'old_output')
    os.makedirs(old_output_folder, exist_ok=True)

    # Eski dosyaları taşı ve adlarının sonuna "old" ekle
    for filename in os.listdir(output_folder):
        file_path = os.path.join(output_folder, filename)
        if os.path.isfile(file_path):
            # Yeni dosya adını oluştur
            new_filename = f"{os.path.splitext(filename)[0]}_old{os.path.splitext(filename)[1]}"
            new_file_path = os.path.join(old_output_folder, new_filename)
            shutil.move(file_path, new_file_path) 

def move_wav_files2(INPUT_DIR):
    ENSEMBLE_DIR = os.path.join(BASE_PATH, 'ensemble')
    os.makedirs(ENSEMBLE_DIR, exist_ok=True)

    # Eski dosyaları taşı ve adlarının sonuna "old" ekle
    for filename in os.listdir(INPUT_DIR):
        file_path = os.path.join(INPUT_DIR, filename)
        if os.path.isfile(file_path):
            # Yeni dosya adını oluştur
            new_filename = f"{os.path.splitext(filename)[0]}_ensemble{os.path.splitext(filename)[1]}"
            new_file_path = os.path.join(ENSEMBLE_DIR, new_filename)
            shutil.move(file_path, new_file_path)             


def extract_model_name(full_model_string):
    """
    Function to clear model name
    """
    if not full_model_string:
        return ""

    cleaned = str(full_model_string)

    # Remove the description
    if ' - ' in cleaned:
        cleaned = cleaned.split(' - ')[0]

    # Remove emoji prefixes
    emoji_prefixes = ['✅ ', '👥 ', '🗣️ ', '🏛️ ', '🔇 ', '🔉 ', '🎬 ', '🎼 ', '✅(?) ']
    for prefix in emoji_prefixes:
        if cleaned.startswith(prefix):
            cleaned = cleaned[len(prefix):]

    return cleaned.strip()

COOKIE_PATH = '/content/'
BASE_PATH = '/content/Music-Source-Separation-Training'
INPUT_DIR = os.path.join(BASE_PATH, 'input')
AUTO_ENSEMBLE_TEMP = os.path.join(BASE_PATH, 'auto_ensemble_temp')
OUTPUT_DIR = '/content/drive/MyDrive/output'
OLD_OUTPUT_DIR = '/content/drive/MyDrive/old_output'
AUTO_ENSEMBLE_OUTPUT = '/content/drive/MyDrive/ensemble_folder'
INFERENCE_SCRIPT_PATH = '/content/Music-Source-Separation-Training/inference.py'
VİDEO_TEMP = '/content/Music-Source-Separation-Training/video_temp'
ENSEMBLE_DIR = '/content/Music-Source-Separation-Training/ensemble'
os.makedirs(VİDEO_TEMP, exist_ok=True)  # Klasörü oluşturduğundan emin ol
Backup = '/content/backup'

def clear_directory(directory):
    """Deletes all files in the given directory."""
    files = glob.glob(os.path.join(directory, '*'))  # Dizin içindeki tüm dosyaları al
    for f in files:
        try:
            os.remove(f)  # remove files
        except Exception as e:
            print(f"{f} could not be deleted: {e}")     

def create_directory(directory):
    """Creates the given directory (if it exists, if not)."""
    if not os.path.exists(directory):
        os.makedirs(directory)
        print(f"{directory} directory created.")
    else:
        print(f"{directory} directory already exists.")     

def convert_to_wav(file_path):
    """Converts the audio file to WAV format and moves it to the ensemble directory."""
    
    BASE_DIR = "/content/Music-Source-Separation-Training"
    ENSEMBLE_DIR = os.path.join(BASE_DIR, "ensemble")  # Define the ensemble directory
    os.makedirs(ENSEMBLE_DIR, exist_ok=True)  # Create the ensemble directory if it doesn't exist

    original_filename = os.path.basename(file_path)
    filename, ext = os.path.splitext(original_filename)
    
    # If already a WAV file, return its path directly
    if ext.lower() == '.wav':
        return file_path  # Return the original path if it's already a WAV file

    try:
        # Prepare for WAV conversion
        wav_output = os.path.join(ENSEMBLE_DIR, f"{filename}.wav")  # Save to ensemble directory
        
        # Run FFmpeg command to convert to WAV
        command = [
            'ffmpeg', '-y', '-i', file_path,
            '-acodec', 'pcm_s16le', '-ar', '44100', wav_output
        ]
        subprocess.run(command, check=True, capture_output=True)

        return wav_output  # Return the path of the converted WAV file
        
    except subprocess.CalledProcessError as e:
        error_msg = f"FFmpeg Error ({e.returncode}): {e.stderr.decode()}"
        print(error_msg)
        return None
    except Exception as e:
        print(f"Error during conversion: {str(e)}")
        return None

def send_audio_file(file_path):
    try:
        if not os.path.exists(file_path):
            print(f"File not found: {file_path}")
            return None, "File not found"

        with open(file_path, 'rb') as f:
            data = f.read()
            print(f"Sending file: {file_path}, Size: {len(data)} bytes")
            return data, "Success"
    except Exception as e:
        print(f"Error sending file: {e}")
        return None, str(e)   
       

def process_audio(input_audio_file, model, chunk_size, overlap, export_format, use_tta, demud_phaseremix_inst, extract_instrumental, clean_model, *args, **kwargs): 
    # Determine the audio path
    if input_audio_file is not None:
        audio_path = input_audio_file.name
    else:
        # Check for existing files in INPUT_DIR
        create_directory(INPUT_DIR)  # Ensure the directory exists
        existing_files = os.listdir(INPUT_DIR)
        if existing_files:
            # Use the first existing file
            audio_path = os.path.join(INPUT_DIR, existing_files[0])
        else:
            print("No audio file provided and no existing file in input directory.")
            return [None] * 14  # Error case

    # Create necessary directories
    create_directory(OUTPUT_DIR)
    create_directory(OLD_OUTPUT_DIR)

    # Move old files to the OLD_OUTPUT_DIR
    move_old_files(OUTPUT_DIR)

    # Clean model name
    clean_model = extract_model_name(model)
    print(f"Processing audio from: {audio_path} using model: {clean_model}")

    # Model configuration (remaining code)
    model_type, config_path, start_check_point = "", "", ""

    if clean_model == 'VOCALS-InstVocHQ':
            model_type = 'mdx23c'
            config_path = 'ckpts/config_vocals_mdx23c.yaml'
            start_check_point = 'ckpts/model_vocals_mdx23c_sdr_10.17.ckpt'
            download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/config_vocals_mdx23c.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.0/model_vocals_mdx23c_sdr_10.17.ckpt')

    elif clean_model == 'VOCALS-MelBand-Roformer (by KimberleyJSN)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_vocals_mel_band_roformer_kj.yaml'
            start_check_point = 'ckpts/MelBandRoformer.ckpt'
            download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/KimberleyJensen/config_vocals_mel_band_roformer_kj.yaml')
            download_file('https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-BS-Roformer_1297 (by viperx)':
            model_type = 'bs_roformer'
            config_path = 'ckpts/model_bs_roformer_ep_317_sdr_12.9755.yaml'
            start_check_point = 'ckpts/model_bs_roformer_ep_317_sdr_12.9755.ckpt'
            download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/viperx/model_bs_roformer_ep_317_sdr_12.9755.yaml')
            download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_317_sdr_12.9755.ckpt')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-BS-Roformer_1296 (by viperx)':
            model_type = 'bs_roformer'
            config_path = 'ckpts/model_bs_roformer_ep_368_sdr_12.9628.yaml'
            start_check_point = 'ckpts/model_bs_roformer_ep_368_sdr_12.9628.ckpt'
            download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_368_sdr_12.9628.ckpt')
            download_file('https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs/model_bs_roformer_ep_368_sdr_12.9628.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-BS-RoformerLargev1 (by unwa)':
            model_type = 'bs_roformer'
            config_path = 'ckpts/config_bsrofoL.yaml'
            start_check_point = 'ckpts/BS-Roformer_LargeV1.ckpt'
            download_file('https://huggingface.co/jarredou/unwa_bs_roformer/resolve/main/BS-Roformer_LargeV1.ckpt')
            download_file('https://huggingface.co/jarredou/unwa_bs_roformer/raw/main/config_bsrofoL.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-Mel-Roformer big beta 4 (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_big_beta4.yaml'
            start_check_point = 'ckpts/melband_roformer_big_beta4.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/melband_roformer_big_beta4.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/raw/main/config_melbandroformer_big_beta4.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-Melband-Roformer BigBeta5e (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/big_beta5e.yaml'
            start_check_point = 'ckpts/big_beta5e.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/big_beta5e.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/big_beta5e.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INST-Mel-Roformer v1 (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_inst.yaml'
            start_check_point = 'ckpts/melband_roformer_inst_v1.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/melband_roformer_inst_v1.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/raw/main/config_melbandroformer_inst.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INST-Mel-Roformer v2 (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_inst_v2.yaml'
            start_check_point = 'ckpts/melband_roformer_inst_v2.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/melband_roformer_inst_v2.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/raw/main/config_melbandroformer_inst_v2.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INST-VOC-Mel-Roformer a.k.a. duality (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_instvoc_duality.yaml'
            start_check_point = 'ckpts/melband_roformer_instvoc_duality_v1.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/resolve/main/melband_roformer_instvoc_duality_v1.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/raw/main/config_melbandroformer_instvoc_duality.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INST-VOC-Mel-Roformer a.k.a. duality v2 (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_instvoc_duality.yaml'
            start_check_point = 'ckpts/melband_roformer_instvox_duality_v2.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/resolve/main/melband_roformer_instvox_duality_v2.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/raw/main/config_melbandroformer_instvoc_duality.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'KARAOKE-MelBand-Roformer (by aufr33 & viperx)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_mel_band_roformer_karaoke.yaml'
            start_check_point = 'ckpts/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt'
            download_file('https://huggingface.co/jarredou/aufr33-viperx-karaoke-melroformer-model/resolve/main/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt')
            download_file('https://huggingface.co/jarredou/aufr33-viperx-karaoke-melroformer-model/resolve/main/config_mel_band_roformer_karaoke.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'OTHER-BS-Roformer_1053 (by viperx)':
            model_type = 'bs_roformer'
            config_path = 'ckpts/model_bs_roformer_ep_937_sdr_10.5309.yaml'
            start_check_point = 'ckpts/model_bs_roformer_ep_937_sdr_10.5309.ckpt'
            download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_937_sdr_10.5309.ckpt')
            download_file('https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs/model_bs_roformer_ep_937_sdr_10.5309.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'CROWD-REMOVAL-MelBand-Roformer (by aufr33)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/model_mel_band_roformer _crowd.yaml'
            start_check_point = 'ckpts/mel_band_roformer_crowd_aufr33_viperx_sdr_8.7144.ckpt'
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.4/mel_band_roformer_crowd_aufr33_viperx_sdr_8.7144.ckpt')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.4/model_mel_band_roformer_crowd.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-VitLarge23 (by ZFTurbo)':
            model_type = 'segm_models'
            config_path = 'ckpts/config_vocals_segm_models.yaml'
            start_check_point = 'ckpts/model_vocals_segm_models_sdr_9.77.ckpt'
            download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/refs/heads/main/configs/config_vocals_segm_models.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.0/model_vocals_segm_models_sdr_9.77.ckpt')

    elif clean_model == 'CINEMATIC-BandIt_Plus (by kwatcharasupat)':
            model_type = 'bandit'
            config_path = 'ckpts/config_dnr_bandit_bsrnn_multi_mus64.yaml'
            start_check_point = 'ckpts/model_bandit_plus_dnr_sdr_11.47.chpt'
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.3/config_dnr_bandit_bsrnn_multi_mus64.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.3/model_bandit_plus_dnr_sdr_11.47.chpt')

    elif clean_model == 'DRUMSEP-MDX23C_DrumSep_6stem (by aufr33 & jarredou)':
            model_type = 'mdx23c'
            config_path = 'ckpts/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.yaml'
            start_check_point = 'ckpts/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.ckpt'
            download_file('https://github.com/jarredou/models/releases/download/aufr33-jarredou_MDX23C_DrumSep_model_v0.1/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.ckpt')
            download_file('https://github.com/jarredou/models/releases/download/aufr33-jarredou_MDX23C_DrumSep_model_v0.1/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.yaml')

    elif clean_model == '4STEMS-SCNet_MUSDB18 (by starrytong)':
            model_type = 'scnet'
            config_path = 'ckpts/config_musdb18_scnet.yaml'
            start_check_point = 'ckpts/scnet_checkpoint_musdb18.ckpt'
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.6/config_musdb18_scnet.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.6/scnet_checkpoint_musdb18.ckpt')

    elif clean_model == 'DE-REVERB-MDX23C (by aufr33 & jarredou)':
            model_type = 'mdx23c'
            config_path = 'ckpts/config_dereverb_mdx23c.yaml'
            start_check_point = 'ckpts/dereverb_mdx23c_sdr_6.9096.ckpt'
            download_file('https://huggingface.co/jarredou/aufr33_jarredou_MDXv3_DeReverb/resolve/main/dereverb_mdx23c_sdr_6.9096.ckpt')
            download_file('https://huggingface.co/jarredou/aufr33_jarredou_MDXv3_DeReverb/resolve/main/config_dereverb_mdx23c.yaml')

    elif clean_model == 'DENOISE-MelBand-Roformer-1 (by aufr33)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
            start_check_point = 'ckpts/denoise_mel_band_roformer_aufr33_sdr_27.9959.ckpt'
            download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/denoise_mel_band_roformer_aufr33_sdr_27.9959.ckpt')
            download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'DENOISE-MelBand-Roformer-2 (by aufr33)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
            start_check_point = 'ckpts/denoise_mel_band_roformer_aufr33_aggr_sdr_27.9768.ckpt'
            download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/denoise_mel_band_roformer_aufr33_aggr_sdr_27.9768.ckpt')
            download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-MelBand-Roformer Kim FT (by Unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
            start_check_point = 'ckpts/kimmel_unwa_ft.ckpt'
            download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft.ckpt')
            download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_v1e (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_melbandroformer_inst.yaml'
            start_check_point = 'ckpts/inst_v1e.ckpt'
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/inst_v1e.ckpt')
            download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/config_melbandroformer_inst.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'bleed_suppressor_v1 (by unwa)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_bleed_suppressor_v1.yaml'
            start_check_point = 'ckpts/bleed_suppressor_v1.ckpt'
            download_file('https://huggingface.co/ASesYusuf1/MODELS/resolve/main/bleed_suppressor_v1.ckpt')
            download_file('https://huggingface.co/ASesYusuf1/MODELS/resolve/main/config_bleed_suppressor_v1.yaml')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-MelBand-Roformer (by Becruily)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_instrumental_becruily.yaml'
            start_check_point = 'ckpts/mel_band_roformer_vocals_becruily.ckpt'
            download_file('https://huggingface.co/becruily/mel-band-roformer-vocals/resolve/main/config_vocals_becruily.yaml')
            download_file('https://huggingface.co/becruily/mel-band-roformer-vocals/resolve/main/mel_band_roformer_vocals_becruily.ckpt')
            conf_edit(config_path, chunk_size, overlap)
    
    elif clean_model == 'INST-MelBand-Roformer (by Becruily)':
            model_type = 'mel_band_roformer'
            config_path = 'ckpts/config_instrumental_becruily.yaml'
            start_check_point = 'ckpts/mel_band_roformer_instrumental_becruily.ckpt'
            download_file('https://huggingface.co/becruily/mel-band-roformer-instrumental/resolve/main/config_instrumental_becruily.yaml')
            download_file('https://huggingface.co/becruily/mel-band-roformer-instrumental/resolve/main/mel_band_roformer_instrumental_becruily.ckpt')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == '4STEMS-SCNet_XL_MUSDB18 (by ZFTurbo)':
            model_type = 'scnet'
            config_path = 'ckpts/config_musdb18_scnet_xl.yaml'
            start_check_point = 'ckpts/model_scnet_ep_54_sdr_9.8051.ckpt'
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.13/config_musdb18_scnet_xl.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.13/model_scnet_ep_54_sdr_9.8051.ckpt')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == '4STEMS-SCNet_Large (by starrytong)':
            model_type = 'scnet'
            config_path = 'ckpts/config_musdb18_scnet_large_starrytong.yaml'
            start_check_point = 'ckpts/SCNet-large_starrytong_fixed.ckpt'
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.9/config_musdb18_scnet_large_starrytong.yaml')
            download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.9/SCNet-large_starrytong_fixed.ckpt')
            conf_edit(config_path, chunk_size, overlap)

    elif clean_model == '4STEMS-BS-Roformer_MUSDB18 (by ZFTurbo)':
           model_type = 'bs_roformer'
           config_path = 'ckpts/config_bs_roformer_384_8_2_485100.yaml'
           start_check_point = 'ckpts/model_bs_roformer_ep_17_sdr_9.6568.ckpt'
           download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.12/config_bs_roformer_384_8_2_485100.yaml')
           download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.12/model_bs_roformer_ep_17_sdr_9.6568.ckpt')
           conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'DE-REVERB-MelBand-Roformer aggr./v2/19.1729 (by anvuew)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
          start_check_point = 'ckpts/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt')
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
          conf_edit(config_path, chunk_size, overlap)
          
    elif clean_model == 'DE-REVERB-Echo-MelBand-Roformer (by Sucial)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config_dereverb-echo_mel_band_roformer.yaml'
          start_check_point = 'ckpts/dereverb-echo_mel_band_roformer_sdr_10.0169.ckpt'
          download_file('https://huggingface.co/Sucial/Dereverb-Echo_Mel_Band_Roformer/resolve/main/dereverb-echo_mel_band_roformer_sdr_10.0169.ckpt')
          download_file('https://huggingface.co/Sucial/Dereverb-Echo_Mel_Band_Roformer/resolve/main/config_dereverb-echo_mel_band_roformer.yaml')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'dereverb_mel_band_roformer_less_aggressive_anvuew':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
          start_check_point = 'ckpts/dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt'
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'dereverb_mel_band_roformer_anvuew':
          model_type = 'mel_band_roformer'
          config_path = 'dereverb_mel_band_roformer_anvuew.yaml'
          start_check_point = 'ckpts/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt')
          conf_edit(config_path, chunk_size, overlap)  


    elif clean_model == 'inst_gabox (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gabox.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_gaboxBV1 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gaboxBv1.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxBv1.ckpt')
          conf_edit(config_path, chunk_size, overlap)


    elif clean_model == 'inst_gaboxBV2 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gaboxBv2.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxBv2.ckpt')
          conf_edit(config_path, chunk_size, overlap)     


    elif clean_model == 'inst_gaboxBFV1 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/gaboxFv1.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv1.ckpt')
          conf_edit(config_path, chunk_size, overlap)


    elif clean_model == 'inst_gaboxFV2 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gaboxFv2.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv2.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    
    elif clean_model == 'VOCALS-Male Female-BS-RoFormer Male Female Beta 7_2889 (by aufr33)':
          model_type = 'bs_roformer'
          config_path = 'ckpts/config_chorus_male_female_bs_roformer.yaml'
          start_check_point = 'ckpts/bs_roformer_male_female_by_aufr33_sdr_7.2889.ckpt'
          download_file('https://huggingface.co/RareSirMix/AIModelRehosting/resolve/main/bs_roformer_male_female_by_aufr33_sdr_7.2889.ckpt')
          download_file('https://huggingface.co/Sucial/Chorus_Male_Female_BS_Roformer/resolve/main/config_chorus_male_female_bs_roformer.yaml')
          conf_edit(config_path, chunk_size, overlap)


    elif clean_model == 'VOCALS-MelBand-Roformer Kim FT 2 (by Unwa)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
          start_check_point = 'ckpts/kimmel_unwa_ft2.ckpt'
          download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
          download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft2.ckpt')
          conf_edit(config_path, chunk_size, overlap)      

    elif clean_model == 'voc_gaboxBSroformer (by Gabox)':
          model_type = 'bs_roformer'
          config_path = 'ckpts/voc_gaboxBSroformer.yaml'
          start_check_point = 'ckpts/voc_gaboxBSR.ckpt'
          download_file('https://huggingface.co/GaboxR67/BSRoformerVocTest/resolve/main/voc_gaboxBSroformer.yaml')
          download_file('https://huggingface.co/GaboxR67/BSRoformerVocTest/resolve/main/voc_gaboxBSR.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'voc_gaboxMelReformer (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/voc_gabox.yaml'
          start_check_point = 'ckpts/voc_gabox.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'voc_gaboxMelReformerFV1 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/voc_gabox.yaml'
          start_check_point = 'ckpts/voc_gaboxFv1.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gaboxFv1.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'voc_gaboxMelReformerFV2 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/voc_gabox.yaml'
          start_check_point = 'ckpts/voc_gaboxFv2.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gaboxFv2.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_GaboxFv3 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gaboxFv3.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv3.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'Intrumental_Gabox (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/intrumental_gabox.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/intrumental_gabox.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_Fv4Noise (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_Fv4Noise.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_Fv4Noise.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_V5 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/INSTV5.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV5.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model1 (by Amane)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config.yaml'
          start_check_point = 'ckpts/model.ckpt'
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model2 (by Amane)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config.yaml'
          start_check_point = 'ckpts/model2.ckpt'
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model2.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model3 (by Amane)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config.yaml'
          start_check_point = 'ckpts/model3.ckpt'
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
          download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model3.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'VOCALS-MelBand-Roformer Kim FT 2 Blendless (by unwa)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
          start_check_point = 'ckpts/kimmel_unwa_ft2_bleedless.ckpt'
          download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
          download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft2_bleedless.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_gaboxFV1 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/inst_gaboxFv1.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv1.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'inst_gaboxFV6 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/INSTV6.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV6.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'denoisedebleed (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
          start_check_point = 'ckpts/denoisedebleed.ckpt'
          download_file('https://huggingface.co/poiqazwsx/melband-roformer-denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/denoisedebleed.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INSTV5N (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/INSTV5N.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV5N.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'Voc_Fv3 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/voc_gabox.yaml'
          start_check_point = 'ckpts/voc_Fv3.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_Fv3.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'MelBandRoformer4StemFTLarge (SYH99999)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config.yaml'
          start_check_point = 'ckpts/MelBandRoformer4StemFTLarge.ckpt'
          download_file('https://huggingface.co/SYH99999/MelBandRoformer4StemFTLarge/resolve/main/config.yaml')
          download_file('https://huggingface.co/SYH99999/MelBandRoformer4StemFTLarge/resolve/main/MelBandRoformer4StemFTLarge.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'dereverb_mel_band_roformer_mono (by anvuew)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
          start_check_point = 'ckpts/dereverb_mel_band_roformer_mono_anvuew_sdr_20.4029.ckpt'
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
          download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_mono_anvuew_sdr_20.4029.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'INSTV6N (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/INSTV6N.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV6N.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'KaraokeGabox':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config_mel_band_roformer_karaoke.yaml'
          start_check_point = 'ckpts/KaraokeGabox.ckpt'
          download_file('https://github.com/deton24/Colab-for-new-MDX_UVR_models/releases/download/v1.0.0/config_mel_band_roformer_karaoke.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/blob/main/melbandroformers/experimental/KaraokeGabox.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'FullnessVocalModel (by Amane)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/config.yaml'
          start_check_point = 'ckpts/FullnessVocalModel.ckpt'
          download_file('https://huggingface.co/Aname-Tommy/MelBandRoformers/blob/main/config.yaml')
          download_file('https://huggingface.co/Aname-Tommy/MelBandRoformers/blob/main/FullnessVocalModel.ckpt')
          conf_edit(config_path, chunk_size, overlap)

    elif clean_model == 'Inst_GaboxV7 (by Gabox)':
          model_type = 'mel_band_roformer'
          config_path = 'ckpts/inst_gabox.yaml'
          start_check_point = 'ckpts/Inst_GaboxV7.ckpt'
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
          download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/Inst_GaboxV7.ckpt')
          conf_edit(config_path, chunk_size, overlap)      









    # Other model options will be added here...
    # (All the elif blocks you gave in the previous code will go here)


    else:
        print(f"Unsupported model: {clean_model}")
        return [None] * 14  # Hata durumu

    result = run_command_and_process_files(model_type, config_path, start_check_point, INPUT_DIR, OUTPUT_DIR, extract_instrumental, use_tta, demud_phaseremix_inst, clean_model)

    # İşlem tamamlandıktan sonra giriş dizinini temizle 

    return result    


def clean_model_name(model):
    """
    Clean and standardize model names for filename
    """
    # Mapping of complex model names to simpler, filename-friendly versions
    model_name_mapping = {
        'VOCALS-InstVocHQ': 'InstVocHQ',
        'VOCALS-MelBand-Roformer (by KimberleyJSN)': 'KimberleyJSN',
        'VOCALS-BS-Roformer_1297 (by viperx)': 'VOCALS_BS_Roformer1297',
        'VOCALS-BS-Roformer_1296 (by viperx)': 'VOCALS-BS-Roformer_1296',
        'VOCALS-BS-RoformerLargev1 (by unwa)': 'UnwaLargeV1',
        'VOCALS-Mel-Roformer big beta 4 (by unwa)': 'UnwaBigBeta4',
        'VOCALS-Melband-Roformer BigBeta5e (by unwa)': 'UnwaBigBeta5e',
        'INST-Mel-Roformer v1 (by unwa)': 'UnwaInstV1',
        'INST-Mel-Roformer v2 (by unwa)': 'UnwaInstV2',
        'INST-VOC-Mel-Roformer a.k.a. duality (by unwa)': 'UnwaDualityV1',
        'INST-VOC-Mel-Roformer a.k.a. duality v2 (by unwa)': 'UnwaDualityV2',
        'KARAOKE-MelBand-Roformer (by aufr33 & viperx)': 'KaraokeMelBandRoformer',
        'VOCALS-VitLarge23 (by ZFTurbo)': 'VitLarge23',
        'VOCALS-MelBand-Roformer (by Becruily)': 'BecruilyVocals',
        'INST-MelBand-Roformer (by Becruily)': 'BecruilyInst',
        'VOCALS-MelBand-Roformer Kim FT (by Unwa)': 'KimFT',
        'INST-MelBand-Roformer Kim FT (by Unwa)': 'KimFTInst',
        'OTHER-BS-Roformer_1053 (by viperx)': 'OtherViperx1053',
        'CROWD-REMOVAL-MelBand-Roformer (by aufr33)': 'CrowdRemovalRoformer',
        'CINEMATIC-BandIt_Plus (by kwatcharasupat)': 'CinematicBandItPlus',
        'DRUMSEP-MDX23C_DrumSep_6stem (by aufr33 & jarredou)': 'DrumSepMDX23C',
        '4STEMS-SCNet_MUSDB18 (by starrytong)': 'FourStemsSCNet',
        'DE-REVERB-MDX23C (by aufr33 & jarredou)': 'DeReverbMDX23C',
        'DENOISE-MelBand-Roformer-1 (by aufr33)': 'DenoiseMelBand1',
        'DENOISE-MelBand-Roformer-2 (by aufr33)': 'DenoiseMelBand2',
        'INST-MelBand-Roformer (by Becruily)': 'BecruilyInst',
        '4STEMS-SCNet_XL_MUSDB18 (by ZFTurbo)': 'FourStemsSCNetXL',
        '4STEMS-SCNet_Large (by starrytong)': 'FourStemsSCNetLarge',
        '4STEMS-BS-Roformer_MUSDB18 (by ZFTurbo)': 'FourStemsBSRoformer',
        'DE-REVERB-MelBand-Roformer aggr./v2/19.1729 (by anvuew)': 'DeReverbMelBandAggr',
        'DE-REVERB-Echo-MelBand-Roformer (by Sucial)': 'DeReverbEchoMelBand',
        'bleed_suppressor_v1 (by unwa)': 'BleedSuppressorV1',
        'inst_v1e (by unwa)': 'InstV1E',
        'inst_gabox ( by Gabox)': 'InstGabox',
        'inst_gaboxBV1 (by Gabox)': 'InstGaboxBV1',
        'inst_gaboxBV2 (by Gabox)': 'InstGaboxBV2',
        'inst_gaboxBFV1 (by Gabox)': 'InstGaboxBFV1',
        'inst_gaboxFV2 (by Gabox)': 'InstGaboxFV2',
        'inst_gaboxFV1 (by Gabox)': 'InstGaboxFV1',
        'dereverb_mel_band_roformer_less_aggressive_anvuew': 'DereverbMelBandRoformerLessAggressive',
        'dereverb_mel_band_roformer_anvuew': 'DereverbMelBandRoformer',
        'VOCALS-Male Female-BS-RoFormer Male Female Beta 7_2889 (by aufr33)': 'MaleFemale-BS-RoFormer-(by aufr33)',
        'VOCALS-MelBand-Roformer (by Becruily)': 'Vocals-MelBand-Roformer-(by Becruily)',
        'VOCALS-MelBand-Roformer Kim FT 2 (by Unwa)': 'Vocals-MelBand-Roformer-KİM-FT-2(by Unwa)',
        'voc_gaboxMelRoformer (by Gabox)': 'voc_gaboxMelRoformer',
        'voc_gaboxBSroformer (by Gabox)': 'voc_gaboxBSroformer',
        'voc_gaboxMelRoformerFV1 (by Gabox)': 'voc_gaboxMelRoformerFV1',
        'voc_gaboxMelRoformerFV2 (by Gabox)': 'voc_gaboxMelRoformerFV2',
        'SYH99999/MelBandRoformerSYHFTB1(by Amane)': 'MelBandRoformerSYHFTB1',
        'inst_V5 (by Gabox)': 'INSTV5-(by Gabox)',
        'inst_Fv4Noise (by Gabox)': 'Inst_Fv4Noise-(by Gabox)',
        'Intrumental_Gabox (by Gabox)': 'Intrumental_Gabox-(by Gabox)',
        'inst_GaboxFv3 (by Gabox)': 'INST_GaboxFv3-(by Gabox)',
        'SYH99999/MelBandRoformerSYHFTB1_Model1 (by Amane)': 'MelBandRoformerSYHFTB1_model1',
        'SYH99999/MelBandRoformerSYHFTB1_Model2 (by Amane)': 'MelBandRoformerSYHFTB1_model2',
        'SYH99999/MelBandRoformerSYHFTB1_Model3 (by Amane)': 'MelBandRoformerSYHFTB1_model3',
        'VOCALS-MelBand-Roformer Kim FT 2 Blendless (by unwa)': 'VOCALS-MelBand-Roformer-Kim-FT-2-Blendless-(by unwa)',
        'inst_gaboxFV6 (by Gabox)': 'inst_gaboxFV6-(by Gabox)',
        'denoisedebleed (by Gabox)': 'denoisedebleed-(by Gabox)',
        'INSTV5N (by Gabox)': 'INSTV5N_(by Gabox)',
        'Voc_Fv3 (by Gabox)': 'Voc_Fv3_(by Gabox)',
        'MelBandRoformer4StemFTLarge (SYH99999)': 'MelBandRoformer4StemFTLarge_(SYH99999)',
        'dereverb_mel_band_roformer_mono (by anvuew)': 'dereverb_mel_band_roformer_mono_(by anvuew)',
        'INSTV6N (by Gabox)': 'INSTV6N_(by Gabox)',
        'KaraokeGabox': 'KaraokeGabox',
        'FullnessVocalModel (by Amane)': 'FullnessVocalModel',
        'Inst_GaboxV7 (by Gabox)': 'Inst_GaboxV7_(by Gabox)',
        
        # Add more mappings as needed
    }

    # Use mapping if exists, otherwise clean the model name
    if model in model_name_mapping:
        return model_name_mapping[model]
    
    # General cleaning if not in mapping
    cleaned = re.sub(r'\s*\(.*?\)', '', model)  # Remove parenthetical info
    cleaned = cleaned.replace('-', '_')
    cleaned = ''.join(char for char in cleaned if char.isalnum() or char == '_')
    
    return cleaned

def shorten_filename(filename, max_length=30):
    """
    Shortens a filename to a specified maximum length
    
    Args:
        filename (str): The filename to be shortened
        max_length (int): Maximum allowed length for the filename
    
    Returns:
        str: Shortened filename
    """
    base, ext = os.path.splitext(filename)
    if len(base) <= max_length:
        return filename
    
    # Take first 15 and last 10 characters
    shortened = base[:15] + "..." + base[-10:] + ext
    return shortened

def clean_filename(filename):
    """
    Temizlenmiş dosya adını döndürür
    """
    # Zaman damgası ve gereksiz etiketleri temizleme desenleri
    cleanup_patterns = [
        r'_\d{8}_\d{6}_\d{6}$',  # _20231215_123456_123456
        r'_\d{14}$',              # _20231215123456
        r'_\d{10}$',              # _1702658400
        r'_\d+$'                  # Herhangi bir sayı
    ]
    
    # Dosya adını ve uzantısını ayır
    base, ext = os.path.splitext(filename)
    
    # Zaman damgalarını temizle
    for pattern in cleanup_patterns:
        base = re.sub(pattern, '', base)
    
    # Dosya türü etiketlerini temizle
    file_types = ['vocals', 'instrumental', 'drum', 'bass', 'other', 'effects', 'speech', 'music', 'dry', 'male', 'female']
    for type_keyword in file_types:
        base = base.replace(f'_{type_keyword}', '')
    
    # Dosya türünü tespit et
    detected_type = None
    for type_keyword in file_types:
        if type_keyword in base.lower():
            detected_type = type_keyword
            break
    
    # Zaman damgaları ve gereksiz etiketlerden temizlenmiş base
    clean_base = base.strip('_- ')
    
    return clean_base, detected_type, ext

def run_command_and_process_files(model_type, config_path, start_check_point, INPUT_DIR, OUTPUT_DIR, extract_instrumental, use_tta, demud_phaseremix_inst, clean_model):
    try:
        # Komut parçalarını oluştur
        cmd_parts = [
            "python", "inference.py",
            "--model_type", model_type,
            "--config_path", config_path,
            "--start_check_point", start_check_point,
            "--input_folder", INPUT_DIR,
            "--store_dir", OUTPUT_DIR,  # İşlenecek ses dosyasının yolu
        ]

        # Opsiyonel parametreleri ekle
        if extract_instrumental:
            cmd_parts.append("--extract_instrumental")

        if use_tta:
            cmd_parts.append("--use_tta")

        if demud_phaseremix_inst:
            cmd_parts.append("--demud_phaseremix_inst")

        # Komutu çalıştır
        process = subprocess.Popen(
            cmd_parts,
            cwd=BASE_PATH,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1,
            universal_newlines=True
        )

        # Çıktıları gerçek zamanlı olarak yazdır
        for line in process.stdout:
            print(line.strip())

        for line in process.stderr:
            print(line.strip())

        process.wait()

        # Model adını temizle
        filename_model = clean_model_name(clean_model)

        # Çıktı dosyalarını al
        output_files = os.listdir(OUTPUT_DIR)

        # Dosya yeniden adlandırma fonksiyonu
        def rename_files_with_model(folder, filename_model):
            for filename in sorted(os.listdir(folder)):
                file_path = os.path.join(folder, filename)

                # Medya dosyası değilse atla
                if not any(filename.lower().endswith(ext) for ext in ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a']):
                    continue

                base, ext = os.path.splitext(filename)

                # Temiz base adı
                clean_base = base.strip('_- ')

                # Yeni dosya adını oluştur
                new_filename = f"{clean_base}_{filename_model}{ext}"

                new_file_path = os.path.join(folder, new_filename)
                os.rename(file_path, new_file_path)

        # Dosyaları yeniden adlandır
        rename_files_with_model(OUTPUT_DIR, filename_model)

        # Güncellenmiş dosya listesini al
        output_files = os.listdir(OUTPUT_DIR)

        # Dosya bulma fonksiyonu
        def find_file(keyword):
            matching_files = [
                os.path.join(OUTPUT_DIR, f) for f in output_files 
                if keyword in f.lower()
            ]
            return matching_files[0] if matching_files else None

        # Farklı dosya türlerini bul
        vocal_file = find_file('vocals')
        instrumental_file = find_file('instrumental')
        phaseremix_file = find_file('phaseremix')
        drum_file = find_file('drum')
        bass_file = find_file('bass')
        other_file = find_file('other')
        effects_file = find_file('effects')
        speech_file = find_file('speech')
        music_file = find_file('music')
        dry_file = find_file('dry')
        male_file = find_file('male')
        female_file = find_file('female')
        bleed_file = find_file('bleed')
        karaoke_file = find_file('karaoke')
        

        # Bulunan dosyaları döndür
        return (
            vocal_file or None,
            instrumental_file or None,
            phaseremix_file or None,
            drum_file or None,
            bass_file or None,
            other_file or None,
            effects_file or None,
            speech_file or None,
            music_file or None,
            dry_file or None,
            male_file or None,
            female_file or None,
            bleed_file or None,
            karaoke_file or None
            
        )

    except Exception as e:
        print(f"An error occurred: {e}")
        return (None,) * 14

       

def create_interface():
    # Let's define the model options in advance
    model_choices = {
        "Vocal Separation": [
            'FullnessVocalModel (by Amane)',
            'Voc_Fv3 (by Gabox)',
            'VOCALS-BS-Roformer_1297 (by viperx)',
            'VOCALS-BS-Roformer_1296 (by viperx)',
            '✅ VOCALS-Mel-Roformer big beta 4 (by unwa) - Melspectrogram based high performance',
            'VOCALS-BS-RoformerLargev1 (by unwa) - Comprehensive model',
            'VOCALS-InstVocHQ - General purpose model',
            'VOCALS-MelBand-Roformer (by KimberleyJSN) - Alternative model',
            'VOCALS-VitLarge23 (by ZFTurbo) - Transformer-based model',
            'VOCALS-MelBand-Roformer Kim FT (by Unwa)',
            'VOCALS-MelBand-Roformer (by Becruily)',
            '✅ VOCALS-Melband-Roformer BigBeta5e (by unwa)',
            'VOCALS-Male Female-BS-RoFormer Male Female Beta 7_2889 (by aufr33)',
            'VOCALS-MelBand-Roformer Kim FT 2 (by Unwa)',
            'voc_gaboxMelRoforner (by Gabox)',
            'voc_gaboxBSroformer (by Gabox)',
            'voc_gaboxMelRoformerFV1 (by Gabox)',
            'voc_gaboxMelRoformerFV2 (by Gabox)',
            'VOCALS-MelBand-Roformer Kim FT 2 Blendless (by unwa)'
        ],
        "Instrumental Separation": [
            'Inst_GaboxV7 (by Gabox)',
            'INSTV5N (by Gabox)',
            'inst_gaboxFV6 (by Gabox)',
            '✅ INST-Mel-Roformer v2 (by unwa) - Most recent instrumental separation model',
            '✅ inst_v1e (by unwa)',
            '✅ INST-Mel-Roformer v1 (by unwa) - Old instrumental separation model',
            'INST-MelBand-Roformer (by Becruily)',
            'inst_gaboxFV2 (by Gabox)',
            'inst_gaboxFV1 (by Gabox)',
            'inst_gaboxBV2 (by Gabox)',
            'inst_gaboxBV1 (by Gabox)',
            'inst_gabox (by Gabox)',
            '✅(?) inst_GaboxFv3 (by Gabox)',
            'Intrumental_Gabox (by Gabox)',
            '✅(?) inst_Fv4Noise (by Gabox)',
            '✅(?) inst_V5 (by Gabox)',
            'INST-VOC-Mel-Roformer a.k.a. duality v2 (by unwa) - Latest version instrumental separation',
            'INST-VOC-Mel-Roformer a.k.a. duality (by unwa) - Previous version',
            'INST-Separator MDX23C (by aufr33) - Alternative instrumental separation',
            'INSTV6N (by Gabox)'
        ],
        "Karaoke & Accompaniment": [
            '✅ KARAOKE-MelBand-Roformer (by aufr33 & viperx) - Advanced karaoke separation',
            'KaraokeGabox'
        ],
        "Noise & Effect Removal": [
            'denoisedebleed (by Gabox)',
            '🔇 DENOISE-MelBand-Roformer-1 (by aufr33) - Basic noise reduction',
            '🔉 DENOISE-MelBand-Roformer-2 (by aufr33) - Advanced noise reduction',
            'bleed_suppressor_v1 (by unwa) - dont use it if you dont know what youre doing',
            'dereverb_mel_band_roformer_mono (by anvuew)',
            '👥 CROWD-REMOVAL-MelBand-Roformer (by aufr33) - Crowd noise removal',
            '🏛️ DE-REVERB-MDX23C (by aufr33 & jarredou) - Reverb reduction',
            '🏛️ DE-REVERB-MelBand-Roformer aggr./v2/19.1729 (by anvuew)',
            '🗣️ DE-REVERB-Echo-MelBand-Roformer (by Sucial)',
            'dereverb_mel_band_roformer_less_aggressive_anvuew',
            'dereverb_mel_band_roformer_anvuew'


        ],
        "Drum Separation": [
            '✅ DRUMSEP-MDX23C_DrumSep_6stem (by aufr33 & jarredou) - Detailed drum separation'
        ],
        "Multi-Stem & Other Models": [
            'MelBandRoformer4StemFTLarge (SYH99999)',
            '🎬 4STEMS-SCNet_MUSDB18 (by starrytong) - Multi-stem separation',
            '🎼 CINEMATIC-BandIt_Plus (by kwatcharasupat) - Cinematic music analysis',
            'OTHER-BS-Roformer_1053 (by viperx) - Other special models',
            '4STEMS-SCNet_XL_MUSDB18 (by ZFTurbo)',
            '4STEMS-SCNet_Large (by starrytong)',
            '4STEMS-BS-Roformer_MUSDB18 (by ZFTurbo)',
            'SYH99999/MelBandRoformerSYHFTB1_Model1 (by Amane)',
            'SYH99999/MelBandRoformerSYHFTB1_Model2 (by Amane)',
            'SYH99999/MelBandRoformerSYHFTB1_Model3 (by Amane)'
        ],
    }


    def update_models(category):
        models = model_choices.get(category, [])
        return gr.Dropdown(
            label="Select Model",
            choices=models,
            value=models[0] if models else None
        )


    def ensemble_files(args):
        """
        Ensemble audio files using the external script
        
        Args:
            args (list): Command-line arguments for ensemble script
        """
        try:
            
            script_path = "/content/Music-Source-Separation-Training/ensemble.py"
            
            
            full_command = ["python", script_path] + args
            
            
            result = subprocess.run(
                full_command,
                capture_output=True,
                text=True,
                check=True
            )
            
            print("Ensemble successful:")
            print(result.stdout)
            return result.stdout
        
        except subprocess.CalledProcessError as e:
            print(f"Ensemble error: {e}")
            print(f"Error output: {e.stderr}")
            raise
        except Exception as e:
            print(f"Unexpected error during ensemble: {e}")
            raise      

    def refresh_audio_files(directory):
        """
        Refreshes and lists audio files in the specified directory and old_output directory.
        
        Args:
            directory (str): Path of the directory to be scanned.
        
        Returns:
            list: List of discovered audio files.
        """
        try:
            audio_extensions = ['.wav', '.mp3', '.flac', '.ogg']
            audio_files = [
                f for f in os.listdir(directory)
                if os.path.isfile(os.path.join(directory, f))
                and os.path.splitext(f)[1].lower() in audio_extensions
            ]
            
            # Eski dosyaları da kontrol et
            old_output_directory = os.path.join(BASE_PATH, 'old_output')
            old_audio_files = [
                f for f in os.listdir(old_output_directory)
                if os.path.isfile(os.path.join(old_output_directory, f))
                and os.path.splitext(f)[1].lower() in audio_extensions
            ]
            
            return sorted(audio_files + old_audio_files)
        except Exception as e:
            print(f"Audio file listing error: {e}")
            return []

    
    # Global değişken tanımlamaları
    BASE_PATH = '/content/Music-Source-Separation-Training'
    AUTO_ENSEMBLE_TEMP = os.path.join(BASE_PATH, 'auto_ensemble_temp')
    model_output_dir = os.path.join(BASE_PATH, 'auto_ensemble_temp')

    def auto_ensemble_process(audio_input, selected_models, chunk_size, overlap, export_format2, 
                         use_tta, extract_instrumental, ensemble_type, 
                         progress=gr.Progress(), *args, **kwargs):
        try:
            # Ensure the ensemble directory exists
            move_wav_files2(INPUT_DIR)
            create_directory(ENSEMBLE_DIR)

            # Handle audio input
            if audio_input is not None:
                temp_path = audio_input.name  # Gradio'nun geçici dosya yolu
                audio_path = os.path.join(ENSEMBLE_DIR, os.path.basename(temp_path))
            else:
                existing_files = os.listdir(ENSEMBLE_DIR)
                if not existing_files:
                    return None, "❌ No audio file found"
                audio_path = os.path.join(ENSEMBLE_DIR, existing_files[0])

            # Model processing
            all_outputs = []
            total_models = len(selected_models)

            for idx, model in enumerate(selected_models):
                progress((idx + 1) / total_models, f"Processing {model}...")
                
                clean_model = extract_model_name(model)
                print(f"Processing using model: {clean_model}")      

                # Model output directory
                model_output_dir = os.path.join(AUTO_ENSEMBLE_TEMP, clean_model)
                os.makedirs(model_output_dir, exist_ok=True)

                model_type, config_path, start_check_point = "", "", ""

                if clean_model == 'VOCALS-InstVocHQ':
                        model_type = 'mdx23c'
                        config_path = 'ckpts/config_vocals_mdx23c.yaml'
                        start_check_point = 'ckpts/model_vocals_mdx23c_sdr_10.17.ckpt'
                        download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/config_vocals_mdx23c.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.0/model_vocals_mdx23c_sdr_10.17.ckpt')

                elif clean_model == 'VOCALS-MelBand-Roformer (by KimberleyJSN)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_vocals_mel_band_roformer_kj.yaml'
                        start_check_point = 'ckpts/MelBandRoformer.ckpt'
                        download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/KimberleyJensen/config_vocals_mel_band_roformer_kj.yaml')
                        download_file('https://huggingface.co/KimberleyJSN/melbandroformer/resolve/main/MelBandRoformer.ckpt')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-BS-Roformer_1297 (by viperx)':
                        model_type = 'bs_roformer'
                        config_path = 'ckpts/model_bs_roformer_ep_317_sdr_12.9755.yaml'
                        start_check_point = 'ckpts/model_bs_roformer_ep_317_sdr_12.9755.ckpt'
                        download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/main/configs/viperx/model_bs_roformer_ep_317_sdr_12.9755.yaml')
                        download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_317_sdr_12.9755.ckpt')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-BS-Roformer_1296 (by viperx)':
                        model_type = 'bs_roformer'
                        config_path = 'ckpts/model_bs_roformer_ep_368_sdr_12.9628.yaml'
                        start_check_point = 'ckpts/model_bs_roformer_ep_368_sdr_12.9628.ckpt'
                        download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_368_sdr_12.9628.ckpt')
                        download_file('https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs/model_bs_roformer_ep_368_sdr_12.9628.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-BS-RoformerLargev1 (by unwa)':
                        model_type = 'bs_roformer'
                        config_path = 'ckpts/config_bsrofoL.yaml'
                        start_check_point = 'ckpts/BS-Roformer_LargeV1.ckpt'
                        download_file('https://huggingface.co/jarredou/unwa_bs_roformer/resolve/main/BS-Roformer_LargeV1.ckpt')
                        download_file('https://huggingface.co/jarredou/unwa_bs_roformer/raw/main/config_bsrofoL.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-Mel-Roformer big beta 4 (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_big_beta4.yaml'
                        start_check_point = 'ckpts/melband_roformer_big_beta4.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/melband_roformer_big_beta4.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/raw/main/config_melbandroformer_big_beta4.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-Melband-Roformer BigBeta5e (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/big_beta5e.yaml'
                        start_check_point = 'ckpts/big_beta5e.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/big_beta5e.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-big/resolve/main/big_beta5e.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INST-Mel-Roformer v1 (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_inst.yaml'
                        start_check_point = 'ckpts/melband_roformer_inst_v1.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/melband_roformer_inst_v1.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/raw/main/config_melbandroformer_inst.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INST-Mel-Roformer v2 (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_inst_v2.yaml'
                        start_check_point = 'ckpts/melband_roformer_inst_v2.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/melband_roformer_inst_v2.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/raw/main/config_melbandroformer_inst_v2.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INST-VOC-Mel-Roformer a.k.a. duality (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_instvoc_duality.yaml'
                        start_check_point = 'ckpts/melband_roformer_instvoc_duality_v1.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/resolve/main/melband_roformer_instvoc_duality_v1.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/raw/main/config_melbandroformer_instvoc_duality.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INST-VOC-Mel-Roformer a.k.a. duality v2 (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_instvoc_duality.yaml'
                        start_check_point = 'ckpts/melband_roformer_instvox_duality_v2.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/resolve/main/melband_roformer_instvox_duality_v2.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-InstVoc-Duality/raw/main/config_melbandroformer_instvoc_duality.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'KARAOKE-MelBand-Roformer (by aufr33 & viperx)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_mel_band_roformer_karaoke.yaml'
                        start_check_point = 'ckpts/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt'
                        download_file('https://huggingface.co/jarredou/aufr33-viperx-karaoke-melroformer-model/resolve/main/mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt')
                        download_file('https://huggingface.co/jarredou/aufr33-viperx-karaoke-melroformer-model/resolve/main/config_mel_band_roformer_karaoke.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'OTHER-BS-Roformer_1053 (by viperx)':
                        model_type = 'bs_roformer'
                        config_path = 'ckpts/model_bs_roformer_ep_937_sdr_10.5309.yaml'
                        start_check_point = 'ckpts/model_bs_roformer_ep_937_sdr_10.5309.ckpt'
                        download_file('https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/model_bs_roformer_ep_937_sdr_10.5309.ckpt')
                        download_file('https://raw.githubusercontent.com/TRvlvr/application_data/main/mdx_model_data/mdx_c_configs/model_bs_roformer_ep_937_sdr_10.5309.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'CROWD-REMOVAL-MelBand-Roformer (by aufr33)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/model_mel_band_roformer _crowd.yaml'
                        start_check_point = 'ckpts/mel_band_roformer_crowd_aufr33_viperx_sdr_8.7144.ckpt'
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.4/mel_band_roformer_crowd_aufr33_viperx_sdr_8.7144.ckpt')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.4/model_mel_band_roformer_crowd.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-VitLarge23 (by ZFTurbo)':
                        model_type = 'segm_models'
                        config_path = 'ckpts/config_vocals_segm_models.yaml'
                        start_check_point = 'ckpts/model_vocals_segm_models_sdr_9.77.ckpt'
                        download_file('https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/refs/heads/main/configs/config_vocals_segm_models.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.0/model_vocals_segm_models_sdr_9.77.ckpt')

                elif clean_model == 'CINEMATIC-BandIt_Plus (by kwatcharasupat)':
                        model_type = 'bandit'
                        config_path = 'ckpts/config_dnr_bandit_bsrnn_multi_mus64.yaml'
                        start_check_point = 'ckpts/model_bandit_plus_dnr_sdr_11.47.chpt'
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.3/config_dnr_bandit_bsrnn_multi_mus64.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.3/model_bandit_plus_dnr_sdr_11.47.chpt')

                elif clean_model == 'DRUMSEP-MDX23C_DrumSep_6stem (by aufr33 & jarredou)':
                        model_type = 'mdx23c'
                        config_path = 'ckpts/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.yaml'
                        start_check_point = 'ckpts/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.ckpt'
                        download_file('https://github.com/jarredou/models/releases/download/aufr33-jarredou_MDX23C_DrumSep_model_v0.1/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.ckpt')
                        download_file('https://github.com/jarredou/models/releases/download/aufr33-jarredou_MDX23C_DrumSep_model_v0.1/aufr33-jarredou_DrumSep_model_mdx23c_ep_141_sdr_10.8059.yaml')

                elif clean_model == '4STEMS-SCNet_MUSDB18 (by starrytong)':
                        model_type = 'scnet'
                        config_path = 'ckpts/config_musdb18_scnet.yaml'
                        start_check_point = 'ckpts/scnet_checkpoint_musdb18.ckpt'
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.6/config_musdb18_scnet.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v.1.0.6/scnet_checkpoint_musdb18.ckpt')

                elif clean_model == 'DE-REVERB-MDX23C (by aufr33 & jarredou)':
                        model_type = 'mdx23c'
                        config_path = 'ckpts/config_dereverb_mdx23c.yaml'
                        start_check_point = 'ckpts/dereverb_mdx23c_sdr_6.9096.ckpt'
                        download_file('https://huggingface.co/jarredou/aufr33_jarredou_MDXv3_DeReverb/resolve/main/dereverb_mdx23c_sdr_6.9096.ckpt')
                        download_file('https://huggingface.co/jarredou/aufr33_jarredou_MDXv3_DeReverb/resolve/main/config_dereverb_mdx23c.yaml')

                elif clean_model == 'DENOISE-MelBand-Roformer-1 (by aufr33)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
                        start_check_point = 'ckpts/denoise_mel_band_roformer_aufr33_sdr_27.9959.ckpt'
                        download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/denoise_mel_band_roformer_aufr33_sdr_27.9959.ckpt')
                        download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'DENOISE-MelBand-Roformer-2 (by aufr33)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
                        start_check_point = 'ckpts/denoise_mel_band_roformer_aufr33_aggr_sdr_27.9768.ckpt'
                        download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/denoise_mel_band_roformer_aufr33_aggr_sdr_27.9768.ckpt')
                        download_file('https://huggingface.co/jarredou/aufr33_MelBand_Denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-MelBand-Roformer Kim FT (by Unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
                        start_check_point = 'ckpts/kimmel_unwa_ft.ckpt'
                        download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft.ckpt')
                        download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_v1e (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_melbandroformer_inst.yaml'
                        start_check_point = 'ckpts/inst_v1e.ckpt'
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/inst_v1e.ckpt')
                        download_file('https://huggingface.co/pcunwa/Mel-Band-Roformer-Inst/resolve/main/config_melbandroformer_inst.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'bleed_suppressor_v1 (by unwa)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_bleed_suppressor_v1.yaml'
                        start_check_point = 'ckpts/bleed_suppressor_v1.ckpt'
                        download_file('https://huggingface.co/ASesYusuf1/MODELS/resolve/main/bleed_suppressor_v1.ckpt')
                        download_file('https://huggingface.co/ASesYusuf1/MODELS/resolve/main/config_bleed_suppressor_v1.yaml')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-MelBand-Roformer (by Becruily)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_instrumental_becruily.yaml'
                        start_check_point = 'ckpts/mel_band_roformer_vocals_becruily.ckpt'
                        download_file('https://huggingface.co/becruily/mel-band-roformer-vocals/resolve/main/config_vocals_becruily.yaml')
                        download_file('https://huggingface.co/becruily/mel-band-roformer-vocals/resolve/main/mel_band_roformer_vocals_becruily.ckpt')
                        conf_edit(config_path, chunk_size, overlap)
                
                elif clean_model == 'INST-MelBand-Roformer (by Becruily)':
                        model_type = 'mel_band_roformer'
                        config_path = 'ckpts/config_instrumental_becruily.yaml'
                        start_check_point = 'ckpts/mel_band_roformer_instrumental_becruily.ckpt'
                        download_file('https://huggingface.co/becruily/mel-band-roformer-instrumental/resolve/main/config_instrumental_becruily.yaml')
                        download_file('https://huggingface.co/becruily/mel-band-roformer-instrumental/resolve/main/mel_band_roformer_instrumental_becruily.ckpt')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == '4STEMS-SCNet_XL_MUSDB18 (by ZFTurbo)':
                        model_type = 'scnet'
                        config_path = 'ckpts/config_musdb18_scnet_xl.yaml'
                        start_check_point = 'ckpts/model_scnet_ep_54_sdr_9.8051.ckpt'
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.13/config_musdb18_scnet_xl.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.13/model_scnet_ep_54_sdr_9.8051.ckpt')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == '4STEMS-SCNet_Large (by starrytong)':
                        model_type = 'scnet'
                        config_path = 'ckpts/config_musdb18_scnet_large_starrytong.yaml'
                        start_check_point = 'ckpts/SCNet-large_starrytong_fixed.ckpt'
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.9/config_musdb18_scnet_large_starrytong.yaml')
                        download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.9/SCNet-large_starrytong_fixed.ckpt')
                        conf_edit(config_path, chunk_size, overlap)

                elif clean_model == '4STEMS-BS-Roformer_MUSDB18 (by ZFTurbo)':
                      model_type = 'bs_roformer'
                      config_path = 'ckpts/config_bs_roformer_384_8_2_485100.yaml'
                      start_check_point = 'ckpts/model_bs_roformer_ep_17_sdr_9.6568.ckpt'
                      download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.12/config_bs_roformer_384_8_2_485100.yaml')
                      download_file('https://github.com/ZFTurbo/Music-Source-Separation-Training/releases/download/v1.0.12/model_bs_roformer_ep_17_sdr_9.6568.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'DE-REVERB-MelBand-Roformer aggr./v2/19.1729 (by anvuew)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
                      start_check_point = 'ckpts/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt')
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
                      conf_edit(config_path, chunk_size, overlap)
                      
                elif clean_model == 'DE-REVERB-Echo-MelBand-Roformer (by Sucial)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config_dereverb-echo_mel_band_roformer.yaml'
                      start_check_point = 'ckpts/dereverb-echo_mel_band_roformer_sdr_10.0169.ckpt'
                      download_file('https://huggingface.co/Sucial/Dereverb-Echo_Mel_Band_Roformer/resolve/main/dereverb-echo_mel_band_roformer_sdr_10.0169.ckpt')
                      download_file('https://huggingface.co/Sucial/Dereverb-Echo_Mel_Band_Roformer/resolve/main/config_dereverb-echo_mel_band_roformer.yaml')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'dereverb_mel_band_roformer_less_aggressive_anvuew':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
                      start_check_point = 'ckpts/dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt'
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_less_aggressive_anvuew_sdr_18.8050.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'dereverb_mel_band_roformer_anvuew':
                      model_type = 'mel_band_roformer'
                      config_path = 'dereverb_mel_band_roformer_anvuew.yaml'
                      start_check_point = 'ckpts/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt'
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt')
                      conf_edit(config_path, chunk_size, overlap)  


                elif clean_model == 'inst_gabox (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gabox.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_gaboxBV1 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gaboxBv1.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxBv1.ckpt')
                      conf_edit(config_path, chunk_size, overlap)


                elif clean_model == 'inst_gaboxBV2 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gaboxBv2.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxBv2.ckpt')
                      conf_edit(config_path, chunk_size, overlap)     


                elif clean_model == 'inst_gaboxBFV1 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/gaboxFv1.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv1.ckpt')
                      conf_edit(config_path, chunk_size, overlap)


                elif clean_model == 'inst_gaboxFV2 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gaboxFv2.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv2.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                
                elif clean_model == 'VOCALS-Male Female-BS-RoFormer Male Female Beta 7_2889 (by aufr33)':
                      model_type = 'bs_roformer'
                      config_path = 'ckpts/config_chorus_male_female_bs_roformer.yaml'
                      start_check_point = 'ckpts/bs_roformer_male_female_by_aufr33_sdr_7.2889.ckpt'
                      download_file('https://huggingface.co/RareSirMix/AIModelRehosting/resolve/main/bs_roformer_male_female_by_aufr33_sdr_7.2889.ckpt')
                      download_file('https://huggingface.co/Sucial/Chorus_Male_Female_BS_Roformer/resolve/main/config_chorus_male_female_bs_roformer.yaml')
                      conf_edit(config_path, chunk_size, overlap)


                elif clean_model == 'VOCALS-MelBand-Roformer Kim FT 2 (by Unwa)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
                      start_check_point = 'ckpts/kimmel_unwa_ft2.ckpt'
                      download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
                      download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft2.ckpt')
                      conf_edit(config_path, chunk_size, overlap)      

                elif clean_model == 'voc_gaboxBSroformer (by Gabox)':
                      model_type = 'bs_roformer'
                      config_path = 'ckpts/voc_gaboxBSroformer.yaml'
                      start_check_point = 'ckpts/voc_gaboxBSR.ckpt'
                      download_file('https://huggingface.co/GaboxR67/BSRoformerVocTest/resolve/main/voc_gaboxBSroformer.yaml')
                      download_file('https://huggingface.co/GaboxR67/BSRoformerVocTest/resolve/main/voc_gaboxBSR.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'voc_gaboxMelReformer (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/voc_gabox.yaml'
                      start_check_point = 'ckpts/voc_gabox.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'voc_gaboxMelReformerFV1 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/voc_gabox.yaml'
                      start_check_point = 'ckpts/voc_gaboxFv1.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gaboxFv1.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'voc_gaboxMelReformerFV2 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/voc_gabox.yaml'
                      start_check_point = 'ckpts/voc_gaboxFv2.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gaboxFv2.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_GaboxFv3 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gaboxFv3.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv3.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'Intrumental_Gabox (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/intrumental_gabox.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/intrumental_gabox.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_Fv4Noise (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_Fv4Noise.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_Fv4Noise.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_V5 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/INSTV5.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV5.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model1 (by Amane)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config.yaml'
                      start_check_point = 'ckpts/model.ckpt'
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model2 (by Amane)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config.yaml'
                      start_check_point = 'ckpts/model2.ckpt'
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model2.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'SYH99999/MelBandRoformerSYHFTB1_Model3 (by Amane)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config.yaml'
                      start_check_point = 'ckpts/model3.ckpt'
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/config.yaml')
                      download_file('https://huggingface.co/SYH99999/MelBandRoformerSYHFTB1/resolve/main/model3.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'VOCALS-MelBand-Roformer Kim FT 2 Blendless (by unwa)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config_kimmel_unwa_ft.yaml'
                      start_check_point = 'ckpts/kimmel_unwa_ft2_bleedless.ckpt'
                      download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/config_kimmel_unwa_ft.yaml')
                      download_file('https://huggingface.co/pcunwa/Kim-Mel-Band-Roformer-FT/resolve/main/kimmel_unwa_ft2_bleedless.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_gaboxFV1 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/inst_gaboxFv1.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gaboxFv1.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'inst_gaboxFV6 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/INSTV6.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV6.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'denoisedebleed (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/model_mel_band_roformer_denoise.yaml'
                      start_check_point = 'ckpts/denoisedebleed.ckpt'
                      download_file('https://huggingface.co/poiqazwsx/melband-roformer-denoise/resolve/main/model_mel_band_roformer_denoise.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/denoisedebleed.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INSTV5N (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/INSTV5N.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV5N.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'Voc_Fv3 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/voc_gabox.yaml'
                      start_check_point = 'ckpts/voc_Fv3.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/vocals/voc_Fv3.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'MelBandRoformer4StemFTLarge (SYH99999)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config.yaml'
                      start_check_point = 'ckpts/MelBandRoformer4StemFTLarge.ckpt'
                      download_file('https://huggingface.co/SYH99999/MelBandRoformer4StemFTLarge/resolve/main/config.yaml')
                      download_file('https://huggingface.co/SYH99999/MelBandRoformer4StemFTLarge/resolve/main/MelBandRoformer4StemFTLarge.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'dereverb_mel_band_roformer_mono (by anvuew)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/dereverb_mel_band_roformer_anvuew.yaml'
                      start_check_point = 'ckpts/dereverb_mel_band_roformer_mono_anvuew_sdr_20.4029.ckpt'
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_anvuew.yaml')
                      download_file('https://huggingface.co/anvuew/dereverb_mel_band_roformer/resolve/main/dereverb_mel_band_roformer_mono_anvuew_sdr_20.4029.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'INSTV6N (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/INSTV6N.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/INSTV6N.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'KaraokeGabox':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config_mel_band_roformer_karaoke.yaml'
                      start_check_point = 'ckpts/KaraokeGabox.ckpt'
                      download_file('https://github.com/deton24/Colab-for-new-MDX_UVR_models/releases/download/v1.0.0/config_mel_band_roformer_karaoke.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/blob/main/melbandroformers/experimental/KaraokeGabox.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'FullnessVocalModel (by Amane)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/config.yaml'
                      start_check_point = 'ckpts/FullnessVocalModel.ckpt'
                      download_file('https://huggingface.co/Aname-Tommy/MelBandRoformers/blob/main/config.yaml')
                      download_file('https://huggingface.co/Aname-Tommy/MelBandRoformers/blob/main/FullnessVocalModel.ckpt')
                      conf_edit(config_path, chunk_size, overlap)

                elif clean_model == 'Inst_GaboxV7 (by Gabox)':
                      model_type = 'mel_band_roformer'
                      config_path = 'ckpts/inst_gabox.yaml'
                      start_check_point = 'ckpts/Inst_GaboxV7.ckpt'
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/inst_gabox.yaml')
                      download_file('https://huggingface.co/GaboxR67/MelBandRoformers/resolve/main/melbandroformers/instrumental/Inst_GaboxV7.ckpt')
                      conf_edit(config_path, chunk_size, overlap)        

              

                # Ana sekme komut yapısını kullan
                cmd = [
                    "python", 
                    "inference.py",
                    "--model_type", model_type,
                    "--config_path", config_path,
                    "--start_check_point", start_check_point,
                    "--input_folder", ENSEMBLE_DIR,
                    "--store_dir", model_output_dir,
                ]

                if use_tta:
                    cmd.append("--use_tta")
                if extract_instrumental:
                    cmd.append("--extract_instrumental")

                print(f"Running command: {' '.join(cmd)}")

                # Hata yakalama ile çalıştırma
                try:
                    result = subprocess.run(cmd, capture_output=True, text=True)
                    print(result.stdout)
                    if result.returncode != 0:
                        print(f"Error: {result.stderr}")
                        return None, f"Model {model} failed: {result.stderr}"
                except Exception as e:
                    return None, f"Critical error with {model}: {str(e)}"

                    # Çıktı dosyalarını topla
                model_outputs = glob.glob(os.path.join(model_output_dir, "*.wav"))
                all_outputs.extend(model_outputs)

                    # 3. Çıktı dosyalarını kontrol et
                output_files = glob.glob(os.path.join(model_output_dir, "*.wav"))
                if not output_files:
                    raise FileNotFoundError(f"{model} failed to produce output")
                    
                model_outputs.extend(output_files)
                

            # 4. Dosya bekletme ve kontrol
            def wait_for_files(files, timeout=300):
                start = time.time()
                while time.time() - start < timeout:
                    missing = [f for f in files if not os.path.exists(f)]
                    if not missing: return True
                    time.sleep(5)
                raise TimeoutError(f"Missing files: {missing[:3]}...")

            wait_for_files(model_outputs)

            # 5. Ensemble komutunu güvenli oluştur
            quoted_files = [f'"{f}"' for f in model_outputs]
            timestamp = str(int(time.time()))
            output_path = os.path.join(AUTO_ENSEMBLE_OUTPUT, f"ensemble_{timestamp}.wav")
            
            ensemble_cmd = [
                "python", "ensemble.py",
                "--files", *quoted_files,
                "--type", ensemble_type,
                "--output", f'"{output_path}"'
            ]

            # 6. Komutu çalıştır
            result = subprocess.run(
                " ".join(ensemble_cmd),
                shell=True,
                capture_output=True,
                text=True,
                check=True
            )

            # 7. Son kontrol
            if not os.path.exists(output_path):
                raise RuntimeError("Ensemble dosyası oluşturulamadı")
                
            return output_path, "✅ Success!"

        except Exception as e:
            return None, f"❌ Error: {str(e)}"
        
        finally:
            # Temizlik
            shutil.rmtree('/content/Music-Source-Separation-Training/ensemble', ignore_errors=True)
            shutil.rmtree('/content/Music-Source-Separation-Training/ensemble', ignore_errors=True)
            clear_directory(VİDEO_TEMP)
            clear_directory(ENSEMBLE_DIR)
            gc.collect()
             

    main_input_key = "shared_audio_input"
    # Global components
    input_audio_file = gr.File(visible=True)
    auto_input_audio_file = gr.File(visible=True)
    original_audio = gr.Audio(visible=True)
    

    css = """
    /* Genel Tema */
    body {
        background: url('/content/logo.jpg') no-repeat center center fixed;
        background-size: cover;
        background-color: #2d0b0b; /* Koyu kırmızı, dublaj stüdyosuna uygun */
        min-height: 100vh;
        margin: 0;
        padding: 1rem;
        font-family: 'Poppins', sans-serif;
        color: #C0C0C0; /* Metalik gümüş metin, profesyonel görünüm */
    }

    body::after {
        content: '';
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(45, 11, 11, 0.9); /* Daha koyu kırmızı overlay */
        z-index: -1;
    }

    /* Logo Stilleri */
    .logo-container {
        position: absolute;
        top: 1rem;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        align-items: center;
        z-index: 2000; /* Diğer öğelerden üstte, mutlaka görünür */
    }

    .logo-img {
        width: 120px;
        height: auto;
    }

    /* Başlık Stilleri */
    .header-text {
      
        text-align: center;
        padding: 80px 20px 20px; /* Logo için alan bırak */
        color: #ff4040; /* Kırmızı, dublaj temasına uygun */
        font-size: 2.5rem; /* Daha etkileyici ve büyük başlık */
        font-weight: 900; /* Daha kalın ve dramatik */
        text-shadow: 0 0 10px rgba(255, 64, 64, 0.5); /* Kırmızı gölge efekti */
        z-index: 1500; /* Tablerden üstte, logonun altında */
    }

    /* Metalik kırmızı parlama animasyonu */
    @keyframes metallic-red-shine {
        0% { filter: brightness(1) saturate(1) drop-shadow(0 0 5px #ff4040); }
        50% { filter: brightness(1.3) saturate(1.7) drop-shadow(0 0 15px #ff6b6b); }
        100% { filter: brightness(1) saturate(1) drop-shadow(0 0 5px #ff4040); }
    }

    /* Dublaj temalı stil */
    .dubbing-theme {
        background: linear-gradient(to bottom, #800000, #2d0b0b); /* Koyu kırmızı gradyan */
        border-radius: 15px;
        padding: 1rem;
        box-shadow: 0 10px 20px rgba(255, 64, 64, 0.3); /* Kırmızı gölge */
    }

    /* Footer Stilleri (Tablerin Üstünde, Şeffaf) */
    .footer {
        text-align: center;
        padding: 10px;
        color: #ff4040; /* Kırmızı metin, dublaj temasına uygun */
        font-size: 14px;
        margin-top: 20px;
        position: relative;
        z-index: 1001; /* Tablerden üstte, logodan düşük */
    }

    /* Düğme ve Yükleme Alanı Stilleri */
    button {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        background: #800000 !important; /* Koyu kırmızı, dublaj temasına uygun */
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        color: #C0C0C0 !important; /* Metalik gümüş metin */
        border-radius: 8px !important;
        padding: 8px 16px !important;
        position: relative;
        overflow: hidden !important;
        font-size: 0.9rem !important;
    }

    button:hover {
        transform: scale(1.05) !important;
        box-shadow: 0 10px 40px rgba(255, 64, 64, 0.7) !important; /* Daha belirgin kırmızı gölge */
        background: #ff4040 !important; /* Daha açık kırmızı hover efekti */
    }

    button::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: linear-gradient(45deg, 
            transparent 20%, 
            rgba(192, 192, 192, 0.3) 50%, /* Metalik gümüş ton */
            transparent 80%);
        animation: button-shine 3s infinite linear;
    }

    /* Resim ve Ses Yükleme Alanı Stili */
    .compact-upload.horizontal {
        display: inline-flex !important;
        align-items: center !important;
        gap: 8px !important;
        max-width: 400px !important;
        height: 40px !important;
        padding: 0 12px !important;
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        background: rgba(128, 0, 0, 0.5) !important; /* Koyu kırmızı, şeffaf */
        border-radius: 8px !important;
        transition: all 0.2s ease !important;
        color: #C0C0C0 !important; /* Metalik gümüş metin */
    }

    .compact-upload.horizontal:hover {
        border-color: #ff6b6b !important; /* Daha açık kırmızı */
        background: rgba(128, 0, 0, 0.7) !important; /* Daha koyu kırmızı hover */
    }

    .compact-upload.horizontal .w-full {
        flex: 1 1 auto !important;
        min-width: 120px !important;
        margin: 0 !important;
        color: #C0C0C0 !important; /* Metalik gümüş */
    }

    .compact-upload.horizontal button {
        padding: 4px 12px !important;
        font-size: 0.75em !important;
        height: 28px !important;
        min-width: 80px !important;
        border-radius: 4px !important;
        background: #800000 !important; /* Koyu kırmızı */
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        color: #C0C0C0 !important; /* Metalik gümüş */
    }

    .compact-upload.horizontal .text-gray-500 {
        font-size: 0.7em !important;
        color: rgba(192, 192, 192, 0.6) !important; /* Şeffaf metalik gümüş */
        white-space: nowrap !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        max-width: 180px !important;
    }

    /* Ekstra Dar Versiyon */
    .compact-upload.horizontal.x-narrow {
        max-width: 320px !important;
        height: 36px !important;
        padding: 0 10px !important;
        gap: 6px !important;
    }

    .compact-upload.horizontal.x-narrow button {
        padding: 3px 10px !important;
        font-size: 0.7em !important;
        height: 26px !important;
        min-width: 70px !important;
    }

    .compact-upload.horizontal.x-narrow .text-gray-500 {
        font-size: 0.65em !important;
        max-width: 140px !important;
    }

    /* Sekmeler İçin Ortak Stiller */
    .gr-tab {
        background: rgba(128, 0, 0, 0.5) !important; /* Koyu kırmızı, şeffaf */
        border-radius: 12px 12px 0 0 !important;
        margin: 0 5px !important;
        color: #C0C0C0 !important; /* Metalik gümüş */
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        z-index: 1500; /* Logo’nun altında, diğer öğelerden üstte */
    }

    .gr-tab-selected {
        background: #800000 !important; /* Koyu kırmızı */
        box-shadow: 0 4px 12px rgba(255, 64, 64, 0.7) !important; /* Daha belirgin kırmızı gölge */
        color: #ffffff !important; /* Beyaz metin (seçili sekme için kontrast) */
        border: 1px solid #ff6b6b !important; /* Daha açık kırmızı */
    }

    /* Manuel Ensemble Özel Stilleri */
    .compact-header {
        font-size: 0.95em !important;
        margin: 0.8rem 0 0.5rem 0 !important;
        color: #C0C0C0 !important; /* Metalik gümüş metin */
    }

    .compact-grid {
        gap: 0.4rem !important;
        max-height: 50vh;
        overflow-y: auto;
        padding: 10px;
        background: rgba(128, 0, 0, 0.3) !important; /* Koyu kırmızı, şeffaf */
        border-radius: 12px;
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
    }

    .compact-dropdown {
        --padding: 8px 12px !important;
        --radius: 10px !important;
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        background: rgba(128, 0, 0, 0.5) !important; /* Koyu kırmızı, şeffaf */
        color: #C0C0C0 !important; /* Metalik gümüş metin */
    }

    .tooltip-icon {
        font-size: 1.4em !important;
        color: #C0C0C0 !important; /* Metalik gümüş */
        cursor: help;
        margin-left: 0.5rem !important;
    }

    .log-box {
        font-family: 'Fira Code', monospace !important;
        font-size: 0.85em !important;
        background-color: rgba(128, 0, 0, 0.3) !important; /* Koyu kırmızı, şeffaf */
        border: 1px solid #ff4040 !important; /* Kırmızı sınır */
        border-radius: 8px;
        padding: 1rem !important;
        color: #C0C0C0 !important; /* Metalik gümüş metin */
    }

    /* Animasyonlar */
    @keyframes text-glow {
        0% { text-shadow: 0 0 5px rgba(192, 192, 192, 0); }
        50% { text-shadow: 0 0 15px rgba(192, 192, 192, 1); }
        100% { text-shadow: 0 0 5px rgba(192, 192, 192, 0); }
    }

    @keyframes button-shine {
        0% { transform: rotate(0deg) translateX(-50%); }
        100% { transform: rotate(360deg) translateX(-50%); }
    }

    /* Responsive Ayarlar */
    @media (max-width: 768px) {
        .compact-grid {
            max-height: 40vh;
        }

        .compact-upload.horizontal {
            max-width: 100% !important;
            width: 100% !important;
        }
        
        .compact-upload.horizontal .text-gray-500 {
            max-width: 100px !important;
        }
        
        .compact-upload.horizontal.x-narrow {
            height: 40px !important;
            padding: 0 8px !important;
        }

        .logo-container {
            width: 80px; /* Mobil cihazlarda daha küçük logo */
            top: 1rem;
            left: 50%;
            transform: translateX(-50%);
        }

        .header-text {
            padding: 60px 20px 20px; /* Mobil için daha az boşluk */
            font-size: 1.8rem; /* Mobil için biraz daha küçük başlık */
        }
    }
    """

    # Arayüz tasarımı
    with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
        with gr.Column():
            # Logo (PNG olarak, dublaj temasına uygun)
            logo_html = """
            <div class="logo-container">
                <img src="/content/gk_logo.png" alt="" class="logo-img">
            </div>
            """
            gr.HTML(logo_html)

            # Başlık (Etkileyici ve dublaj temalı)
            gr.HTML("""
            <div class="header-text">
                Gecekondu Dubbing Production
            </div>
            """)
            
        with gr.Tabs():
            with gr.Tab("Audio Separation", elem_id="separation_tab"):
                with gr.Row(equal_height=True):
                    # Sol Panel - Kontroller
                    with gr.Column(scale=1, min_width=380):
                        with gr.Accordion("📥 Input & Model", open=True):
                            with gr.Tabs():
                                with gr.Tab("🖥 Upload"):
                                    input_audio_file = gr.File(
                                        file_types=[".wav", ".mp3", ".m4a", ".mp4", ".mkv", ".flac"],
                                        elem_classes=["compact-upload", "horizontal", "x-narrow"],
                                        label="",
                                        scale=1
                                    )

                                with gr.Tab("📂 Path"):
                                    file_path_input = gr.Textbox(placeholder="/path/to/audio.wav")
             
                            
                            with gr.Row():
                                model_category = gr.Dropdown(
                                    label="Category",
                                    choices=list(model_choices.keys()),
                                    value="Vocal Separation"
                                )
                                model_dropdown = gr.Dropdown(label="Model")

                        with gr.Accordion("⚙ Settings", open=False):
                            with gr.Row():
                                export_format = gr.Dropdown(
                                    label="Format",
                                    choices=['wav FLOAT', 'flac PCM_16', 'flac PCM_24'],
                                    value='wav FLOAT'
                                )
                                chunk_size = gr.Dropdown(
                                    label="Chunk Size",
                                    choices=[352800, 485100],
                                    value=352800,
                                    info="Don't change unless you have specific requirements"
                                )
                            
                            with gr.Row():
                                overlap = gr.Slider(2, 50, step=1, label="Overlap")
                                info="Recommended: 2-10 (Higher values increase quality but require more VRAM)"
                                use_tta = gr.Checkbox(label="TTA Boost")
                                info="Improves quality but increases processing time"

                            with gr.Row():
                                use_demud_phaseremix_inst = gr.Checkbox(label="Phase Fix")
                                info="Advanced phase correction for instrumental tracks"
                                extract_instrumental = gr.Checkbox(label="Instrumental")

                        with gr.Row():
                            process_btn = gr.Button("🚀 Process", variant="primary")
                            clear_old_output_btn = gr.Button("🧹 Reset", variant="secondary")
                            clear_old_output_status = gr.Textbox(label="Status", interactive=False)

                    # Sağ Panel - Sonuçlar
                    with gr.Column(scale=2, min_width=800):
                        with gr.Tabs():
                            with gr.Tab("🎧 Main"):
                                with gr.Column():
                                    original_audio = gr.Audio(label="Original", interactive=False)
                                    with gr.Row():
                                        vocals_audio = gr.Audio(label="Vocals", show_download_button=True)
                                        instrumental_audio = gr.Audio(label="Instrumental", show_download_button=True)

                            with gr.Tab("🔍 Details"):
                                with gr.Column():
                                    with gr.Row():
                                        male_audio = gr.Audio(label="Male")
                                        female_audio = gr.Audio(label="Female")
                                        speech_audio = gr.Audio(label="Speech")
                                    with gr.Row():
                                        drum_audio = gr.Audio(label="Drums")
                                        bass_audio = gr.Audio(label="Bass")
                                    with gr.Row():
                                        other_audio = gr.Audio(label="Other")
                                        effects_audio = gr.Audio(label="Effects")

                            with gr.Tab("⚙ Advanced"):
                                with gr.Column():
                                    with gr.Row():
                                        phaseremix_audio = gr.Audio(label="Phase Remix")
                                        dry_audio = gr.Audio(label="Dry")
                                    with gr.Row():
                                        music_audio = gr.Audio(label="Music")
                                        karaoke_audio = gr.Audio(label="Karaoke")
                                        bleed_audio = gr.Audio(label="Bleed") 
                       
                            with gr.Row():
                        
                                gr.Markdown("""
                                <div style="
                                    background: rgba(245,245,220,0.15);
                                    padding: 1rem;
                                    border-radius: 8px;
                                    border-left: 3px solid #6c757d;
                                    margin: 1rem 0 1.5rem 0;
                                ">
                                    <b>🔈 Processing Tip:</b> For noisy results, use <code>bleed_suppressor_v1</code> 
                                    or <code>denoisedebleed</code> models in the <i>"Denoise & Effect Removal"</i> 
                                    category to clean the output
                                </div>
                                """)                                        
                        



            # Oto Ensemble Sekmesi
            with gr.Tab("Auto Ensemble"):
                with gr.Row():
                    with gr.Column():
                        with gr.Group():
                            auto_input_audio_file = gr.File(label="Upload file")
                            auto_file_path_input = gr.Textbox(
                                label="Or enter file path",
                                placeholder="Enter full path to audio file",
                                interactive=True
                            )

                        with gr.Accordion("⚙️ Advanced Settings", open=False):
                            with gr.Row():
                                auto_use_tta = gr.Checkbox(label="Use TTA", value=False)
                                auto_extract_instrumental = gr.Checkbox(label="Instrumental Only")
                            
                            with gr.Row():
                                auto_overlap = gr.Slider(
                                    label="Overlap",
                                    minimum=2,
                                    maximum=50,
                                    value=2,
                                    step=1
                                )
                                auto_chunk_size = gr.Dropdown(
                                    label="Chunk Size",
                                    choices=[352800, 485100],
                                    value=352800
                                )
                                export_format2 = gr.Dropdown(
                                    label="Output Format",
                                    choices=['wav FLOAT', 'flac PCM_16', 'flac PCM_24'],
                                    value='wav FLOAT'
                                )

                        # Model Seçim Bölümü
                        with gr.Group():
                            gr.Markdown("### 🧠 Model Selection") 
                            with gr.Row():
                                auto_category_dropdown = gr.Dropdown(
                                label="Model Category",
                                choices=list(model_choices.keys()),
                                value="Vocal Separation"
                            )

                            # Model seçimi (tek seferde)
                            auto_model_dropdown = gr.Dropdown(
                                label="Select Models from Category",
                                choices=model_choices["Vocal Separation"],
                                multiselect=True,
                                max_choices=50,
                                interactive=True
                            )

                            # Seçilen modellerin listesi (ayrı kutucuk)
                            selected_models = gr.Dropdown(
                                label="Selected Models",
                                choices=[],
                                multiselect=True,
                                interactive=False  # Kullanıcı buraya direkt seçim yapamaz
                            )

                            
                            with gr.Row():
                                add_btn = gr.Button("➕ Add Selected", variant="secondary")
                                clear_btn = gr.Button("🗑️ Clear All", variant="stop")

                        # Ensemble Ayarları
                        with gr.Group():
                            gr.Markdown("### ⚡ Ensemble Settings")
                            with gr.Row():
                                auto_ensemble_type = gr.Dropdown(
                                    label="Method",
                                    choices=['avg_wave', 'median_wave', 'min_wave', 'max_wave',
                                          'avg_fft', 'median_fft', 'min_fft', 'max_fft'],
                                    value='avg_wave'
                                )
                            
                            gr.Markdown("**Recommendation:** avg_wave and max_fft best results")

                        auto_process_btn = gr.Button("🚀 Start Processing", variant="primary")

                    with gr.Column():
                        with gr.Tabs():
                            with gr.Tab("🔊 Original Audio"):
                                original_audio2 = gr.Audio(
                                        label=" Original Audio",
                                        interactive=False,
                                        every=1,  # Her 1 saniyede bir güncelle
                                        elem_id="original_audio_player"
                                    )
                            with gr.Tab("🎚️ Ensemble Result"):
                                auto_output_audio = gr.Audio(
                                    label="Output Preview",
                                    show_download_button=True,
                                    interactive=False
                                )
                        
                        auto_status = gr.Textbox(
                            label="Processing Status",
                            interactive=False,
                            placeholder="Waiting for processing...",
                            elem_classes="status-box"
                        )

                        gr.Markdown("""
                            <div style="
                                background: rgba(110, 142, 251, 0.1);
                                padding: 1.2rem;
                                border-radius: 12px;
                                border-left: 4px solid #6e8efb;
                                margin: 1rem 0;
                                backdrop-filter: blur(3px);
                                border: 1px solid rgba(255,255,255,0.2);
                            ">
                                <div style="display: flex; align-items: start; gap: 1rem;">
                                    <div style="
                                        font-size: 1.4em;
                                        color: #6e8efb;
                                        margin-top: -2px;
                                    ">⚠️</div>
                                    <div style="color: #2d3748;">
                                        <h4 style="
                                            margin: 0 0 0.8rem 0;
                                            color: #4a5568;
                                            font-weight: 600;
                                            font-size: 1.1rem;
                                        ">
                                            Model Selection Guidelines
                                        </h4>
                                        <ul style="
                                            margin: 0;
                                            padding-left: 1.2rem;
                                            color: #4a5568;
                                            line-height: 1.6;
                                        ">
                                            <li><strong>Avoid cross-category mixing:</strong> Combining vocal and instrumental models may create unwanted blends</li>
                                            <li><strong>Special model notes:</strong>
                                                <ul style="padding-left: 1.2rem; margin: 0.5rem 0;">
                                                    <li>Duality models (v1/v2) - Output both stems</li>
                                                    <li>MDX23C Separator - Hybrid results</li>
                                                </ul>
                                            </li>
                                            <li><strong>Best practice:</strong> Use 3-5 similar models from same category</li>
                                        </ul>
                                        <div style="
                                            margin-top: 1rem;
                                            padding: 0.8rem;
                                            background: rgba(167, 119, 227, 0.1);
                                            border-radius: 8px;
                                            color: #6e8efb;
                                            font-size: 0.9rem;
                                        ">
                                            💡 Pro Tip: Start with "VOCALS-MelBand-Roformer BigBeta5e" + "VOCALS-BS-Roformer_1297" combination
                                        </div>
                                    </div>
                                </div>
                            </div>
                            """)

                # Kategori değişim fonksiyonunu güncelleyelim
                def update_models(category):
                    return gr.Dropdown(choices=model_choices[category])

                def add_models(new_models, existing_models):
                    updated = list(set(existing_models + new_models))
                    return gr.Dropdown(choices=updated, value=updated)

                def clear_models():
                    return gr.Dropdown(choices=[], value=[]) 

                # Etkileşimler
                def update_category(target):
                    category_map = {
                        "Only Vocals": "Vocal Separation",
                        "Only Instrumental": "Instrumental Separation"
                    }
                    return category_map.get(target, "Vocal Separation")

                # Otomatik yenileme için olayı bağla
                input_audio_file.upload(
                    fn=lambda x, y: handle_file_upload(x, y, is_auto_ensemble=False),
                    inputs=[input_audio_file, file_path_input],
                    outputs=[input_audio_file, original_audio]
                )

                file_path_input.change(
                    fn=lambda x, y: handle_file_upload(x, y, is_auto_ensemble=False),
                    inputs=[input_audio_file, file_path_input],
                    outputs=[input_audio_file, original_audio]
                )

                auto_input_audio_file.upload(
                    fn=lambda x, y: handle_file_upload(x, y, is_auto_ensemble=True),
                    inputs=[auto_input_audio_file, auto_file_path_input],
                    outputs=[auto_input_audio_file, original_audio2]
                )

                auto_file_path_input.change(
                    fn=lambda x, y: handle_file_upload(x, y, is_auto_ensemble=True),
                    inputs=[auto_input_audio_file, auto_file_path_input],
                    outputs=[auto_input_audio_file, original_audio2]
                )

                auto_category_dropdown.change(
                    fn=update_models,
                    inputs=auto_category_dropdown,
                    outputs=auto_model_dropdown
                )

                add_btn.click(
                     fn=add_models,
                     inputs=[auto_model_dropdown, selected_models],
                     outputs=selected_models
                )

                clear_btn.click(
                     fn=clear_models,
                     inputs=[],
                     outputs=selected_models
                )

                auto_process_btn.click(
                    fn=auto_ensemble_process,
                    inputs=[
                        auto_input_audio_file,
                        selected_models,
                        auto_chunk_size,
                        auto_overlap,
                        export_format2,
                        auto_use_tta,
                        auto_extract_instrumental,
                        auto_ensemble_type,
                        gr.State(None)
                    ],
                    outputs=[auto_output_audio, auto_status]
                )                        

            # İndirme Sekmesi
            with gr.Tab("Download Sources"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### 🗂️ Cloud Storage")
                        drive_url_input = gr.Textbox(label="Google Drive Shareable Link")
                        drive_download_btn = gr.Button("⬇️ Download from Drive", variant="secondary")
                        drive_download_status = gr.Textbox(label="Download Status")
                        drive_download_output = gr.File(label="Downloaded File", interactive=False)

                    with gr.Column():
                        gr.Markdown("### 🌐 Direct Links")
                        direct_url_input = gr.Textbox(label="Audio File URL")
                        direct_download_btn = gr.Button("⬇️ Download from URL", variant="secondary")
                        direct_download_status = gr.Textbox(label="Download Status")
                        direct_download_output = gr.File(label="Downloaded File", interactive=False)

                    with gr.Column():
                        gr.Markdown("### 🍪 Cookie Management")
                        cookie_file = gr.File(
                            label="Upload Cookies.txt",
                            file_types=[".txt"],
                            interactive=True,
                            elem_id="cookie_upload"
                        )
                        gr.Markdown("""
                        <div style="margin-left:15px; font-size:0.95em">
                        
                        **📌 Why Needed?**  
                        - Access age-restricted content  
                        - Download private/unlisted videos  
                        - Bypass regional restrictions  
                        - Avoid YouTube download limits  

                        **⚠️ Important Notes**  
                        - NEVER share your cookie files!  
                        - Refresh cookies when:  
                          • Getting "403 Forbidden" errors  
                          • Downloads suddenly stop  
                          • Seeing "Session expired" messages  

                        **🔄 Renewal Steps**  
                        1. Install this <a href="https://chromewebstore.google.com/detail/get-cookiestxt-clean/ahmnmhfbokciafffnknlekllgcnafnie" target="_blank">Chrome extension</a>  
                        2. Login to YouTube in Chrome  
                        3. Click extension icon → "Export"  
                        4. Upload the downloaded file here  

                        **⏳ Cookie Lifespan**  
                        - Normal sessions: 24 hours  
                        - Sensitive operations: 1 hour  
                        - Password changes: Immediate invalidation  

                        </div>
                        """)


                        # Event handlers
                        model_category.change(
                            fn=update_models,
                            inputs=model_category,
                            outputs=model_dropdown
                        )

                        clear_old_output_btn.click(
                            fn=clear_old_output,
                            outputs=clear_old_output_status
                        )

                        process_btn.click(
                            fn=process_audio,
                            inputs=[
                                input_audio_file,
                                model_dropdown,
                                chunk_size,
                                overlap,
                                export_format,
                                use_tta,
                                use_demud_phaseremix_inst,
                                extract_instrumental,
                                gr.State(None),
                                gr.State(None)
                            ],
                            outputs=[
                                vocals_audio, instrumental_audio, phaseremix_audio,
                                drum_audio, karaoke_audio, bass_audio, other_audio, effects_audio,
                                speech_audio, bleed_audio, music_audio, dry_audio, male_audio, female_audio
                            ]
                        )

                        drive_download_btn.click(
                            fn=download_callback,
                            inputs=[drive_url_input, gr.State('drive')],
                            outputs=[
                                drive_download_output,  # 0. Dosya çıktısı
                                drive_download_status,  # 1. Durum mesajı
                                input_audio_file,       # 2. Ana ses dosyası girişi
                                auto_input_audio_file,  # 3. Oto ensemble girişi
                                original_audio,         # 4. Orijinal ses çıktısı
                                original_audio2 
                            ]
                        )

                        direct_download_btn.click(
                            fn=download_callback,
                            inputs=[direct_url_input, gr.State('direct'), cookie_file],
                            outputs=[
                                direct_download_output,  # 0. Dosya çıktısı
                                direct_download_status,  # 1. Durum mesajı
                                input_audio_file,        # 2. Ana ses dosyası girişi
                                auto_input_audio_file,   # 3. Oto ensemble girişi
                                original_audio,           # 4. Orijinal ses çıktısı
                                original_audio2 
                            ]
                        )

            
            with gr.Tab("🎚️ Manuel Ensemble"):
                with gr.Row(equal_height=True):
                    # Sol Panel - Giriş ve Ayarlar
                    with gr.Column(scale=1, min_width=400):
                        with gr.Accordion("📂 Input Sources", open=True):
                            with gr.Row():
                                refresh_btn = gr.Button("🔄 Refresh", variant="secondary", size="sm")
                                ensemble_type = gr.Dropdown(
                                label="Ensemble Algorithm",
                                choices=[
                                    'avg_wave',
                                    'median_wave',
                                    'min_wave',
                                    'max_wave',
                                    'avg_fft',
                                    'median_fft',
                                    'min_fft',
                                    'max_fft'
                                ],
                                value='avg_wave'
                            )
                            
                            # Dosya listesini belirli bir yoldan al
                            file_path = "/content/drive/MyDrive/output"  # Sabit yol
                            initial_files = glob.glob(f"{file_path}/*.wav") + glob.glob("/content/Music-Source-Separation-Training/old_output/*.wav")
                            
                            gr.Markdown("### Select Audio Files")
                            file_dropdown = gr.Dropdown(
                                choices=initial_files,
                                label="Available Files",
                                multiselect=True,
                                interactive=True,
                                elem_id="file-dropdown"
                            )
                            
                            weights_input = gr.Textbox(
                                label="Custom Weights (comma separated)",
                                placeholder="Example: 0.8, 1.2, 1.0, ...",
                                info="Leave empty for equal weights"
                            )

                    # Sağ Panel - Sonuçlar
                    with gr.Column(scale=2, min_width=800):
                        with gr.Tabs():
                            with gr.Tab("🎧 Result Preview"):
                                ensemble_output_audio = gr.Audio(
                                    label="Ensembled Output",
                                    interactive=False,
                                    show_download_button=True,
                                    elem_id="output-audio"
                                )
                            
                            with gr.Tab("📋 Processing Log"):
                                ensemble_status = gr.Textbox(
                                    label="Processing Details",
                                    interactive=False,
                                    elem_id="log-box"
                                )

                            with gr.Row(): 

                                ensemble_process_btn = gr.Button(
                                    "⚡ Process Ensemble", 
                                    variant="primary",
                                    size="sm",  # Boyutu küçülttüm
                                    elem_id="process-btn"
                                )

                # Etkileşimler
                def update_file_list():
                    files = glob.glob(f"{file_path}/*.wav") + glob.glob("/content/Music-Source-Separation-Training/old_output/*.wav")
                    return gr.Dropdown(choices=files)

                refresh_btn.click(
                    fn=update_file_list,
                    outputs=file_dropdown
                )
                
                def ensemble_audio_fn(files, method, weights):
                    try:
                        if len(files) < 2:
                            return None, "⚠️ Minimum 2 files required"
                        
                        # Dosya yollarını kontrol et
                        valid_files = [f for f in files if os.path.exists(f)]
                        
                        if len(valid_files) < 2:
                            return None, "❌ Valid files not found"
                        
                        # Create output directory if needed
                        output_dir = "/content/drive/MyDrive/ensembles"
                        os.makedirs(output_dir, exist_ok=True)  # This line fixes the error
                        
                        # Create output path
                        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                        output_path = f"{output_dir}/ensemble_{timestamp}.wav"
                        
                        # Ensemble işlemi
                        ensemble_args = [
                            "--files", *valid_files,
                            "--type", method.lower().replace(' ', '_'),
                            "--output", output_path
                        ]
                        
                        if weights and weights.strip():
                            weights_list = [str(w) for w in map(float, weights.split(','))]
                            ensemble_args += ["--weights", *weights_list]
                        
                        result = subprocess.run(
                            ["python", "ensemble.py"] + ensemble_args,
                            capture_output=True,
                            text=True
                        )
                        
                        log = f"✅ Success!\n{result.stdout}" if not result.stderr else f"❌ Error!\n{result.stderr}"
                        return output_path, log

                    except Exception as e:
                        return None, f"⛔ Critical Error: {str(e)}"

                ensemble_process_btn.click(
                    fn=ensemble_audio_fn,
                    inputs=[file_dropdown, ensemble_type, weights_input],
                    outputs=[ensemble_output_audio, ensemble_status]
                )
        
        gr.HTML("""
        <div class="footer">
            Presented by Gecekondu Production
        </div>
        """)

    return demo

def launch_with_share():
    try:
        port = generate_random_port()
        demo = create_interface()
        
        share_link = demo.launch(
            share=True,
            server_port=port,
            server_name='0.0.0.0',
            inline=False,
            allowed_paths=[
                '/content',
                '/content/drive/MyDrive/output',
                '/tmp'
                '/model_output_dir',
                'model_output_dir'
            ]
        )
        
        print(f"🌐 Gradio Share Link: {share_link}")
        print(f"🔌 Local Server Port: {port}")
        
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        print("🛑 Server stopped by user.")
    except Exception as e:
        print(f"❌ Error during server launch: {e}")
    finally:
        try:
            demo.close()
        except:
            pass

if __name__ == "__main__":
    launch_with_share()