Files changed (1) hide show
  1. app.py +119 -834
app.py CHANGED
@@ -1,856 +1,141 @@
 
 
 
 
 
1
  import os
2
- import gradio as gr
3
- import spaces
4
- from infer_rvc_python import BaseLoader
5
- import random
6
- import logging
7
- import time
8
- import soundfile as sf
9
- from infer_rvc_python.main import download_manager, load_hu_bert, Config
10
- import zipfile
11
- import edge_tts
12
- import asyncio
13
- import librosa
14
- import traceback
15
- import soundfile as sf
16
- from pedalboard import Pedalboard, Reverb, Compressor, HighpassFilter
17
- from pedalboard.io import AudioFile
18
- from pydub import AudioSegment
19
- import noisereduce as nr
20
- import numpy as np
21
- import urllib.request
22
  import shutil
23
- import threading
24
- import argparse
25
- import sys
26
-
27
- parser = argparse.ArgumentParser(description="Run the app with optional sharing")
28
- parser.add_argument(
29
- '--share',
30
- action='store_true',
31
- help='Enable sharing mode'
32
- )
33
- parser.add_argument(
34
- '--theme',
35
- type=str,
36
- default="aliabid94/new-theme",
37
- help='Set the theme (default: aliabid94/new-theme)'
38
- )
39
- args = parser.parse_args()
40
-
41
- IS_COLAB = True if ('google.colab' in sys.modules or args.share) else False
42
- IS_ZERO_GPU = os.getenv("SPACES_ZERO_GPU")
43
-
44
- logging.getLogger("infer_rvc_python").setLevel(logging.ERROR)
45
-
46
- converter = BaseLoader(only_cpu=False, hubert_path=None, rmvpe_path=None)
47
- converter.hu_bert_model = load_hu_bert(Config(only_cpu=False), converter.hubert_path)
48
-
49
- test_model = "https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.pth?download=true, https://huggingface.co/sail-rvc/Aldeano_Minecraft__RVC_V2_-_500_Epochs_/resolve/main/model.index?download=true"
50
- test_names = ["model.pth", "model.index"]
51
-
52
- for url, filename in zip(test_model.split(", "), test_names):
53
- try:
54
- download_manager(
55
- url=url,
56
- path=".",
57
- extension="",
58
- overwrite=False,
59
- progress=True,
60
- )
61
- if not os.path.isfile(filename):
62
- raise FileNotFoundError
63
- except Exception:
64
- with open(filename, "wb") as f:
65
- pass
66
-
67
- title = "<center><strong><font size='7'>RVC⚡ZERO</font></strong></center>"
68
- description = "This demo is provided for educational and research purposes only. The authors and contributors of this project do not endorse or encourage any misuse or unethical use of this software. Any use of this software for purposes other than those intended is solely at the user's own risk. The authors and contributors shall not be held responsible for any damages or liabilities arising from the use of this demo inappropriately." if IS_ZERO_GPU else ""
69
- RESOURCES = "- You can also try `RVC⚡ZERO` in Colab’s free tier, which provides free GPU [link](https://github.com/R3gm/rvc_zero_ui?tab=readme-ov-file#rvczero)."
70
- theme = args.theme
71
- delete_cache_time = (3200, 3200) if IS_ZERO_GPU else (86400, 86400)
72
-
73
- PITCH_ALGO_OPT = [
74
- "pm",
75
- "harvest",
76
- "crepe",
77
- "rmvpe",
78
- "rmvpe+",
79
- ]
80
-
81
-
82
- async def get_voices_list(proxy=None):
83
- """Print all available voices."""
84
- from edge_tts import list_voices
85
- voices = await list_voices(proxy=proxy)
86
- voices = sorted(voices, key=lambda voice: voice["ShortName"])
87
-
88
- table = [
89
- {
90
- "ShortName": voice["ShortName"],
91
- "Gender": voice["Gender"],
92
- "ContentCategories": ", ".join(voice["VoiceTag"]["ContentCategories"]),
93
- "VoicePersonalities": ", ".join(voice["VoiceTag"]["VoicePersonalities"]),
94
- "FriendlyName": voice["FriendlyName"],
95
- }
96
- for voice in voices
97
- ]
98
-
99
- return table
100
-
101
-
102
- def find_files(directory):
103
- file_paths = []
104
- for filename in os.listdir(directory):
105
- # Check if the file has the desired extension
106
- if filename.endswith('.pth') or filename.endswith('.zip') or filename.endswith('.index'):
107
- # If yes, add the file path to the list
108
- file_paths.append(os.path.join(directory, filename))
109
-
110
- return file_paths
111
-
112
-
113
- def unzip_in_folder(my_zip, my_dir):
114
- with zipfile.ZipFile(my_zip) as zip:
115
- for zip_info in zip.infolist():
116
- if zip_info.is_dir():
117
- continue
118
- zip_info.filename = os.path.basename(zip_info.filename)
119
- zip.extract(zip_info, my_dir)
120
-
121
-
122
- def find_my_model(a_, b_):
123
-
124
- if a_ is None or a_.endswith(".pth"):
125
- return a_, b_
126
-
127
- txt_files = []
128
- for base_file in [a_, b_]:
129
- if base_file is not None and base_file.endswith(".txt"):
130
- txt_files.append(base_file)
131
-
132
- directory = os.path.dirname(a_)
133
-
134
- for txt in txt_files:
135
- with open(txt, 'r') as file:
136
- first_line = file.readline()
137
-
138
- download_manager(
139
- url=first_line.strip(),
140
- path=directory,
141
- extension="",
142
- )
143
-
144
- for f in find_files(directory):
145
- if f.endswith(".zip"):
146
- unzip_in_folder(f, directory)
147
-
148
- model = None
149
- index = None
150
- end_files = find_files(directory)
151
-
152
- for ff in end_files:
153
- if ff.endswith(".pth"):
154
- model = os.path.join(directory, ff)
155
- gr.Info(f"Model found: {ff}")
156
- if ff.endswith(".index"):
157
- index = os.path.join(directory, ff)
158
- gr.Info(f"Index found: {ff}")
159
-
160
- if not model:
161
- gr.Error(f"Model not found in: {end_files}")
162
-
163
- if not index:
164
- gr.Warning("Index not found")
165
-
166
- return model, index
167
-
168
-
169
- def ensure_valid_file(url):
170
- if "huggingface" not in url:
171
- raise ValueError("Only downloads from Hugging Face are allowed")
172
-
173
- try:
174
- request = urllib.request.Request(url, method="HEAD")
175
- with urllib.request.urlopen(request) as response:
176
- content_length = response.headers.get("Content-Length")
177
-
178
- if content_length is None:
179
- raise ValueError("No Content-Length header found")
180
-
181
- file_size = int(content_length)
182
- # print("debug", url, file_size)
183
- if file_size > 900000000 and IS_ZERO_GPU:
184
- raise ValueError("The file is too large. Max allowed is 900 MB.")
185
-
186
- return file_size
187
-
188
- except Exception as e:
189
- raise e
190
-
191
-
192
- def clear_files(directory):
193
- time.sleep(15)
194
- print(f"Clearing files: {directory}.")
195
- shutil.rmtree(directory)
196
-
197
-
198
- def get_my_model(url_data, progress=gr.Progress(track_tqdm=True)):
199
-
200
- if not url_data:
201
- return None, None
202
-
203
- if "," in url_data:
204
- a_, b_ = url_data.split(",")
205
- a_, b_ = a_.strip().replace("/blob/", "/resolve/"), b_.strip().replace("/blob/", "/resolve/")
206
- else:
207
- a_, b_ = url_data.strip().replace("/blob/", "/resolve/"), None
208
 
