consertada a indentificação

This commit is contained in:
2026-02-10 00:56:46 +00:00
parent d77f17df27
commit bd59ba234c
4 changed files with 200 additions and 203 deletions

View File

@@ -74,7 +74,7 @@ class DirectoryWatcher:
self.abort_flag = False self.abort_flag = False
state.current_file = fname state.current_file = fname
# Etapa 1: Identificação (Global 0-15%) # --- 1. IDENTIFICAÇÃO ---
state.update_task(fname, 'running', progress=5, label=f"Identificando: {fname}...") state.update_task(fname, 'running', progress=5, label=f"Identificando: {fname}...")
state.log(f"🔄 Iniciando: {fname}") state.log(f"🔄 Iniciando: {fname}")
@@ -119,21 +119,35 @@ class DirectoryWatcher:
if self.abort_flag: return if self.abort_flag: return
# Etapa 2: Categoria # --- METADADOS E CATEGORIA ---
category = self.find_category(target_info['type'])
if not category:
state.update_task(fname, 'error', 0, label="Sem Categoria")
return
# Etapa 3: Conversão
try: try:
details = self.renamer.get_details(target_info['tmdb_id'], target_info['type']) details = self.renamer.get_details(target_info['tmdb_id'], target_info['type'])
r_title = getattr(details, 'title', getattr(details, 'name', 'Unknown')) or 'Unknown' r_title = getattr(details, 'title', getattr(details, 'name', 'Unknown')) or 'Unknown'
# Extração de IDs e Códigos para a nova Lógica
# IDs de Gênero (Ex: [16, 28])
tmdb_genre_ids = [str(g['id']) for g in getattr(details, 'genres', [])]
# Países de Origem (Ex: ['JP', 'US'])
origin_countries = getattr(details, 'origin_country', [])
if isinstance(origin_countries, str): origin_countries = [origin_countries]
origin_countries = [c.upper() for c in origin_countries]
state.log(f" Dados: Gêneros={tmdb_genre_ids} | Países={origin_countries}")
full_details = {'title': r_title, 'year': '0000', 'type': target_info['type']} full_details = {'title': r_title, 'year': '0000', 'type': target_info['type']}
d_date = getattr(details, 'release_date', getattr(details, 'first_air_date', '0000')) d_date = getattr(details, 'release_date', getattr(details, 'first_air_date', '0000'))
if d_date: full_details['year'] = str(d_date)[:4] if d_date: full_details['year'] = str(d_date)[:4]
# --- 2. CATEGORIA INTELIGENTE (NOVA LÓGICA) ---
category = self.find_best_category(target_info['type'], tmdb_genre_ids, origin_countries)
if not category:
state.update_task(fname, 'error', 0, label="Sem Categoria")
return
state.log(f"📂 Categoria Vencedora: {category.name}")
# --- 3. CONVERSÃO ---
guessed_data = result.get('guessed', {}) guessed_data = result.get('guessed', {})
relative_path = self.renamer.build_path(category, full_details, guessed_data) relative_path = self.renamer.build_path(category, full_details, guessed_data)
@@ -143,71 +157,40 @@ class DirectoryWatcher:
state.update_task(fname, 'running', progress=15, label=f"Convertendo: {full_details['title']}") state.update_task(fname, 'running', progress=15, label=f"Convertendo: {full_details['title']}")
engine = FFmpegEngine() engine = FFmpegEngine()
# Tenta pegar duração total em Segundos
total_duration_sec = engine.get_duration(str(filepath)) total_duration_sec = engine.get_duration(str(filepath))
# Converte para microsegundos para bater com o FFmpeg
total_duration_us = total_duration_sec * 1000000 total_duration_us = total_duration_sec * 1000000
cmd = engine.build_command(str(filepath), str(temp_output)) cmd = engine.build_command(str(filepath), str(temp_output))
cmd.insert(1, '-progress'); cmd.insert(2, 'pipe:1')
# --- MODIFICAÇÃO: Injeta flag para saída legível por máquina (stdout) ---
# Isso garante que teremos dados de progresso confiáveis
cmd.insert(1, '-progress')
cmd.insert(2, 'pipe:1')
# Redireciona stdout para pegarmos os dados. Stderr fica para erros/warnings.
self.current_process = await asyncio.create_subprocess_exec( self.current_process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
) )
# --- LOOP DE PROGRESSO (MÉTODO KEY=VALUE) ---
current_speed_str = "" current_speed_str = ""
while True: while True:
if self.abort_flag: if self.abort_flag:
self.current_process.kill() self.current_process.kill()
break break
# Lê stdout (progresso)
line_bytes = await self.current_process.stdout.readline() line_bytes = await self.current_process.stdout.readline()
if not line_bytes: break if not line_bytes: break
line = line_bytes.decode('utf-8', errors='ignore').strip() line = line_bytes.decode('utf-8', errors='ignore').strip()
# O formato é chave=valor
if '=' in line: if '=' in line:
key, value = line.split('=', 1) key, value = line.split('=', 1)
key = key.strip() key = key.strip(); value = value.strip()
value = value.strip()
# 1. Tempo decorrido (em microsegundos)
if key == 'out_time_us': if key == 'out_time_us':
try: try:
current_us = int(value) current_us = int(value)
if total_duration_us > 0: if total_duration_us > 0:
file_pct = (current_us / total_duration_us) * 100 file_pct = (current_us / total_duration_us) * 100
if file_pct > 100: file_pct = 100 if file_pct > 100: file_pct = 100
if file_pct < 0: file_pct = 0 # As vezes vem negativo no inicio if file_pct < 0: file_pct = 0
# Global: 15% a 99%
global_pct = 15 + (file_pct * 0.84) global_pct = 15 + (file_pct * 0.84)
state.update_task(fname, 'running', progress=global_pct, file_progress=file_pct, speed=current_speed_str, label=f"Processando: {full_details['title']}")
state.update_task(
fname, 'running',
progress=global_pct,
file_progress=file_pct,
speed=current_speed_str,
label=f"Processando: {full_details['title']}"
)
except: pass except: pass
elif key == 'speed': current_speed_str = value
# 2. Velocidade
elif key == 'speed':
current_speed_str = value
await self.current_process.wait() await self.current_process.wait()
# -----------------------------------
if self.abort_flag: if self.abort_flag:
state.update_task(fname, 'error', 0, label="Abortado") state.update_task(fname, 'error', 0, label="Abortado")
@@ -215,14 +198,13 @@ class DirectoryWatcher:
return return
if self.current_process.returncode != 0: if self.current_process.returncode != 0:
# Se falhar, lemos o stderr para saber o motivo
err_log = await self.current_process.stderr.read() err_log = await self.current_process.stderr.read()
state.log(f"❌ Erro FFmpeg: {err_log.decode('utf-8')[-200:]}") state.log(f"❌ Erro FFmpeg: {err_log.decode('utf-8')[-200:]}")
state.update_task(fname, 'error', 0, label="Erro FFmpeg") state.update_task(fname, 'error', 0, label="Erro FFmpeg")
return return
self.current_process = None self.current_process = None
# Etapa 4: Deploy # --- 4. DEPLOY ---
state.update_task(fname, 'running', progress=99, label="Organizando...") state.update_task(fname, 'running', progress=99, label="Organizando...")
final_full_path = Path(category.target_path) / relative_path final_full_path = Path(category.target_path) / relative_path
final_full_path.parent.mkdir(parents=True, exist_ok=True) final_full_path.parent.mkdir(parents=True, exist_ok=True)
@@ -253,12 +235,78 @@ class DirectoryWatcher:
state.log(f"Erro Pipeline: {e}") state.log(f"Erro Pipeline: {e}")
state.update_task(fname, 'error', 0, label=f"Erro: {e}") state.update_task(fname, 'error', 0, label=f"Erro: {e}")
def find_category(self, media_type): def find_best_category(self, media_type, genre_ids, countries):
keywords = ['movie', 'film', 'filme'] if media_type == 'movie' else ['tv', 'serie', 'série'] """
Sistema de Pontuação 3.0 (Regras Estritas)
Agora compara IDs e Siglas, não texto.
"""
all_cats = list(Category.select()) all_cats = list(Category.select())
if not all_cats: return None
candidates = []
# 1. Filtro Rígido de TIPO (Movie vs Series)
for cat in all_cats: for cat in all_cats:
if not cat.match_keywords: continue if media_type == 'movie' and cat.content_type == 'series': continue
cat_keys = [k.strip().lower() for k in cat.match_keywords.split(',')] if media_type != 'movie' and cat.content_type == 'movie': continue
if any(k in cat_keys for k in keywords): candidates.append(cat)
return cat
return all_cats[0] if all_cats else None if not candidates: return all_cats[0]
scored_cats = []
for cat in candidates:
score = 0
# Carrega filtros da categoria
cat_genres = cat.genre_filters.split(',') if cat.genre_filters else []
cat_countries = cat.country_filters.split(',') if cat.country_filters else []
cat_genres = [g for g in cat_genres if g] # Limpa vazios
cat_countries = [c for c in cat_countries if c]
# --- Lógica de Correspondência ---
match_genre = False
match_country = False
# Verifica Gêneros (Se a categoria tiver filtros, TEM que bater)
if cat_genres:
# Se o arquivo tiver pelo menos UM dos gêneros da lista
if any(gid in cat_genres for gid in genre_ids):
match_genre = True
score += 50 # Ganha muitos pontos por match específico
else:
# Se a categoria exige gênero e o arquivo não tem -> Categoria Descartada
score = -1000
else:
# Categoria genérica de gênero (aceita tudo)
match_genre = True
score += 10 # Pontuação base baixa
# Verifica Países
if cat_countries:
if any(cc in cat_countries for cc in countries):
match_country = True
score += 50 # Ganha pontos por match de país
else:
score = -1000 # Exige país mas não bate -> Descartada
else:
match_country = True
score += 10
# Bônus se for categoria Mista (geralmente usada para Anime/Desenho)
if cat.content_type == 'mixed' and score > 0:
score += 5
scored_cats.append((score, cat))
# Ordena
scored_cats.sort(key=lambda x: x[0], reverse=True)
best_match = scored_cats[0]
# Se a pontuação for negativa, significa que nenhuma regra bateu.
# Devemos pegar uma categoria genérica (sem filtros)
if best_match[0] < 0:
for cat in candidates:
if not cat.genre_filters and not cat.country_filters:
return cat
return best_match[1]

