Thang6822
Deploy OHLC4 forecast line and Hugging Face runtime fixes
43b0e93
Raw
History Blame
1.35 kB
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())