LosCaquitos commited on
Commit
fa2737f
·
verified ·
1 Parent(s): 3501efb

Update setup_examples.py

Browse files
Files changed (1) hide show
  1. setup_examples.py +216 -46
setup_examples.py CHANGED
@@ -1,62 +1,232 @@
1
  #!/usr/bin/env python3
2
  """
3
- setup_examples.py - Script para gerar automaticamente os arquivos de exemplo
4
- Execute: python setup_examples.py
 
 
 
 
 
 
 
 
 
5
  """
 
6
  import os
7
- import sys
8
  import subprocess
 
 
9
  from pathlib import Path
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def setup_examples():
12
  print("=" * 60)
13
- print("🎵 Setting up RVC Examples")
14
  print("=" * 60)
15
-
16
- # Verificar se estamos na pasta correta
17
- base_dir = Path(__file__).parent
18
- examples_dir = base_dir / "examples"
19
- sample_outputs_dir = examples_dir / "sample_outputs"
20
-
21
- print(f"📁 Base directory: {base_dir}")
22
- print(f"📁 Examples directory: {examples_dir}")
23
-
24
  # Criar diretórios
25
- sample_outputs_dir.mkdir(parents=True, exist_ok=True)
26
- print(f"✅ Created directory: {sample_outputs_dir}")
27
-
28
- # Verificar se o script generate_sample_files.py existe
29
- generate_script = examples_dir / "generate_sample_files.py"
30
- if not generate_script.exists():
31
- print(f" Script not found: {generate_script}")
32
- print(" Please create examples/generate_sample_files.py first")
33
- return False
34
-
35
- # Executar o script de geração
36
- print("\n🎤 Generating sample files...")
37
- try:
38
- result = subprocess.run(
39
- [sys.executable, str(generate_script)],
40
- cwd=str(examples_dir),
41
- capture_output=True,
42
- text=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  )
44
- print(result.stdout)
45
- if result.stderr:
46
- print("Warnings:", result.stderr)
47
- except Exception as e:
48
- print(f"❌ Error running script: {e}")
49
- return False
50
-
51
- # Verificar arquivos gerados
52
- print("\n📋 Generated files:")
53
- for file in sorted(sample_outputs_dir.glob("*.mp3")):
54
- size = file.stat().st_size / 1024
55
- print(f" ✅ {file.name} ({size:.1f} KB)")
56
-
57
- print("\n" + "=" * 60)
58
- print(" Setup complete! Sample files are ready.")
 
 
59
  print("=" * 60)
 
60
  return True
61
 
62
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
  """
3
+ setup_examples.py - Gerador completo de arquivos de exemplo para o RVC Full Suite.
4
+
5
+ Executa: python setup_examples.py
6
+
7
+ Cria:
8
+ - examples/sample_inputs/ (arquivos de entrada: sample_audio.wav, sample_video.mp4)
9
+ - examples/sample_outputs/ (5 arquivos: entrada_acapella.mp3, entrada.mp3,
10
+ entrada_instrumental.mp3, saida.mp3, saida_acapella.mp3)
11
+
12
+ Os arquivos são sintéticos (senoides + ruído) e podem ser usados para testar a interface
13
+ sem depender de conversões reais. Se quiser exemplos reais, descomente a seção de pipeline.
14
  """
15
+
16
  import os
 
17
  import subprocess
18
+ import sys
19
+ import tempfile
20
  from pathlib import Path
21
 