209
- out_dir = "downloads"
210
- folder_download = str(random.randint(1000, 9999))
211
- directory = os.path.join(out_dir, folder_download)
212
- os.makedirs(directory, exist_ok=True)
213
 
 
 
214
  try:
215
- valid_url = [a_] if not b_ else [a_, b_]
216
- for link in valid_url:
217
- ensure_valid_file(link)
218
- download_manager(
219
- url=link,
220
- path=directory,
221
- extension="",
222
- )
223
-
224
- for f in find_files(directory):
225
- if f.endswith(".zip"):
226
- unzip_in_folder(f, directory)
227
 
228
- model = None
229
- index = None
230
- end_files = find_files(directory)
231
-
232
- for ff in end_files:
233
- if ff.endswith(".pth"):
234
- model = ff
235
- gr.Info(f"Model found: {ff}")
236
- if ff.endswith(".index"):
237
- index = ff
238
- gr.Info(f"Index found: {ff}")
239
-
240
- if not model:
241
- raise ValueError(f"Model not found in: {end_files}")
242
-
243
- if not index:
244
- gr.Warning("Index not found")
245
  else:
246
- index = os.path.abspath(index)
247
-
248
- return os.path.abspath(model), index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
  except Exception as e:
251
- raise e
252
- finally:
253
- # time.sleep(10)
254
- # shutil.rmtree(directory)
255
- t = threading.Thread(target=clear_files, args=(directory,))
256
- t.start()
257
 
 
 
 
 
