#!/usr/bin/env python3 """ Enhanced startup script for SyncMaster with debugging capabilities نص بدء التشغيل المحسن لـ SyncMaster مع قدرات التتبع """ import os import sys import time import socket import subprocess import psutil from pathlib import Path def check_port_available(port): """Check if a port is available""" try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('localhost', port)) return True except: return False def kill_processes_on_port(port): """Kill processes using a specific port""" try: for proc in psutil.process_iter(['pid', 'name', 'connections']): try: connections = proc.info['connections'] if connections: for conn in connections: if conn.laddr.port == port: print(f"🔄 Killing process {proc.info['name']} (PID: {proc.info['pid']}) using port {port}") proc.kill() time.sleep(1) except (psutil.NoSuchProcess, psutil.AccessDenied): continue except Exception as e: print(f"⚠️ Error killing processes on port {port}: {e}") def check_dependencies(): """Check if required dependencies are installed""" required_packages = [ 'streamlit', 'flask', 'librosa', 'soundfile', 'google-generativeai', 'python-dotenv' ] missing_packages = [] for package in required_packages: try: __import__(package.replace('-', '_')) except ImportError: missing_packages.append(package) if missing_packages: print(f"❌ Missing packages: {', '.join(missing_packages)}") print("📦 Installing missing packages...") subprocess.run([sys.executable, '-m', 'pip', 'install'] + missing_packages) return False return True def check_env_file(): """Check if .env file exists and has required keys""" env_path = Path('.env') if not env_path.exists(): print("❌ .env file not found!") print("📝 Creating sample .env file...") with open('.env', 'w') as f: f.write("GEMINI_API_KEY=your_api_key_here\n") print("✅ Please add your Gemini API key to .env file") return False # Check if API key is set try: from dotenv import load_dotenv load_dotenv() api_key = os.getenv("GEMINI_API_KEY") if not api_key or api_key == "your_api_key_here": print("⚠️ GEMINI_API_KEY not properly set in .env file") return False except Exception as e: print(f"❌ Error reading .env file: {e}") return False return True def start_recorder_server(): """Start the recorder server""" print("🎙️ Starting recorder server...") # Kill any existing processes on port 5001 if not check_port_available(5001): print("🔄 Port 5001 is busy, killing existing processes...") kill_processes_on_port(5001) time.sleep(2) if check_port_available(5001): try: # Start recorder server server_process = subprocess.Popen( [sys.executable, 'recorder_server.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.CREATE_NEW_CONSOLE if os.name == 'nt' else 0 ) # Wait for server to start time.sleep(3) # Test server connection import requests try: response = requests.get('http://localhost:5001/record', timeout=5) if response.status_code == 200: print("✅ Recorder server started successfully on port 5001") return server_process else: raise Exception(f"Server responded with status {response.status_code}") except Exception as e: print(f"❌ Failed to connect to recorder server: {e}") server_process.terminate() return None except Exception as e: print(f"❌ Failed to start recorder server: {e}") return None else: print("❌ Port 5001 is still not available") return None def start_main_app(): """Start the main Streamlit application""" print("🚀 Starting main SyncMaster application...") # Find available port for Streamlit streamlit_port = 8501 while not check_port_available(streamlit_port) and streamlit_port < 8510: streamlit_port += 1 if streamlit_port >= 8510: print("❌ No available ports for Streamlit (tried 8501-8509)") return None try: # Start Streamlit app subprocess.run([ sys.executable, '-m', 'streamlit', 'run', 'app.py', '--server.port', str(streamlit_port), '--server.address', 'localhost', '--browser.gatherUsageStats', 'false' ]) except KeyboardInterrupt: print("\n🛑 Application stopped by user") except Exception as e: print(f"❌ Failed to start main application: {e}") def main(): """Main startup function""" print("=" * 60) print("🎵 SyncMaster Enhanced - Startup Script") print("منصة المزامنة الذكية - سكريبت البدء") print("=" * 60) # Change to script directory script_dir = Path(__file__).parent os.chdir(script_dir) print(f"📁 Working directory: {script_dir}") # Step 1: Check dependencies print("\n📦 Checking dependencies...") if not check_dependencies(): print("❌ Please restart after installing dependencies") return print("✅ All dependencies available") # Step 2: Check environment file print("\n🔑 Checking environment configuration...") if not check_env_file(): print("❌ Please configure .env file and restart") return print("✅ Environment configuration OK") # Step 3: Start recorder server print("\n🎙️ Starting recording server...") server_process = start_recorder_server() if not server_process: print("❌ Failed to start recorder server") return # Step 4: Start main application print("\n🌐 Starting web interface...") print("📱 The application will open in your browser") print("🎙️ Recording interface: http://localhost:5001") print("💻 Main interface: http://localhost:8501") print("\nPress Ctrl+C to stop all services") try: start_main_app() finally: # Cleanup print("\n🧹 Cleaning up...") if server_process: server_process.terminate() print("✅ Recorder server stopped") print("👋 Goodbye!") if __name__ == "__main__": main()