File size: 2,377 Bytes
045edbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Cross-platform launcher for Gradio UI
Automatically finds an available port if the default is in use
"""
import os
import sys
import socket
from pathlib import Path

# Add current directory to path
sys.path.insert(0, str(Path(__file__).parent))


def is_port_in_use(port: int) -> bool:
    """Check if a port is already in use"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind(("0.0.0.0", port))
            return False
        except OSError:
            return True


def find_available_port(start_port: int = 7860, max_attempts: int = 10) -> int:
    """Find an available port starting from start_port"""
    for port in range(start_port, start_port + max_attempts):
        if not is_port_in_use(port):
            return port
    raise RuntimeError(f"Could not find available port in range {start_port}-{start_port + max_attempts}")


def main():
    """Main launcher function"""
    # Get port from environment or use default
    default_port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
    
    # Check if default port is available
    if is_port_in_use(default_port):
        print(f"โš ๏ธ  Port {default_port} is already in use!")
        print(f"   Finding an available port...")
        
        try:
            port = find_available_port(default_port + 1)
            print(f"โœ… Found available port: {port}")
            os.environ["GRADIO_SERVER_PORT"] = str(port)
        except RuntimeError as e:
            print(f"โŒ {e}")
            print(f"\nPlease manually specify a port:")
            print(f"  GRADIO_SERVER_PORT=8080 python launch.py")
            sys.exit(1)
    else:
        port = default_port
    
    print(f"\n๐Ÿš€ Starting Gradio UI...")
    print(f"   Port: {port}")
    print(f"   URL: http://localhost:{port}")
    print(f"\n   Press Ctrl+C to stop\n")
    
    # Import and launch the app
    from app import create_interface
    import gradio as gr
    
    app = create_interface()
    app.launch(
        server_name="0.0.0.0",
        server_port=port,
        share=False,
        theme=gr.themes.Soft()
    )


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n๐Ÿ‘‹ Shutting down Gradio UI...")
        sys.exit(0)
    except Exception as e:
        print(f"\nโŒ Error: {e}")
        sys.exit(1)