22
+ # Tenta importar bibliotecas necessárias; se faltarem, instala automaticamente
23
+ try:
24
+ import numpy as np
25
+ from scipy.io.wavfile import write as write_wav
26
+ except ImportError:
27
+ print("Instalando dependências necessárias...")
28
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "numpy", "scipy"])
29
+ import numpy as np
30
+ from scipy.io.wavfile import write as write_wav
31
+
32
+ try:
33
+ from moviepy.video.io.VideoFileClip import VideoFileClip
34
+ from moviepy.audio.io.AudioFileClip import AudioFileClip
35
+ except ImportError:
36
+ print("Instalando moviepy para geração de vídeo...")
37
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "moviepy"])
38
+ from moviepy.video.io.VideoFileClip import VideoFileClip
39
+ from moviepy.audio.io.AudioFileClip import AudioFileClip
40
+
41
+ # ============================================================================
42
+ # CONFIGURAÇÕES
43
+ # ============================================================================
44
+ SAMPLE_RATE = 22050
45
+ DURATION_SEC = 8 # 8 segundos de exemplo
46
+ BASE_DIR = Path(__file__).parent
47
+ EXAMPLES_DIR = BASE_DIR / "examples"
48
+ INPUTS_DIR = EXAMPLES_DIR / "sample_inputs"
49
+ OUTPUTS_DIR = EXAMPLES_DIR / "sample_outputs"
50
+
51
+ # ============================================================================
52
+ # FUNÇÕES DE GERAÇÃO DE ÁUDIO SINTÉTICO
53
+ # ============================================================================
54
+ def generate_sine_tone(freq_hz, duration_sec, sample_rate):
55
+ """Gera um tom senoidal puro."""
56
+ t = np.linspace(0, duration_sec, int(sample_rate * duration_sec), endpoint=False)
57
+ return 0.5 * np.sin(2 * np.pi * freq_hz * t)
58
+
59
+ def generate_voice_like(duration_sec, sample_rate):
60
+ """
61
+ Simula uma voz humana com tons modulados (formantes simples).
62
+ Combina duas senoides com vibrato.
63
+ """
64
+ t = np.linspace(0, duration_sec, int(sample_rate * duration_sec), endpoint=False)
65
+ # Frequência fundamental (voz masculina ~110 Hz, feminina ~220 Hz)
66
+ f0 = 180.0
67
+ # Vibrato: modulação de frequência
68
+ vibrato = 5.0 # Hz
69
+ freq_mod = f0 + 10 * np.sin(2 * np.pi * vibrato * t)
70
+ # Gera a onda com fase acumulada
71
+ phase = 2 * np.pi * np.cumsum(freq_mod) / sample_rate
72
+ voice = 0.7 * np.sin(phase)
73
+ # Adiciona um harmônico (formante)
74
+ voice += 0.3 * np.sin(2 * np.pi * 2 * f0 * t)
75
+ # Envelope para suavizar início/fim
76
+ envelope = np.ones_like(t)
77
+ attack = int(0.1 * sample_rate)
78
+ decay = int(0.2 * sample_rate)
79
+ envelope[:attack] = np.linspace(0, 1, attack)
80
+ envelope[-decay:] = np.linspace(1, 0, decay)
81
+ voice *= envelope
82
+ return voice.astype(np.float32)
83
+
84
+ def generate_instrumental(duration_sec, sample_rate):
85
+ """Gera um fundo instrumental simples (acorde + percussão leve)."""
86
+ t = np.linspace(0, duration_sec, int(sample_rate * duration_sec), endpoint=False)
87
+ # Acorde: C maior (262, 330, 392 Hz)
88
+ chord = (0.2 * np.sin(2 * np.pi * 262 * t) +
89
+ 0.2 * np.sin(2 * np.pi * 330 * t) +
90
+ 0.2 * np.sin(2 * np.pi * 392 * t))
91
+ # Percussão: ruído branco filtrado
92
+ noise = np.random.normal(0, 0.05, len(t))
93
+ # Envelope
94
+ envelope = np.ones_like(t)
95
+ attack = int(0.05 * sample_rate)
96
+ envelope[:attack] = np.linspace(0, 1, attack)
97
+ chord *= envelope
98
+ noise *= envelope
99
+ instrumental = chord + noise
100
+ return instrumental.astype(np.float32)
101
+
102
+ def save_audio(file_path, audio_array, sample_rate=SAMPLE_RATE):
103
+ """Salva array como arquivo WAV e depois converte para MP3 usando ffmpeg."""
104
+ # Salva WAV temporário
105
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_wav:
106
+ tmp_wav_path = tmp_wav.name
107
+ write_wav(tmp_wav_path, sample_rate, audio_array)
108
+ # Converte para MP3
109
+ subprocess.run([
110
+ "ffmpeg", "-y", "-i", tmp_wav_path,
111
+ "-acodec", "libmp3lame", "-b:a", "192k",
112
+ str(file_path)
113
+ ], check=True, capture_output=True)
114
+ os.unlink(tmp_wav_path)
115
+ print(f" ✅ Gerado: {file_path.name}")
116
+
117
+ # ============================================================================
118
+ # GERAÇÃO DOS ARQUIVOS DE EXEMPLO
119
+ # ============================================================================
120
  def setup_examples():
121
  print("=" * 60)
122
+ print("🎵 Setting up RVC Full Suite Examples")
123
  print("=" * 60)
124
+
 
 
 
 
 
 
 
 
125
  # Criar diretórios