View File

@@ -29,9 +29,12 @@ class AppConfig(BaseModel):
class Category(BaseModel): class Category(BaseModel):
name = CharField(unique=True) name = CharField(unique=True)
target_path = CharField() target_path = CharField()
match_keywords = CharField(null=True) # Ex: movie, film match_keywords = CharField(null=True) # Mantido para legado, mas vamos priorizar os filtros abaixo
# NOVO CAMPO: Tipo de conteúdo (movie, series, mixed) content_type = CharField(default='mixed') # movie, series, mixed
content_type = CharField(default='mixed')
# NOVOS CAMPOS DE FILTRAGEM
genre_filters = CharField(null=True) # Ex: "16,28,35" (IDs do TMDb)
country_filters = CharField(null=True) # Ex: "JP,US,BR" (Siglas ISO)
class FFmpegProfile(BaseModel): class FFmpegProfile(BaseModel):
name = CharField() name = CharField()
@@ -46,12 +49,17 @@ def init_db():
db.connect() db.connect()
db.create_tables([AppConfig, Category, FFmpegProfile], safe=True) db.create_tables([AppConfig, Category, FFmpegProfile], safe=True)
# Migração segura para adicionar coluna se não existir # Migrações Seguras (Adiciona colunas se não existirem)
try: try: db.execute_sql('ALTER TABLE category ADD COLUMN content_type VARCHAR DEFAULT "mixed"')
db.execute_sql('ALTER TABLE category ADD COLUMN content_type VARCHAR DEFAULT "mixed"') except: pass
except: pass # Já existe
# Perfil padrão se não existir try: db.execute_sql('ALTER TABLE category ADD COLUMN genre_filters VARCHAR DEFAULT ""')
except: pass
try: db.execute_sql('ALTER TABLE category ADD COLUMN country_filters VARCHAR DEFAULT ""')
except: pass
# Perfil padrão
if FFmpegProfile.select().count() == 0: if FFmpegProfile.select().count() == 0:
FFmpegProfile.create(name="Padrão VAAPI (Intel)", video_codec="h264_vaapi", is_active=True) FFmpegProfile.create(name="Padrão VAAPI (Intel)", video_codec="h264_vaapi", is_active=True)