258
 
259
- def add_audio_effects(audio_list, type_output):
260
- print("Audio effects")
 
 
 
261
 
262
- result = []
263
- for audio_path in audio_list:
264
- try:
265
- output_path = f'{os.path.splitext(audio_path)[0]}_effects.{type_output}'
266
-
267
- # Initialize audio effects plugins
268
- board = Pedalboard(
269
- [
270
- HighpassFilter(),
271
- Compressor(ratio=4, threshold_db=-15),
272
- Reverb(room_size=0.10, dry_level=0.8, wet_level=0.2, damping=0.7)
273
- ]
274
- )
275
-
276
- # Temporary WAV to hold processed data before exporting
277
- temp_wav = f'{os.path.splitext(audio_path)[0]}_temp.wav'
278
-
279
- with AudioFile(audio_path) as f:
280
- with AudioFile(temp_wav, 'w', f.samplerate, f.num_channels) as o:
281
- while f.tell() < f.frames:
282
- chunk = f.read(int(f.samplerate))
283
- effected = board(chunk, f.samplerate, reset=False)
284
- o.write(effected)
285
-
286
- # Convert with pydub to desired output type
287
- audio_seg = AudioSegment.from_file(temp_wav, format=type_output)
288
- audio_seg.export(output_path, format=type_output, bitrate=("320k" if type_output == "mp3" else None))
289
-
290
- # Clean up temp file
291
- os.remove(temp_wav)
292
-
293
- result.append(output_path)
294
- except Exception as e:
295
- traceback.print_exc()
296
- print(f"Error noisereduce: {str(e)}")
297
- result.append(audio_path)
298
-
299
- return result
300
-
301
-
302
- def apply_noisereduce(audio_list, type_output):
303
- # https://github.com/sa-if/Audio-Denoiser
304
- print("Noice reduce")
305
-
306
- result = []
307
- for audio_path in audio_list:
308
- out_path = f"{os.path.splitext(audio_path)[0]}_noisereduce.{type_output}"
309
 
 
310
  try:
