|
|
|
|
|
""" |
|
|
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 |
|
|
|
|
|
|
|
|
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""" |
|
|
|
|
|
default_port = int(os.getenv("GRADIO_SERVER_PORT", "7860")) |
|
|
|
|
|
|
|
|
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") |
|
|
|
|
|
|
|
|
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) |
|
|
|