Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

improve install scripts and session management

Bingxi Zhao5dcda4948fc6
diff --git a/README.md b/README.md
index 788da2823..764834876 100644
--- a/README.md
+++ b/README.md
@@ -232,13 +232,14 @@ cd DeepTutor
# Set Up Virtual Environment (Choose One Option)
# Option A: Using conda (Recommended)
-conda create -n aitutor python=3.10
-conda activate aitutor
+conda create -n deeptutor python=3.10
+conda activate deeptutor
# Option B: Using venv
python -m venv venv
# On Windows:
venv\Scripts\activate
+
# On macOS/Linux:
source venv/bin/activate
```
@@ -248,10 +249,10 @@ source venv/bin/activate
Run the automated installation script to install all required dependencies:
```bash
-# Recommended: Automated Installation
+# Recommended
bash scripts/install_all.sh
-# Alternative: Manual Installation
+# Alternative Python Scripts
python scripts/install_all.py
# Or Install Dependencies Manually
diff --git a/scripts/install_all.py b/scripts/install_all.py
index 3b86c13bd..fa248e9ef 100644
--- a/scripts/install_all.py
+++ b/scripts/install_all.py
@@ -64,6 +64,152 @@ def print_warning(message: str):
print(f"⚠️ {message}")
+def install_with_uv(requirements_file: Path, project_root: Path) -> bool:
+ """Try installing dependencies using uv (faster and better resolver)"""
+ uv_path = shutil.which("uv")
+
+ if not uv_path:
+ # Try to install uv first
+ print_info("uv not found, attempting to install uv...")
+ try:
+ result = subprocess.run(
+ [sys.executable, "-m", "pip", "install", "uv"],
+ check=False,
+ timeout=120,
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 0:
+ print_success("uv installed successfully")
+ else:
+ return False
+ except Exception:
+ return False
+
+ print_info("Using uv for faster dependency resolution...")
+ try:
+ cmd = [sys.executable, "-m", "uv", "pip", "install", "-r", str(requirements_file)]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=900,
+ capture_output=False,
+ text=True,
+ )
+ return result.returncode == 0
+ except Exception as e:
+ print_warning(f"uv installation failed: {e}")
+ return False
+
+
+def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool:
+ """Install dependencies in stages to avoid resolution-too-deep error"""
+ print_info("Using staged pip installation to avoid dependency resolution issues...")
+
+ # Stage 1: Install core dependencies first (without complex RAG packages)
+ core_deps = [
+ "python-dotenv>=1.0.0",
+ "PyYAML>=6.0",
+ "tiktoken>=0.5.0",
+ "requests>=2.31.0",
+ "openai>=1.0.0",
+ "aiohttp>=3.9.0",
+ "httpx>=0.25.0",
+ "nest_asyncio>=1.5.8",
+ "fastapi>=0.100.0",
+ "uvicorn[standard]>=0.24.0",
+ "websockets>=12.0",
+ "python-multipart>=0.0.6",
+ "pydantic>=2.0.0",
+ "arxiv>=2.0.0",
+ "pre-commit>=3.0.0",
+ ]
+
+ print_info("Stage 1/3: Installing core dependencies...")
+ try:
+ cmd = [sys.executable, "-m", "pip", "install"] + core_deps
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=600,
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ print_error("Failed to install core dependencies")
+ return False
+ print_success("Core dependencies installed")
+ except Exception as e:
+ print_error(f"Error installing core dependencies: {e}")
+ return False
+
+ # Stage 2: Install lightrag-hku
+ print_info("Stage 2/3: Installing lightrag-hku...")
+ try:
+ cmd = [sys.executable, "-m", "pip", "install", "lightrag-hku>=1.0.0"]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=600,
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ print_warning("lightrag-hku installation had issues, continuing...")
+ except Exception as e:
+ print_warning(f"lightrag-hku installation error: {e}")
+
+ # Stage 3: Install raganything with special handling
+ print_info("Stage 3/3: Installing raganything (this may take a while)...")
+ try:
+ # First try normal install
+ cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0"]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=900, # 15 minutes for complex package
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ # Try with --no-deps and install deps separately
+ print_warning("Standard install failed, trying with --no-deps...")
+ cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0", "--no-deps"]
+ result = subprocess.run(
+ cmd,
+ check=False,
+ cwd=project_root,
+ timeout=300,
+ capture_output=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ print_warning("raganything installation had issues")
+ except Exception as e:
+ print_warning(f"raganything installation error: {e}")
+
+ # Try to install any remaining optional deps
+ try:
+ optional_deps = ["perplexityai>=0.1.0", "dashscope>=1.14.0"]
+ for dep in optional_deps:
+ subprocess.run(
+ [sys.executable, "-m", "pip", "install", dep],
+ check=False,
+ cwd=project_root,
+ timeout=120,
+ capture_output=True,
+ text=True,
+ )
+ except Exception:
+ pass
+
+ return True
+
+
def install_backend_deps(project_root: Path) -> bool:
"""Install backend dependencies"""
print_step("Step 1/3: Installing backend dependencies")
@@ -76,8 +222,22 @@ def install_backend_deps(project_root: Path) -> bool:
print_info(f"Using Python: {sys.executable}")
print_info(f"Requirements file: {requirements_file}")
+ # Strategy 1: Try using uv (fastest and best resolver)
+ print_info("Attempting installation with uv (recommended)...")
+ if install_with_uv(requirements_file, project_root):
+ print_success("Backend dependencies installed successfully with uv")
+ return True
+
+ print_warning("uv installation failed, falling back to staged pip installation...")
+
+ # Strategy 2: Staged pip installation
+ if install_with_pip_staged(requirements_file, project_root):
+ print_success("Backend dependencies installed successfully with staged pip")
+ return True
+
+ # Strategy 3: Direct pip install as last resort
+ print_warning("Staged installation had issues, trying direct pip install...")
try:
- # Install using pip
cmd = [sys.executable, "-m", "pip", "install", "-r", str(requirements_file)]
print_info("Installing backend dependencies, please wait...")
diff --git a/scripts/install_all.sh b/scripts/install_all.sh
index 7878b5ad5..ff8915bdd 100644
--- a/scripts/install_all.sh
+++ b/scripts/install_all.sh
@@ -80,13 +80,94 @@ fi
print_info "Using Python: $(which python)"
print_info "Requirements file: $REQUIREMENTS_FILE"
+
+# Function to install with uv (faster and better resolver)
+install_with_uv() {
+ # Check if uv is available
+ if ! command -v uv &> /dev/null; then
+ print_info "Installing uv for better dependency resolution..."
+ if python -m pip install uv; then
+ print_success "uv installed successfully"
+ else
+ return 1
+ fi
+ fi
+
+ print_info "Using uv for faster dependency resolution..."
+ if python -m uv pip install -r "$REQUIREMENTS_FILE"; then
+ return 0
+ else
+ return 1
+ fi
+}
+
+# Function to install with staged pip (avoids resolution-too-deep)
+install_with_pip_staged() {
+ print_info "Using staged pip installation to avoid dependency resolution issues..."
+
+ # Stage 1: Core dependencies
+ print_info "Stage 1/3: Installing core dependencies..."
+ if python -m pip install \
+ "python-dotenv>=1.0.0" \
+ "PyYAML>=6.0" \
+ "tiktoken>=0.5.0" \
+ "requests>=2.31.0" \
+ "openai>=1.0.0" \
+ "aiohttp>=3.9.0" \
+ "httpx>=0.25.0" \
+ "nest_asyncio>=1.5.8" \
+ "fastapi>=0.100.0" \
+ "uvicorn[standard]>=0.24.0" \
+ "websockets>=12.0" \
+ "python-multipart>=0.0.6" \
+ "pydantic>=2.0.0" \
+ "arxiv>=2.0.0" \
+ "pre-commit>=3.0.0"; then
+ print_success "Core dependencies installed"
+ else
+ print_error "Failed to install core dependencies"
+ return 1
+ fi
+
+ # Stage 2: lightrag-hku
+ print_info "Stage 2/3: Installing lightrag-hku..."
+ python -m pip install "lightrag-hku>=1.0.0" || print_warning "lightrag-hku installation had issues"
+
+ # Stage 3: raganything (complex dependencies)
+ print_info "Stage 3/3: Installing raganything (this may take a while)..."
+ if ! python -m pip install "raganything>=0.1.0"; then
+ print_warning "Standard install failed, trying with --no-deps..."
+ python -m pip install "raganything>=0.1.0" --no-deps || print_warning "raganything installation had issues"
+ fi
+
+ # Optional deps
+ python -m pip install "perplexityai>=0.1.0" "dashscope>=1.14.0" 2>/dev/null || true
+
+ return 0
+}
+
print_info "Installing backend dependencies, please wait..."
-if python -m pip install -r "$REQUIREMENTS_FILE"; then
- print_success "Backend dependencies installed successfully"
+# Strategy 1: Try uv first (recommended)
+print_info "Attempting installation with uv (recommended)..."
+if install_with_uv; then
+ print_success "Backend dependencies installed successfully with uv"
else
- print_error "Backend dependencies installation failed"
- exit 1
+ print_warning "uv installation failed, falling back to staged pip installation..."
+
+ # Strategy 2: Staged pip installation
+ if install_with_pip_staged; then
+ print_success "Backend dependencies installed successfully with staged pip"
+ else
+ # Strategy 3: Direct pip as last resort
+ print_warning "Staged installation had issues, trying direct pip install..."
+ if python -m pip install -r "$REQUIREMENTS_FILE"; then
+ print_success "Backend dependencies installed successfully"
+ else
+ print_error "Backend dependencies installation failed"
+ exit 1
+ fi
+ fi
fi
# Step 2: Install frontend dependencies
diff --git a/scripts/start_web.py b/scripts/start_web.py
index 104a4733d..fffb31c9f 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -1,6 +1,7 @@
import os
from pathlib import Path
import shutil
+import signal
import subprocess
import sys
import time
@@ -17,6 +18,77 @@ def print_flush(*args, **kwargs):
print(*args, **kwargs)
+def terminate_process_tree(process, name="Process", timeout=5):
+ """
+ Terminate a process and all its children (process group).
+
+ On Unix: Uses process group (PGID) to kill all children including uvicorn workers.
+ On Windows: Uses taskkill /T to kill the process tree.
+
+ Args:
+ process: subprocess.Popen object
+ name: Display name for logging
+ timeout: Seconds to wait for graceful termination before SIGKILL
+ """
+ if process is None or process.poll() is not None:
+ return # Process already terminated
+
+ pid = process.pid
+ print_flush(f"🛑 Stopping {name} (PID: {pid})...")
+
+ try:
+ if os.name == "nt":
+ # Windows: Use taskkill with /T to kill process tree
+ subprocess.run(
+ ["taskkill", "/F", "/T", "/PID", str(pid)],
+ check=False,
+ stderr=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ )
+ else:
+ # Unix: Kill the entire process group
+ pgid = os.getpgid(pid)
+
+ # Step 1: Send SIGTERM to the process group for graceful shutdown
+ try:
+ os.killpg(pgid, signal.SIGTERM)
+ print_flush(f" Sent SIGTERM to process group {pgid}")
+ except ProcessLookupError:
+ print_flush(f" Process group {pgid} already terminated")
+ return
+ except PermissionError:
+ # Fallback: try to terminate just the main process
+ print_flush(f" Cannot kill process group, trying single process")
+ process.terminate()
+
+ # Step 2: Wait for graceful termination
+ try:
+ process.wait(timeout=timeout)
+ print_flush(f" ✅ {name} terminated gracefully")
+ return
+ except subprocess.TimeoutExpired:
+ print_flush(f" ⚠️ {name} did not terminate in {timeout}s, sending SIGKILL...")
+
+ # Step 3: Force kill with SIGKILL
+ try:
+ os.killpg(pgid, signal.SIGKILL)
+ process.wait(timeout=2)
+ print_flush(f" ✅ {name} force killed")
+ except ProcessLookupError:
+ print_flush(f" Process group already terminated")
+ except Exception as e:
+ print_flush(f" ⚠️ Error during force kill: {e}")
+ # Last resort: try to kill just the main process
+ try:
+ process.kill()
+ process.wait(timeout=2)
+ except Exception:
+ pass
+
+ except Exception as e:
+ print_flush(f" ⚠️ Error stopping {name}: {e}")
+
+
def start_backend():
print_flush(f"🚀 Starting FastAPI Backend using {sys.executable}...")
base_dir = os.path.dirname(os.path.abspath(__file__))
@@ -67,18 +139,25 @@ def start_backend():
if os.name == "nt":
env["PYTHONLEGACYWINDOWSSTDIO"] = "0"
- process = subprocess.Popen(
- cmd,
- cwd=project_root, # Run in project root directory, not scripts directory
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- bufsize=1,
- shell=False,
- encoding="utf-8",
- errors="replace",
- env=env,
- )
+ # Use start_new_session=True on Unix to create a new process group
+ # This allows us to kill all child processes (including uvicorn workers) at once
+ popen_kwargs = {
+ "cwd": project_root, # Run in project root directory, not scripts directory
+ "stdout": subprocess.PIPE,
+ "stderr": subprocess.STDOUT,
+ "text": True,
+ "bufsize": 1,
+ "shell": False,
+ "encoding": "utf-8",
+ "errors": "replace",
+ "env": env,
+ }
+
+ # On Unix, create a new session so we can kill the entire process group
+ if os.name != "nt":
+ popen_kwargs["start_new_session"] = True
+
+ process = subprocess.Popen(cmd, **popen_kwargs)
# Start a thread to output logs in real-time
import threading
@@ -95,6 +174,8 @@ def start_backend():
log_thread.start()
print_flush(f"✅ Backend process started (PID: {process.pid})")
+ if os.name != "nt":
+ print_flush(f" Process group ID (PGID): {os.getpgid(process.pid)}")
return process
@@ -213,17 +294,28 @@ def start_frontend():
env["PYTHONLEGACYWINDOWSSTDIO"] = "0"
npm_cmd = shutil.which("npm") or "npm"
+
+ # Use start_new_session=True on Unix to create a new process group
+ # This allows us to kill all child processes (including Next.js workers) at once
+ popen_kwargs = {
+ "cwd": web_dir,
+ "shell": False,
+ "stdout": subprocess.PIPE,
+ "stderr": subprocess.STDOUT,
+ "text": True,
+ "bufsize": 1,
+ "env": env,
+ "encoding": "utf-8",
+ "errors": "replace",
+ }
+
+ # On Unix, create a new session so we can kill the entire process group
+ if os.name != "nt":
+ popen_kwargs["start_new_session"] = True
+
frontend_process = subprocess.Popen(
[npm_cmd, "run", "dev", "--", "-p", str(frontend_port)],
- cwd=web_dir,
- shell=False,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- bufsize=1,
- env=env,
- encoding="utf-8",
- errors="replace",
+ **popen_kwargs,
)
# Start a thread to output frontend logs in real-time
@@ -241,6 +333,8 @@ def start_frontend():
log_thread.start()
print_flush(f"✅ Frontend process started (PID: {frontend_process.pid})")
+ if os.name != "nt":
+ print_flush(f" Process group ID (PGID): {os.getpgid(frontend_process.pid)}")
return frontend_process
@@ -342,34 +436,9 @@ if __name__ == "__main__":
traceback.print_exc()
finally:
- if backend:
- try:
- if os.name == "nt":
- subprocess.run(
- ["taskkill", "/F", "/T", "/PID", str(backend.pid)],
- check=False,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- )
- else:
- backend.terminate()
- backend.wait(timeout=5)
- except Exception as e:
- print_flush(f"Error stopping backend: {e}")
-
- if frontend:
- try:
- if os.name == "nt":
- subprocess.run(
- ["taskkill", "/F", "/T", "/PID", str(frontend.pid)],
- check=False,
- stderr=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- )
- else:
- frontend.terminate()
- frontend.wait(timeout=5)
- except Exception as e:
- print_flush(f"Error stopping frontend: {e}")
-
- print_flush("✅ Services stopped.")
+ # Use terminate_process_tree to properly kill all child processes
+ # including uvicorn workers and Next.js child processes
+ terminate_process_tree(backend, name="Backend", timeout=5)
+ terminate_process_tree(frontend, name="Frontend", timeout=5)
+
+ print_flush("✅ All services stopped.")
diff --git a/web/package-lock.json b/web/package-lock.json
index a0626d94b..1b63f1bc7 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -937,6 +937,7 @@
"resolved": "https://registry.npmmirror.com/@types/react/-/react-18.3.27.tgz",
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
@@ -1379,6 +1380,7 @@
"resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
+ "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -1850,6 +1852,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.25",
"caniuse-lite": "^1.0.30001754",
@@ -2069,6 +2072,7 @@
"resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz",
"integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==",
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"@chevrotain/cst-dts-gen": "11.0.3",
"@chevrotain/gast": "11.0.3",
@@ -2264,6 +2268,7 @@
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",
"integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=0.10"
}
@@ -2673,6 +2678,7 @@
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"license": "ISC",
+ "peer": true,
"engines": {
"node": ">=12"
}
@@ -3233,6 +3239,7 @@
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1",
@@ -3401,6 +3408,7 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@@ -5111,6 +5119,7 @@
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"jiti": "bin/jiti.js"
}
@@ -6969,6 +6978,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -7190,6 +7200,7 @@
"resolved": "https://registry.npmmirror.com/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -7202,6 +7213,7 @@
"resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -8276,6 +8288,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -8474,6 +8487,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"