View File

@@ -2,67 +2,63 @@ from nicegui import ui
import os import os
from database import Category, FFmpegProfile, AppConfig from database import Category, FFmpegProfile, AppConfig
# Lista de idiomas (ISO 639-2) # --- 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 = { ISO_LANGS = {
'por': 'Português (por)', 'eng': 'Inglês (eng)', 'jpn': 'Japonês (jpn)', 'por': 'Português (por)', 'eng': 'Inglês (eng)', 'jpn': 'Japonês (jpn)',
'spa': 'Espanhol (spa)', 'fra': 'Francês (fra)', 'ger': 'Alemão (ger)', 'spa': 'Espanhol (spa)', 'fra': 'Francês (fra)', 'ger': 'Alemão (ger)',
'ita': 'Italiano (ita)', 'rus': 'Russo (rus)', 'und': 'Indefinido (und)' 'ita': 'Italiano (ita)', 'rus': 'Russo (rus)', 'kor': 'Coreano (kor)',
'zho': 'Chinês (zho)', 'und': 'Indefinido (und)'
} }
# --- COMPONENTE: SELETOR DE PASTAS (Restrito ao /media) --- # --- SELETOR DE PASTAS ---
async def pick_folder_dialog(start_path='/media'): async def pick_folder_dialog(start_path='/media'):
"""Abre um modal para escolher pastas, restrito a /media"""
ALLOWED_ROOT = '/media' ALLOWED_ROOT = '/media'
if not start_path or not start_path.startswith(ALLOWED_ROOT): start_path = ALLOWED_ROOT
# Garante que começa dentro do permitido
if not start_path or not start_path.startswith(ALLOWED_ROOT):
start_path = ALLOWED_ROOT
result = {'path': None} result = {'path': None}
with ui.dialog() as dialog, ui.card().classes('w-96 h-[500px] flex flex-col'): 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') 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') 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') scroll = ui.scroll_area().classes('flex-grow border rounded p-1 mt-2 bg-white')
async def load_dir(path): async def load_dir(path):
# Segurança extra
if not path.startswith(ALLOWED_ROOT): path = ALLOWED_ROOT if not path.startswith(ALLOWED_ROOT): path = ALLOWED_ROOT
path_label.text = path path_label.text = path
scroll.clear() scroll.clear()
try: try:
# Botão Voltar (Só aparece se NÃO estiver na raiz permitida)
if path != ALLOWED_ROOT: if path != ALLOWED_ROOT:
parent = os.path.dirname(path) parent = os.path.dirname(path)
# Garante que o parent não suba além do permitido
if not parent.startswith(ALLOWED_ROOT): parent = ALLOWED_ROOT 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:
ui.button('.. (Voltar)', on_click=lambda: load_dir(parent)).props('flat dense icon=arrow_upward align=left w-full')
# Lista Pastas
with scroll: with scroll:
# Tenta listar. Se diretório não existir (ex: nome novo), mostra vazio
if os.path.exists(path): 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()): 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') 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: else: ui.label('Pasta nova').classes('text-gray-400 italic p-2')
ui.label('Pasta não criada ainda.').classes('text-gray-400 italic p-2')
except Exception as e: except Exception as e:
with scroll: ui.label(f'Erro: {e}').classes('text-red text-xs') with scroll: ui.label(f'Erro: {e}').classes('text-red text-xs')
def select_this(): result['path'] = path_label.text; dialog.close()
def select_this():
result['path'] = path_label.text
dialog.close()
with ui.row().classes('w-full justify-between mt-auto pt-2'): 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('Cancelar', on_click=dialog.close).props('flat color=grey')
ui.button('Selecionar Esta', on_click=select_this).props('flat icon=check color=green') ui.button('Selecionar Esta', on_click=select_this).props('flat icon=check color=green')
await load_dir(start_path) await load_dir(start_path)
await dialog await dialog
return result['path'] return result['path']
@@ -79,7 +75,7 @@ def show():
tab_ffmpeg = ui.tab('Motor (FFmpeg)', icon='movie') tab_ffmpeg = ui.tab('Motor (FFmpeg)', icon='movie')
tab_telegram = ui.tab('Telegram', icon='send') tab_telegram = ui.tab('Telegram', icon='send')
with ui.tab_panels(tabs, value=tab_ident).classes('w-full bg-gray-50 p-4 rounded border'): with ui.tab_panels(tabs).classes('w-full bg-gray-50 p-4 rounded border'):
# --- ABA 1: IDENTIFICAÇÃO --- # --- ABA 1: IDENTIFICAÇÃO ---
with ui.tab_panel(tab_ident): with ui.tab_panel(tab_ident):
@@ -89,63 +85,63 @@ def show():
lang = AppConfig.get_val('tmdb_language', 'pt-BR') lang = AppConfig.get_val('tmdb_language', 'pt-BR')
confidence = AppConfig.get_val('min_confidence', '90') confidence = AppConfig.get_val('min_confidence', '90')
ui.label('API Key do TMDb').classes('font-bold text-sm') 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')
key_input = ui.input(placeholder='Ex: 8a9b...', value=tmdb_key).props('password').classes('w-full mb-4')
ui.markdown('[Clique aqui para pegar sua API Key](https://www.themoviedb.org/settings/api)').classes('text-xs text-blue-500 mb-6')
with ui.grid(columns=2).classes('w-full gap-4'): with ui.grid(columns=2).classes('w-full gap-4'):
lang_input = ui.input('Idioma', value=lang, placeholder='pt-BR') ui.input('Idioma', value=lang, on_change=lambda e: AppConfig.set_val('tmdb_language', e.value))
conf_input = ui.number('Confiança Auto (%)', value=int(confidence), min=50, max=100) 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')
def save_ident(): # --- ABA 2: CATEGORIAS ---
AppConfig.set_val('tmdb_api_key', key_input.value)
AppConfig.set_val('tmdb_language', lang_input.value)
AppConfig.set_val('min_confidence', str(int(conf_input.value)))
ui.notify('Salvo!', type='positive')
ui.button('Salvar', on_click=save_ident).props('icon=save color=indigo').classes('w-full mt-6')
# --- ABA 2: CATEGORIAS (ATUALIZADA) ---
with ui.tab_panel(tab_cats): with ui.tab_panel(tab_cats):
ui.label('Bibliotecas e Tipos').classes('text-xl text-gray-700 mb-2') ui.label('Regras de Organização').classes('text-xl text-gray-700 mb-2')
cats_container = ui.column().classes('w-full gap-2') cats_container = ui.column().classes('w-full gap-2')
def load_cats(): def load_cats():
cats_container.clear() cats_container.clear()
cats = list(Category.select()) cats = list(Category.select())
if not cats: ui.label('Nenhuma categoria.').classes('text-gray-400') if not cats: ui.label('Nenhuma categoria criada.').classes('text-gray-400')
for cat in cats: for cat in cats:
# Define ícone e cor baseados no tipo # Processa filtros para exibição
icon = 'movie' if cat.content_type == 'movie' else 'tv' g_ids = cat.genre_filters.split(',') if cat.genre_filters else []
if cat.content_type == 'mixed': icon = 'shuffle' c_codes = cat.country_filters.split(',') if cat.country_filters else []
color_cls = 'bg-blue-50 border-blue-200' g_names = [TMDB_GENRES.get(gid, gid) for gid in g_ids if gid]
if cat.content_type == 'series': color_cls = 'bg-green-50 border-green-200' c_names = [COMMON_COUNTRIES.get(cc, cc) for cc in c_codes if cc]
if cat.content_type == 'mixed': color_cls = 'bg-purple-50 border-purple-200'
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 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'): 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') ui.icon(icon).classes('text-gray-600')
with ui.column().classes('gap-0'): with ui.column().classes('gap-0'):
ui.label(cat.name).classes('font-bold text-lg') ui.label(cat.name).classes('font-bold text-lg')
# Mostra o tipo visualmente ui.label(desc_text).classes('text-xs text-gray-500')
type_map = {'movie': 'Só Filmes', 'series': 'Só Séries', 'mixed': 'Misto (Filmes e Séries)'}
ui.label(f"Tipo: {type_map.get(cat.content_type, 'Misto')} | Tags: {cat.match_keywords}").classes('text-xs text-gray-500')
ui.button(icon='delete', color='red', on_click=lambda c=cat: delete_cat(c)).props('flat dense') ui.button(icon='delete', color='red', on_click=lambda c=cat: delete_cat(c)).props('flat dense')
def add_cat(): def add_cat():
if not name_input.value: return 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: try:
Category.create( Category.create(
name=name_input.value, name=name_input.value,
target_path=f"/media/{name_input.value}", target_path=f"/media/{name_input.value}",
match_keywords=keywords_input.value, content_type=type_select.value,
content_type=type_select.value # Salva o tipo escolhido genre_filters=g_str,
country_filters=c_str
) )
name_input.value = ''; keywords_input.value = '' name_input.value = ''; genre_select.value = []; country_select.value = []
ui.notify('Categoria criada!', type='positive') ui.notify('Categoria criada!', type='positive')
load_cats() load_cats()
except Exception as e: ui.notify(f'Erro: {e}', type='negative') except Exception as e: ui.notify(f'Erro: {e}', type='negative')
@@ -154,132 +150,75 @@ def show():
cat.delete_instance() cat.delete_instance()
load_cats() load_cats()
# Formulário de Criação # Formulário de Criação Inteligente
with ui.card().classes('w-full mb-4 bg-gray-100 p-4'): with ui.card().classes('w-full mb-4 bg-gray-100 p-4'):
ui.label('Nova Biblioteca').classes('font-bold text-gray-700') ui.label('Nova Biblioteca').classes('font-bold text-gray-700')
with ui.row().classes('w-full items-start gap-2'): with ui.grid(columns=4).classes('w-full gap-2'):
name_input = ui.input('Nome (ex: Animes)').classes('w-1/4') name_input = ui.input('Nome (ex: Animes)')
keywords_input = ui.input('Tags (ex: anime, animation)').classes('w-1/4')
# NOVO SELETOR DE TIPO
type_select = ui.select({ type_select = ui.select({
'mixed': 'Misto (Filmes e Séries)', 'mixed': 'Misto (Filmes e Séries)',
'movie': 'Apenas Filmes', 'movie': 'Apenas Filmes',
'series': 'Apenas Séries' 'series': 'Apenas Séries'
}, value='mixed', label='Tipo de Conteúdo').classes('w-1/4') }, value='mixed', label='Tipo de Conteúdo')
ui.button('Adicionar', on_click=add_cat).props('icon=add color=green').classes('mt-2') # 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() load_cats()
# --- ABA 3: DEPLOY & CAMINHOS ---
with ui.tab_panel(tab_deploy):
# Helper para o Picker funcionar com categorias ou solto # --- ABA 3: DEPLOY ---
with ui.tab_panel(tab_deploy):
async def open_picker(input_element): async def open_picker(input_element):
# Seletor de pastas (inicia onde estiver escrito no input ou na raiz)
start = input_element.value if input_element.value else '/' start = input_element.value if input_element.value else '/'
selected = await pick_folder_dialog(start) selected = await pick_folder_dialog(start)
if selected: input_element.value = selected if selected: input_element.value = selected
# --- 1. CONFIGURAÇÃO DA ORIGEM (MONITORAMENTO) ---
with ui.card().classes('w-full mb-6 border-l-4 border-amber-500 bg-amber-50'): 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') ui.label('📡 Origem dos Arquivos').classes('text-lg font-bold mb-2 text-amber-900')
ui.label('Qual pasta o Clei-Flow deve vigiar?').classes('text-xs text-amber-700 mb-2')
monitor_path = AppConfig.get_val('monitor_path', '/downloads') monitor_path = AppConfig.get_val('monitor_path', '/downloads')
with ui.row().classes('w-full items-center gap-2'): with ui.row().classes('w-full items-center gap-2'):
mon_input = ui.input('Pasta Monitorada (Container)', value=monitor_path).classes('flex-grow font-mono bg-white rounded px-2') mon_input = ui.input('Pasta Monitorada', value=monitor_path).classes('flex-grow font-mono bg-white rounded px-2')
# Botão de Pasta (reutilizando o dialog, mas permitindo sair do /media se quiser, ou ajustamos o dialog depois)
# Nota: O pick_folder_dialog atual trava em /media. Se sua pasta de downloads for fora,
# precisaremos liberar o picker. Por enquanto assumimos que o usuário digita ou está montado.
ui.button(icon='folder', on_click=lambda i=mon_input: open_picker(i)).props('flat dense color=amber-9') 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')
def save_monitor():
if not mon_input.value.startswith('/'):
ui.notify('Caminho deve ser absoluto (/...)', type='warning'); return
AppConfig.set_val('monitor_path', mon_input.value)
ui.notify('Pasta de monitoramento salva! (Reinicie se necessário)', type='positive')
ui.button('Salvar Origem', on_click=save_monitor).classes('mt-2 bg-amber-600 text-white')
ui.separator()
# --- 2. REGRAS GLOBAIS DE DEPLOY ---
with ui.card().classes('w-full mb-6 border-l-4 border-indigo-500'):
ui.label('⚙️ Regras de Destino (Deploy)').classes('font-bold mb-2')
deploy_mode = AppConfig.get_val('deploy_mode', 'move')
conflict_mode = AppConfig.get_val('conflict_mode', 'skip')
cleanup = AppConfig.get_val('cleanup_empty_folders', 'true')
with ui.grid(columns=2).classes('w-full gap-4'):
mode_select = ui.select({'move': 'Mover (Recortar)', 'copy': 'Copiar'}, value=deploy_mode, label='Modo')
conflict_select = ui.select({'skip': 'Ignorar', 'overwrite': 'Sobrescrever', 'rename': 'Renomear Auto'}, value=conflict_mode, label='Conflito')
cleanup_switch = ui.switch('Limpar pastas vazias na origem', value=(cleanup == 'true')).classes('mt-2')
def save_global_deploy():
AppConfig.set_val('deploy_mode', mode_select.value)
AppConfig.set_val('conflict_mode', conflict_select.value)
AppConfig.set_val('cleanup_empty_folders', str(cleanup_switch.value).lower())
ui.notify('Regras salvas!', type='positive')
ui.button('Salvar Regras', on_click=save_global_deploy).classes('mt-2')
ui.separator()
# --- 3. MAPEAMENTO DE DESTINOS ---
ui.label('📂 Mapeamento de Destinos (/media)').classes('text-xl text-gray-700 mt-4') ui.label('📂 Mapeamento de Destinos (/media)').classes('text-xl text-gray-700 mt-4')
paths_container = ui.column().classes('w-full gap-2') paths_container = ui.column().classes('w-full gap-2')
def save_cat_path(cat, new_path):
if not new_path.startswith('/media'):
ui.notify('O caminho deve começar com /media', type='warning'); return
cat.target_path = new_path
cat.save()
ui.notify(f'Caminho de "{cat.name}" salvo!')
def load_deploy_paths(): def load_deploy_paths():
paths_container.clear() paths_container.clear()
cats = list(Category.select()) for cat in list(Category.select()):
if not cats: return
for cat in cats:
with paths_container, ui.card().classes('w-full p-4 flex-row items-center gap-4'): with paths_container, ui.card().classes('w-full p-4 flex-row items-center gap-4'):
with ui.column().classes('min-w-[150px]'): ui.label(cat.name).classes('font-bold w-32')
ui.label(cat.name).classes('font-bold') path_input = ui.input(value=cat.target_path).classes('flex-grow font-mono')
ui.icon('arrow_forward', color='gray') ui.button(icon='folder', on_click=lambda i=path_input: open_picker(i)).props('flat dense color=amber-8')
with ui.row().classes('flex-grow items-center gap-2'): 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')
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: save_cat_path(c, p.value)).props('flat round color=green')
load_deploy_paths() load_deploy_paths()
ui.button('Recarregar', on_click=load_deploy_paths, icon='refresh').props('flat dense').classes('mt-2 self-center')
# --- ABA 4: FFMPEG (Com VAAPI) --- # --- ABA 4: FFMPEG (AGORA COM ISO_LANGS CORRIGIDO) ---
with ui.tab_panel(tab_ffmpeg): with ui.tab_panel(tab_ffmpeg):
ui.label('Perfis de Conversão').classes('text-xl text-gray-700') ui.label('Perfis de Conversão').classes('text-xl text-gray-700')
# 1. Carrega dados
profiles_query = list(FFmpegProfile.select()) profiles_query = list(FFmpegProfile.select())
profiles_dict = {p.id: p.name for p in profiles_query} profiles_dict = {p.id: p.name for p in profiles_query}
# 2. Ativo
active_profile = next((p for p in profiles_query if p.is_active), None) active_profile = next((p for p in profiles_query if p.is_active), None)
initial_val = active_profile.id if active_profile else None initial_val = active_profile.id if active_profile else None
# 3. Função
def set_active_profile(e): def set_active_profile(e):
if not e.value: return if not e.value: return
FFmpegProfile.update(is_active=False).execute() FFmpegProfile.update(is_active=False).execute()
FFmpegProfile.update(is_active=True).where(FFmpegProfile.id == int(e.value)).execute() FFmpegProfile.update(is_active=True).where(FFmpegProfile.id == int(e.value)).execute()
ui.notify(f'Perfil "{profiles_dict[e.value]}" ativado!', type='positive') ui.notify(f'Perfil "{profiles_dict[e.value]}" ativado!', type='positive')
# 4. Select
select_profile = ui.select(profiles_dict, value=initial_val, label='Perfil Ativo', on_change=set_active_profile).classes('w-64 mb-6') select_profile = ui.select(profiles_dict, value=initial_val, label='Perfil Ativo', on_change=set_active_profile).classes('w-64 mb-6')
ui.separator() ui.separator()
# Editor
for p in profiles_query: for p in profiles_query:
with ui.expansion(f"{p.name}", icon='tune').classes('w-full bg-white mb-2 border rounded'): 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.column().classes('p-4 w-full'):
@@ -297,6 +236,8 @@ def show():
audios = p.audio_langs.split(',') if p.audio_langs else [] audios = p.audio_langs.split(',') if p.audio_langs else []
subs = p.subtitle_langs.split(',') if p.subtitle_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_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') c_sub = ui.select(ISO_LANGS, value=subs, multiple=True, label='Legendas').props('use-chips')