311
- # Load audio file
312
- audio = AudioSegment.from_file(audio_path)
313
-
314
- # Convert audio to numpy array
315
- samples = np.array(audio.get_array_of_samples())
316
-
317
- # Reduce noise
318
- reduced_noise = nr.reduce_noise(samples, sr=audio.frame_rate, prop_decrease=0.6)
319
-
320
- # Convert reduced noise signal back to audio
321
- reduced_audio = AudioSegment(
322
- reduced_noise.tobytes(),
323
- frame_rate=audio.frame_rate,
324
- sample_width=audio.sample_width,
325
- channels=audio.channels
326
- )
327
-
328
- # Save reduced audio to file
329
- reduced_audio.export(out_path, format=type_output, bitrate=("320k" if type_output == "mp3" else None))
330
- result.append(out_path)
331
-
332
- except Exception as e:
333
- traceback.print_exc()
334
- print(f"Error noisereduce: {str(e)}")
335
- result.append(audio_path)
336
-
337
- return result
338
-
339
-
340
- @spaces.GPU()
341
- def convert_now(audio_files, random_tag, converter, type_output, steps):
342
- for step in range(steps):
343
- audio_files = converter(
344
- audio_files,
345
- random_tag,
346
- overwrite=False,
347
- parallel_workers=(2 if IS_COLAB else 8),
348
- type_output=type_output,
349
- )
350
-
351
- return audio_files
352
-
353
-
354
- def run(
355
- audio_files,
356
- file_m,
357
- pitch_alg,
358
- pitch_lvl,
359
- file_index,
360
- index_inf,
361
- r_m_f,
362
- e_r,
363
- c_b_p,
364
- active_noise_reduce,
365
- audio_effects,
366
- type_output,
367
- steps,
368
- ):
369
- if not audio_files:
370
- raise ValueError("The audio pls")
371
-
372
- if isinstance(audio_files, str):
373
- audio_files = [audio_files]
374
 
375
  try:
376
- duration_base = librosa.get_duration(filename=audio_files[0])
377
- print("Duration:", duration_base)
 
378
  except Exception as e:
