concertado o deploy

This commit is contained in:
2026-02-03 00:51:41 +00:00
parent 935b15980c
commit 833378b307
9 changed files with 143 additions and 106 deletions

View File

@@ -5,7 +5,8 @@ import time
import subprocess
import json
import re
import math # <--- ADICIONADO AQUI
import math
import shutil
from collections import deque
from datetime import datetime
@@ -22,6 +23,9 @@ BAD_DRIVERS = [
"/usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so.1"
]
# Extensões de legenda que vamos procurar
SUBTITLE_EXTS = ('.srt', '.sub', '.sbv', '.ass', '.vtt', '.ssa')
# VARIÁVEIS DE ESTADO (MEMÓRIA RAM)
CURRENT_STATUS = {
"running": False,
@@ -50,8 +54,7 @@ def prepare_driver_environment():
if os.path.exists(driver):
try:
os.remove(driver)
except Exception as e:
print(f"Erro ao remover driver: {e}")
except: pass
def get_video_duration(filepath):
"""Usa ffprobe para descobrir a duração total do vídeo em segundos."""
@@ -78,10 +81,7 @@ def parse_time_to_seconds(time_str):
def format_size(size_bytes):
"""Formata bytes para leitura humana (MB, GB)."""
if size_bytes == 0:
return "0B"
# --- CORREÇÃO AQUI (Math em vez de os.path) ---
if size_bytes == 0: return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
try:
i = int(math.log(size_bytes, 1024) // 1)
@@ -93,10 +93,7 @@ def format_size(size_bytes):
def clean_metadata_title(title):
"""Limpa o título das faixas de áudio/legenda usando Regex."""
if not title:
return ""
# Lista de termos para remover (Case Insensitive)
if not title: return ""
junk_terms = [
r'\b5\.1\b', r'\b7\.1\b', r'\b2\.0\b',
r'\baac\b', r'\bac3\b', r'\beac3\b', r'\batmos\b', r'\bdts\b', r'\btruehd\b',
@@ -104,14 +101,34 @@ def clean_metadata_title(title):
r'\bbludv\b', r'\bcomandotorrents\b', r'\brarbg\b', r'\bwww\..+\.com\b',
r'\bcópia\b', r'\boriginal\b'
]
clean_title = title
for pattern in junk_terms:
clean_title = re.sub(pattern, '', clean_title, flags=re.IGNORECASE)
clean_title = re.sub(r'\s+', ' ', clean_title).strip()
return clean_title.strip('-.|[]()').strip()
def handle_external_subtitles(src_video_path, dest_folder, delete_original=False):
"""
Procura legendas externas com o mesmo nome base do vídeo e as copia/move.
"""
try:
src_folder = os.path.dirname(src_video_path)
video_name = os.path.basename(src_video_path)
video_stem = os.path.splitext(video_name)[0]
for file in os.listdir(src_folder):
if file.lower().endswith(SUBTITLE_EXTS):
if file.startswith(video_stem):
remaining = file[len(video_stem):]
if not remaining or remaining.startswith('.'):
src_sub = os.path.join(src_folder, file)
dest_sub = os.path.join(dest_folder, file)
shutil.copy2(src_sub, dest_sub)
if delete_original:
os.remove(src_sub)
except Exception as e:
print(f"Erro legendas: {e}")
# ==============================================================================
# --- SEÇÃO 3: LÓGICA DO FFMPEG ---
@@ -119,7 +136,6 @@ def clean_metadata_title(title):
def build_ffmpeg_command(input_file, output_file):
"""Constrói o comando FFmpeg inteligente."""
cmd_probe = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", input_file]
try:
res = subprocess.run(cmd_probe, capture_output=True, text=True, env=os.environ)
@@ -134,7 +150,6 @@ def build_ffmpeg_command(input_file, output_file):
input_streams = data.get('streams', [])
map_args = ["-map", "0:v:0"]
metadata_args = []
found_pt_audio = False
# ÁUDIO
@@ -161,13 +176,11 @@ def build_ffmpeg_command(input_file, output_file):
found_pt_audio = True
else:
metadata_args.extend([f"-disposition:a:{audio_idx}", "0"])
audio_idx += 1
if audio_idx == 0:
map_args.extend(["-map", "0:a"])
if audio_idx == 0: map_args.extend(["-map", "0:a"])
# LEGENDAS
# LEGENDAS INTERNAS
sub_idx = 0
for stream in input_streams:
if stream['codec_type'] == 'subtitle':
@@ -178,7 +191,6 @@ def build_ffmpeg_command(input_file, output_file):
if lang in ['por', 'pt', 'pob', 'pt-br']:
map_args.extend(["-map", f"0:{stream['index']}"])
new_title = clean_metadata_title(title)
metadata_args.extend([f"-metadata:s:s:{sub_idx}", f"title={new_title}"])
@@ -186,23 +198,16 @@ def build_ffmpeg_command(input_file, output_file):
metadata_args.extend([f"-disposition:s:{sub_idx}", "forced"])
else:
metadata_args.extend([f"-disposition:s:{sub_idx}", "0"])
sub_idx += 1
cmd = [
"ffmpeg", "-y",
"-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128",
"-hwaccel_output_format", "vaapi",
"-i", input_file
"ffmpeg", "-y", "-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128",
"-hwaccel_output_format", "vaapi", "-i", input_file
]
cmd += map_args
cmd += [
"-c:v", "h264_vaapi", "-qp", "25", "-compression_level", "0",
"-c:a", "copy", "-c:s", "copy"
]
cmd += ["-c:v", "h264_vaapi", "-qp", "25", "-compression_level", "0", "-c:a", "copy", "-c:s", "copy"]
cmd += metadata_args
cmd.append(output_file)
return cmd
@@ -235,11 +240,9 @@ class EncoderWorker(threading.Thread):
CURRENT_STATUS["total_files"] = len(files_to_process)
for i, fpath in enumerate(files_to_process):
if CURRENT_STATUS["stop_requested"]:
break
if CURRENT_STATUS["stop_requested"]: break
fname = os.path.basename(fpath)
CURRENT_STATUS["file"] = fname
CURRENT_STATUS["current_index"] = i + 1
CURRENT_STATUS["pct_file"] = 0
@@ -248,7 +251,9 @@ class EncoderWorker(threading.Thread):
rel = os.path.relpath(fpath, self.input_folder)
out_file = os.path.join(OUTPUT_BASE, os.path.basename(self.input_folder), rel)
out_file = os.path.splitext(out_file)[0] + ".mkv"
os.makedirs(os.path.dirname(out_file), exist_ok=True)
dest_folder = os.path.dirname(out_file)
os.makedirs(dest_folder, exist_ok=True)
size_before = os.path.getsize(fpath)
cmd = build_ffmpeg_command(fpath, out_file)
@@ -260,27 +265,21 @@ class EncoderWorker(threading.Thread):
if CURRENT_STATUS["stop_requested"]:
proc.terminate()
break
if "time=" in line:
match = re.search(r"time=(\d{2}:\d{2}:\d{2}\.\d{2})", line)
if match:
sec = parse_time_to_seconds(match.group(1))
pct = min(int((sec/total_sec)*100), 100)
CURRENT_STATUS["pct_file"] = pct
speed_match = re.search(r"speed=\s*(\S+)", line)
if speed_match:
CURRENT_STATUS["speed"] = speed_match.group(1)
CURRENT_STATUS["log"] = f"Vel: {CURRENT_STATUS['speed']}"
speed = re.search(r"speed=\s*(\S+)", line)
if speed: CURRENT_STATUS["log"] = f"Vel: {speed.group(1)}"
proc.wait()
final_status = "Erro"
if CURRENT_STATUS["stop_requested"]:
if os.path.exists(out_file): os.remove(out_file)
final_status = "Cancelado"
elif proc.returncode == 0:
final_status = "✅ Sucesso"
size_after = os.path.getsize(out_file) if os.path.exists(out_file) else 0
@@ -295,10 +294,12 @@ class EncoderWorker(threading.Thread):
"diff": ("+" if diff > 0 else "") + format_size(diff)
})
handle_external_subtitles(fpath, dest_folder, self.delete_original)
if self.delete_original:
try:
os.remove(fpath)
CURRENT_STATUS["log"] = "Original excluído com sucesso."
CURRENT_STATUS["log"] = "Original excluído."
except: pass
else:
HISTORY_LOG.appendleft({
@@ -357,13 +358,10 @@ class EncoderInterface:
def start_encoding(self):
should_delete = self.delete_switch.value if self.delete_switch else False
CURRENT_STATUS["pct_file"] = 0
CURRENT_STATUS["pct_total"] = 0
t = EncoderWorker(self.path, delete_original=should_delete)
t.start()
ui.notify('Iniciando Conversão...', type='positive')
self.view_mode = 'monitor'
self.refresh_ui()
@@ -394,20 +392,20 @@ class EncoderInterface:
try:
entries = sorted([e for e in os.scandir(self.path) if e.is_dir() and not e.name.startswith('.')], key=lambda e: e.name.lower())
except: return
with ui.column().classes('w-full gap-1 mt-2'):
if self.path != ROOT_DIR:
with ui.item(on_click=lambda: self.navigate(os.path.dirname(self.path))).classes('bg-gray-200 hover:bg-gray-300 cursor-pointer rounded'):
with ui.item_section().props('avatar'): ui.icon('arrow_upward', color='grey')
with ui.item_section(): ui.item_label('.. (Subir nível)')
if not entries:
ui.label("Nenhuma subpasta encontrada aqui.").classes('text-grey italic p-4')
# Sintaxe correta: usando context manager (with)
with ui.item_section().props('avatar'):
ui.icon('arrow_upward', color='grey')
with ui.item_section():
ui.item_label('.. (Subir nível)')
for entry in entries:
with ui.item(on_click=lambda p=entry.path: self.navigate(p)).classes('hover:bg-blue-50 cursor-pointer rounded border-b border-gray-100'):
with ui.item_section().props('avatar'): ui.icon('folder', color='amber')
with ui.item_section(): ui.item_label(entry.name).classes('font-medium')
with ui.item_section().props('avatar'):
ui.icon('folder', color='amber')
with ui.item_section():
ui.item_label(entry.name).classes('font-medium')
def render_history_btn(self):
ui.separator().classes('mt-4')
@@ -419,7 +417,6 @@ class EncoderInterface:
def render_history_table(self):
ui.label('Histórico de Conversões').classes('text-xl font-bold mb-4')
columns = [
{'name': 'time', 'label': 'Hora', 'field': 'time', 'align': 'left'},
{'name': 'file', 'label': 'Arquivo', 'field': 'file', 'align': 'left'},
@@ -428,21 +425,16 @@ class EncoderInterface:
{'name': 'final', 'label': 'Tam. Final', 'field': 'final_size'},
{'name': 'diff', 'label': 'Diferença', 'field': 'diff'},
]
rows = list(HISTORY_LOG)
ui.table(columns=columns, rows=rows, row_key='file').classes('w-full')
ui.table(columns=columns, rows=list(HISTORY_LOG), row_key='file').classes('w-full')
ui.button('Voltar', on_click=lambda: self.set_view('explorer')).props('outline mt-4')
def render_monitor(self):
ui.label('Monitor de Conversão').classes('text-xl font-bold mb-4')
lbl_file = ui.label('Inicializando...')
progress_file = ui.linear_progress(value=0).classes('w-full')
lbl_log = ui.label('---').classes('text-caption text-grey')
ui.separator().classes('my-4')
lbl_total = ui.label('Total: 0/0')
progress_total = ui.linear_progress(value=0).classes('w-full')
@@ -461,15 +453,10 @@ class EncoderInterface:
lbl_file.text = f"Arquivo: {CURRENT_STATUS['file']}"
progress_file.value = CURRENT_STATUS['pct_file'] / 100
lbl_log.text = f"{int(CURRENT_STATUS['pct_file'])}% | {CURRENT_STATUS['log']}"
lbl_total.text = f"Fila: {CURRENT_STATUS['current_index']} de {CURRENT_STATUS['total_files']}"
progress_total.value = CURRENT_STATUS['pct_total'] / 100
self.timer = ui.timer(0.5, update_monitor)
# ==============================================================================
# --- SEÇÃO 6: EXPORTAÇÃO PARA O MAIN.PY ---
# ==============================================================================
def create_ui():
return EncoderInterface()