Update app_hf.py
Browse files
app_hf.py
CHANGED
|
@@ -1,357 +1,357 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import os
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
import subprocess
|
| 5 |
-
import asyncio
|
| 6 |
-
import threading
|
| 7 |
-
import signal
|
| 8 |
-
import sys
|
| 9 |
-
import re
|
| 10 |
-
import shutil
|
| 11 |
-
from typing import Optional, List, Tuple
|
| 12 |
-
from i18n.i18n import I18nAuto
|
| 13 |
-
from header import badges, description
|
| 14 |
-
i18n = I18nAuto()
|
| 15 |
-
|
| 16 |
-
# Variável global para armazenar o processo atual
|
| 17 |
-
current_process: Optional[subprocess.Popen] = None
|
| 18 |
-
|
| 19 |
-
# Força o uso de UTF-8 para o Python
|
| 20 |
-
os.environ["PYTHONIOENCODING"] = "utf-8"
|
| 21 |
-
|
| 22 |
-
# Para garantir que a codificação esteja correta no terminal
|
| 23 |
-
if sys.platform == "win32":
|
| 24 |
-
os.system('chcp 65001')
|
| 25 |
-
|
| 26 |
-
# Redefine a configuração de codificação da saída padrão
|
| 27 |
-
sys.stdout.reconfigure(encoding='utf-8')
|
| 28 |
-
sys.stderr.reconfigure(encoding='utf-8')
|
| 29 |
-
|
| 30 |
-
# Criar diretórios necessários se não existirem
|
| 31 |
-
def ensure_directories():
|
| 32 |
-
directories = ['uploaded_videos', 'softsubs_output', 'hardsubs_output']
|
| 33 |
-
for directory in directories:
|
| 34 |
-
os.makedirs(os.path.join(os.getcwd(), directory), exist_ok=True)
|
| 35 |
-
return os.path.join(os.getcwd(), 'uploaded_videos')
|
| 36 |
-
|
| 37 |
-
def save_uploaded_files(files):
|
| 38 |
-
"""Salva os arquivos enviados na pasta uploaded_videos"""
|
| 39 |
-
if not files:
|
| 40 |
-
return "No files uploaded"
|
| 41 |
-
|
| 42 |
-
upload_dir = ensure_directories()
|
| 43 |
-
saved_files = []
|
| 44 |
-
|
| 45 |
-
for file in files:
|
| 46 |
-
filename = os.path.basename(file.name)
|
| 47 |
-
destination = os.path.join(upload_dir, filename)
|
| 48 |
-
shutil.copy2(file.name, destination)
|
| 49 |
-
saved_files.append(filename)
|
| 50 |
-
|
| 51 |
-
return f"Uploaded files: {', '.join(saved_files)}"
|
| 52 |
-
|
| 53 |
-
def get_output_files() -> Tuple[List[str], List[str]]:
|
| 54 |
-
"""Retorna listas de arquivos nas pastas de saída"""
|
| 55 |
-
softsubs_dir = os.path.join(os.getcwd(), 'softsubs_output')
|
| 56 |
-
hardsubs_dir = os.path.join(os.getcwd(), 'hardsubs_output')
|
| 57 |
-
|
| 58 |
-
softsubs_files = [os.path.join(softsubs_dir, f) for f in os.listdir(softsubs_dir) if os.path.isfile(os.path.join(softsubs_dir, f))]
|
| 59 |
-
hardsubs_files = [os.path.join(hardsubs_dir, f) for f in os.listdir(hardsubs_dir) if os.path.isfile(os.path.join(hardsubs_dir, f))]
|
| 60 |
-
|
| 61 |
-
return softsubs_files, hardsubs_files
|
| 62 |
-
|
| 63 |
-
def clean_ansi(text: str) -> str:
|
| 64 |
-
"""Remove códigos ANSI e limpa o texto para exibição"""
|
| 65 |
-
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
| 66 |
-
return ansi_escape.sub('', text)
|
| 67 |
-
|
| 68 |
-
def process_output(line: str, progress: gr.Progress) -> str:
|
| 69 |
-
"""Processa uma linha de saída e atualiza o progresso"""
|
| 70 |
-
clean_line = clean_ansi(line.strip())
|
| 71 |
-
|
| 72 |
-
if "%" in clean_line:
|
| 73 |
-
try:
|
| 74 |
-
progress_match = re.search(r'(\d+\.?\d*)%', clean_line)
|
| 75 |
-
if progress_match:
|
| 76 |
-
progress_value = float(progress_match.group(1)) / 100
|
| 77 |
-
progress(progress_value, desc=clean_line)
|
| 78 |
-
except ValueError:
|
| 79 |
-
pass
|
| 80 |
-
|
| 81 |
-
return clean_line
|
| 82 |
-
|
| 83 |
-
def stop_process():
|
| 84 |
-
global current_process
|
| 85 |
-
if current_process:
|
| 86 |
-
try:
|
| 87 |
-
if os.name == 'nt':
|
| 88 |
-
current_process.terminate()
|
| 89 |
-
else:
|
| 90 |
-
os.killpg(os.getpgid(current_process.pid), signal.SIGTERM)
|
| 91 |
-
current_process.wait(timeout=5)
|
| 92 |
-
except subprocess.TimeoutExpired:
|
| 93 |
-
if os.name == 'nt':
|
| 94 |
-
current_process.kill()
|
| 95 |
-
else:
|
| 96 |
-
os.killpg(os.getpgid(current_process.pid), signal.SIGKILL)
|
| 97 |
-
current_process = None
|
| 98 |
-
return "Process stopped by user"
|
| 99 |
-
return "No process running"
|
| 100 |
-
|
| 101 |
-
def run_legen(
|
| 102 |
-
transcription_engine,
|
| 103 |
-
transcription_model,
|
| 104 |
-
compute_type,
|
| 105 |
-
device,
|
| 106 |
-
batch_size,
|
| 107 |
-
input_lang,
|
| 108 |
-
translate_lang,
|
| 109 |
-
video_codec,
|
| 110 |
-
audio_codec,
|
| 111 |
-
normalize,
|
| 112 |
-
overwrite,
|
| 113 |
-
copy_files,
|
| 114 |
-
disable_srt,
|
| 115 |
-
disable_softsubs,
|
| 116 |
-
disable_hardsubs,
|
| 117 |
-
progress=gr.Progress()
|
| 118 |
-
):
|
| 119 |
-
global current_process
|
| 120 |
-
|
| 121 |
-
input_dir = ensure_directories()
|
| 122 |
-
if not os.path.exists(input_dir) or not os.listdir(input_dir):
|
| 123 |
-
return "No files found in uploaded_videos directory"
|
| 124 |
-
|
| 125 |
-
if not os.path.exists("legen.py"):
|
| 126 |
-
return "legen.py not found in current directory"
|
| 127 |
-
|
| 128 |
-
cmd = ["python", "legen.py", "-i", input_dir]
|
| 129 |
-
|
| 130 |
-
# Adiciona as flags baseadas nos checkboxes
|
| 131 |
-
if normalize: cmd.append("--norm")
|
| 132 |
-
if overwrite: cmd.append("--overwrite")
|
| 133 |
-
if copy_files: cmd.append("--copy_files")
|
| 134 |
-
if disable_srt: cmd.append("--disable_srt")
|
| 135 |
-
if disable_softsubs: cmd.append("--disable_softsubs")
|
| 136 |
-
if disable_hardsubs: cmd.append("--disable_hardsubs")
|
| 137 |
-
|
| 138 |
-
# Adiciona configurações de transcrição
|
| 139 |
-
cmd.extend(["-ts:e", transcription_engine])
|
| 140 |
-
cmd.extend(["-ts:m", transcription_model])
|
| 141 |
-
cmd.extend(["-ts:d", device])
|
| 142 |
-
cmd.extend(["-ts:c", compute_type])
|
| 143 |
-
cmd.extend(["-ts:b", str(batch_size)])
|
| 144 |
-
|
| 145 |
-
if translate_lang != "none":
|
| 146 |
-
cmd.extend(["--translate", translate_lang])
|
| 147 |
-
if input_lang != "auto":
|
| 148 |
-
cmd.extend(["--input_lang", input_lang])
|
| 149 |
-
|
| 150 |
-
# Adiciona configurações de codec
|
| 151 |
-
cmd.extend(["-c:v", video_codec])
|
| 152 |
-
cmd.extend(["-c:a", audio_codec])
|
| 153 |
-
|
| 154 |
-
# Adiciona caminhos de saída fixos
|
| 155 |
-
cmd.extend(["-o:s", os.path.join(os.getcwd(), "softsubs_output")])
|
| 156 |
-
cmd.extend(["-o:h", os.path.join(os.getcwd(), "hardsubs_output")])
|
| 157 |
-
|
| 158 |
-
try:
|
| 159 |
-
startupinfo = None
|
| 160 |
-
if os.name == 'nt':
|
| 161 |
-
startupinfo = subprocess.STARTUPINFO()
|
| 162 |
-
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
| 163 |
-
|
| 164 |
-
current_process = subprocess.Popen(
|
| 165 |
-
cmd,
|
| 166 |
-
stdout=subprocess.PIPE,
|
| 167 |
-
stderr=subprocess.STDOUT,
|
| 168 |
-
text=True,
|
| 169 |
-
bufsize=1,
|
| 170 |
-
universal_newlines=True,
|
| 171 |
-
startupinfo=startupinfo,
|
| 172 |
-
encoding='utf-8',
|
| 173 |
-
errors='replace',
|
| 174 |
-
preexec_fn=None if os.name == 'nt' else os.setsid
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
output_lines: List[str] = []
|
| 178 |
-
last_progress_update = 0
|
| 179 |
-
|
| 180 |
-
while True:
|
| 181 |
-
line = current_process.stdout.readline()
|
| 182 |
-
|
| 183 |
-
if not line and current_process.poll() is not None:
|
| 184 |
-
break
|
| 185 |
-
|
| 186 |
-
if line:
|
| 187 |
-
try:
|
| 188 |
-
clean_line = process_output(line, progress)
|
| 189 |
-
output_lines.append(clean_line)
|
| 190 |
-
|
| 191 |
-
if len(output_lines) - last_progress_update >= 5:
|
| 192 |
-
yield "\n".join(output_lines)
|
| 193 |
-
last_progress_update = len(output_lines)
|
| 194 |
-
|
| 195 |
-
except Exception as e:
|
| 196 |
-
output_lines.append(f"Error processing output: {str(e)}")
|
| 197 |
-
|
| 198 |
-
if current_process.poll() == 0:
|
| 199 |
-
final_output = "Processing completed successfully!\n\n" + "\n".join(output_lines)
|
| 200 |
-
else:
|
| 201 |
-
final_output = f"Process ended with error code {current_process.poll()}\n\n" + "\n".join(output_lines)
|
| 202 |
-
|
| 203 |
-
current_process = None
|
| 204 |
-
return final_output
|
| 205 |
-
|
| 206 |
-
except Exception as e:
|
| 207 |
-
current_process = None
|
| 208 |
-
return f"Error: {str(e)}"
|
| 209 |
-
|
| 210 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 211 |
-
gr.Markdown(badges)
|
| 212 |
-
gr.Markdown(description)
|
| 213 |
-
title = "LeGen"
|
| 214 |
-
|
| 215 |
-
ensure_directories() # Garante que os diretórios existam ao iniciar
|
| 216 |
-
|
| 217 |
-
with gr.Row():
|
| 218 |
-
with gr.Column(scale=1):
|
| 219 |
-
# Upload Section
|
| 220 |
-
with gr.Group():
|
| 221 |
-
upload_files = gr.Files(
|
| 222 |
-
label=i18n("Upload Videos"),
|
| 223 |
-
file_types=["video"],
|
| 224 |
-
file_count="multiple"
|
| 225 |
-
)
|
| 226 |
-
upload_button = gr.Button(i18n("Upload to processing directory"))
|
| 227 |
-
|
| 228 |
-
# Transcription Settings
|
| 229 |
-
with gr.Group():
|
| 230 |
-
transcription_engine = gr.Dropdown(
|
| 231 |
-
choices=["whisperx", "whisper"],
|
| 232 |
-
value="whisperx",
|
| 233 |
-
label=i18n("Transcription Engine")
|
| 234 |
-
)
|
| 235 |
-
with gr.Row():
|
| 236 |
-
transcription_model = gr.Dropdown(
|
| 237 |
-
choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo"],
|
| 238 |
-
value="large-v3",
|
| 239 |
-
label=i18n("Model")
|
| 240 |
-
)
|
| 241 |
-
compute_type = gr.Dropdown(
|
| 242 |
-
choices=["auto", "int8", "float16", "float32"],
|
| 243 |
-
value="auto",
|
| 244 |
-
label=i18n("Compute Type")
|
| 245 |
-
)
|
| 246 |
-
with gr.Row():
|
| 247 |
-
device = gr.Dropdown(
|
| 248 |
-
choices=["auto", "cpu", "cuda"],
|
| 249 |
-
value="auto",
|
| 250 |
-
label=i18n("Device")
|
| 251 |
-
)
|
| 252 |
-
batch_size = gr.Number(
|
| 253 |
-
value=4,
|
| 254 |
-
label=i18n("Batch Size"),
|
| 255 |
-
precision=0
|
| 256 |
-
)
|
| 257 |
-
with gr.Row():
|
| 258 |
-
input_lang = gr.Dropdown(
|
| 259 |
-
choices=["auto", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
|
| 260 |
-
value="auto",
|
| 261 |
-
label=i18n("Input Language")
|
| 262 |
-
)
|
| 263 |
-
translate_lang = gr.Dropdown(
|
| 264 |
-
choices=["none", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
|
| 265 |
-
value="none",
|
| 266 |
-
label=i18n("Translate to")
|
| 267 |
-
)
|
| 268 |
-
|
| 269 |
-
with gr.Column(scale=1):
|
| 270 |
-
# Output Settings
|
| 271 |
-
with gr.Group():
|
| 272 |
-
with gr.Row():
|
| 273 |
-
video_codec = gr.Dropdown(
|
| 274 |
-
choices=["h264", "libx264", "h264_vaapi", "h264_nvenc", "hevc", "libx265", "hevc_vaapi"],
|
| 275 |
-
value="h264",
|
| 276 |
-
label=i18n("Video Codec")
|
| 277 |
-
)
|
| 278 |
-
audio_codec = gr.Dropdown(
|
| 279 |
-
choices=["aac", "libopus", "mp3", "vorbis"],
|
| 280 |
-
value="aac",
|
| 281 |
-
label=i18n("Audio Codec")
|
| 282 |
-
)
|
| 283 |
-
|
| 284 |
-
# Options
|
| 285 |
-
with gr.Group():
|
| 286 |
-
with gr.Row():
|
| 287 |
-
normalize = gr.Checkbox(label=i18n("Normalize folder times"), value=False)
|
| 288 |
-
overwrite = gr.Checkbox(label=i18n("Overwrite existing files"), value=False)
|
| 289 |
-
copy_files = gr.Checkbox(label=i18n("Copy non-video files"), value=False)
|
| 290 |
-
with gr.Row():
|
| 291 |
-
disable_srt = gr.Checkbox(label=i18n("Disable SRT generation"), value=False)
|
| 292 |
-
disable_softsubs = gr.Checkbox(label=i18n("Disable softsubs"), value=False)
|
| 293 |
-
disable_hardsubs = gr.Checkbox(label=i18n("Disable hardsubs"), value=False)
|
| 294 |
-
|
| 295 |
-
# Output Files Display
|
| 296 |
-
with gr.Group():
|
| 297 |
-
softsubs_files = gr.Files(label="Softsubs Output Files", file_count="multiple", interactive=False)
|
| 298 |
-
hardsubs_files = gr.Files(label="Hardsubs Output Files", file_count="multiple", interactive=False)
|
| 299 |
-
|
| 300 |
-
# Run Button, Stop Button and Output
|
| 301 |
-
with gr.Row():
|
| 302 |
-
with gr.Column(scale=1):
|
| 303 |
-
run_btn = gr.Button(i18n("Run LeGen"), variant="primary")
|
| 304 |
-
stop_btn = gr.Button(i18n("Stop"), variant="stop")
|
| 305 |
-
output = gr.Textbox(label=i18n("Output"), lines=2, interactive=False, elem_id="output")
|
| 306 |
-
|
| 307 |
-
# Event handlers
|
| 308 |
-
upload_button.click(
|
| 309 |
-
fn=save_uploaded_files,
|
| 310 |
-
inputs=[upload_files],
|
| 311 |
-
outputs=[output]
|
| 312 |
-
)
|
| 313 |
-
|
| 314 |
-
def update_output_files():
|
| 315 |
-
softsubs_files, hardsubs_files = get_output_files()
|
| 316 |
-
return softsubs_files, hardsubs_files
|
| 317 |
-
|
| 318 |
-
# Connect the run button to the processing function
|
| 319 |
-
run_btn.click(
|
| 320 |
-
fn=run_legen,
|
| 321 |
-
inputs=[
|
| 322 |
-
transcription_engine,
|
| 323 |
-
transcription_model,
|
| 324 |
-
compute_type,
|
| 325 |
-
device,
|
| 326 |
-
batch_size,
|
| 327 |
-
input_lang,
|
| 328 |
-
translate_lang,
|
| 329 |
-
video_codec,
|
| 330 |
-
audio_codec,
|
| 331 |
-
normalize,
|
| 332 |
-
overwrite,
|
| 333 |
-
copy_files,
|
| 334 |
-
disable_srt,
|
| 335 |
-
disable_softsubs,
|
| 336 |
-
disable_hardsubs
|
| 337 |
-
],
|
| 338 |
-
outputs=output
|
| 339 |
-
).then(
|
| 340 |
-
fn=update_output_files,
|
| 341 |
-
inputs=[],
|
| 342 |
-
outputs=[softsubs_files, hardsubs_files]
|
| 343 |
-
)
|
| 344 |
-
|
| 345 |
-
stop_btn.click(
|
| 346 |
-
fn=stop_process,
|
| 347 |
-
inputs=[],
|
| 348 |
-
outputs=output
|
| 349 |
-
)
|
| 350 |
-
|
| 351 |
-
gr.Markdown("""
|
| 352 |
-
<center>WebUI Desenvolvida por Rafa.Godoy</center>
|
| 353 |
-
<center>Agradecimentos ao MatheusBach por desenvolver o LeGen</center>
|
| 354 |
-
""")
|
| 355 |
-
|
| 356 |
-
if __name__ == "__main__":
|
| 357 |
demo.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import subprocess
|
| 5 |
+
import asyncio
|
| 6 |
+
import threading
|
| 7 |
+
import signal
|
| 8 |
+
import sys
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
from typing import Optional, List, Tuple
|
| 12 |
+
from i18n.i18n import I18nAuto
|
| 13 |
+
from header import badges, description
|
| 14 |
+
i18n = I18nAuto()
|
| 15 |
+
|
| 16 |
+
# Variável global para armazenar o processo atual | ...
|
| 17 |
+
current_process: Optional[subprocess.Popen] = None
|
| 18 |
+
|
| 19 |
+
# Força o uso de UTF-8 para o Python
|
| 20 |
+
os.environ["PYTHONIOENCODING"] = "utf-8"
|
| 21 |
+
|
| 22 |
+
# Para garantir que a codificação esteja correta no terminal
|
| 23 |
+
if sys.platform == "win32":
|
| 24 |
+
os.system('chcp 65001')
|
| 25 |
+
|
| 26 |
+
# Redefine a configuração de codificação da saída padrão
|
| 27 |
+
sys.stdout.reconfigure(encoding='utf-8')
|
| 28 |
+
sys.stderr.reconfigure(encoding='utf-8')
|
| 29 |
+
|
| 30 |
+
# Criar diretórios necessários se não existirem
|
| 31 |
+
def ensure_directories():
|
| 32 |
+
directories = ['uploaded_videos', 'softsubs_output', 'hardsubs_output']
|
| 33 |
+
for directory in directories:
|
| 34 |
+
os.makedirs(os.path.join(os.getcwd(), directory), exist_ok=True)
|
| 35 |
+
return os.path.join(os.getcwd(), 'uploaded_videos')
|
| 36 |
+
|
| 37 |
+
def save_uploaded_files(files):
|
| 38 |
+
"""Salva os arquivos enviados na pasta uploaded_videos"""
|
| 39 |
+
if not files:
|
| 40 |
+
return "No files uploaded"
|
| 41 |
+
|
| 42 |
+
upload_dir = ensure_directories()
|
| 43 |
+
saved_files = []
|
| 44 |
+
|
| 45 |
+
for file in files:
|
| 46 |
+
filename = os.path.basename(file.name)
|
| 47 |
+
destination = os.path.join(upload_dir, filename)
|
| 48 |
+
shutil.copy2(file.name, destination)
|
| 49 |
+
saved_files.append(filename)
|
| 50 |
+
|
| 51 |
+
return f"Uploaded files: {', '.join(saved_files)}"
|
| 52 |
+
|
| 53 |
+
def get_output_files() -> Tuple[List[str], List[str]]:
|
| 54 |
+
"""Retorna listas de arquivos nas pastas de saída"""
|
| 55 |
+
softsubs_dir = os.path.join(os.getcwd(), 'softsubs_output')
|
| 56 |
+
hardsubs_dir = os.path.join(os.getcwd(), 'hardsubs_output')
|
| 57 |
+
|
| 58 |
+
softsubs_files = [os.path.join(softsubs_dir, f) for f in os.listdir(softsubs_dir) if os.path.isfile(os.path.join(softsubs_dir, f))]
|
| 59 |
+
hardsubs_files = [os.path.join(hardsubs_dir, f) for f in os.listdir(hardsubs_dir) if os.path.isfile(os.path.join(hardsubs_dir, f))]
|
| 60 |
+
|
| 61 |
+
return softsubs_files, hardsubs_files
|
| 62 |
+
|
| 63 |
+
def clean_ansi(text: str) -> str:
|
| 64 |
+
"""Remove códigos ANSI e limpa o texto para exibição"""
|
| 65 |
+
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
|
| 66 |
+
return ansi_escape.sub('', text)
|
| 67 |
+
|
| 68 |
+
def process_output(line: str, progress: gr.Progress) -> str:
|
| 69 |
+
"""Processa uma linha de saída e atualiza o progresso"""
|
| 70 |
+
clean_line = clean_ansi(line.strip())
|
| 71 |
+
|
| 72 |
+
if "%" in clean_line:
|
| 73 |
+
try:
|
| 74 |
+
progress_match = re.search(r'(\d+\.?\d*)%', clean_line)
|
| 75 |
+
if progress_match:
|
| 76 |
+
progress_value = float(progress_match.group(1)) / 100
|
| 77 |
+
progress(progress_value, desc=clean_line)
|
| 78 |
+
except ValueError:
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
return clean_line
|
| 82 |
+
|
| 83 |
+
def stop_process():
|
| 84 |
+
global current_process
|
| 85 |
+
if current_process:
|
| 86 |
+
try:
|
| 87 |
+
if os.name == 'nt':
|
| 88 |
+
current_process.terminate()
|
| 89 |
+
else:
|
| 90 |
+
os.killpg(os.getpgid(current_process.pid), signal.SIGTERM)
|
| 91 |
+
current_process.wait(timeout=5)
|
| 92 |
+
except subprocess.TimeoutExpired:
|
| 93 |
+
if os.name == 'nt':
|
| 94 |
+
current_process.kill()
|
| 95 |
+
else:
|
| 96 |
+
os.killpg(os.getpgid(current_process.pid), signal.SIGKILL)
|
| 97 |
+
current_process = None
|
| 98 |
+
return "Process stopped by user"
|
| 99 |
+
return "No process running"
|
| 100 |
+
|
| 101 |
+
def run_legen(
|
| 102 |
+
transcription_engine,
|
| 103 |
+
transcription_model,
|
| 104 |
+
compute_type,
|
| 105 |
+
device,
|
| 106 |
+
batch_size,
|
| 107 |
+
input_lang,
|
| 108 |
+
translate_lang,
|
| 109 |
+
video_codec,
|
| 110 |
+
audio_codec,
|
| 111 |
+
normalize,
|
| 112 |
+
overwrite,
|
| 113 |
+
copy_files,
|
| 114 |
+
disable_srt,
|
| 115 |
+
disable_softsubs,
|
| 116 |
+
disable_hardsubs,
|
| 117 |
+
progress=gr.Progress()
|
| 118 |
+
):
|
| 119 |
+
global current_process
|
| 120 |
+
|
| 121 |
+
input_dir = ensure_directories()
|
| 122 |
+
if not os.path.exists(input_dir) or not os.listdir(input_dir):
|
| 123 |
+
return "No files found in uploaded_videos directory"
|
| 124 |
+
|
| 125 |
+
if not os.path.exists("legen.py"):
|
| 126 |
+
return "legen.py not found in current directory"
|
| 127 |
+
|
| 128 |
+
cmd = ["python", "legen.py", "-i", input_dir]
|
| 129 |
+
|
| 130 |
+
# Adiciona as flags baseadas nos checkboxes
|
| 131 |
+
if normalize: cmd.append("--norm")
|
| 132 |
+
if overwrite: cmd.append("--overwrite")
|
| 133 |
+
if copy_files: cmd.append("--copy_files")
|
| 134 |
+
if disable_srt: cmd.append("--disable_srt")
|
| 135 |
+
if disable_softsubs: cmd.append("--disable_softsubs")
|
| 136 |
+
if disable_hardsubs: cmd.append("--disable_hardsubs")
|
| 137 |
+
|
| 138 |
+
# Adiciona configurações de transcrição
|
| 139 |
+
cmd.extend(["-ts:e", transcription_engine])
|
| 140 |
+
cmd.extend(["-ts:m", transcription_model])
|
| 141 |
+
cmd.extend(["-ts:d", device])
|
| 142 |
+
cmd.extend(["-ts:c", compute_type])
|
| 143 |
+
cmd.extend(["-ts:b", str(batch_size)])
|
| 144 |
+
|
| 145 |
+
if translate_lang != "none":
|
| 146 |
+
cmd.extend(["--translate", translate_lang])
|
| 147 |
+
if input_lang != "auto":
|
| 148 |
+
cmd.extend(["--input_lang", input_lang])
|
| 149 |
+
|
| 150 |
+
# Adiciona configurações de codec
|
| 151 |
+
cmd.extend(["-c:v", video_codec])
|
| 152 |
+
cmd.extend(["-c:a", audio_codec])
|
| 153 |
+
|
| 154 |
+
# Adiciona caminhos de saída fixos
|
| 155 |
+
cmd.extend(["-o:s", os.path.join(os.getcwd(), "softsubs_output")])
|
| 156 |
+
cmd.extend(["-o:h", os.path.join(os.getcwd(), "hardsubs_output")])
|
| 157 |
+
|
| 158 |
+
try:
|
| 159 |
+
startupinfo = None
|
| 160 |
+
if os.name == 'nt':
|
| 161 |
+
startupinfo = subprocess.STARTUPINFO()
|
| 162 |
+
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
| 163 |
+
|
| 164 |
+
current_process = subprocess.Popen(
|
| 165 |
+
cmd,
|
| 166 |
+
stdout=subprocess.PIPE,
|
| 167 |
+
stderr=subprocess.STDOUT,
|
| 168 |
+
text=True,
|
| 169 |
+
bufsize=1,
|
| 170 |
+
universal_newlines=True,
|
| 171 |
+
startupinfo=startupinfo,
|
| 172 |
+
encoding='utf-8',
|
| 173 |
+
errors='replace',
|
| 174 |
+
preexec_fn=None if os.name == 'nt' else os.setsid
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
output_lines: List[str] = []
|
| 178 |
+
last_progress_update = 0
|
| 179 |
+
|
| 180 |
+
while True:
|
| 181 |
+
line = current_process.stdout.readline()
|
| 182 |
+
|
| 183 |
+
if not line and current_process.poll() is not None:
|
| 184 |
+
break
|
| 185 |
+
|
| 186 |
+
if line:
|
| 187 |
+
try:
|
| 188 |
+
clean_line = process_output(line, progress)
|
| 189 |
+
output_lines.append(clean_line)
|
| 190 |
+
|
| 191 |
+
if len(output_lines) - last_progress_update >= 5:
|
| 192 |
+
yield "\n".join(output_lines)
|
| 193 |
+
last_progress_update = len(output_lines)
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
output_lines.append(f"Error processing output: {str(e)}")
|
| 197 |
+
|
| 198 |
+
if current_process.poll() == 0:
|
| 199 |
+
final_output = "Processing completed successfully!\n\n" + "\n".join(output_lines)
|
| 200 |
+
else:
|
| 201 |
+
final_output = f"Process ended with error code {current_process.poll()}\n\n" + "\n".join(output_lines)
|
| 202 |
+
|
| 203 |
+
current_process = None
|
| 204 |
+
return final_output
|
| 205 |
+
|
| 206 |
+
except Exception as e:
|
| 207 |
+
current_process = None
|
| 208 |
+
return f"Error: {str(e)}"
|
| 209 |
+
|
| 210 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 211 |
+
gr.Markdown(badges)
|
| 212 |
+
gr.Markdown(description)
|
| 213 |
+
title = "LeGen"
|
| 214 |
+
|
| 215 |
+
ensure_directories() # Garante que os diretórios existam ao iniciar
|
| 216 |
+
|
| 217 |
+
with gr.Row():
|
| 218 |
+
with gr.Column(scale=1):
|
| 219 |
+
# Upload Section
|
| 220 |
+
with gr.Group():
|
| 221 |
+
upload_files = gr.Files(
|
| 222 |
+
label=i18n("Upload Videos"),
|
| 223 |
+
file_types=["video"],
|
| 224 |
+
file_count="multiple"
|
| 225 |
+
)
|
| 226 |
+
upload_button = gr.Button(i18n("Upload to processing directory"))
|
| 227 |
+
|
| 228 |
+
# Transcription Settings
|
| 229 |
+
with gr.Group():
|
| 230 |
+
transcription_engine = gr.Dropdown(
|
| 231 |
+
choices=["whisperx", "whisper"],
|
| 232 |
+
value="whisperx",
|
| 233 |
+
label=i18n("Transcription Engine")
|
| 234 |
+
)
|
| 235 |
+
with gr.Row():
|
| 236 |
+
transcription_model = gr.Dropdown(
|
| 237 |
+
choices=["tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "large-v3-turbo"],
|
| 238 |
+
value="large-v3",
|
| 239 |
+
label=i18n("Model")
|
| 240 |
+
)
|
| 241 |
+
compute_type = gr.Dropdown(
|
| 242 |
+
choices=["auto", "int8", "float16", "float32"],
|
| 243 |
+
value="auto",
|
| 244 |
+
label=i18n("Compute Type")
|
| 245 |
+
)
|
| 246 |
+
with gr.Row():
|
| 247 |
+
device = gr.Dropdown(
|
| 248 |
+
choices=["auto", "cpu", "cuda"],
|
| 249 |
+
value="auto",
|
| 250 |
+
label=i18n("Device")
|
| 251 |
+
)
|
| 252 |
+
batch_size = gr.Number(
|
| 253 |
+
value=4,
|
| 254 |
+
label=i18n("Batch Size"),
|
| 255 |
+
precision=0
|
| 256 |
+
)
|
| 257 |
+
with gr.Row():
|
| 258 |
+
input_lang = gr.Dropdown(
|
| 259 |
+
choices=["auto", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
|
| 260 |
+
value="auto",
|
| 261 |
+
label=i18n("Input Language")
|
| 262 |
+
)
|
| 263 |
+
translate_lang = gr.Dropdown(
|
| 264 |
+
choices=["none", "en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh"],
|
| 265 |
+
value="none",
|
| 266 |
+
label=i18n("Translate to")
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
with gr.Column(scale=1):
|
| 270 |
+
# Output Settings
|
| 271 |
+
with gr.Group():
|
| 272 |
+
with gr.Row():
|
| 273 |
+
video_codec = gr.Dropdown(
|
| 274 |
+
choices=["h264", "libx264", "h264_vaapi", "h264_nvenc", "hevc", "libx265", "hevc_vaapi"],
|
| 275 |
+
value="h264",
|
| 276 |
+
label=i18n("Video Codec")
|
| 277 |
+
)
|
| 278 |
+
audio_codec = gr.Dropdown(
|
| 279 |
+
choices=["aac", "libopus", "mp3", "vorbis"],
|
| 280 |
+
value="aac",
|
| 281 |
+
label=i18n("Audio Codec")
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# Options
|
| 285 |
+
with gr.Group():
|
| 286 |
+
with gr.Row():
|
| 287 |
+
normalize = gr.Checkbox(label=i18n("Normalize folder times"), value=False)
|
| 288 |
+
overwrite = gr.Checkbox(label=i18n("Overwrite existing files"), value=False)
|
| 289 |
+
copy_files = gr.Checkbox(label=i18n("Copy non-video files"), value=False)
|
| 290 |
+
with gr.Row():
|
| 291 |
+
disable_srt = gr.Checkbox(label=i18n("Disable SRT generation"), value=False)
|
| 292 |
+
disable_softsubs = gr.Checkbox(label=i18n("Disable softsubs"), value=False)
|
| 293 |
+
disable_hardsubs = gr.Checkbox(label=i18n("Disable hardsubs"), value=False)
|
| 294 |
+
|
| 295 |
+
# Output Files Display
|
| 296 |
+
with gr.Group():
|
| 297 |
+
softsubs_files = gr.Files(label="Softsubs Output Files", file_count="multiple", interactive=False)
|
| 298 |
+
hardsubs_files = gr.Files(label="Hardsubs Output Files", file_count="multiple", interactive=False)
|
| 299 |
+
|
| 300 |
+
# Run Button, Stop Button and Output
|
| 301 |
+
with gr.Row():
|
| 302 |
+
with gr.Column(scale=1):
|
| 303 |
+
run_btn = gr.Button(i18n("Run LeGen"), variant="primary")
|
| 304 |
+
stop_btn = gr.Button(i18n("Stop"), variant="stop")
|
| 305 |
+
output = gr.Textbox(label=i18n("Output"), lines=2, interactive=False, elem_id="output")
|
| 306 |
+
|
| 307 |
+
# Event handlers
|
| 308 |
+
upload_button.click(
|
| 309 |
+
fn=save_uploaded_files,
|
| 310 |
+
inputs=[upload_files],
|
| 311 |
+
outputs=[output]
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
def update_output_files():
|
| 315 |
+
softsubs_files, hardsubs_files = get_output_files()
|
| 316 |
+
return softsubs_files, hardsubs_files
|
| 317 |
+
|
| 318 |
+
# Connect the run button to the processing function
|
| 319 |
+
run_btn.click(
|
| 320 |
+
fn=run_legen,
|
| 321 |
+
inputs=[
|
| 322 |
+
transcription_engine,
|
| 323 |
+
transcription_model,
|
| 324 |
+
compute_type,
|
| 325 |
+
device,
|
| 326 |
+
batch_size,
|
| 327 |
+
input_lang,
|
| 328 |
+
translate_lang,
|
| 329 |
+
video_codec,
|
| 330 |
+
audio_codec,
|
| 331 |
+
normalize,
|
| 332 |
+
overwrite,
|
| 333 |
+
copy_files,
|
| 334 |
+
disable_srt,
|
| 335 |
+
disable_softsubs,
|
| 336 |
+
disable_hardsubs
|
| 337 |
+
],
|
| 338 |
+
outputs=output
|
| 339 |
+
).then(
|
| 340 |
+
fn=update_output_files,
|
| 341 |
+
inputs=[],
|
| 342 |
+
outputs=[softsubs_files, hardsubs_files]
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
stop_btn.click(
|
| 346 |
+
fn=stop_process,
|
| 347 |
+
inputs=[],
|
| 348 |
+
outputs=output
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
gr.Markdown("""
|
| 352 |
+
<center>WebUI Desenvolvida por Rafa.Godoy</center>
|
| 353 |
+
<center>Agradecimentos ao MatheusBach por desenvolver o LeGen</center>
|
| 354 |
+
""")
|
| 355 |
+
|
| 356 |
+
if __name__ == "__main__":
|
| 357 |
demo.launch()
|