File size: 4,779 Bytes
03b4754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5471b23
 
03b4754
5471b23
03b4754
 
5471b23
03b4754
 
 
5471b23
03b4754
 
5471b23
 
 
 
 
 
 
 
 
03b4754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5471b23
 
 
 
 
 
 
 
03b4754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5471b23
03b4754
 
5471b23
 
 
 
 
 
 
03b4754
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
HuggingFace Spaces Startup Script
Handles bot and server startup with proper port management
"""
import os
import sys
import time
import signal
import socket
import subprocess
from pathlib import Path

PORT = int(os.environ.get("PORT", 7860))

def is_port_in_use(port):
    """Check if a port is in use"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', port)) == 0

def kill_port_process(port):
    """Kill process using a specific port"""
    try:
        # Try fuser first
        result = subprocess.run(
            f"fuser -k {port}/tcp",
            shell=True,
            capture_output=True,
            timeout=5
        )
        if result.returncode == 0:
            print(f"✅ Killed process on port {port} using fuser")
            return True
    except:
        pass
    
    try:
        # Try lsof
        result = subprocess.run(
            f"lsof -t -i:{port}",
            shell=True,
            capture_output=True,
            timeout=5
        )
        if result.returncode == 0:
            pids = result.stdout.decode().strip().split('\n')
            for pid in pids:
                if pid:
                    os.kill(int(pid), signal.SIGKILL)
            print(f"✅ Killed process(es) on port {port} using lsof")
            return True
    except:
        pass
    
    return False

def start_bot():
    """Start the Ultroid bot in background"""
    print("🤖 Starting Ultroid bot...")
    print(f"   SESSION1 env: {'SET' if os.environ.get('SESSION1') else 'NOT SET'}")
    print(f"   Current dir: {os.getcwd()}")
    
    # Don't pipe output - let it show in logs
    if os.environ.get("SESSION1"):
        bot_process = subprocess.Popen(
            [sys.executable, "multi_client.py"]
        )
    else:
        bot_process = subprocess.Popen(
            [sys.executable, "-m", "pyUltroid"]
        )
    
    print(f"✅ Bot process started with PID: {bot_process.pid}")
    
    # Check if process is still running after 1 second
    time.sleep(1)
    if bot_process.poll() is not None:
        print(f"❌ Bot process died immediately! Exit code: {bot_process.returncode}")
    else:
        print(f"✅ Bot is running")
    
    return bot_process

def start_server(port):
    """Start the FastAPI server"""
    print(f"🚀 Starting API server on port {port}...")
    
    # Import and run server
    os.environ["PORT"] = str(port)
    
    # Run server.py directly
    subprocess.run([sys.executable, "server.py"])

def main():
    print("=" * 50)
    print("🚀 Ultroid HuggingFace Startup (Python)")
    print("=" * 50)
    
    # Change to repo directory
    repo_dir = Path("/app/repo")
    if repo_dir.exists():
        os.chdir(repo_dir)
        print(f"📂 Working directory: {repo_dir}")
    else:
        print(f"❌ Repo directory not found: {repo_dir}")
        sys.exit(1)
    
    # Debug: Show environment
    print(f"🔍 Environment check:")
    print(f"   PORT: {PORT}")
    print(f"   SESSION1: {'SET ✅' if os.environ.get('SESSION1') else 'NOT SET ⚠️'}")
    print(f"   API_ID: {'SET ✅' if os.environ.get('API_ID') else 'NOT SET ❌'}")
    print(f"   API_HASH: {'SET ✅' if os.environ.get('API_HASH') else 'NOT SET ❌'}")
    print(f"   SESSION: {'SET ✅' if os.environ.get('SESSION') else 'NOT SET ❌'}")
    
    # Check if port is in use
    if is_port_in_use(PORT):
        print(f"⚠️  Port {PORT} is already in use!")
        print(f"🧹 Attempting to free port {PORT}...")
        
        if kill_port_process(PORT):
            time.sleep(2)
            if is_port_in_use(PORT):
                print(f"❌ Failed to free port {PORT}")
                sys.exit(1)
        else:
            print(f"⚠️  Could not kill process on port {PORT}")
    else:
        print(f"✅ Port {PORT} is available")
    
    # Start bot in background
    bot_process = start_bot()
    
    # Wait for bot to initialize
    print("⏳ Waiting 5 seconds for bot to initialize...")
    time.sleep(5)
    
    # Check if bot is still running
    if bot_process.poll() is not None:
        print(f"❌ WARNING: Bot process died! Exit code: {bot_process.returncode}")
        print(f"⚠️  Server will start anyway, but bot is NOT running!")
    else:
        print(f"✅ Bot is still running (PID: {bot_process.pid})")
    
    # Check port one more time before starting server
    if is_port_in_use(PORT):
        print(f"❌ Port {PORT} was taken while bot was starting!")
        kill_port_process(PORT)
        time.sleep(2)
    
    # Start server (blocks here)
    print(f"📊 Dashboard will be available on port {PORT}")
    print("=" * 50)
    start_server(PORT)

if __name__ == "__main__":
    main()