concertado o deploy
This commit is contained in:
BIN
app/img/icone.ico
Normal file
BIN
app/img/icone.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 79 KiB |
BIN
app/img/logo.png
Normal file
BIN
app/img/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
BIN
app/img/logotexto.png
Normal file
BIN
app/img/logotexto.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 144 KiB |
40
app/main.py
40
app/main.py
@@ -1,18 +1,26 @@
|
|||||||
from nicegui import ui, app
|
from nicegui import ui, app
|
||||||
# ADICIONE 'downloader' AQUI:
|
|
||||||
from modules import file_manager, renamer, encoder, downloader, deployer
|
from modules import file_manager, renamer, encoder, downloader, deployer
|
||||||
app.add_static_files('/files', '/downloads')
|
|
||||||
|
|
||||||
# ATUALIZE AS ABAS:
|
# --- CONFIGURAÇÃO DE ARQUIVOS ESTÁTICOS ---
|
||||||
with ui.tabs().classes('w-full') as tabs:
|
app.add_static_files('/files', '/downloads')
|
||||||
|
app.add_static_files('/img', '/app/img')
|
||||||
|
|
||||||
|
# --- CABEÇALHO (HEADER) ---
|
||||||
|
# Cor alterada para 'bg-blue-700'
|
||||||
|
with ui.header(elevated=True).classes('items-center justify-center bg-slate-700 p-2'):
|
||||||
|
# Tamanho específico solicitado: w-1/2 com máximo de 100px
|
||||||
|
ui.image('/img/logotexto.png').classes('w-1/2 max-w-[100px] object-contain')
|
||||||
|
|
||||||
|
# --- NAVEGAÇÃO (TABS) ---
|
||||||
|
with ui.tabs().classes('w-full sticky top-0 z-10 bg-white shadow-sm') as tabs:
|
||||||
t_files = ui.tab('Gerenciador', icon='folder')
|
t_files = ui.tab('Gerenciador', icon='folder')
|
||||||
t_rename = ui.tab('Renomeador', icon='edit')
|
t_rename = ui.tab('Renomeador', icon='edit')
|
||||||
t_encode = ui.tab('Encoder', icon='movie')
|
t_encode = ui.tab('Encoder', icon='movie')
|
||||||
t_down = ui.tab('Downloader', icon='download') # NOVA ABA
|
t_down = ui.tab('Downloader', icon='download')
|
||||||
t_deploy = ui.tab('Mover Final', icon='publish') # NOVA ABA
|
t_deploy = ui.tab('Mover Final', icon='publish')
|
||||||
|
|
||||||
# ATUALIZE OS PAINÉIS:
|
# --- PAINÉIS DE CONTEÚDO ---
|
||||||
with ui.tab_panels(tabs, value=t_files).classes('w-full p-0'):
|
with ui.tab_panels(tabs, value=t_files).classes('w-full p-0 pb-12'): # pb-12 dá espaço para o footer não cobrir o conteúdo
|
||||||
|
|
||||||
with ui.tab_panel(t_files).classes('p-0'):
|
with ui.tab_panel(t_files).classes('p-0'):
|
||||||
file_manager.create_ui()
|
file_manager.create_ui()
|
||||||
@@ -23,11 +31,23 @@ with ui.tab_panels(tabs, value=t_files).classes('w-full p-0'):
|
|||||||
with ui.tab_panel(t_encode):
|
with ui.tab_panel(t_encode):
|
||||||
encoder.create_ui()
|
encoder.create_ui()
|
||||||
|
|
||||||
# NOVO PAINEL:
|
|
||||||
with ui.tab_panel(t_down):
|
with ui.tab_panel(t_down):
|
||||||
downloader.create_ui()
|
downloader.create_ui()
|
||||||
|
|
||||||
with ui.tab_panel(t_deploy):
|
with ui.tab_panel(t_deploy):
|
||||||
deployer.create_ui()
|
deployer.create_ui()
|
||||||
|
|
||||||
ui.run(title='PyMedia Manager', port=8080, reload=True, storage_secret='secret')
|
# --- RODAPÉ (FOOTER) ---
|
||||||
|
# Fixo na parte inferior, mesma cor do header, texto centralizado
|
||||||
|
with ui.footer().classes('bg-slate-700 justify-center items-center py-1'):
|
||||||
|
# Texto com estilo levemente menor e fonte monoespaçada para dar o ar de "sistema/server"
|
||||||
|
ui.label('Criado por Creidsu. Clei-Server').classes('text-xs text-white opacity-90 font-mono tracking-wide')
|
||||||
|
|
||||||
|
# --- INICIALIZAÇÃO ---
|
||||||
|
ui.run(
|
||||||
|
title='PyMedia Manager',
|
||||||
|
port=8080,
|
||||||
|
reload=True,
|
||||||
|
storage_secret='secret',
|
||||||
|
favicon='/app/img/icone.ico' # Caminho absoluto
|
||||||
|
)
|
||||||
Binary file not shown.
Binary file not shown.
@@ -3,11 +3,14 @@ import os
|
|||||||
import shutil
|
import shutil
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import datetime
|
||||||
|
from collections import deque # Import necessário para ler as últimas linhas de forma eficiente
|
||||||
|
|
||||||
# --- CONFIGURAÇÕES DE DIRETÓRIOS ---
|
# --- CONFIGURAÇÕES DE DIRETÓRIOS ---
|
||||||
SRC_ROOT = "/downloads"
|
SRC_ROOT = "/downloads"
|
||||||
DST_ROOT = "/media"
|
DST_ROOT = "/media"
|
||||||
CONFIG_PATH = "/app/data/presets.json"
|
CONFIG_PATH = "/app/data/presets.json"
|
||||||
|
LOG_PATH = "/app/data/history.log" # Novo arquivo de log persistente
|
||||||
|
|
||||||
class DeployManager:
|
class DeployManager:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@@ -16,8 +19,42 @@ class DeployManager:
|
|||||||
self.selected_items = []
|
self.selected_items = []
|
||||||
self.container = None
|
self.container = None
|
||||||
self.presets = self.load_presets()
|
self.presets = self.load_presets()
|
||||||
self.pendencies = [] # {'name':, 'src':, 'dst':}
|
self.pendencies = []
|
||||||
self.logs = []
|
# 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) ---
|
# --- 1. PERSISTÊNCIA (JSON) ---
|
||||||
def load_presets(self):
|
def load_presets(self):
|
||||||
@@ -43,49 +80,45 @@ class DeployManager:
|
|||||||
json.dump(self.presets, f)
|
json.dump(self.presets, f)
|
||||||
self.refresh()
|
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):
|
def confirm_preset_execution(self, name, paths):
|
||||||
"""Abre janela para confirmar antes de rodar o Smart Deploy"""
|
|
||||||
src = paths['src']
|
src = paths['src']
|
||||||
dst = paths['dst']
|
dst = paths['dst']
|
||||||
|
|
||||||
# Verificação básica antes de abrir o diálogo
|
|
||||||
if not os.path.exists(src):
|
if not os.path.exists(src):
|
||||||
ui.notify(f'Erro: Pasta de origem não existe: {src}', type='negative')
|
ui.notify(f'Erro: Pasta de origem não existe: {src}', type='negative')
|
||||||
return
|
return
|
||||||
|
|
||||||
# Conta itens para mostrar no aviso
|
|
||||||
try:
|
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)
|
count = len(items)
|
||||||
except: count = 0
|
except: count = 0
|
||||||
|
|
||||||
with ui.dialog() as dialog, ui.card():
|
with ui.dialog() as dialog, ui.card():
|
||||||
ui.label(f'Executar: {name}?').classes('text-xl font-bold text-blue-900')
|
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(f'Origem: {src}').classes('font-mono text-xs bg-gray-100 p-1 rounded w-full break-all')
|
||||||
ui.label(src).classes('font-mono text-sm 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')
|
||||||
|
|
||||||
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')
|
|
||||||
|
|
||||||
if count > 0:
|
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:
|
else:
|
||||||
ui.label('Atenção: A pasta de origem parece vazia.').classes('font-bold text-orange-600 mt-2')
|
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'):
|
with ui.row().classes('w-full justify-end mt-4'):
|
||||||
ui.button('Cancelar', on_click=dialog.close).props('flat text-color=grey')
|
ui.button('Cancelar', on_click=dialog.close).props('flat text-color=grey')
|
||||||
# Botão que realmente executa a ação
|
ui.button('CONFIRMAR', on_click=execute_action).props('color=green icon=check')
|
||||||
ui.button('CONFIRMAR MOVIMENTAÇÃO',
|
|
||||||
on_click=lambda: [dialog.close(), self.move_process_from_preset(paths)])\
|
|
||||||
.props('color=green icon=check')
|
|
||||||
|
|
||||||
dialog.open()
|
dialog.open()
|
||||||
|
|
||||||
# --- 3. MOVIMENTAÇÃO E PENDÊNCIAS ---
|
# --- 3. MOVIMENTAÇÃO E PENDÊNCIAS ---
|
||||||
async def move_process(self, items_to_move, target_folder):
|
async def move_process(self, items_to_move, target_folder):
|
||||||
"""Move arquivos em background e detecta conflitos"""
|
|
||||||
for item_path in items_to_move:
|
for item_path in items_to_move:
|
||||||
if not os.path.exists(item_path): continue
|
if not os.path.exists(item_path): continue
|
||||||
|
|
||||||
@@ -109,7 +142,6 @@ class DeployManager:
|
|||||||
self.refresh()
|
self.refresh()
|
||||||
|
|
||||||
async def move_process_from_preset(self, paths):
|
async def move_process_from_preset(self, paths):
|
||||||
"""Executa a movimentação após confirmação"""
|
|
||||||
src, dst = paths['src'], paths['dst']
|
src, dst = paths['src'], paths['dst']
|
||||||
if os.path.exists(src):
|
if os.path.exists(src):
|
||||||
items = [os.path.join(src, f) for f in os.listdir(src)]
|
items = [os.path.join(src, f) for f in os.listdir(src)]
|
||||||
@@ -148,7 +180,7 @@ class DeployManager:
|
|||||||
|
|
||||||
if refresh: self.refresh()
|
if refresh: self.refresh()
|
||||||
|
|
||||||
# --- 5. NAVEGAÇÃO (BREADCRUMBS) ---
|
# --- 5. NAVEGAÇÃO ---
|
||||||
def render_breadcrumbs(self, current_path, root_dir, nav_callback):
|
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'):
|
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')
|
ui.button('🏠', on_click=lambda: nav_callback(root_dir)).props('flat dense size=sm')
|
||||||
@@ -177,10 +209,6 @@ class DeployManager:
|
|||||||
self.refresh()
|
self.refresh()
|
||||||
|
|
||||||
# --- 6. INTERFACE PRINCIPAL ---
|
# --- 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):
|
def refresh(self):
|
||||||
if self.container:
|
if self.container:
|
||||||
self.container.clear()
|
self.container.clear()
|
||||||
@@ -194,7 +222,6 @@ class DeployManager:
|
|||||||
ui.label('SMART DEPLOYS:').classes('font-bold text-blue-900 mr-4')
|
ui.label('SMART DEPLOYS:').classes('font-bold text-blue-900 mr-4')
|
||||||
for name, paths in self.presets.items():
|
for name, paths in self.presets.items():
|
||||||
with ui.button_group().props('rounded'):
|
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(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')
|
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
|
# PAINEL DE LOGS
|
||||||
with ui.card().classes('flex-grow h-64 bg-slate-900 text-slate-200 shadow-none'):
|
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'):
|
with ui.scroll_area().classes('w-full h-full'):
|
||||||
|
# Renderiza os logs carregados
|
||||||
for log in self.logs:
|
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
|
# BOTÃO GLOBAL
|
||||||
ui.button('INICIAR MOVIMENTAÇÃO DOS SELECIONADOS', on_click=lambda: self.move_process(self.selected_items, self.dst_path))\
|
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')\
|
.props('color=green-7 icon=forward')\
|
||||||
.bind_enabled_from(self, 'selected_items', backward=lambda x: len(x) > 0)
|
.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):
|
def render_file_list(self, path, is_source):
|
||||||
try:
|
try:
|
||||||
entries = sorted(os.scandir(path), key=lambda e: (not e.is_dir(), e.name.lower()))
|
entries = sorted(os.scandir(path), key=lambda e: (not e.is_dir(), e.name.lower()))
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import time
|
|||||||
import subprocess
|
import subprocess
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import math # <--- ADICIONADO AQUI
|
import math
|
||||||
|
import shutil
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
@@ -22,6 +23,9 @@ BAD_DRIVERS = [
|
|||||||
"/usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so.1"
|
"/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)
|
# VARIÁVEIS DE ESTADO (MEMÓRIA RAM)
|
||||||
CURRENT_STATUS = {
|
CURRENT_STATUS = {
|
||||||
"running": False,
|
"running": False,
|
||||||
@@ -50,8 +54,7 @@ def prepare_driver_environment():
|
|||||||
if os.path.exists(driver):
|
if os.path.exists(driver):
|
||||||
try:
|
try:
|
||||||
os.remove(driver)
|
os.remove(driver)
|
||||||
except Exception as e:
|
except: pass
|
||||||
print(f"Erro ao remover driver: {e}")
|
|
||||||
|
|
||||||
def get_video_duration(filepath):
|
def get_video_duration(filepath):
|
||||||
"""Usa ffprobe para descobrir a duração total do vídeo em segundos."""
|
"""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):
|
def format_size(size_bytes):
|
||||||
"""Formata bytes para leitura humana (MB, GB)."""
|
"""Formata bytes para leitura humana (MB, GB)."""
|
||||||
if size_bytes == 0:
|
if size_bytes == 0: return "0B"
|
||||||
return "0B"
|
|
||||||
|
|
||||||
# --- CORREÇÃO AQUI (Math em vez de os.path) ---
|
|
||||||
size_name = ("B", "KB", "MB", "GB", "TB")
|
size_name = ("B", "KB", "MB", "GB", "TB")
|
||||||
try:
|
try:
|
||||||
i = int(math.log(size_bytes, 1024) // 1)
|
i = int(math.log(size_bytes, 1024) // 1)
|
||||||
@@ -93,10 +93,7 @@ def format_size(size_bytes):
|
|||||||
|
|
||||||
def clean_metadata_title(title):
|
def clean_metadata_title(title):
|
||||||
"""Limpa o título das faixas de áudio/legenda usando Regex."""
|
"""Limpa o título das faixas de áudio/legenda usando Regex."""
|
||||||
if not title:
|
if not title: return ""
|
||||||
return ""
|
|
||||||
|
|
||||||
# Lista de termos para remover (Case Insensitive)
|
|
||||||
junk_terms = [
|
junk_terms = [
|
||||||
r'\b5\.1\b', r'\b7\.1\b', r'\b2\.0\b',
|
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',
|
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'\bbludv\b', r'\bcomandotorrents\b', r'\brarbg\b', r'\bwww\..+\.com\b',
|
||||||
r'\bcópia\b', r'\boriginal\b'
|
r'\bcópia\b', r'\boriginal\b'
|
||||||
]
|
]
|
||||||
|
|
||||||
clean_title = title
|
clean_title = title
|
||||||
for pattern in junk_terms:
|
for pattern in junk_terms:
|
||||||
clean_title = re.sub(pattern, '', clean_title, flags=re.IGNORECASE)
|
clean_title = re.sub(pattern, '', clean_title, flags=re.IGNORECASE)
|
||||||
|
|
||||||
clean_title = re.sub(r'\s+', ' ', clean_title).strip()
|
clean_title = re.sub(r'\s+', ' ', clean_title).strip()
|
||||||
return clean_title.strip('-.|[]()').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 ---
|
# --- SEÇÃO 3: LÓGICA DO FFMPEG ---
|
||||||
@@ -119,7 +136,6 @@ def clean_metadata_title(title):
|
|||||||
|
|
||||||
def build_ffmpeg_command(input_file, output_file):
|
def build_ffmpeg_command(input_file, output_file):
|
||||||
"""Constrói o comando FFmpeg inteligente."""
|
"""Constrói o comando FFmpeg inteligente."""
|
||||||
|
|
||||||
cmd_probe = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", input_file]
|
cmd_probe = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", input_file]
|
||||||
try:
|
try:
|
||||||
res = subprocess.run(cmd_probe, capture_output=True, text=True, env=os.environ)
|
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', [])
|
input_streams = data.get('streams', [])
|
||||||
map_args = ["-map", "0:v:0"]
|
map_args = ["-map", "0:v:0"]
|
||||||
metadata_args = []
|
metadata_args = []
|
||||||
|
|
||||||
found_pt_audio = False
|
found_pt_audio = False
|
||||||
|
|
||||||
# ÁUDIO
|
# ÁUDIO
|
||||||
@@ -161,13 +176,11 @@ def build_ffmpeg_command(input_file, output_file):
|
|||||||
found_pt_audio = True
|
found_pt_audio = True
|
||||||
else:
|
else:
|
||||||
metadata_args.extend([f"-disposition:a:{audio_idx}", "0"])
|
metadata_args.extend([f"-disposition:a:{audio_idx}", "0"])
|
||||||
|
|
||||||
audio_idx += 1
|
audio_idx += 1
|
||||||
|
|
||||||
if audio_idx == 0:
|
if audio_idx == 0: map_args.extend(["-map", "0:a"])
|
||||||
map_args.extend(["-map", "0:a"])
|
|
||||||
|
|
||||||
# LEGENDAS
|
# LEGENDAS INTERNAS
|
||||||
sub_idx = 0
|
sub_idx = 0
|
||||||
for stream in input_streams:
|
for stream in input_streams:
|
||||||
if stream['codec_type'] == 'subtitle':
|
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']:
|
if lang in ['por', 'pt', 'pob', 'pt-br']:
|
||||||
map_args.extend(["-map", f"0:{stream['index']}"])
|
map_args.extend(["-map", f"0:{stream['index']}"])
|
||||||
|
|
||||||
new_title = clean_metadata_title(title)
|
new_title = clean_metadata_title(title)
|
||||||
metadata_args.extend([f"-metadata:s:s:{sub_idx}", f"title={new_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"])
|
metadata_args.extend([f"-disposition:s:{sub_idx}", "forced"])
|
||||||
else:
|
else:
|
||||||
metadata_args.extend([f"-disposition:s:{sub_idx}", "0"])
|
metadata_args.extend([f"-disposition:s:{sub_idx}", "0"])
|
||||||
|
|
||||||
sub_idx += 1
|
sub_idx += 1
|
||||||
|
|
||||||
cmd = [
|
cmd = [
|
||||||
"ffmpeg", "-y",
|
"ffmpeg", "-y", "-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128",
|
||||||
"-hwaccel", "vaapi", "-hwaccel_device", "/dev/dri/renderD128",
|
"-hwaccel_output_format", "vaapi", "-i", input_file
|
||||||
"-hwaccel_output_format", "vaapi",
|
|
||||||
"-i", input_file
|
|
||||||
]
|
]
|
||||||
cmd += map_args
|
cmd += map_args
|
||||||
cmd += [
|
cmd += ["-c:v", "h264_vaapi", "-qp", "25", "-compression_level", "0", "-c:a", "copy", "-c:s", "copy"]
|
||||||
"-c:v", "h264_vaapi", "-qp", "25", "-compression_level", "0",
|
|
||||||
"-c:a", "copy", "-c:s", "copy"
|
|
||||||
]
|
|
||||||
cmd += metadata_args
|
cmd += metadata_args
|
||||||
cmd.append(output_file)
|
cmd.append(output_file)
|
||||||
|
|
||||||
return cmd
|
return cmd
|
||||||
|
|
||||||
|
|
||||||
@@ -235,11 +240,9 @@ class EncoderWorker(threading.Thread):
|
|||||||
CURRENT_STATUS["total_files"] = len(files_to_process)
|
CURRENT_STATUS["total_files"] = len(files_to_process)
|
||||||
|
|
||||||
for i, fpath in enumerate(files_to_process):
|
for i, fpath in enumerate(files_to_process):
|
||||||
if CURRENT_STATUS["stop_requested"]:
|
if CURRENT_STATUS["stop_requested"]: break
|
||||||
break
|
|
||||||
|
|
||||||
fname = os.path.basename(fpath)
|
fname = os.path.basename(fpath)
|
||||||
|
|
||||||
CURRENT_STATUS["file"] = fname
|
CURRENT_STATUS["file"] = fname
|
||||||
CURRENT_STATUS["current_index"] = i + 1
|
CURRENT_STATUS["current_index"] = i + 1
|
||||||
CURRENT_STATUS["pct_file"] = 0
|
CURRENT_STATUS["pct_file"] = 0
|
||||||
@@ -248,7 +251,9 @@ class EncoderWorker(threading.Thread):
|
|||||||
rel = os.path.relpath(fpath, self.input_folder)
|
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.join(OUTPUT_BASE, os.path.basename(self.input_folder), rel)
|
||||||
out_file = os.path.splitext(out_file)[0] + ".mkv"
|
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)
|
size_before = os.path.getsize(fpath)
|
||||||
cmd = build_ffmpeg_command(fpath, out_file)
|
cmd = build_ffmpeg_command(fpath, out_file)
|
||||||
@@ -260,27 +265,21 @@ class EncoderWorker(threading.Thread):
|
|||||||
if CURRENT_STATUS["stop_requested"]:
|
if CURRENT_STATUS["stop_requested"]:
|
||||||
proc.terminate()
|
proc.terminate()
|
||||||
break
|
break
|
||||||
|
|
||||||
if "time=" in line:
|
if "time=" in line:
|
||||||
match = re.search(r"time=(\d{2}:\d{2}:\d{2}\.\d{2})", line)
|
match = re.search(r"time=(\d{2}:\d{2}:\d{2}\.\d{2})", line)
|
||||||
if match:
|
if match:
|
||||||
sec = parse_time_to_seconds(match.group(1))
|
sec = parse_time_to_seconds(match.group(1))
|
||||||
pct = min(int((sec/total_sec)*100), 100)
|
pct = min(int((sec/total_sec)*100), 100)
|
||||||
CURRENT_STATUS["pct_file"] = pct
|
CURRENT_STATUS["pct_file"] = pct
|
||||||
|
speed = re.search(r"speed=\s*(\S+)", line)
|
||||||
speed_match = re.search(r"speed=\s*(\S+)", line)
|
if speed: CURRENT_STATUS["log"] = f"Vel: {speed.group(1)}"
|
||||||
if speed_match:
|
|
||||||
CURRENT_STATUS["speed"] = speed_match.group(1)
|
|
||||||
CURRENT_STATUS["log"] = f"Vel: {CURRENT_STATUS['speed']}"
|
|
||||||
|
|
||||||
proc.wait()
|
proc.wait()
|
||||||
|
|
||||||
final_status = "Erro"
|
final_status = "Erro"
|
||||||
|
|
||||||
if CURRENT_STATUS["stop_requested"]:
|
if CURRENT_STATUS["stop_requested"]:
|
||||||
if os.path.exists(out_file): os.remove(out_file)
|
if os.path.exists(out_file): os.remove(out_file)
|
||||||
final_status = "Cancelado"
|
final_status = "Cancelado"
|
||||||
|
|
||||||
elif proc.returncode == 0:
|
elif proc.returncode == 0:
|
||||||
final_status = "✅ Sucesso"
|
final_status = "✅ Sucesso"
|
||||||
size_after = os.path.getsize(out_file) if os.path.exists(out_file) else 0
|
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)
|
"diff": ("+" if diff > 0 else "") + format_size(diff)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
handle_external_subtitles(fpath, dest_folder, self.delete_original)
|
||||||
|
|
||||||
if self.delete_original:
|
if self.delete_original:
|
||||||
try:
|
try:
|
||||||
os.remove(fpath)
|
os.remove(fpath)
|
||||||
CURRENT_STATUS["log"] = "Original excluído com sucesso."
|
CURRENT_STATUS["log"] = "Original excluído."
|
||||||
except: pass
|
except: pass
|
||||||
else:
|
else:
|
||||||
HISTORY_LOG.appendleft({
|
HISTORY_LOG.appendleft({
|
||||||
@@ -357,13 +358,10 @@ class EncoderInterface:
|
|||||||
|
|
||||||
def start_encoding(self):
|
def start_encoding(self):
|
||||||
should_delete = self.delete_switch.value if self.delete_switch else False
|
should_delete = self.delete_switch.value if self.delete_switch else False
|
||||||
|
|
||||||
CURRENT_STATUS["pct_file"] = 0
|
CURRENT_STATUS["pct_file"] = 0
|
||||||
CURRENT_STATUS["pct_total"] = 0
|
CURRENT_STATUS["pct_total"] = 0
|
||||||
|
|
||||||
t = EncoderWorker(self.path, delete_original=should_delete)
|
t = EncoderWorker(self.path, delete_original=should_delete)
|
||||||
t.start()
|
t.start()
|
||||||
|
|
||||||
ui.notify('Iniciando Conversão...', type='positive')
|
ui.notify('Iniciando Conversão...', type='positive')
|
||||||
self.view_mode = 'monitor'
|
self.view_mode = 'monitor'
|
||||||
self.refresh_ui()
|
self.refresh_ui()
|
||||||
@@ -394,20 +392,20 @@ class EncoderInterface:
|
|||||||
try:
|
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())
|
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
|
except: return
|
||||||
|
|
||||||
with ui.column().classes('w-full gap-1 mt-2'):
|
with ui.column().classes('w-full gap-1 mt-2'):
|
||||||
if self.path != ROOT_DIR:
|
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(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')
|
# Sintaxe correta: usando context manager (with)
|
||||||
with ui.item_section(): ui.item_label('.. (Subir nível)')
|
with ui.item_section().props('avatar'):
|
||||||
|
ui.icon('arrow_upward', color='grey')
|
||||||
if not entries:
|
with ui.item_section():
|
||||||
ui.label("Nenhuma subpasta encontrada aqui.").classes('text-grey italic p-4')
|
ui.item_label('.. (Subir nível)')
|
||||||
|
|
||||||
for entry in entries:
|
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(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().props('avatar'):
|
||||||
with ui.item_section(): ui.item_label(entry.name).classes('font-medium')
|
ui.icon('folder', color='amber')
|
||||||
|
with ui.item_section():
|
||||||
|
ui.item_label(entry.name).classes('font-medium')
|
||||||
|
|
||||||
def render_history_btn(self):
|
def render_history_btn(self):
|
||||||
ui.separator().classes('mt-4')
|
ui.separator().classes('mt-4')
|
||||||
@@ -419,7 +417,6 @@ class EncoderInterface:
|
|||||||
|
|
||||||
def render_history_table(self):
|
def render_history_table(self):
|
||||||
ui.label('Histórico de Conversões').classes('text-xl font-bold mb-4')
|
ui.label('Histórico de Conversões').classes('text-xl font-bold mb-4')
|
||||||
|
|
||||||
columns = [
|
columns = [
|
||||||
{'name': 'time', 'label': 'Hora', 'field': 'time', 'align': 'left'},
|
{'name': 'time', 'label': 'Hora', 'field': 'time', 'align': 'left'},
|
||||||
{'name': 'file', 'label': 'Arquivo', 'field': 'file', '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': 'final', 'label': 'Tam. Final', 'field': 'final_size'},
|
||||||
{'name': 'diff', 'label': 'Diferença', 'field': 'diff'},
|
{'name': 'diff', 'label': 'Diferença', 'field': 'diff'},
|
||||||
]
|
]
|
||||||
|
ui.table(columns=columns, rows=list(HISTORY_LOG), row_key='file').classes('w-full')
|
||||||
rows = list(HISTORY_LOG)
|
|
||||||
ui.table(columns=columns, rows=rows, row_key='file').classes('w-full')
|
|
||||||
|
|
||||||
ui.button('Voltar', on_click=lambda: self.set_view('explorer')).props('outline mt-4')
|
ui.button('Voltar', on_click=lambda: self.set_view('explorer')).props('outline mt-4')
|
||||||
|
|
||||||
def render_monitor(self):
|
def render_monitor(self):
|
||||||
ui.label('Monitor de Conversão').classes('text-xl font-bold mb-4')
|
ui.label('Monitor de Conversão').classes('text-xl font-bold mb-4')
|
||||||
|
|
||||||
lbl_file = ui.label('Inicializando...')
|
lbl_file = ui.label('Inicializando...')
|
||||||
progress_file = ui.linear_progress(value=0).classes('w-full')
|
progress_file = ui.linear_progress(value=0).classes('w-full')
|
||||||
lbl_log = ui.label('---').classes('text-caption text-grey')
|
lbl_log = ui.label('---').classes('text-caption text-grey')
|
||||||
|
|
||||||
ui.separator().classes('my-4')
|
ui.separator().classes('my-4')
|
||||||
|
|
||||||
lbl_total = ui.label('Total: 0/0')
|
lbl_total = ui.label('Total: 0/0')
|
||||||
progress_total = ui.linear_progress(value=0).classes('w-full')
|
progress_total = ui.linear_progress(value=0).classes('w-full')
|
||||||
|
|
||||||
@@ -461,15 +453,10 @@ class EncoderInterface:
|
|||||||
lbl_file.text = f"Arquivo: {CURRENT_STATUS['file']}"
|
lbl_file.text = f"Arquivo: {CURRENT_STATUS['file']}"
|
||||||
progress_file.value = CURRENT_STATUS['pct_file'] / 100
|
progress_file.value = CURRENT_STATUS['pct_file'] / 100
|
||||||
lbl_log.text = f"{int(CURRENT_STATUS['pct_file'])}% | {CURRENT_STATUS['log']}"
|
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']}"
|
lbl_total.text = f"Fila: {CURRENT_STATUS['current_index']} de {CURRENT_STATUS['total_files']}"
|
||||||
progress_total.value = CURRENT_STATUS['pct_total'] / 100
|
progress_total.value = CURRENT_STATUS['pct_total'] / 100
|
||||||
|
|
||||||
self.timer = ui.timer(0.5, update_monitor)
|
self.timer = ui.timer(0.5, update_monitor)
|
||||||
|
|
||||||
# ==============================================================================
|
|
||||||
# --- SEÇÃO 6: EXPORTAÇÃO PARA O MAIN.PY ---
|
|
||||||
# ==============================================================================
|
|
||||||
|
|
||||||
def create_ui():
|
def create_ui():
|
||||||
return EncoderInterface()
|
return EncoderInterface()
|
||||||
@@ -1 +1 @@
|
|||||||
{"Filmes": {"src": "/downloads/finalizados/Filmes", "dst": "/media/Jellyfin/onedrive/Jellyfin/Filmes"}}
|
{"Filmes": {"src": "/downloads/finalizados/Filmes", "dst": "/media/Jellyfin/onedrive/Jellyfin/Filmes"}, "S\u00e9ries": {"src": "/downloads/finalizados/S\u00e9ries", "dst": "/media/Jellyfin/onedrive/Jellyfin/Series"}, "Desenhos": {"src": "/downloads/finalizados/Desenhos", "dst": "/media/Jellyfin/onedrive/Jellyfin/Desenhos"}, "Animes": {"src": "/downloads/finalizados/Animes", "dst": "/media/Jellyfin/onedrive/Jellyfin/Animes"}}
|
||||||
Reference in New Issue
Block a user