#!/usr/bin/env python """DeepTutor Web Launcher — starts backend + frontend from the active .env.""" from __future__ import annotations import os from pathlib import Path import shutil import signal import subprocess import sys import threading import time PROJECT_ROOT = Path(__file__).resolve().parent.parent if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) def _load_runtime_deps(): from _cli_kit import accent, banner, bold, dim, log_error, log_info, log_success, warn from deeptutor.services.config import get_env_store return accent, banner, bold, dim, log_error, log_info, log_success, warn, get_env_store accent, banner, bold, dim, log_error, log_info, log_success, warn, get_env_store = ( _load_runtime_deps() ) # --------------------------------------------------------------------------- # Process management (unchanged logic) # --------------------------------------------------------------------------- def _stream_output(prefix: str, process: subprocess.Popen[str]) -> None: assert process.stdout is not None for line in process.stdout: print(f" {dim(prefix)} {line.rstrip()}", flush=True) def _terminate(process: subprocess.Popen[str] | None, name: str) -> None: if process is None or process.poll() is not None: return log_info(f"Stopping {name} (PID {process.pid})") try: if os.name == "nt": process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined] try: process.wait(timeout=5) return except subprocess.TimeoutExpired: process.kill() else: os.killpg(os.getpgid(process.pid), signal.SIGTERM) try: process.wait(timeout=5) return except subprocess.TimeoutExpired: os.killpg(os.getpgid(process.pid), signal.SIGKILL) except Exception: process.kill() def _spawn( command: list[str], *, cwd: Path, env: dict[str, str], name: str, ) -> subprocess.Popen[str]: kwargs: dict[str, object] = { "cwd": str(cwd), "env": env, "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT, "text": True, "bufsize": 1, } if os.name == "nt": kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined] else: kwargs["start_new_session"] = True process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type] thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True) thread.start() return process # --------------------------------------------------------------------------- # Entry point # --------------------------------------------------------------------------- def main() -> None: summary = get_env_store().as_summary() backend_port = summary.backend_port frontend_port = summary.frontend_port npm = shutil.which("npm") if not npm: log_error("npm not found. Run `python scripts/start_tour.py` first.") raise SystemExit(1) # Banner banner( "DeepTutor", [ f"Backend http://localhost:{backend_port}", f"Frontend http://localhost:{frontend_port}", ], ) backend_env = os.environ.copy() backend_env["PYTHONUNBUFFERED"] = "1" frontend_env = os.environ.copy() frontend_env["NEXT_PUBLIC_API_BASE"] = f"http://localhost:{backend_port}" backend_cmd = [sys.executable, "-m", "deeptutor.api.run_server"] frontend_cmd = [npm, "run", "dev", "--", "--port", str(frontend_port)] log_info("Starting backend ...") backend = _spawn(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend") time.sleep(1.5) log_info("Starting frontend ...") frontend = _spawn(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend") log_success(f"Open {bold(f'http://localhost:{frontend_port}')} in your browser.") print() try: while True: if backend.poll() is not None: log_error(f"Backend exited with code {backend.returncode}") raise SystemExit(1) if frontend.poll() is not None: log_error(f"Frontend exited with code {frontend.returncode}") raise SystemExit(1) time.sleep(1) except KeyboardInterrupt: print() log_info("Shutting down ...") finally: _terminate(frontend, "frontend") _terminate(backend, "backend") if __name__ == "__main__": main()