launch.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import subprocess
  2. import os
  3. import time
  4. import webbrowser
  5. import sys
  6. sys.path.append(os.getcwd())
  7. import uvicorn
  8. import threading
  9. import asyncio
  10. import logging
  11. from server import app
  12. server = None
  13. sys.path.append((os.path.dirname(os.path.abspath(__file__))))
  14. logging.getLogger("uvicorn.error").disabled = True
  15. logging.getLogger("uvicorn.access").disabled = True
  16. def start_server():
  17. global server
  18. config = uvicorn.Config(app, host="0.0.0.0", port=8000, log_level="critical")
  19. server = uvicorn.Server(config)
  20. thread = threading.Thread(target=server.run)
  21. thread.start()
  22. print("Server started")
  23. def stop_server():
  24. global server
  25. if server:
  26. server.should_exit = True
  27. server.force_exit = True
  28. try:
  29. asyncio.run(server.shutdown())
  30. except RuntimeError:
  31. loop = asyncio.new_event_loop()
  32. asyncio.set_event_loop(loop)
  33. loop.run_until_complete(server.shutdown())
  34. loop.close()
  35. except asyncio.CancelledError:
  36. pass
  37. print("Server stopped")
  38. else:
  39. print("Server is not running")
  40. def run_npm(open: bool=False):
  41. # Change directory to the 'web' subdirectory
  42. os.chdir('agenthub')
  43. # Run npm run dev asynchronously
  44. if "node_modules" not in os.listdir():
  45. install_process = subprocess.Popen(['npm', 'install'])
  46. install_process.wait()
  47. subprocess.Popen(['npm', 'run', 'dev'])
  48. if open:
  49. time.sleep(5)
  50. webbrowser.open_new_tab("http://localhost:3000")
  51. if __name__ == "__main__":
  52. start_server()
  53. run_npm(True)
  54. try:
  55. while True:
  56. time.sleep(1)
  57. finally:
  58. stop_server()