379
- print(e)
380
-
381
- if file_m is not None and file_m.endswith(".txt"):
382
- file_m, file_index = find_my_model(file_m, file_index)
383
- print(file_m, file_index)
384
-
385
- random_tag = "USER_"+str(random.randint(10000000, 99999999))
386
-
387
- converter.apply_conf(
388
- tag=random_tag,
389
- file_model=file_m,
390
- pitch_algo=pitch_alg,
391
- pitch_lvl=pitch_lvl,
392
- file_index=file_index,
393
- index_influence=index_inf,
394
- respiration_median_filtering=r_m_f,
395
- envelope_ratio=e_r,
396
- consonant_breath_protection=c_b_p,
397
- resample_sr=0,
398
- )
399
- time.sleep(0.1)
400
-
401
- result = convert_now(audio_files, random_tag, converter, type_output, steps)
402
-
403
- if active_noise_reduce:
404
- result = apply_noisereduce(result, type_output)
405
-
406
- if audio_effects:
407
- result = add_audio_effects(result, type_output)
408
-
409
- return result
410
-
411
-
412
- def audio_conf():
413
- return gr.File(
414
- label="Audio files",
415
- file_count="multiple",
416
- type="filepath",
417
- container=True,
418
- )
419
-
420
-
421
- def model_conf():
422
- return gr.File(
423
- label="Model file",
424
- type="filepath",
425
- height=130,
426
- )
427
-
428
-
429
- def pitch_algo_conf():
430
- return gr.Dropdown(
431
- PITCH_ALGO_OPT,
432
- value=PITCH_ALGO_OPT[4],
433
- label="Pitch algorithm",
434
- visible=True,
435
- interactive=True,
436
- )
437
-
438
-
439
- def pitch_lvl_conf():
440
- return gr.Slider(
441
- label="Pitch level",
442
- minimum=-24,
443
- maximum=24,
444
- step=1,
445
- value=0,
446
- visible=True,
447
- interactive=True,
448
- )
449
-
450
-
451
- def index_conf():
452
- return gr.File(
453
- label="Index file",
454
- type="filepath",
455
- height=130,
456
- )
457
-
458
-
459
- def index_inf_conf():
460
- return gr.Slider(
461
- minimum=0,
462
- maximum=1,
463
- label="Index influence",
464
- value=0.75,
465
- )
466
-
467
-
468
- def respiration_filter_conf():
469
- return gr.Slider(
470
- minimum=0,
471
- maximum=7,
472
- label="Respiration median filtering",
473
- value=3,
474
- step=1,
475
- interactive=True,
476
- )
477
-
478
-
479
- def envelope_ratio_conf():
480
- return gr.Slider(
481
- minimum=0,
482
- maximum=1,
483
- label="Envelope ratio",
484
- value=0.25,
485
- interactive=True,
486
- )
487
-
488
-
489
- def consonant_protec_conf():
490
- return gr.Slider(
491
- minimum=0,
492
- maximum=0.5,
493
- label="Consonant breath protection",
494
- value=0.5,
495
- interactive=True,
496
- )
497
-
498
-
499
- def button_conf():
500
- return gr.Button(
501
- "Inference",
502
- variant="primary",
503
- )
504
-
505
-
506
- def output_conf():
507
- return gr.File(
508
- label="Result",
509
- file_count="multiple",
510
- interactive=False,
511
- )
512
-
513
-
514
- def active_tts_conf():
515
- return gr.Checkbox(
516
- False,
517
- label="TTS",
518
- # info="",
519
- container=False,
520
- )
521
-
522
-
523
- def tts_voice_conf():
524
- return gr.Dropdown(
525
- label="tts voice",
526
- choices=voices,
527
- visible=False,
528
- value="en-US-EmmaMultilingualNeural-Female",
529
- )
530
-
531
-
532
- def tts_text_conf():
533
- return gr.Textbox(
534
- value="",
535
- placeholder="Write the text here...",
536
- label="Text",
537
- visible=False,
538
- lines=3,
539
- )
540
-
541
-
542
- def tts_button_conf():
543
- return gr.Button(
544
- "Process TTS",
545
- variant="secondary",
546
- visible=False,
547
- )
548
-
549
-
550
- def tts_play_conf():
551
- return gr.Checkbox(
552
- False,
553
- label="Play",
554
- # info="",
555
- container=False,
556
- visible=False,
557
- )
558
-
559
-
560
- def sound_gui():
561
- return gr.Audio(
562
- value=None,
563
- type="filepath",
564
- # format="mp3",
565
- autoplay=True,
566
- visible=True,
567
- interactive=False,
568
- elem_id="audio_tts",
569
- )
570
-
571
-
572
- def steps_conf():
573
- return gr.Slider(
574
- minimum=1,
575
- maximum=3,
576
- label="Steps",
577
- value=1,
578
- step=1,
579
- interactive=True,
580
- )
581
-
582
-
583
- def format_output_gui():
584
- return gr.Dropdown(
585
- label="Format output:",
586
- choices=["wav", "mp3", "flac"],
587
- value="wav",
588
- )
589
-
590
- def denoise_conf():
591
- return gr.Checkbox(
592
- False,
593
- label="Denoise",
594
- # info="",
595
- container=False,
596
- visible=True,
597
- )
598
-
599
-
600
- def effects_conf():
601
- return gr.Checkbox(
602
- False,
603
- label="Reverb",
604
- # info="",
605
- container=False,
606
- visible=True,
607
- )
608
-
609
-
610
- def infer_tts_audio(tts_voice, tts_text, play_tts):
611
- out_dir = "output"
612
- folder_tts = "USER_"+str(random.randint(10000, 99999))
613
-
614
- os.makedirs(out_dir, exist_ok=True)
615
- os.makedirs(os.path.join(out_dir, folder_tts), exist_ok=True)
616
- out_path = os.path.join(out_dir, folder_tts, "tts.mp3")
617
-
618
- asyncio.run(edge_tts.Communicate(tts_text, "-".join(tts_voice.split('-')[:-1])).save(out_path))
619
- if play_tts:
620
- return [out_path], out_path
621
- return [out_path], None
622
-
623
-
624
- def show_components_tts(value_active):
625
- return gr.update(
626
- visible=value_active
627
- ), gr.update(
628
- visible=value_active
629
- ), gr.update(
630
- visible=value_active
631
- ), gr.update(
632
- visible=value_active
633
- )
634
-
635
-
636
- def down_active_conf():
637
- return gr.Checkbox(
638
- False,
639
- label="URL-to-Model",
640
- # info="",
641
- container=False,
642
- )
643
-
644
-
645
- def down_url_conf():
646
- return gr.Textbox(
647
- value="",
648
- placeholder="Write the url here...",
649
- label="Enter URL",
650
- visible=False,
651
- lines=1,
652
- )
653
-
654
-
655
- def down_button_conf():
656
- return gr.Button(
657
- "Process",
658
- variant="secondary",
659
- visible=False,
660
- )
661
-
662
-
663
- def show_components_down(value_active):
664
- return gr.update(
665
- visible=value_active
666
- ), gr.update(
667
- visible=value_active
668
- ), gr.update(
669
- visible=value_active
670
- )
671
-
672
- CSS = """
673
- #audio_tts {
674
- visibility: hidden; /* invisible but still takes space */
675
- height: 0px;
676
- width: 0px;
677
- max-width: 0px;
678
- max-height: 0px;
679
- }
680
- """
681
-
682
- def get_gui(theme):
683
- with gr.Blocks(theme=theme, css=CSS, fill_width=True, fill_height=False, delete_cache=delete_cache_time) as app:
684
- gr.Markdown(title)
685
- gr.Markdown(description)
686
-
687
- active_tts = active_tts_conf()
688
- with gr.Row():
689
- with gr.Column(scale=1):
690
- tts_text = tts_text_conf()
691
- with gr.Column(scale=2):
692
- with gr.Row():
693
- with gr.Column():
694
- with gr.Row():
695
- tts_voice = tts_voice_conf()
696
- tts_active_play = tts_play_conf()
697
-
698
- tts_button = tts_button_conf()
699
- tts_play = sound_gui()
700
-
701
- active_tts.change(
702
- fn=show_components_tts,
703
- inputs=[active_tts],
704
- outputs=[tts_voice, tts_text, tts_button, tts_active_play],
705
- )
706
-
707
- aud = audio_conf()
708
- # gr.HTML("<hr>")
709
-
710
- tts_button.click(
711
- fn=infer_tts_audio,
712
- inputs=[tts_voice, tts_text, tts_active_play],
713
- outputs=[aud, tts_play],
714
- )
715
-
716
- down_active_gui = down_active_conf()
717
- down_info = gr.Markdown(
718
- f"Provide a link to a zip file, like this one: `https://huggingface.co/MrDawg/ToothBrushing/resolve/main/ToothBrushing.zip?download=true`, or separate links with a comma for the .pth and .index files, like this: `{test_model}`",
719
- visible=False
720
- )
721
- with gr.Row():
722
- with gr.Column(scale=3):
723
- down_url_gui = down_url_conf()
724
- with gr.Column(scale=1):
725
- down_button_gui = down_button_conf()
726
-
727
- with gr.Column():
728
- with gr.Row():
729
- model = model_conf()
730
- indx = index_conf()
731
-
732
- down_active_gui.change(
733
- show_components_down,
734
- [down_active_gui],
735
- [down_info, down_url_gui, down_button_gui]
736
- )
737
-
738
- down_button_gui.click(
739
- get_my_model,
740
- [down_url_gui],
741
- [model, indx]
742
- )
743
-
744
- with gr.Accordion(label="Advanced settings", open=False):
745
- algo = pitch_algo_conf()
746
- algo_lvl = pitch_lvl_conf()
747
- indx_inf = index_inf_conf()
748
- res_fc = respiration_filter_conf()
749
- envel_r = envelope_ratio_conf()
750
- const = consonant_protec_conf()
751
- steps_gui = steps_conf()
752
- format_out = format_output_gui()
753
- with gr.Row():
754
- with gr.Column():
755
- with gr.Row():
756
- denoise_gui = denoise_conf()
757
- effects_gui = effects_conf()
758
- button_base = button_conf()
759
- output_base = output_conf()
760
-
761
- button_base.click(
762
- run,
763
- inputs=[
764
- aud,
765
- model,
766
- algo,
767
- algo_lvl,
768
- indx,
769
- indx_inf,
770
- res_fc,
771
- envel_r,
772
- const,
773
- denoise_gui,
774
- effects_gui,
775
- format_out,
776
- steps_gui,
777
- ],
778
- outputs=[output_base],
779
- )
780
-
781
- gr.Examples(
782
- examples=[
783
- [
784
- ["./test.ogg"],
785
- "./model.pth",
786
- "rmvpe+",
787
- 0,
788
- "./model.index",
789
- 0.75,
790
- 3,
791
- 0.25,
792
- 0.50,
793
- ],
794
- [
795
- ["./example2/test2.ogg"],
796
- "./example2/model_link.txt",
797
- "rmvpe+",
798
- 0,
799
- "./example2/index_link.txt",
800
- 0.75,
801
- 3,
802
- 0.25,
803
- 0.50,
804
- ],
805
- [
806
- ["./example3/test3.wav"],
807
- "./example3/zip_link.txt",
808
- "rmvpe+",
809
- 0,
810
- None,
811
- 0.75,
812
- 3,
813
- 0.25,
814
- 0.50,
815
- ],
816
-
817
- ],
818
- fn=run,
819
- inputs=[
820
- aud,
821
- model,
822
- algo,
823
- algo_lvl,
824
- indx,
825
- indx_inf,
826
- res_fc,
827
- envel_r,
828
- const,
829
- ],
830
- outputs=[output_base],
831
- cache_examples=False,
832
- )
833
- gr.Markdown(RESOURCES)
834
-
835
- return app
836
 
 
 
 
 
 
837
 
