#!/usr/bin/env bash
# OCR Worker 安装（RapidOCR / ONNX，无需 Paddle/GPU）
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
VENV="${ROOT}/.venv"
PORT="${OCR_PORT:-23567}"
PIP_MIRROR="${PIP_MIRROR:-https://pypi.tuna.tsinghua.edu.cn/simple}"

echo "==> OCR Worker 安装目录: ${ROOT}"
echo "==> 引擎: RapidOCR (ONNX CPU，无需 cuDNN/GPU)"

if ! command -v python3 >/dev/null; then
  echo "错误: 请先安装 python3"
  exit 1
fi

if [[ -d "${VENV}" ]]; then
  echo "==> 已有虚拟环境"
else
  python3 -m venv "${VENV}"
fi

# shellcheck disable=SC1091
source "${VENV}/bin/activate"
pip install -U pip wheel -i "${PIP_MIRROR}"
pip uninstall -y paddlepaddle paddlepaddle-gpu paddleocr 2>/dev/null || true
pip install -r "${ROOT}/requirements.txt" -i "${PIP_MIRROR}"
chmod +x "${ROOT}/run.sh" "${ROOT}/start.sh" 2>/dev/null || true

echo ""
python3 -c "from rapidocr_onnxruntime import RapidOCR; print('RapidOCR OK')"
echo ""
echo "==> 安装完成。管理: bash $(dirname "$ROOT")/ocr-screen.sh status"