126
+ INPUTS_DIR.mkdir(parents=True, exist_ok=True)
127
+ OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)
128
+ print(f"📁 Criado: {INPUTS_DIR}")
129
+ print(f"📁 Criado: {OUTPUTS_DIR}")
130
+
131
+ # 1. Gerar áudio de entrada (voz simulada)
132
+ print("\n🎤 Gerando áudio de entrada (sample_audio.wav)...")
133
+ voice_audio = generate_voice_like(DURATION_SEC, SAMPLE_RATE)
134
+ input_wav = INPUTS_DIR / "sample_audio.wav"
135
+ write_wav(str(input_wav), SAMPLE_RATE, voice_audio)
136
+ print(f" ✅ Criado: {input_wav.name}")
137
+
138
+ # 2. Gerar vídeo de exemplo com este áudio
139
+ print("\n🎬 Gerando vídeo de exemplo (sample_video.mp4)...")
140
+ video_path = INPUTS_DIR / "sample_video.mp4"
141
+ # Cria um clipe de vídeo com cor sólida e o áudio gerado
142
+ from moviepy.video.VideoClip import ColorClip
143
+ from moviepy.audio.AudioClip import AudioArrayClip
144
+ audio_clip = AudioArrayClip(voice_audio, fps=SAMPLE_RATE)
145
+ video_clip = ColorClip(size=(640, 480), color=(50, 100, 150), duration=DURATION_SEC)
146
+ video_clip = video_clip.with_audio(audio_clip)
147
+ video_clip.write_videofile(str(video_path), fps=24, logger=None, verbose=False)
148
+ print(f" ✅ Criado: {video_path.name}")
149
+
150
+ # 3. Gerar os 5 arquivos de saída sintéticos (simulam resultado do pipeline)
151
+ print("\n📦 Gerando 5 arquivos de saída sintéticos (placeholders)...")
152
+ # a) entrada.mp3 - o mesmo áudio original
153
+ entrada_mp3 = OUTPUTS_DIR / "entrada.mp3"
154
+ save_audio(entrada_mp3, voice_audio)
155
+
156
+ # b) entrada_acapella.mp3 - versão filtrada (voz mais isolada)
157
+ # Simula um acapella (apenas a voz, sem instrumental)
158
+ save_audio(OUTPUTS_DIR / "entrada_acapella.mp3", voice_audio)
159
+
160
+ # c) entrada_instrumental.mp3 - instrumental sintético
161
+ instrumental = generate_instrumental(DURATION_SEC, SAMPLE_RATE)
162
+ save_audio(OUTPUTS_DIR / "entrada_instrumental.mp3", instrumental)
163
+
164
+ # d) saida.mp3 - RVC sobre original (simula conversão com pitch shift)
165
+ # Aplica um pitch shift simples: estica o sinal (exemplo)
166
+ from scipy import signal
167
+ stretched = signal.resample(voice_audio, int(len(voice_audio) * 1.2)) # +3 semitons aprox
168
+ save_audio(OUTPUTS_DIR / "saida.mp3", stretched[:len(voice_audio)])
169
+
170
+ # e) saida_acapella.mp3 - RVC sobre acapella
171
+ # Mesmo tratamento
172
+ stretched_acap = signal.resample(voice_audio, int(len(voice_audio) * 1.2))
173
+ save_audio(OUTPUTS_DIR / "saida_acapella.mp3", stretched_acap[:len(voice_audio)])
174
+
175
+ # 4. (Opcional) Executar pipeline real se houver modelos RVC disponíveis
176
+ print("\n⚠️ Nota: Os arquivos gerados são SINTÉTICOS (placeholders).")
177
+ print(" Para gerar exemplos REAIS com RVC, descomente a seção abaixo")
178
+ print(" e certifique-se de ter um modelo carregado e o ffmpeg instalado.\n")
179
+
180
+ # Exemplo de como chamar o pipeline real (comentado):
181
+ """
182
+ from lib.jobs import submit_full_pipeline
183
+ from lib.config import MODELS_DIR
184
+
185
+ # Verifica se há pelo menos um modelo
186
+ models = list_models()
187
+ if models:
188
+ print("🎛️ Executando pipeline real com o primeiro modelo disponível...")
189
+ status, acap, orig, instr, saida, saida_acap = submit_full_pipeline(
190
+ video_file=None,
191
+ audio_mic=None,
192
+ audio_file=str(input_wav),
193
+ model=models[0],
194
+ pitch=0,
195
+ f0_method="rmvpe",
196
+ index_rate=0.75,
197
+ protect=0.5,
198
+ vol_env=0.25,
199
+ clean_cb=False,
200
+ clean_strength=0.5,
201
+ split_cb=False,
202
+ autotune_cb=False,
203
+ autotune_strength=1.0,
204
+ filter_radius=3,
205
+ output_format="MP3",
206
+ reverb_cb=False,
207
+ reverb_room=0.15,
208
+ reverb_damp=0.7,
209
+ reverb_wet=0.15,
210
  )
211
+ # Copia os resultados para OUTPUTS_DIR
212
+ import shutil
213
+ for src, dst_name in [(orig, "entrada.mp3"), (acap, "entrada_acapella.mp3"),
214
+ (instr, "entrada_instrumental.mp3"), (saida, "saida.mp3"),
215
+ (saida_acap, "saida_acapella.mp3")]:
216
+ if src and Path(src).exists():
217
+ shutil.copy2(src, OUTPUTS_DIR / dst_name)
218
+ print("✅ Exemplos reais gerados com sucesso!")
219
+ else:
220
+ print("⚠️ Nenhum modelo RVC encontrado. Pulando geração real.")
221
+ """
222
+
223
+ print("=" * 60)
224
+ print(" Setup concluído!")
225
+ print(f"📁 Arquivos de exemplo disponíveis em: {EXAMPLES_DIR}")
226
+ print(" - sample_inputs/ (áudio e vídeo de entrada)")
227
+ print(" - sample_outputs/ (5 arquivos de saída sintéticos)")
228
  print("=" * 60)
229
+
230
  return True
231
 
232
  if __name__ == "__main__":