teste
This commit is contained in:
1 parent
6c8b67cfd4
commit
52b6e42990
17 files changed
+163827
-139801
No files matched your search
+119
-211
@@ -7,6 +7,7 @@ import multiprocessing
|
||||
import logging
|
||||
import time
|
||||
import platform
|
||||
import sys # Adicionado para sair do script se faltar dependência
|
||||
from datetime import datetime
|
||||
|
||||
# Importando seus módulos
|
||||
@@ -24,23 +25,37 @@ from utils import (
|
||||
MMP_FOLDER,
|
||||
)
|
||||
|
||||
|
||||
# Caminho para os Logs
|
||||
# Assumindo que este script roda dentro de scripts/handler/
|
||||
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
LOG_FOLDER = os.path.join(CURRENT_DIR, "logs")
|
||||
|
||||
|
||||
def check_system_dependencies():
|
||||
"""Verifica se as ferramentas necessárias estão instaladas antes de iniciar."""
|
||||
required_tools = ["lmms"]
|
||||
missing = []
|
||||
for tool in required_tools:
|
||||
if shutil.which(tool) is None:
|
||||
missing.append(tool)
|
||||
|
||||
if missing:
|
||||
logging.critical(f"FERRAMENTAS FALTANDO: {', '.join(missing)}")
|
||||
logging.critical("Por favor instale: sudo apt-get install " + " ".join(missing))
|
||||
sys.exit(1) # Encerra o script imediatamente
|
||||
|
||||
|
||||
def get_linux_mem_info():
|
||||
"""Lê /proc/meminfo para obter memória total de forma nativa no Linux."""
|
||||
try:
|
||||
with open("/proc/meminfo", "r") as f:
|
||||
for line in f:
|
||||
if "MemTotal" in line:
|
||||
# Ex: MemTotal: 16303032 kB
|
||||
kb_value = int(line.split()[1])
|
||||
return kb_value / (1024 * 1024) # Retorna em GB
|
||||
except:
|
||||
return kb_value / (1024 * 1024)
|
||||
except (IOError, ValueError): # Melhoria: Captura apenas erros de arquivo/valor
|
||||
return 0
|
||||
except Exception as e:
|
||||
logging.warning(f"Erro ao ler memória: {e}")
|
||||
return 0
|
||||
|
||||
|
||||
@@ -51,319 +66,212 @@ def get_cpu_model_name():
|
||||
for line in f:
|
||||
if "model name" in line:
|
||||
return line.split(":")[1].strip()
|
||||
except:
|
||||
except Exception:
|
||||
return platform.processor()
|
||||
|
||||
|
||||
def log_system_info():
|
||||
"""
|
||||
Registra informações do hardware usando apenas bibliotecas nativas do Python.
|
||||
"""
|
||||
# Apenas certifique-se de manter a indentação correta
|
||||
try:
|
||||
logging.info("=" * 30)
|
||||
logging.info("AUDITORIA DE AMBIENTE (HARDWARE)")
|
||||
logging.info("=" * 30)
|
||||
|
||||
# 1. Sistema Operacional
|
||||
uname = platform.uname()
|
||||
logging.info(f"Sistema: {uname.system} {uname.release}")
|
||||
logging.info(f"Kernel: {uname.version}")
|
||||
logging.info(
|
||||
f"Node: {uname.node}"
|
||||
) # Nome do servidor (provavelmente 'alice')
|
||||
|
||||
# 2. CPU (Processamento)
|
||||
logging.info(f"Node: {uname.node}")
|
||||
cpu_model = get_cpu_model_name()
|
||||
cores_logical = multiprocessing.cpu_count()
|
||||
# os.sched_getaffinity pega os cores que o processo PODE usar (útil em cluster compartilhado)
|
||||
try:
|
||||
cores_available = len(os.sched_getaffinity(0))
|
||||
except AttributeError:
|
||||
cores_available = cores_logical
|
||||
|
||||
logging.info(f"CPU Modelo: {cpu_model}")
|
||||
logging.info(f"Núcleos (Log): {cores_logical}")
|
||||
logging.info(f"Núcleos (Disp): {cores_available} (Alocados para este script)")
|
||||
|
||||
# 3. Memória RAM
|
||||
mem_total_gb = get_linux_mem_info()
|
||||
logging.info(f"CPU Modelo: {cpu_model}")
|
||||
logging.info(f"Núcleos: {cores_logical}")
|
||||
logging.info(f"Memória Total: {mem_total_gb:.2f} GB")
|
||||
|
||||
# 4. Armazenamento (Disco onde o script está rodando)
|
||||
# Pega o uso do disco no diretório atual (.)
|
||||
total, used, free = shutil.disk_usage(".")
|
||||
logging.info(f"Disco (Total): {total // (2**30)} GB")
|
||||
logging.info(f"Disco (Livre): {free // (2**30)} GB")
|
||||
|
||||
logging.info("=" * 30)
|
||||
|
||||
except Exception as e:
|
||||
logging.warning(f"Falha ao coletar info do sistema: {e}")
|
||||
|
||||
|
||||
def setup_logger():
|
||||
"""
|
||||
Configura o logger para escrever no terminal e em arquivo simultaneamente.
|
||||
"""
|
||||
# Cria pasta de logs se não existir
|
||||
os.makedirs(LOG_FOLDER, exist_ok=True)
|
||||
|
||||
# Nome do arquivo com Timestamp
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
||||
log_filename = os.path.join(LOG_FOLDER, f"execucao_{timestamp}.log")
|
||||
|
||||
# Configuração do Logger
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
# Formato da mensagem
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s [%(levelname)s] %(message)s", datefmt="%d/%m/%Y %H:%M:%S"
|
||||
)
|
||||
|
||||
# Handler Arquivo
|
||||
file_handler = logging.FileHandler(log_filename, encoding="utf-8")
|
||||
file_handler.setFormatter(formatter)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
# Handler Terminal (Console)
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
return logger, log_filename
|
||||
|
||||
|
||||
def process_single_file(file_name):
|
||||
"""
|
||||
Worker: Processa um arquivo. Retorna um dict com status de sucesso/erro.
|
||||
"""
|
||||
"""Worker robusto com melhor tratamento de Subprocesso."""
|
||||
file_path = os.path.join(MMP_FOLDER, file_name)
|
||||
pid = os.getpid()
|
||||
|
||||
# Resultado padrão
|
||||
result = {"success": False, "file": file_name, "data": None, "error": None}
|
||||
|
||||
try:
|
||||
logging.info(f"[PID {pid}] Processando: {file_name}")
|
||||
|
||||
mmp_data = None
|
||||
|
||||
# 1. Tratamento MMPZ
|
||||
if file_name.endswith(".mmpz"):
|
||||
destination_path = os.path.join(MMPZ_FOLDER, file_name)
|
||||
|
||||
# Movimentação de arquivo
|
||||
# Move arquivo se necessário
|
||||
if not os.path.exists(destination_path):
|
||||
shutil.move(file_path, destination_path)
|
||||
logging.info(f"[PID {pid}] Movido para: {destination_path}")
|
||||
else:
|
||||
logging.info(
|
||||
f"[PID {pid}] Arquivo já existe em {destination_path}, usando existente."
|
||||
)
|
||||
if os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
elif os.path.exists(file_path):
|
||||
os.remove(file_path)
|
||||
|
||||
mmp_name = os.path.splitext(file_name)[0] + ".mmp"
|
||||
output_mmp_path = os.path.join(MMP_FOLDER, mmp_name)
|
||||
|
||||
# Ambiente para LMMS Headless
|
||||
env = os.environ.copy()
|
||||
env["QT_QPA_PLATFORM"] = "offscreen"
|
||||
# Usa caminho absoluto para evitar erros do LMMS
|
||||
abs_dest = os.path.abspath(destination_path)
|
||||
abs_mmp_out = os.path.abspath(output_mmp_path)
|
||||
|
||||
# Conversão MMPZ -> MMP
|
||||
convert_cmd = f'lmms --dump "{destination_path}" > "{output_mmp_path}"'
|
||||
try:
|
||||
# capture_output=True permite jogar o log do LMMS para o nosso arquivo de log
|
||||
subprocess.run(
|
||||
convert_cmd,
|
||||
shell=True,
|
||||
check=True,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
logging.info(f"[PID {pid}] {file_name}: Convertido para .mmp")
|
||||
except subprocess.CalledProcessError as e:
|
||||
error_msg = f"Erro conversão .mmp (LMMS): {e.stderr}"
|
||||
logging.error(f"[PID {pid}] {file_name}: {error_msg}")
|
||||
result["error"] = error_msg
|
||||
return result
|
||||
|
||||
# Conversão -> WAV
|
||||
wav_output_path = os.path.join(WAV_FOLDER, os.path.splitext(file_name)[0])
|
||||
wav_convert_cmd = (
|
||||
f'lmms -r "{destination_path}" -o "{wav_output_path}" -f wav'
|
||||
)
|
||||
# Lista ao invés de string (Sem shell=True)
|
||||
# Comando dump: LMMS escreve no stdout, então precisamos capturar
|
||||
dump_cmd = ["lmms", "--dump", abs_dest]
|
||||
|
||||
try:
|
||||
subprocess.run(
|
||||
wav_convert_cmd,
|
||||
shell=True,
|
||||
check=True,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
logging.info(f"[PID {pid}] {file_name}: Convertido para .wav")
|
||||
with open(abs_mmp_out, "w") as outfile:
|
||||
subprocess.run(
|
||||
dump_cmd,
|
||||
stdout=outfile, # Redireciona saida direto pro arquivo
|
||||
stderr=subprocess.PIPE, # Captura erros
|
||||
check=True,
|
||||
env={"QT_QPA_PLATFORM": "offscreen", **os.environ},
|
||||
)
|
||||
logging.info(f"[PID {pid}] Dump MMP criado.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
# Erro no WAV não para o processo de indexação, apenas loga
|
||||
logging.warning(
|
||||
f"[PID {pid}] {file_name}: Falha no render WAV: {e.stderr}"
|
||||
)
|
||||
|
||||
if os.path.exists(output_mmp_path):
|
||||
mmp_data = parse_mmp_file(output_mmp_path)
|
||||
else:
|
||||
result["error"] = "Arquivo .mmp não foi gerado após dump."
|
||||
result["error"] = f"Erro no dump MMP: {e.stderr.decode('utf-8')}"
|
||||
logging.error(f"[PID {pid}] {result['error']}")
|
||||
return result
|
||||
|
||||
# Conversão WAV
|
||||
wav_name = os.path.splitext(file_name)[0] + ".wav"
|
||||
abs_wav_out = os.path.abspath(os.path.join(WAV_FOLDER, wav_name))
|
||||
|
||||
# Comando em lista: Mais seguro e organizado
|
||||
wav_cmd = [
|
||||
"lmms",
|
||||
"-r",
|
||||
abs_dest,
|
||||
"-o",
|
||||
abs_wav_out,
|
||||
"-f",
|
||||
"wav",
|
||||
]
|
||||
|
||||
try:
|
||||
subprocess.run(wav_cmd, check=True, capture_output=True, text=True)
|
||||
# Log em vez de Print
|
||||
logging.info(f"[PID {pid}] Áudio WAV gerado com sucesso.")
|
||||
except subprocess.CalledProcessError as e:
|
||||
# Não paramos o fluxo por erro no WAV, mas logamos como erro
|
||||
logging.warning(f"[PID {pid}] Falha no WAV: {e.stderr}")
|
||||
|
||||
# Define o caminho para o parser
|
||||
file_to_parse = output_mmp_path
|
||||
|
||||
elif file_name.endswith(".mmp"):
|
||||
mmp_data = parse_mmp_file(file_path)
|
||||
file_to_parse = file_path
|
||||
|
||||
# Salvamento Individual
|
||||
if mmp_data:
|
||||
json_file_path = os.path.join(
|
||||
METADATA_FOLDER, os.path.splitext(file_name)[0] + ".json"
|
||||
)
|
||||
yaml_file_path = os.path.join(
|
||||
DATA_FOLDER, os.path.splitext(file_name)[0] + ".yml"
|
||||
)
|
||||
# 2. Parsing e Salvamento
|
||||
if os.path.exists(file_to_parse):
|
||||
mmp_data = parse_mmp_file(file_to_parse)
|
||||
|
||||
save_to_yaml(mmp_data, yaml_file_path)
|
||||
save_to_json(mmp_data, json_file_path)
|
||||
if mmp_data:
|
||||
base_name = os.path.splitext(file_name)[0]
|
||||
save_to_json(
|
||||
mmp_data, os.path.join(METADATA_FOLDER, base_name + ".json")
|
||||
)
|
||||
save_to_yaml(mmp_data, os.path.join(DATA_FOLDER, base_name + ".yml"))
|
||||
|
||||
result["success"] = True
|
||||
result["data"] = mmp_data
|
||||
return result
|
||||
result["success"] = True
|
||||
result["data"] = mmp_data
|
||||
else:
|
||||
result["error"] = "Dados vazios após parsing."
|
||||
else:
|
||||
result["error"] = "Parser retornou dados vazios."
|
||||
return result
|
||||
result["error"] = "Arquivo MMP não encontrado para parsing."
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Exceção não tratada: {str(e)}"
|
||||
logging.error(f"[PID {pid}] {file_name}: {error_msg}")
|
||||
result["error"] = error_msg
|
||||
return result
|
||||
result["error"] = f"Erro geral: {str(e)}"
|
||||
logging.error(f"[PID {pid}] {file_name}: {result['error']}")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def main_parallel():
|
||||
# 1. Configura Logger e Timer
|
||||
logger, log_file_path = setup_logger()
|
||||
start_time = time.time()
|
||||
|
||||
# Informações do PC/S.O
|
||||
# MELHORIA 4: Fail Fast
|
||||
check_system_dependencies()
|
||||
|
||||
log_system_info()
|
||||
logging.info("=== Iniciando Pipeline Otimizado ===")
|
||||
|
||||
logging.info("=== Iniciando Pipeline de Indexação Paralela ===")
|
||||
logging.info(f"Log sendo salvo em: {log_file_path}")
|
||||
|
||||
# 2. Criação de Pastas
|
||||
create_folders_if_not_exist([MMPZ_FOLDER, WAV_FOLDER, METADATA_FOLDER, DATA_FOLDER])
|
||||
|
||||
# 3. Listagem
|
||||
if not os.path.exists(MMP_FOLDER):
|
||||
logging.critical(f"Pasta {MMP_FOLDER} não encontrada.")
|
||||
return
|
||||
|
||||
all_files = [
|
||||
f for f in os.listdir(MMP_FOLDER) if f.endswith(".mmp") or f.endswith(".mmpz")
|
||||
]
|
||||
total_files = len(all_files)
|
||||
all_files = [f for f in os.listdir(MMP_FOLDER) if f.endswith((".mmp", ".mmpz"))]
|
||||
|
||||
if total_files == 0:
|
||||
logging.warning("Nenhum arquivo .mmp ou .mmpz encontrado para processar.")
|
||||
if not all_files:
|
||||
logging.warning("Nenhum arquivo encontrado.")
|
||||
return
|
||||
|
||||
logging.info(f"Iniciando processamento de {total_files} arquivos.")
|
||||
|
||||
# 4. Pool Paralelo (ETAPA 1: Processamento Pesado)
|
||||
num_cores = multiprocessing.cpu_count()
|
||||
logging.info(f"Utilizando {num_cores} núcleos de CPU.")
|
||||
logging.info(f"Processando {len(all_files)} arquivos com {num_cores} workers.")
|
||||
|
||||
with multiprocessing.Pool(processes=num_cores) as pool:
|
||||
results = pool.map(process_single_file, all_files)
|
||||
|
||||
# 5. Processamento dos Resultados
|
||||
successful_data = []
|
||||
failed_files = []
|
||||
# Processamento de resultados (igual ao seu)
|
||||
successful_data = [r["data"] for r in results if r["success"]]
|
||||
failed_files = [r for r in results if not r["success"]]
|
||||
|
||||
for res in results:
|
||||
if res["success"]:
|
||||
successful_data.append(res["data"])
|
||||
else:
|
||||
failed_files.append(res)
|
||||
|
||||
# 6. Salvamento Consolidado
|
||||
if successful_data:
|
||||
save_to_json(successful_data, os.path.join(METADATA_FOLDER, "all.json"))
|
||||
save_to_yaml(successful_data, os.path.join(DATA_FOLDER, "all.yml"))
|
||||
logging.info("Arquivos 'all.json' e 'all.yml' gerados com sucesso.")
|
||||
|
||||
# >>> ETAPA 2: Geração de Manifestos <<<
|
||||
manifest_report = {"generated": [], "failed": []}
|
||||
# Geração de Manifestos
|
||||
try:
|
||||
# Capturamos o relatório retornado pela função
|
||||
manifest_report = generate_manifests(BASE_PATH)
|
||||
except Exception as e:
|
||||
logging.error(f"Falha crítica no gerador de manifestos: {e}")
|
||||
|
||||
# 7. Relatório Final Completo
|
||||
end_time = time.time()
|
||||
duration = end_time - start_time
|
||||
manifest_report = {"generated": [], "failed": [str(e)]}
|
||||
|
||||
# Relatório Final
|
||||
duration = time.time() - start_time
|
||||
logging.info("=" * 60)
|
||||
logging.info(
|
||||
f"RELATÓRIO DE EXECUÇÃO - {datetime.now().strftime('%d/%m/%Y %H:%M:%S')}"
|
||||
f"FIM - Tempo: {duration:.2f}s | Sucessos: {len(successful_data)} | Falhas: {len(failed_files)}"
|
||||
)
|
||||
logging.info("=" * 60)
|
||||
|
||||
logging.info(f"Tempo Total do Pipeline: {duration:.2f} segundos")
|
||||
|
||||
# Seção 1: Processamento Paralelo (Arquivos MMP)
|
||||
logging.info("-" * 20)
|
||||
logging.info("[1] Indexação Paralela (Arquivos .mmp/.mmpz)")
|
||||
logging.info(f" Total Encontrado: {total_files}")
|
||||
logging.info(f" Sucessos: {len(successful_data)}")
|
||||
logging.info(f" Falhas: {len(failed_files)}")
|
||||
|
||||
if failed_files:
|
||||
for fail in failed_files:
|
||||
logging.error(f" -> FALHA: {fail['file']} | Erro: {fail['error']}")
|
||||
logging.info("--- Detalhe das Falhas ---")
|
||||
for f in failed_files:
|
||||
logging.error(f"{f['file']}: {f['error']}")
|
||||
|
||||
# Seção 2: Geração de Manifestos
|
||||
logging.info("-" * 20)
|
||||
logging.info("[2] Geração de Manifestos (Frontend)")
|
||||
|
||||
if manifest_report["generated"]:
|
||||
for item in manifest_report["generated"]:
|
||||
logging.info(f" [OK] {item}")
|
||||
|
||||
if manifest_report["failed"]:
|
||||
for item in manifest_report["failed"]:
|
||||
logging.error(f" [X] {item}")
|
||||
|
||||
if not manifest_report["generated"] and not manifest_report["failed"]:
|
||||
logging.warning(" [!] Nenhum manifesto foi processado.")
|
||||
|
||||
logging.info("=" * 60)
|
||||
logging.info("Pipeline finalizado.")
|
||||
|
||||
# >>> ETAPA 3: Análise de Integridade (NOVO) <<<
|
||||
# Verificação de Dependências (Projetos)
|
||||
try:
|
||||
# Caminhos (ajuste conforme sua estrutura real)
|
||||
PROJECTS_DB = os.path.join(METADATA_FOLDER, "all.json")
|
||||
SAMPLES_MANIFEST = os.path.join(METADATA_FOLDER, "samples-manifest.json")
|
||||
REPORT_FILE = os.path.join(METADATA_FOLDER, "dependency_report.json")
|
||||
|
||||
if os.path.exists(PROJECTS_DB) and os.path.exists(SAMPLES_MANIFEST):
|
||||
check_dependencies(PROJECTS_DB, SAMPLES_MANIFEST, REPORT_FILE)
|
||||
else:
|
||||
logging.warning(
|
||||
"Arquivos necessários para verificação de dependência não encontrados."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Erro na verificação de dependências: {e}")
|
||||
check_dependencies(
|
||||
os.path.join(METADATA_FOLDER, "all.json"),
|
||||
os.path.join(METADATA_FOLDER, "samples-manifest.json"),
|
||||
os.path.join(METADATA_FOLDER, "dependency_report.json"),
|
||||
)
|
||||
except Exception:
|
||||
pass # Erro já logado na função ou irrelevante se arquivos não existirem
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user