Spaces:
Build error
Build error
| # Mach5.py - O Orquestrador do Sistema Mach5 | |
| import subprocess | |
| import time | |
| import os | |
| import sys | |
| # --- CONFIGURAÇÕES DE PORTAS --- | |
| # Portas preferenciais para os serviços | |
| PORT_TSOCIAL = 8085 | |
| PORT_TMEMORIA = 8083 | |
| PORT_CEREBRO_MEMORIA = 8088 # NOVA PORTA PARA O NOVO SERVIÇO DE MEMÓRIA | |
| PORT_CHAT = 8081 | |
| # --- CAMINHOS DOS SCRIPTS --- | |
| SCRIPT_TSOCIAL = "t-social.py" | |
| SCRIPT_TMEMORIA = "t_memoria.py" | |
| SCRIPT_CEREBRO_MEMORIA = "t_cerebro_memoria.py" # NOVO SCRIPT | |
| SCRIPT_CHAT = "mach5_terminal_chat.py" | |
| def start_server(script_name, port, log_file): | |
| """Inicia um servidor Flask em um subprocesso e redireciona a saída para um arquivo de log.""" | |
| print(f"Iniciando {script_name} na porta {port}...") | |
| try: | |
| # Passa a porta explicitamente para o subprocesso via variável de ambiente PORT | |
| # Isso permite que os scripts leiam os.environ.get("PORT", default_port) | |
| env = os.environ.copy() | |
| env["PORT"] = str(port) | |
| with open(log_file, "w", encoding="utf-8") as f_log: | |
| process = subprocess.Popen([sys.executable, script_name], stdout=f_log, stderr=f_log, env=env) | |
| print(f"{script_name} iniciado. Logs em {log_file}") | |
| return process | |
| except Exception as e: | |
| print(f"ERRO ao iniciar {script_name}: {e}") | |
| return None | |
| def clean_up_logs(): | |
| """Limpa arquivos de log antigos.""" | |
| log_files = [ | |
| f"{os.path.splitext(SCRIPT_TSOCIAL)[0]}.log", | |
| f"{os.path.splitext(SCRIPT_TMEMORIA)[0]}.log", | |
| f"{os.path.splitext(SCRIPT_CEREBRO_MEMORIA)[0]}.log", # Novo log a ser limpo | |
| f"{os.path.splitext(SCRIPT_CHAT)[0]}.log" | |
| ] | |
| for log_file in log_files: | |
| if os.path.exists(log_file): | |
| try: | |
| os.remove(log_file) | |
| print(f"Log antigo {log_file} removido.") | |
| except Exception as e: | |
| print(f"Não foi possível remover o log {log_file}: {e}") | |
| if __name__ == "__main__": | |
| print("--- Iniciando o Sistema Mach5 ---") | |
| clean_up_logs() | |
| processes = [] | |
| # Ordem de inicialização: | |
| # 1. t_cerebro_memoria.py (repositório central de dados, outros dependem dele) | |
| p_cerebro_memoria = start_server(SCRIPT_CEREBRO_MEMORIA, PORT_CEREBRO_MEMORIA, f"{os.path.splitext(SCRIPT_CEREBRO_MEMORIA)[0]}.log") | |
| if p_cerebro_memoria: | |
| processes.append(p_cerebro_memoria) | |
| time.sleep(3) # Tempo para o serviço de memória inicializar e carregar seus arquivos | |
| # 2. t-social.py (pode ser iniciado a qualquer momento, mas é melhor antes do chat) | |
| p_tsocial = start_server(SCRIPT_TSOCIAL, PORT_TSOCIAL, f"{os.path.splitext(SCRIPT_TSOCIAL)[0]}.log") | |
| if p_tsocial: | |
| processes.append(p_tsocial) | |
| time.sleep(2) # Aguarda inicialização | |
| # 3. t_memoria.py (depende do t_cerebro_memoria.py para obter o estado inicial) | |
| p_tmemoria = start_server(SCRIPT_TMEMORIA, PORT_TMEMORIA, f"{os.path.splitext(SCRIPT_TMEMORIA)[0]}.log") | |
| if p_tmemoria: | |
| processes.append(p_tmemoria) | |
| time.sleep(3) # Dê um pouco mais de tempo, pois ele busca dados do cerebro_memoria | |
| # 4. mach5_terminal_chat.py (depende de todos os outros serviços) | |
| p_chat = start_server(SCRIPT_CHAT, PORT_CHAT, f"{os.path.splitext(SCRIPT_CHAT)[0]}.log") | |
| if p_chat: | |
| processes.append(p_chat) | |
| time.sleep(2) | |
| if not processes: | |
| print("Nenhum servidor foi iniciado com sucesso. Verifique os erros acima.") | |
| sys.exit(1) | |
| print("\nTodos os servidores Mach5 foram iniciados em segundo plano.") | |
| print(f"Você pode acessar a interface do chat em: http://127.0.0.1:{PORT_CHAT}") | |
| print("Os logs de cada servidor estão em arquivos .log correspondentes (e.g., t-social.log).") | |
| print("\nPressione Ctrl+C para encerrar todos os servidores.") | |
| try: | |
| while True: | |
| time.sleep(1) | |
| except KeyboardInterrupt: | |
| print("\nEncerrando servidores Mach5...") | |
| for p in processes: | |
| if p.poll() is None: | |
| p.terminate() | |
| try: | |
| p.wait(timeout=5) | |
| except subprocess.TimeoutExpired: | |
| p.kill() | |
| print("Todos os servidores Mach5 encerrados.") | |
| sys.exit(0) | |