Spaces:
Running
Running
File size: 1,349 Bytes
43b0e93 7c78a60 43b0e93 7c78a60 43b0e93 7c78a60 43b0e93 7c78a60 43b0e93 | 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 | from __future__ import annotations
import os
import socket
import uvicorn
def find_free_port(host: str = "127.0.0.1") -> int:
"""Ask the OS for a currently available local TCP port."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((host, 0))
server_socket.listen(1)
return int(server_socket.getsockname()[1])
def is_huggingface_space() -> bool:
"""Return True when running inside a Hugging Face Space runtime."""
return bool(os.getenv("SPACE_ID") or os.getenv("SPACE_HOST"))
def bootstrap_runtime_port() -> None:
"""Seed PORT early so backend imports cannot override the Hugging Face runtime port."""
if is_huggingface_space() and not os.getenv("PORT", "").strip():
os.environ["PORT"] = "7860"
bootstrap_runtime_port()
from backend.main import app
def resolve_server_port() -> int:
"""Use the runtime PORT when defined, keep Hugging Face on 7860, else pick a free local port."""
raw_port = os.getenv("PORT", "").strip()
if raw_port:
return int(raw_port)
if is_huggingface_space():
os.environ["PORT"] = "7860"
return 7860
port = find_free_port()
os.environ["PORT"] = str(port)
return port
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=resolve_server_port())
|