RaiSantos commited on
Commit
596d0fe
·
verified ·
1 Parent(s): d70f87b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -52
app.py CHANGED
@@ -89,13 +89,16 @@ corretor_disponivel = False
89
 
90
  def get_system_info():
91
  """Retorna informações do sistema"""
92
- if torch.cuda.is_available():
93
- gpu_name = torch.cuda.get_device_name(0)
94
- gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
95
- return f"{gpu_name} ({gpu_memory:.1f}GB)"
96
- else:
97
- ram = psutil.virtual_memory().total / 1024**3
98
- return f"CPU ({ram:.1f}GB RAM)"
 
 
 
99
 
100
  def inicializar_modelos(modelo_selecionado, progress=gr.Progress()):
101
  """Inicializa os modelos necessários"""
@@ -108,30 +111,43 @@ def inicializar_modelos(modelo_selecionado, progress=gr.Progress()):
108
 
109
  # Carregar WhisperX se não estiver em cache
110
  if modelo_selecionado not in whisper_models:
111
- whisper_models[modelo_selecionado] = whisperx.load_model(
112
- modelo_selecionado,
113
- device,
114
- compute_type=compute_type,
115
- language=LANGUAGE,
116
- asr_options={
117
- "beam_size": config["beam_size"],
118
- "best_of": config["best_of"],
119
- "temperature": config["temperature"],
120
- "condition_on_previous_text": True,
121
- "word_timestamps": True,
122
- "prepend_punctuations": "\"'"¿([{-",
123
- "append_punctuations": "\"'.。,,!!??::")]}、",
124
- "vad_filter": True,
125
- "vad_parameters": dict(min_silence_duration_ms=500)
126
- }
127
- )
 
 
 
 
 
 
 
 
 
128
 
129
  progress(0.3, desc="🎯 Carregando alinhamento temporal...")
130
  if align_model is None:
131
- align_model, metadata = whisperx.load_align_model(
132
- language_code=LANGUAGE,
133
- device=device
134
- )
 
 
 
 
135
 
136
  progress(0.5, desc="📝 Carregando corretor PTT5...")
137
  if not corretor_disponivel:
@@ -227,16 +243,29 @@ def processar_audio(audio_file, modelo_selecionado, progress=gr.Progress()):
227
  progress(0.6, desc="🎯 Alinhamento temporal de precisão...")
228
 
229
  # Alinhamento com configurações para VSL
230
- aligned = whisperx.align(
231
- result["segments"],
232
- align_model,
233
- metadata,
234
- audio,
235
- device,
236
- return_char_alignments=False,
237
- interpolate_method="linear",
238
- extend_duration=0.1
239
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
  progress(0.8, desc="📝 Aplicando correções para VSL...")
242
 
@@ -458,7 +487,10 @@ def criar_interface():
458
  )
459
 
460
  # Sistema info
461
- system_info_display = gr.Markdown(f"🖥️ **Sistema:** {get_system_info()}")
 
 
 
462
 
463
  # Atualizar info do modelo
464
  def atualizar_info_modelo(modelo):
@@ -527,16 +559,27 @@ def criar_interface():
527
 
528
  # === EXECUÇÃO ===
529
  if __name__ == "__main__":
530
- print("🎤 Transcritor VSL Pro - WhisperX")
531
- print(f"🖥️ Sistema: {get_system_info()}")
532
- print("🎯 Otimizado para VSL de até 15 minutos")
533
-
534
- demo = criar_interface()
535
- demo.launch(
536
- server_name="0.0.0.0",
537
- server_port=7860,
538
- share=False,
539
- show_error=True,
540
- quiet=False,
541
- show_tips=True
542
- )
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def get_system_info():
91
  """Retorna informações do sistema"""
92
+ try:
93
+ if torch.cuda.is_available():
94
+ gpu_name = torch.cuda.get_device_name(0)
95
+ gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
96
+ return f"{gpu_name} ({gpu_memory:.1f}GB)"
97
+ else:
98
+ ram = psutil.virtual_memory().total / 1024**3
99
+ return f"CPU ({ram:.1f}GB RAM)"
100
+ except:
101
+ return "Sistema não identificado"
102
 
103
  def inicializar_modelos(modelo_selecionado, progress=gr.Progress()):