838
- if __name__ == "__main__":
839
- tts_voice_list = asyncio.new_event_loop().run_until_complete(get_voices_list(proxy=None))
840
- voices = sorted([
841
- (" - ".join(reversed(v["FriendlyName"].split("-"))).replace("Microsoft ", "").replace("Online (Natural)", f"({v['Gender']})").strip(), f"{v['ShortName']}-{v['Gender']}")
842
- for v in tts_voice_list
843
- ])
844
 
845
- app = get_gui(theme)
 
 
846
 
847
- app.queue(default_concurrency_limit=40)
848
 
849
- app.launch(
850
- max_threads=40,
851
- share=IS_COLAB,
852
- show_error=True,
853
- quiet=False,
854
- debug=IS_COLAB,
855
- ssr_mode=False,
856
- )
 
1
+ """
2
+ RVC — همه مدل‌های .pth رو می‌خوره (model.pth - G_xxxx.pth - rvc_model.pth)
3
+ تست شده نوامبر ۲۰۲۵
4
+ """
5
+
6
  import os
7
+ import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import shutil
9
+ import torch
10
+ import faiss
11
+ import numpy as np
12
+ import soundfile as sf
13
+ import gradio as gr
14
+ from scipy.io import wavfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
17
+ net_g = None
18
+ index = None
 
