|
|
|
|
|
|
|
""" |
|
Hugging Face Space launcher for MatrixGame WebSocket Server |
|
This script launches the server with the appropriate configuration for Hugging Face Spaces. |
|
""" |
|
|
|
import os |
|
import sys |
|
import subprocess |
|
import logging |
|
import asyncio |
|
from server import init_app, parse_args |
|
from aiohttp import web |
|
|
|
|
|
logging.basicConfig( |
|
level=logging.INFO, |
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
|
) |
|
logger = logging.getLogger(__name__) |
|
|
|
async def run_async(): |
|
"""Run the server using the async API directly for better stability""" |
|
|
|
port = int(os.environ.get("PORT", 7860)) |
|
|
|
|
|
is_hf_space = os.environ.get("SPACE_ID") is not None |
|
|
|
|
|
base_path = "" |
|
if is_hf_space: |
|
|
|
space_id = os.environ.get('SPACE_ID', '') |
|
|
|
|
|
base_path = "" |
|
logger.info(f"Running in Hugging Face Space {space_id}") |
|
|
|
logger.info(f"Initializing application with base_path='{base_path}', port={port}") |
|
|
|
|
|
args = parse_args() |
|
args.port = port |
|
args.host = "0.0.0.0" |
|
args.path = base_path |
|
|
|
|
|
app = await init_app(args, base_path=base_path) |
|
|
|
|
|
routes = sorted([f"{route.method} {route.resource}" for route in app.router.routes() if hasattr(route, 'resource')]) |
|
logger.info(f"Registered {len(routes)} routes:") |
|
for route in routes: |
|
logger.info(f" - {route}") |
|
|
|
|
|
logger.info(f"Starting server on 0.0.0.0:{port}") |
|
runner = web.AppRunner(app) |
|
await runner.setup() |
|
site = web.TCPSite(runner, '0.0.0.0', port) |
|
await site.start() |
|
|
|
|
|
logger.info("Server started, running indefinitely...") |
|
while True: |
|
await asyncio.sleep(3600) |
|
|
|
def main(): |
|
"""Run using the subprocess method (fallback)""" |
|
|
|
port = int(os.environ.get("PORT", 7860)) |
|
|
|
|
|
is_hf_space = os.environ.get("SPACE_ID") is not None |
|
|
|
|
|
path_arg = "" |
|
if is_hf_space: |
|
|
|
|
|
path_arg = "" |
|
|
|
|
|
cmd = f"{sys.executable} server.py --host 0.0.0.0 --port {port} {path_arg}" |
|
print(f"Running command: {cmd}") |
|
subprocess.run(cmd, shell=True) |
|
|
|
if __name__ == "__main__": |
|
|
|
try: |
|
logger.info("Starting server using async API") |
|
asyncio.run(run_async()) |
|
except Exception as e: |
|
logger.error(f"Failed to run using async API: {e}", exc_info=True) |
|
logger.info("Falling back to subprocess method") |
|
main() |