syncmaster6 / start_debug.py
aseelflihan's picture
Initial commit without node_modules
6123728
#!/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()