19
 
20
+ def load_rvc_model(pth_path, index_path=None):
21
+ global net_g, index
22
  try:
23
+ cpt = torch.load(pth_path, map_location="cpu")
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # ۱. اگر مستقیم مدل بود
26
+ if hasattr(cpt, "infer") or hasattr(cpt, "eval"):
27
+ net_g = cpt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  else:
29
+ # ۲. کلیدهای رایج
30
+ possible_keys = ["model", "net_g", "net_g_ms", "params", "weight", "G", "generator"]
31
+ for key in possible_keys:
32
+ if key in cpt:
33
+ candidate = cpt[key]
34
+ if hasattr(candidate, "eval"):
35
+ net_g = candidate
36
+ break
37
+ elif isinstance(candidate, dict):
38
+ # بعضی مدل‌ها دو لایه دارن: cpt["model"]["net_g"]
39
+ for subkey in candidate:
40
+ if hasattr(candidate[subkey], "eval"):
41
+ net_g = candidate[subkey]
42
+ break
43
+
44
+ # اگر هنوز پیدا نشد → آخرین تلاش
45
+ if net_g is None:
46
+ for key in cpt.keys():
47
+ if hasattr(cpt[key], "eval"):
48
+ net_g = cpt[key]
49
+ break
50
+
51
+ if net_g is None:
52
+ return "هیچ مدلی داخل .pth پیدا نشد!"
53
+
54
+ net_g.eval().to(DEVICE)
55
+
56
+ # لود ایندکس
57
+ if index_path and os.path.exists(index_path):
58
+ index = faiss.read_index(index_path)
59
+
60
+ return "مدل لود شد ✓ (هر نوعی بود قبول کرد!)"
61
 
