Spaces:
Runtime error
Runtime error
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,116 +0,0 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
|
| 3 |
-
import os
|
| 4 |
-
import zipfile
|
| 5 |
-
from tqdm import tqdm
|
| 6 |
-
from faster_whisper import WhisperModel
|
| 7 |
-
from datetime import timedelta
|
| 8 |
-
import srt
|
| 9 |
-
from transformers import pipeline
|
| 10 |
-
import torch
|
| 11 |
-
import gradio as gr
|
| 12 |
-
|
| 13 |
-
# --- CONFIGURAÇÕES GERAIS E INICIALIZAÇÃO ---
|
| 14 |
-
|
| 15 |
-
# Diretórios para organizar os arquivos
|
| 16 |
-
OUTPUT_DIR = "outputs"
|
| 17 |
-
LEGENDAS_DIR = os.path.join(OUTPUT_DIR, "legendas")
|
| 18 |
-
os.makedirs(LEGENDAS_DIR, exist_ok=True)
|
| 19 |
-
|
| 20 |
-
# Dicionário de idiomas
|
| 21 |
-
IDIOMAS = {
|
| 22 |
-
"Alemão": "de", "Cebuano": "ceb", "Chinês": "zh", "Coreano": "ko",
|
| 23 |
-
"Espanhol": "es", "Francês": "fr", "Inglês": "en", "Italiano": "it",
|
| 24 |
-
"Japonês": "ja", "Português": "pt", "Russo": "ru", "Tagalog": "tl"
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
# --- CARREGAMENTO PESADO DOS MODELOS ---
|
| 28 |
-
print("Carregando modelos de IA... Este processo acontece uma vez quando a aplicação inicia.")
|
| 29 |
-
|
| 30 |
-
try:
|
| 31 |
-
# AJUSTE: Usando um modelo menor e mais eficiente para o servidor gratuito
|
| 32 |
-
MODELO_WHISPER = "medium"
|
| 33 |
-
|
| 34 |
-
# Otimização para usar CPU, que é o padrão em servidores gratuitos
|
| 35 |
-
device = "cpu"
|
| 36 |
-
compute_type = "int8"
|
| 37 |
-
|
| 38 |
-
model_whisper = WhisperModel(MODELO_WHISPER, device=device, compute_type=compute_type)
|
| 39 |
-
model_translator = pipeline("translation", model="facebook/m2m100_418M")
|
| 40 |
-
print("Modelos carregados com sucesso!")
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"Erro ao carregar os modelos: {e}")
|
| 43 |
-
model_whisper = None
|
| 44 |
-
model_translator = None
|
| 45 |
-
|
| 46 |
-
# --- FUNÇÃO PRINCIPAL DA INTERFACE ---
|
| 47 |
-
def gerar_legenda_interface(arquivos_path, idioma_origem, idioma_destino, progresso=gr.Progress(track_tqdm=True)):
|
| 48 |
-
if not arquivos_path:
|
| 49 |
-
raise gr.Error("Por favor, envie pelo menos um arquivo de vídeo ou áudio.")
|
| 50 |
-
if not idioma_origem or not idioma_destino:
|
| 51 |
-
raise gr.Error("Por favor, selecione o idioma de origem e o idioma da legenda.")
|
| 52 |
-
|
| 53 |
-
lang_origem_code = IDIOMAS[idioma_origem]
|
| 54 |
-
lang_destino_code = IDIOMAS[idioma_destino]
|
| 55 |
-
|
| 56 |
-
if os.path.exists(LEGENDAS_DIR):
|
| 57 |
-
for f in os.listdir(LEGENDAS_DIR):
|
| 58 |
-
os.remove(os.path.join(LEGENDAS_DIR, f))
|
| 59 |
-
|
| 60 |
-
for caminho_video in tqdm(arquivos_path, desc="Processando arquivos"):
|
| 61 |
-
nome_base = os.path.splitext(os.path.basename(caminho_video))[0]
|
| 62 |
-
# Adicionado log_progress=False para compatibilidade
|
| 63 |
-
segmentos, _ = model_whisper.transcribe(caminho_video, language=lang_origem_code, beam_size=5, log_progress=False)
|
| 64 |
-
|
| 65 |
-
segmentos_lista = list(segmentos)
|
| 66 |
-
textos_originais = [seg.text.strip() for seg in segmentos_lista]
|
| 67 |
-
|
| 68 |
-
if lang_origem_code != lang_destino_code:
|
| 69 |
-
textos_finais = model_translator(textos_originais, src_lang=lang_origem_code, tgt_lang=lang_destino_code)
|
| 70 |
-
textos_finais = [t['translation_text'] for t in textos_finais]
|
| 71 |
-
else:
|
| 72 |
-
textos_finais = textos_originais
|
| 73 |
-
|
| 74 |
-
legendas = []
|
| 75 |
-
for i, seg in enumerate(segmentos_lista):
|
| 76 |
-
legenda = srt.Subtitle(
|
| 77 |
-
index=i + 1,
|
| 78 |
-
start=timedelta(seconds=seg.start),
|
| 79 |
-
end=timedelta(seconds=seg.end),
|
| 80 |
-
content=textos_finais[i]
|
| 81 |
-
)
|
| 82 |
-
legendas.append(legenda)
|
| 83 |
-
|
| 84 |
-
nome_srt = f"{nome_base}_{lang_destino_code}.srt"
|
| 85 |
-
caminho_srt = os.path.join(LEGENDAS_DIR, nome_srt)
|
| 86 |
-
with open(caminho_srt, "w", encoding="utf-8") as f:
|
| 87 |
-
f.write(srt.compose(legendas))
|
| 88 |
-
|
| 89 |
-
zip_path = os.path.join(OUTPUT_DIR, "legendas_geradas.zip")
|
| 90 |
-
with zipfile.ZipFile(zip_path, 'w') as zipf:
|
| 91 |
-
for file in os.listdir(LEGENDAS_DIR):
|
| 92 |
-
zipf.write(os.path.join(LEGENDAS_DIR, file), arcname=file)
|
| 93 |
-
|
| 94 |
-
return zip_path
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
# --- CONSTRUÇÃO DA INTERFACE GRÁFICA ---
|
| 98 |
-
with gr.Blocks(theme=gr.themes.Default(), title="Gerador de Legendas") as interface:
|
| 99 |
-
gr.Markdown("# 🎬 Gerador Automático de Legendas e Traduções")
|
| 100 |
-
|
| 101 |
-
with gr.Row():
|
| 102 |
-
with gr.Column(scale=1):
|
| 103 |
-
input_arquivos = gr.File(label="1. Envie seus arquivos de vídeo ou áudio", file_count="multiple", type="filepath")
|
| 104 |
-
input_idioma_origem = gr.Dropdown(choices=sorted(list(IDIOMAS.keys())), label="2. Idioma original do áudio", value="Inglês")
|
| 105 |
-
input_idioma_destino = gr.Dropdown(choices=sorted(list(IDIOMAS.keys())), label="3. Idioma desejado para a legenda", value="Português")
|
| 106 |
-
botao_gerar = gr.Button("✨ Gerar Legendas!", variant="primary")
|
| 107 |
-
with gr.Column(scale=1):
|
| 108 |
-
output_legenda = gr.File(label="Resultado para Download (Arquivo .ZIP)", interactive=False)
|
| 109 |
-
|
| 110 |
-
botao_gerar.click(
|
| 111 |
-
fn=gerar_legenda_interface,
|
| 112 |
-
inputs=[input_arquivos, input_idioma_origem, input_idioma_destino],
|
| 113 |
-
outputs=[output_legenda]
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|