Files
clei-flow/app/ui/settings.py
2026-02-10 00:56:46 +00:00

267 lines
16 KiB
Python
Executable File

from nicegui import ui
import os
from database import Category, FFmpegProfile, AppConfig
# --- CONSTANTES DE DADOS ---
# 1. Gêneros TMDb (Para as Categorias)
TMDB_GENRES = {
'28': 'Ação (Action)', '12': 'Aventura (Adventure)', '16': 'Animação (Animation)',
'35': 'Comédia (Comedy)', '80': 'Crime', '99': 'Documentário', '18': 'Drama',
'10751': 'Família (Family)', '14': 'Fantasia (Fantasy)', '36': 'História',
'27': 'Terror (Horror)', '10402': 'Música (Music)', '9648': 'Mistério',
'10749': 'Romance', '878': 'Ficção Científica (Sci-Fi)', '10770': 'Cinema TV',
'53': 'Thriller', '10752': 'Guerra (War)', '37': 'Faroeste (Western)',
'10759': 'Action & Adventure (TV)', '10762': 'Kids (TV)', '10765': 'Sci-Fi & Fantasy (TV)'
}
# 2. Países Comuns (Para as Categorias)
COMMON_COUNTRIES = {
'JP': '🇯🇵 Japão (Anime)', 'US': '🇺🇸 EUA (Hollywood)', 'BR': '🇧🇷 Brasil',
'KR': '🇰🇷 Coreia do Sul (Dorama)', 'GB': '🇬🇧 Reino Unido', 'ES': '🇪🇸 Espanha',
'FR': '🇫🇷 França', 'CN': '🇨🇳 China', 'IN': '🇮🇳 Índia'
}
# 3. Idiomas ISO-639-2 (Para o FFmpeg - ESTAVA FALTANDO ISSO)
ISO_LANGS = {
'por': 'Português (por)', 'eng': 'Inglês (eng)', 'jpn': 'Japonês (jpn)',
'spa': 'Espanhol (spa)', 'fra': 'Francês (fra)', 'ger': 'Alemão (ger)',
'ita': 'Italiano (ita)', 'rus': 'Russo (rus)', 'kor': 'Coreano (kor)',
'zho': 'Chinês (zho)', 'und': 'Indefinido (und)'
}
# --- SELETOR DE PASTAS ---
async def pick_folder_dialog(start_path='/media'):
ALLOWED_ROOT = '/media'
if not start_path or not start_path.startswith(ALLOWED_ROOT): start_path = ALLOWED_ROOT
result = {'path': None}
with ui.dialog() as dialog, ui.card().classes('w-96 h-[500px] flex flex-col'):
ui.label('Selecionar Pasta (/media)').classes('font-bold text-lg mb-2')
path_label = ui.label(start_path).classes('text-xs bg-gray-100 p-2 border rounded w-full break-all font-mono')
scroll = ui.scroll_area().classes('flex-grow border rounded p-1 mt-2 bg-white')
async def load_dir(path):
if not path.startswith(ALLOWED_ROOT): path = ALLOWED_ROOT
path_label.text = path
scroll.clear()
try:
if path != ALLOWED_ROOT:
parent = os.path.dirname(path)
if not parent.startswith(ALLOWED_ROOT): parent = ALLOWED_ROOT
with scroll: ui.button('.. (Voltar)', on_click=lambda: load_dir(parent)).props('flat dense icon=arrow_upward align=left w-full')
with scroll:
if os.path.exists(path):
for entry in sorted([e for e in os.scandir(path) if e.is_dir()], key=lambda x: x.name.lower()):
ui.button(entry.name, on_click=lambda p=entry.path: load_dir(p)).props('flat dense icon=folder align=left w-full color=amber-8')
else: ui.label('Pasta nova').classes('text-gray-400 italic p-2')
except Exception as e:
with scroll: ui.label(f'Erro: {e}').classes('text-red text-xs')
def select_this(): result['path'] = path_label.text; dialog.close()
with ui.row().classes('w-full justify-between mt-auto pt-2'):
ui.button('Cancelar', on_click=dialog.close).props('flat color=grey')
ui.button('Selecionar Esta', on_click=select_this).props('flat icon=check color=green')
await load_dir(start_path)
await dialog
return result['path']
# --- TELA PRINCIPAL ---
def show():
with ui.column().classes('w-full p-6'):
ui.label('Configurações').classes('text-3xl font-light text-gray-800 mb-4')
with ui.tabs().classes('w-full') as tabs:
tab_ident = ui.tab('Identificação', icon='search')
tab_cats = ui.tab('Categorias', icon='category')
tab_deploy = ui.tab('Deploy & Caminhos', icon='move_to_inbox')
tab_ffmpeg = ui.tab('Motor (FFmpeg)', icon='movie')
tab_telegram = ui.tab('Telegram', icon='send')
with ui.tab_panels(tabs).classes('w-full bg-gray-50 p-4 rounded border'):
# --- ABA 1: IDENTIFICAÇÃO ---
with ui.tab_panel(tab_ident):
with ui.card().classes('w-full max-w-2xl mx-auto p-6'):
ui.label('🔍 Configuração do Identificador').classes('text-2xl font-bold mb-4 text-indigo-600')
tmdb_key = AppConfig.get_val('tmdb_api_key', '')
lang = AppConfig.get_val('tmdb_language', 'pt-BR')
confidence = AppConfig.get_val('min_confidence', '90')
ui.input('API Key do TMDb', value=tmdb_key, password=True, on_change=lambda e: AppConfig.set_val('tmdb_api_key', e.value)).classes('w-full mb-4')
with ui.grid(columns=2).classes('w-full gap-4'):
ui.input('Idioma', value=lang, on_change=lambda e: AppConfig.set_val('tmdb_language', e.value))
ui.number('Confiança Auto (%)', value=int(confidence), min=50, max=100, on_change=lambda e: AppConfig.set_val('min_confidence', str(int(e.value))))
ui.notify('As alterações são salvas automaticamente.', type='info', position='bottom')
# --- ABA 2: CATEGORIAS ---
with ui.tab_panel(tab_cats):
ui.label('Regras de Organização').classes('text-xl text-gray-700 mb-2')
cats_container = ui.column().classes('w-full gap-2')
def load_cats():
cats_container.clear()
cats = list(Category.select())
if not cats: ui.label('Nenhuma categoria criada.').classes('text-gray-400')
for cat in cats:
# Processa filtros para exibição
g_ids = cat.genre_filters.split(',') if cat.genre_filters else []
c_codes = cat.country_filters.split(',') if cat.country_filters else []
g_names = [TMDB_GENRES.get(gid, gid) for gid in g_ids if gid]
c_names = [COMMON_COUNTRIES.get(cc, cc) for cc in c_codes if cc]
desc_text = f"Tipo: {cat.content_type.upper()}"
if g_names: desc_text += f" | Gêneros: {', '.join(g_names)}"
if c_names: desc_text += f" | Países: {', '.join(c_names)}"
if not g_names and not c_names: desc_text += " | (Genérico/Padrão)"
color_cls = 'bg-white border-gray-200'
if 'Animação' in str(g_names) and 'Japão' in str(c_names): color_cls = 'bg-purple-50 border-purple-200' # Anime visual
elif 'Animação' in str(g_names): color_cls = 'bg-yellow-50 border-yellow-200' # Desenho visual
with cats_container, ui.card().classes(f'w-full flex-row items-center justify-between p-3 border {color_cls}'):
with ui.row().classes('items-center gap-4'):
icon = 'movie' if cat.content_type == 'movie' else ('tv' if cat.content_type == 'series' else 'shuffle')
ui.icon(icon).classes('text-gray-600')
with ui.column().classes('gap-0'):
ui.label(cat.name).classes('font-bold text-lg')
ui.label(desc_text).classes('text-xs text-gray-500')
ui.button(icon='delete', color='red', on_click=lambda c=cat: delete_cat(c)).props('flat dense')
def add_cat():
if not name_input.value: return
# Converte listas para string CSV
g_str = ",".join(genre_select.value) if genre_select.value else ""
c_str = ",".join(country_select.value) if country_select.value else ""
try:
Category.create(
name=name_input.value,
target_path=f"/media/{name_input.value}",
content_type=type_select.value,
genre_filters=g_str,
country_filters=c_str
)
name_input.value = ''; genre_select.value = []; country_select.value = []
ui.notify('Categoria criada!', type='positive')
load_cats()
except Exception as e: ui.notify(f'Erro: {e}', type='negative')
def delete_cat(cat):
cat.delete_instance()
load_cats()
# Formulário de Criação Inteligente
with ui.card().classes('w-full mb-4 bg-gray-100 p-4'):
ui.label('Nova Biblioteca').classes('font-bold text-gray-700')
with ui.grid(columns=4).classes('w-full gap-2'):
name_input = ui.input('Nome (ex: Animes)')
type_select = ui.select({
'mixed': 'Misto (Filmes e Séries)',
'movie': 'Apenas Filmes',
'series': 'Apenas Séries'
}, value='mixed', label='Tipo de Conteúdo')
# Novos Seletores Múltiplos
genre_select = ui.select(TMDB_GENRES, multiple=True, label='Filtrar Gêneros (Opcional)').props('use-chips')
country_select = ui.select(COMMON_COUNTRIES, multiple=True, label='Filtrar País (Opcional)').props('use-chips')
ui.button('Adicionar Regra', on_click=add_cat).props('icon=add color=green').classes('mt-2 w-full')
load_cats()
# --- ABA 3: DEPLOY ---
with ui.tab_panel(tab_deploy):
async def open_picker(input_element):
start = input_element.value if input_element.value else '/'
selected = await pick_folder_dialog(start)
if selected: input_element.value = selected
with ui.card().classes('w-full mb-6 border-l-4 border-amber-500 bg-amber-50'):
ui.label('📡 Origem dos Arquivos').classes('text-lg font-bold mb-2 text-amber-900')
monitor_path = AppConfig.get_val('monitor_path', '/downloads')
with ui.row().classes('w-full items-center gap-2'):
mon_input = ui.input('Pasta Monitorada', value=monitor_path).classes('flex-grow font-mono bg-white rounded px-2')
ui.button(icon='folder', on_click=lambda i=mon_input: open_picker(i)).props('flat dense color=amber-9')
ui.button('Salvar Origem', on_click=lambda: (AppConfig.set_val('monitor_path', mon_input.value), ui.notify('Salvo!'))).classes('mt-2 bg-amber-600 text-white')
ui.label('📂 Mapeamento de Destinos (/media)').classes('text-xl text-gray-700 mt-4')
paths_container = ui.column().classes('w-full gap-2')
def load_deploy_paths():
paths_container.clear()
for cat in list(Category.select()):
with paths_container, ui.card().classes('w-full p-4 flex-row items-center gap-4'):
ui.label(cat.name).classes('font-bold w-32')
path_input = ui.input(value=cat.target_path).classes('flex-grow font-mono')
ui.button(icon='folder', on_click=lambda i=path_input: open_picker(i)).props('flat dense color=amber-8')
ui.button(icon='save', on_click=lambda c=cat, p=path_input: (setattr(c, 'target_path', p.value), c.save(), ui.notify('Salvo!'))).props('flat round color=green')
load_deploy_paths()
# --- ABA 4: FFMPEG (AGORA COM ISO_LANGS CORRIGIDO) ---
with ui.tab_panel(tab_ffmpeg):
ui.label('Perfis de Conversão').classes('text-xl text-gray-700')
profiles_query = list(FFmpegProfile.select())
profiles_dict = {p.id: p.name for p in profiles_query}
active_profile = next((p for p in profiles_query if p.is_active), None)
initial_val = active_profile.id if active_profile else None
def set_active_profile(e):
if not e.value: return
FFmpegProfile.update(is_active=False).execute()
FFmpegProfile.update(is_active=True).where(FFmpegProfile.id == int(e.value)).execute()
ui.notify(f'Perfil "{profiles_dict[e.value]}" ativado!', type='positive')
select_profile = ui.select(profiles_dict, value=initial_val, label='Perfil Ativo', on_change=set_active_profile).classes('w-64 mb-6')
ui.separator()
for p in profiles_query:
with ui.expansion(f"{p.name}", icon='tune').classes('w-full bg-white mb-2 border rounded'):
with ui.column().classes('p-4 w-full'):
with ui.grid(columns=2).classes('w-full gap-4'):
c_name = ui.input('Nome', value=p.name)
c_codec = ui.select({
'h264_vaapi': 'Intel VAAPI (Linux/Docker)',
'h264_qsv': 'Intel QuickSync',
'h264_nvenc': 'Nvidia NVENC',
'libx264': 'CPU',
'copy': 'Copy'
}, value=p.video_codec, label='Codec')
c_preset = ui.select(['fast', 'medium', 'slow'], value=p.preset, label='Preset')
c_crf = ui.number('CRF/QP', value=p.crf, min=0, max=51)
audios = p.audio_langs.split(',') if p.audio_langs else []
subs = p.subtitle_langs.split(',') if p.subtitle_langs else []
# AQUI ESTAVA O ERRO (ISO_LANGS faltando)
c_audio = ui.select(ISO_LANGS, value=audios, multiple=True, label='Áudios').props('use-chips')
c_sub = ui.select(ISO_LANGS, value=subs, multiple=True, label='Legendas').props('use-chips')
def save_profile(prof=p, n=c_name, c=c_codec, pr=c_preset, cr=c_crf, a=c_audio, s=c_sub):
prof.name = n.value; prof.video_codec = c.value; prof.preset = pr.value
prof.crf = int(cr.value); prof.audio_langs = ",".join(a.value); prof.subtitle_langs = ",".join(s.value)
prof.save()
profiles_dict[prof.id] = prof.name
select_profile.options = profiles_dict
select_profile.update()
ui.notify('Salvo!')
ui.button('Salvar', on_click=save_profile).classes('mt-2')
# --- ABA 5: TELEGRAM ---
with ui.tab_panel(tab_telegram):
with ui.card().classes('w-full max-w-lg mx-auto p-6'):
ui.label('🤖 Integração Telegram').classes('text-2xl font-bold mb-4 text-blue-600')
t_token = AppConfig.get_val('telegram_token', '')
t_chat = AppConfig.get_val('telegram_chat_id', '')
token_input = ui.input('Bot Token', value=t_token).props('password').classes('w-full mb-2')
chat_input = ui.input('Chat ID', value=t_chat).classes('w-full mb-6')
def save_telegram():
AppConfig.set_val('telegram_token', token_input.value)
AppConfig.set_val('telegram_chat_id', chat_input.value)
ui.notify('Salvo!', type='positive')
ui.button('Salvar', on_click=save_telegram).props('icon=save color=blue').classes('w-full')