#!/usr/bin/env bash # Start (or health-probe) the omniparse parsing service. Idempotent: if a # healthy service answers on the port, reports it and exits 0. # # OMNI_CUDA_DEVICE=0 GPU index for the service (default 0; -1 = CPU) # OMNI_API_PORT=8898 listen port # OMNI_TOKEN_FILE token file (default ~/.config/omniparse_token; # created with a random token if missing) # OMNI_PYTHON python interpreter (default .venv/bin/python, # else python3 from PATH) set -u REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PORT="${OMNI_API_PORT:-8898}" LOG="${OMNI_LOG_FILE:-/tmp/omniparse.log}" TOKEN_FILE="${OMNI_TOKEN_FILE:-$HOME/.config/omniparse_token}" if [[ -x "$REPO/.venv/bin/uvicorn" ]]; then ENVBIN="$REPO/.venv/bin" else ENVBIN="" # bare install: uvicorn/python must be on PATH fi PY="${OMNI_PYTHON:-${ENVBIN:+$ENVBIN/}python3}" if curl -sf --max-time 2 "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1; then echo "already up: $(curl -s --max-time 5 "http://127.0.0.1:$PORT/healthz")" exit 0 fi umask 077 [[ -f "$TOKEN_FILE" ]] || { mkdir -p "$(dirname "$TOKEN_FILE")" "$PY" -c 'import secrets; print(secrets.token_hex(16))' | tee "$TOKEN_FILE"; } TOKEN="$(cat "$TOKEN_FILE")" cd "$REPO" export OMNI_API_TOKEN="$TOKEN" PYTHONPATH="$REPO" if [[ "${OMNI_CUDA_DEVICE:-0}" == "-1" ]]; then export CUDA_VISIBLE_DEVICES="" else export CUDA_VISIBLE_DEVICES="${OMNI_CUDA_DEVICE:-0}" fi nohup "$PY" -m uvicorn omni_api.server:app --host "${OMNI_API_HOST:-0.0.0.0}" \ --port "$PORT" --log-level warning >>"$LOG" 2>&1 & echo "started (pid $!) port $PORT card ${OMNI_CUDA_DEVICE:-0}; first parse pays a ~10 s lazy OCR load; log: $LOG" for _ in $(seq 1 120); do sleep 2 S="$(curl -sf --max-time 3 "http://127.0.0.1:$PORT/healthz" 2>/dev/null)" [[ "$S" == *'"ready"'* ]] && break done [[ "$S" == *'"ready"'* ]] || { echo "FAILED: models never loaded; see $LOG"; exit 1; } # Readiness = an actual parse, not just loaded models: OCR loads lazily and its # detection peak is what OOMs when another process shares the card. IMG_B64="$("$PY" -c 'import base64, io from PIL import Image img = Image.new("RGB", (64, 64), (90, 120, 200)) buf = io.BytesIO(); img.save(buf, "PNG") print(base64.b64encode(buf.getvalue()).decode())')" SMOKE="$(curl -s --max-time 120 -X POST "http://127.0.0.1:$PORT/parse" \ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ -d "{\"image_b64\": \"$IMG_B64\", \"format\": \"view\"}")" if [[ "$SMOKE" == *'"n_elements"'* ]]; then echo "READY (warm smoke parse ok)" else echo "WARNING: models loaded but smoke parse failed: ${SMOKE:0:200}"; exit 1 fi IP="$(hostname -I 2>/dev/null | awk '{print $1}')" echo "url: http://${IP:-127.0.0.1}:$PORT (docs at /docs)"