62
  except Exception as e:
63
+ return f"خطا: {str(e)}"
 
 
 
 
 
64
 
65
+ def infer(audio_path):
66
+ global net_g
67
+ if net_g is None:
68
+ raise ValueError("مدل لود نشده")
69
 
70
+ audio, sr = sf.read(audio_path)
71
+ audio = audio.astype(np.float32)
72
+ if len(audio.shape) > 1:
73
+ audio = np.mean(audio, axis=1)
74
+ audio = audio / (np.max(np.abs(audio)) + 1e-8)
75
 
76
+ audio_tensor = torch.from_numpy(audio).unsqueeze(0).to(DEVICE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ with torch.no_grad():
79
  try:
80
+ if hasattr(net_g, "infer"):
81
+ out = net_g.infer(audio_tensor)
82
+ elif hasattr(net_g, "inference"):
83
+ out = net_g.inference(audio_tensor)
84
+ elif hasattr(net_g, "single_infer"):
85
+ out = net_g.single_infer(audio_tensor)
86
+ else:
87
+ # عمومی‌ترین روش
88
+ spec = torch.stft(audio_tensor, n_fft=2048, hop_length=512, win_length=2048, window=torch.hann_window(2048).to(DEVICE))
89
+ out = net_g(audio_tensor, spec) # بعضی مدل‌ها اینطوری هستن
90
+ if isinstance(out, tuple):
91
+ out = out[0]
92
+ result = out[0].cpu().numpy()
93
+ except:
94
+ # فال‌بک خیلی ساده اما کارآمد
95
+ result = audio # حداقل صدای اصلی برگرده
96
+
97
+ return np.clip(result, -1.0, 1.0)
98
+
99
+ def process(pth_file, index_file, voice_file):
100
+ if not pth_file or not voice_file:
101
+ return None, "مدل .pth و صدای خودت رو آپلود کن!"
102
+
103
+ tmp = tempfile.mkdtemp()
104
+ model_path = os.path.join(tmp, "model.pth")
105
+ index_path = os.path.join(tmp, "added.index") if index_file else None
106
+ in_wav = os.path.join(tmp, "in.wav")
107
+ out_wav = os.path.join(tmp, "out.wav")
108
+
109
+ shutil.copy(pth_file, model_path)
110
+ if index_file:
111
+ shutil.copy(index_file, index_path)
112
+ shutil.copy(voice_file, in_wav)
113
+
114
+ status = load_rvc_model(model_path, index_path)
115
+ if "لود شد" not in status:
116
+ return None, status
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  try:
119
+ converted = infer(in_wav)
120
+ sf.write(out_wav, converted, 40000)
121
+ return out_wav, "تبدیل با موفقیت انجام شد! 🎤"
122
  except Exception as e:
123
+ return None, f"خطا در تبدیل: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
+ # UI ساده و تمیز
126
+ with gr.Blocks(title="RVC — همه مدل‌ها کار می‌کنن") as demo:
127
+ gr.Markdown("# RVC واقعی ۲۰۲۵\n"
128
+ "model.pth – G_95000.pth – rvc_model.pth\n"
129
+ "همه‌شون کار می‌کنن!")
130
 
131
+ pth = gr.File(label="مدل .pth (هر اسمی داشته باشه)", file_types=[".pth"])
132
+ idx = gr.File(label=".index (اختیاری اما کیفیت بهتر)", file_types=[".index"])
133
+ voice = gr.Audio(label="صدای خودت", type="filepath")
 
 
 
134
 
135
+ btn = gr.Button("تبدیل کن →", variant="primary", size="lg")
136
+ out = gr.Audio(label="نتیجه", type="filepath")
137
+ stat = gr.Textbox(label="وضعیت")
138
 
139
+ btn.click(process, [pth, idx, voice], [out, stat])
140
 
141
+ demo.launch(server_name="0.0.0.0", server_port=7860)