mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 03:39:27 +08:00
Two independent issues that block `python scripts/start_web.py` after a
clean install on Windows:
1. UnicodeDecodeError when streaming subprocess output
`_spawn()` opened the backend / frontend stdout pipe with `text=True`
but no explicit encoding. On Windows this defaults to the system
ANSI codepage (e.g. `gbk` on Chinese Windows), which raises
`UnicodeDecodeError` as soon as the child process emits a UTF-8 byte.
Fix: pin `encoding="utf-8"` and `errors="replace"` so any locale
produces clean, lossless output.
2. Missing runtime dependencies in requirements/server.txt
`deeptutor/services/llm/provider_core/__init__.py` unconditionally
imports `AnthropicProvider`, `OpenAICompatProvider`, and
`OpenAIResponses`, which in turn import:
- `loguru` (provider_core/base.py, openai_codex_provider.py,
openai_responses/parsing.py)
- `json_repair` (anthropic_provider.py, openai_compat_provider.py,
openai_responses/parsing.py)
These are declared only in `requirements/tutorbot.txt`, so
`pip install -r requirements/server.txt && pip install -e .` followed
by `python scripts/start_web.py` crashes with `ModuleNotFoundError`
before the API server can serve a single request.
Fix: declare both packages in `server.txt` with the same version
bounds used by `tutorbot.txt`.
Reproduced and verified on Windows 11 + Python 3.12 + a fresh venv.
167 lines
5.0 KiB
Python
167 lines
5.0 KiB
Python
#!/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,
|
|
"encoding": "utf-8",
|
|
"errors": "replace",
|
|
}
|
|
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}",
|
|
],
|
|
)
|
|
|
|
api_base = f"http://localhost:{backend_port}"
|
|
|
|
# Write web/.env.local so the frontend picks up the correct backend port
|
|
# even when started independently (e.g. `npm run dev` without this launcher).
|
|
env_local_path = PROJECT_ROOT / "web" / ".env.local"
|
|
env_local_path.write_text(
|
|
f"# Auto-generated by start_web.py — do not edit manually\n"
|
|
f"NEXT_PUBLIC_API_BASE={api_base}\n"
|
|
)
|
|
|
|
backend_env = os.environ.copy()
|
|
backend_env["PYTHONUNBUFFERED"] = "1"
|
|
|
|
frontend_env = os.environ.copy()
|
|
frontend_env["NEXT_PUBLIC_API_BASE"] = api_base
|
|
|
|
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()
|