File size: 7,138 Bytes
6123728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/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()