syncmaster2 / start_debug.py
aseelflihan's picture
Re-upload correct version of SyncMaster2
a4fc4ec
#!/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()