#!/usr/bin/env bash
# 供 screen 会话调用：OCR 模型常驻 GPU，异常退出自动重启
set -uo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
VENV="${ROOT}/.venv"
PORT="${OCR_PORT:-23567}"

export OCR_USE_GPU="${OCR_USE_GPU:-false}"
export OCR_HOST="${OCR_HOST:-0.0.0.0}"

if [[ ! -d "${VENV}" ]]; then
  echo "错误: 请先运行 bash install.sh"
  exit 1
fi

# shellcheck disable=SC1091
source "${VENV}/bin/activate"
cd "${ROOT}"

echo "=========================================="
echo " OCR Worker  |  GPU=${OCR_USE_GPU}  |  :${PORT}"
echo " $(date -Iseconds)"
echo " 退出 screen: Ctrl+A 然后 D"
echo "=========================================="

while true; do
  uvicorn app:app --host "${OCR_HOST}" --port "${PORT}" --log-level info
  code=$?
  echo "[$(date -Iseconds)] uvicorn 退出 code=${code}，5 秒后重启…"
  sleep 5
done