104
  """Inicializa os modelos necessários"""
 
111
 
112
  # Carregar WhisperX se não estiver em cache
113
  if modelo_selecionado not in whisper_models:
114
+ try:
115
+ whisper_models[modelo_selecionado] = whisperx.load_model(
116
+ modelo_selecionado,
117
+ device,
118
+ compute_type=compute_type,
119
+ language=LANGUAGE,
120
+ asr_options={
121
+ "beam_size": config["beam_size"],
122
+ "best_of": config["best_of"],
123
+ "temperature": config["temperature"],
124
+ "condition_on_previous_text": True,
125
+ "word_timestamps": True,
126
+ "prepend_punctuations": "\"'([{-",
127
+ "append_punctuations": "\"'.,:!?)]}-",
128
+ "vad_filter": True,
129
+ "vad_parameters": dict(min_silence_duration_ms=500)
130
+ }
131
+ )
132
+ except Exception as model_error:
133
+ # Fallback sem opções avançadas se der erro
134
+ whisper_models[modelo_selecionado] = whisperx.load_model(
135
+ modelo_selecionado,
136
+ device,
137
+ compute_type=compute_type,
138
+ language=LANGUAGE
139
+ )
140
 
141
  progress(0.3, desc="🎯 Carregando alinhamento temporal...")
142
  if align_model is None:
143
+ try:
144
+ align_model, metadata = whisperx.load_align_model(
145
+ language_code=LANGUAGE,
146
+ device=device
147
+ )
148
+ except Exception as align_error:
149
+ print(f"Erro no alinhamento: {align_error}")
150
+ return f"❌ Erro ao carregar modelo de alinhamento: {str(align_error)}"
151
 
152
  progress(0.5, desc="📝 Carregando corretor PTT5...")
153
  if not corretor_disponivel:
 
243
  progress(0.6, desc="🎯 Alinhamento temporal de precisão...")
244
 
245
  # Alinhamento com configurações para VSL
246
+ try:
247
+ aligned = whisperx.align(
248
+ result["segments"],
249
+ align_model,
250
+ metadata,
251
+ audio,
252
+ device,
253
+ return_char_alignments=False,
254
+ interpolate_method="linear"
255
+ )
256
+ except Exception as align_error:
257
+ print(f"Erro no alinhamento: {align_error}")
258
+ # Fallback: usar segmentos originais sem alinhamento fino
259
+ aligned = {"word_segments": []}
260
+ for segment in result.get("segments", []):
261
+ if "words" in segment:
262
+ for word in segment["words"]:
263
+ aligned["word_segments"].append({
264
+ "word": word.get("word", ""),
265
+ "start": word.get("start", 0),
266
+ "end": word.get("end", 0),
267
+ "score": word.get("probability", 0.5)
268
+ })
269
 
270
  progress(0.8, desc="📝 Aplicando correções para VSL...")
271
 
 
487
  )
488
 
489
  # Sistema info
490
+ try:
491
+ system_info_display = gr.Markdown(f"🖥️ **Sistema:** {get_system_info()}")
492
+ except:
493
+ system_info_display = gr.Markdown("🖥️ **Sistema:** Carregando...")
494
 
495
  # Atualizar info do modelo
496
  def atualizar_info_modelo(modelo):
 
559
 
560
  # === EXECUÇÃO ===
561
  if __name__ == "__main__":
562
+ try:
563
+ print("🎤 Transcritor VSL Pro - WhisperX")
564
+ print(f"🖥️ Sistema: {get_system_info()}")
565
+ print("🎯 Otimizado para VSL de até 15 minutos")
566
+
567
+ demo = criar_interface()
568
+ demo.launch(
569
+ server_name="0.0.0.0",
570
+ server_port=7860,
571
+ share=False,
572
+ show_error=True,
573
+ quiet=False,
574
+ show_tips=True
575
+ )
576
+ except Exception as e:
577
+ print(f"Erro na inicialização: {e}")
578
+ # Fallback simples
579
+ demo = gr.Interface(
580
+ fn=lambda x: "Sistema em manutenção",
581
+ inputs=gr.Audio(),
582
+ outputs=gr.Textbox(),
583
+ title="🎤 Transcritor VSL Pro"
584
+ )
585
+ demo.launch()