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

@@ -3,11 +3,14 @@ import os
import shutil
import json
import asyncio
import datetime
from collections import deque # Import necessário para ler as últimas linhas de forma eficiente
# --- CONFIGURAÇÕES DE DIRETÓRIOS ---
SRC_ROOT = "/downloads"
DST_ROOT = "/media"
CONFIG_PATH = "/app/data/presets.json"
LOG_PATH = "/app/data/history.log" # Novo arquivo de log persistente
class DeployManager:
def __init__(self):
@@ -16,8 +19,42 @@ class DeployManager:
self.selected_items = []
self.container = None
self.presets = self.load_presets()
self.pendencies = [] # {'name':, 'src':, 'dst':}
self.logs = []
self.pendencies = []
# CARREGA OS LOGS DO ARQUIVO AO INICIAR
self.logs = self.load_logs_from_file()
# --- NOVO: GERENCIAMENTO DE LOGS PERSISTENTES ---
def load_logs_from_file(self):
"""Lê as últimas 50 linhas do arquivo de log"""
if not os.path.exists(LOG_PATH):
return []
try:
# Lê as últimas 50 linhas do arquivo
with open(LOG_PATH, 'r', encoding='utf-8') as f:
# deque(..., maxlen=50) pega automaticamente as últimas 50
last_lines = list(deque(f, maxlen=50))
# Inverte a ordem para mostrar o mais recente no topo da lista visual
# remove quebras de linha com .strip()
return [line.strip() for line in reversed(last_lines)]
except:
return []
def add_log(self, message, type="info"):
"""Adiciona log na memória E no arquivo"""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
full_msg = f"[{timestamp}] {message}"
# 1. Atualiza a lista da memória (para a UI)
self.logs.insert(0, full_msg)
if len(self.logs) > 50: self.logs.pop() # Limpa memória excedente
# 2. Salva no arquivo (Modo 'a' = append/adicionar no fim)
try:
with open(LOG_PATH, 'a', encoding='utf-8') as f:
f.write(full_msg + "\n")
except Exception as e:
print(f"Erro ao salvar log: {e}")
# --- 1. PERSISTÊNCIA (JSON) ---
def load_presets(self):
@@ -43,49 +80,45 @@ class DeployManager:
json.dump(self.presets, f)
self.refresh()
# --- 2. DIÁLOGO DE CONFIRMAÇÃO DO PRESET (NOVO) ---
# --- 2. DIÁLOGO DE CONFIRMAÇÃO DO PRESET ---
def confirm_preset_execution(self, name, paths):
"""Abre janela para confirmar antes de rodar o Smart Deploy"""
src = paths['src']
dst = paths['dst']
# Verificação básica antes de abrir o diálogo
if not os.path.exists(src):
ui.notify(f'Erro: Pasta de origem não existe: {src}', type='negative')
return
# Conta itens para mostrar no aviso
try:
items = [f for f in os.listdir(src) if not f.startswith('.')] # Ignora ocultos
items = [f for f in os.listdir(src) if not f.startswith('.')]
count = len(items)
except: count = 0
with ui.dialog() as dialog, ui.card():
ui.label(f'Executar: {name}?').classes('text-xl font-bold text-blue-900')
ui.label('Isso moverá TODOS os arquivos de:').classes('text-xs text-gray-500 mt-2')
ui.label(src).classes('font-mono text-sm bg-gray-100 p-1 rounded w-full break-all')
ui.label('Para:').classes('text-xs text-gray-500 mt-2')
ui.label(dst).classes('font-mono text-sm bg-gray-100 p-1 rounded w-full break-all')
ui.label(f'Origem: {src}').classes('font-mono text-xs bg-gray-100 p-1 rounded w-full break-all')
ui.label(f'Destino: {dst}').classes('font-mono text-xs bg-gray-100 p-1 rounded w-full break-all')
if count > 0:
ui.label(f'{count} itens encontrados prontos para mover.').classes('font-bold text-green-700 mt-2')
ui.label(f'{count} itens encontrados.').classes('font-bold text-green-700 mt-2')
else:
ui.label('Atenção: A pasta de origem parece vazia.').classes('font-bold text-orange-600 mt-2')
# Função wrapper para rodar o async corretamente
async def execute_action():
dialog.close()
await asyncio.sleep(0.1)
await self.move_process_from_preset(paths)
with ui.row().classes('w-full justify-end mt-4'):
ui.button('Cancelar', on_click=dialog.close).props('flat text-color=grey')
# Botão que realmente executa a ação
ui.button('CONFIRMAR MOVIMENTAÇÃO',
on_click=lambda: [dialog.close(), self.move_process_from_preset(paths)])\
.props('color=green icon=check')
ui.button('CONFIRMAR', on_click=execute_action).props('color=green icon=check')
dialog.open()
# --- 3. MOVIMENTAÇÃO E PENDÊNCIAS ---
async def move_process(self, items_to_move, target_folder):
"""Move arquivos em background e detecta conflitos"""
for item_path in items_to_move:
if not os.path.exists(item_path): continue
@@ -109,7 +142,6 @@ class DeployManager:
self.refresh()
async def move_process_from_preset(self, paths):
"""Executa a movimentação após confirmação"""
src, dst = paths['src'], paths['dst']
if os.path.exists(src):
items = [os.path.join(src, f) for f in os.listdir(src)]
@@ -148,7 +180,7 @@ class DeployManager:
if refresh: self.refresh()
# --- 5. NAVEGAÇÃO (BREADCRUMBS) ---
# --- 5. NAVEGAÇÃO ---
def render_breadcrumbs(self, current_path, root_dir, nav_callback):
with ui.row().classes('items-center gap-1 bg-gray-100 p-1 rounded w-full mb-2'):
ui.button('🏠', on_click=lambda: nav_callback(root_dir)).props('flat dense size=sm')
@@ -177,10 +209,6 @@ class DeployManager:
self.refresh()
# --- 6. INTERFACE PRINCIPAL ---
def add_log(self, message, type="info"):
self.logs.insert(0, message)
if len(self.logs) > 30: self.logs.pop()
def refresh(self):
if self.container:
self.container.clear()
@@ -194,7 +222,6 @@ class DeployManager:
ui.label('SMART DEPLOYS:').classes('font-bold text-blue-900 mr-4')
for name, paths in self.presets.items():
with ui.button_group().props('rounded'):
# AQUI MUDOU: Chama o diálogo de confirmação em vez de mover direto
ui.button(name, on_click=lambda n=name, p=paths: self.confirm_preset_execution(n, p)).props('color=blue-6')
ui.button(on_click=lambda n=name: self.delete_preset(n)).props('icon=delete color=red-4')
@@ -233,10 +260,13 @@ class DeployManager:
# PAINEL DE LOGS
with ui.card().classes('flex-grow h-64 bg-slate-900 text-slate-200 shadow-none'):
ui.label('📜 Log de Atividades').classes('font-bold border-b border-slate-700 w-full pb-2')
ui.label('📜 Log de Atividades (Persistente)').classes('font-bold border-b border-slate-700 w-full pb-2')
with ui.scroll_area().classes('w-full h-full'):
# Renderiza os logs carregados
for log in self.logs:
ui.label(f"> {log}").classes('text-[10px] font-mono leading-tight')
# Pinta de vermelho se tiver erro, verde se sucesso
color_cls = 'text-red-400' if '' in log else 'text-green-400' if '' in log else 'text-slate-300'
ui.label(f"> {log}").classes(f'text-[10px] font-mono leading-tight {color_cls}')
# BOTÃO GLOBAL
ui.button('INICIAR MOVIMENTAÇÃO DOS SELECIONADOS', on_click=lambda: self.move_process(self.selected_items, self.dst_path))\
@@ -244,7 +274,7 @@ class DeployManager:
.props('color=green-7 icon=forward')\
.bind_enabled_from(self, 'selected_items', backward=lambda x: len(x) > 0)
# --- AUXILIARES (Listas, Checkbox, etc) ---
# --- AUXILIARES ---
def render_file_list(self, path, is_source):
try:
entries = sorted(os.scandir(path), key=lambda e: (not e.is_dir(), e.name.lower()))

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()