Files
secondary-school-grade-archive/deploy/ocr-common.sh
T

101 lines
3.0 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# OCR Worker 共用函数:同机 GPU 识别 + screen 常驻
OCR_SCREEN_NAME="${OCR_SCREEN_NAME:-ocr-worker}"
OCR_PORT="${OCR_PORT:-23567}"
ocr_worker_dir() {
echo "${INSTALL_DIR}/deploy/ocr-worker"
}
install_ocr_worker() {
local worker_dir
worker_dir="$(ocr_worker_dir)"
if [[ ! -d "${worker_dir}" ]]; then
log_error "未找到 ${worker_dir}"
return 1
fi
log_info "安装/更新 OCR Worker (PaddleOCR GPU)…"
chmod +x "${worker_dir}"/*.sh 2>/dev/null || true
OCR_PORT="${OCR_PORT}" bash "${worker_dir}/install.sh"
}
ocr_screen_running() {
screen -list 2>/dev/null | grep -q "\.${OCR_SCREEN_NAME}[[:space:]]"
}
start_ocr_screen() {
local worker_dir
worker_dir="$(ocr_worker_dir)"
if [[ ! -x "${worker_dir}/.venv/bin/uvicorn" ]]; then
log_warn "OCR Worker 未安装,跳过 screen 启动"
return 1
fi
if ! command -v screen >/dev/null; then
log_error "未安装 screen,请 apt install screen"
return 1
fi
log_info "启动 OCR Worker → screen 会话「${OCR_SCREEN_NAME}」(GPU 常驻, 端口 ${OCR_PORT})"
if ocr_screen_running; then
screen -S "${OCR_SCREEN_NAME}" -X quit 2>/dev/null || true
sleep 1
fi
mkdir -p "${INSTALL_DIR}/logs" 2>/dev/null || true
local log_file="${INSTALL_DIR}/logs/ocr-worker.log"
screen -dmS "${OCR_SCREEN_NAME}" bash -c "
cd '${worker_dir}' &&
export OCR_USE_GPU=true OCR_PORT='${OCR_PORT}' OCR_HOST=0.0.0.0 &&
exec bash run.sh >> '${log_file}' 2>&1
"
sleep 2
log_info "OCR 日志: ${log_file}"
}
stop_ocr_screen() {
if ocr_screen_running; then
log_info "停止 OCR screen 会话…"
screen -S "${OCR_SCREEN_NAME}" -X quit 2>/dev/null || true
fi
}
wait_ocr_healthy() {
local max="${1:-30}"
local i
log_info "等待 OCR 就绪(最多 ${max}×2 秒,首次加载模型较慢)…"
for i in $(seq 1 "${max}"); do
if curl -sf "http://127.0.0.1:${OCR_PORT}/health" >/dev/null 2>&1; then
log_info "OCR 健康检查通过 — http://127.0.0.1:${OCR_PORT}/health"
return 0
fi
if (( i % 5 == 0 )); then
echo -ne "\r${YELLOW}[INFO]${NC} 仍在等待 OCR… ${i}/${max}(可另开终端: tail -f ${INSTALL_DIR}/logs/ocr-worker.log"
fi
sleep 2
done
echo ""
log_warn "OCR 尚未响应(可能仍在下载/加载模型,主程序可先继续)"
log_warn "稍后执行: bash ${INSTALL_DIR}/deploy/ocr-screen.sh status"
return 1
}
show_ocr_status() {
echo ""
echo "--- OCR Worker (screen: ${OCR_SCREEN_NAME}) ---"
if ocr_screen_running; then
echo "screen: 运行中"
screen -list 2>/dev/null | grep "${OCR_SCREEN_NAME}" || true
else
echo "screen: 未运行"
fi
if curl -sf "http://127.0.0.1:${OCR_PORT}/health" 2>/dev/null; then
echo ""
else
echo "health: 无响应 (http://127.0.0.1:${OCR_PORT}/health)"
fi
if command -v nvidia-smi >/dev/null; then
nvidia-smi --query-gpu=name,memory.used,memory.total,utilization.gpu --format=csv,noheader 2>/dev/null || true
fi
}