#!/bin/sh
# pdf-ocr-text.sh: a ripgrep-all (rga) custom adapter that also reads scanned PDF pages.
# rga sends the PDF on stdin. This prints the text of each page and a form feed after it.
# A page with a text layer gives its text (pdftotext). A page with no text gets Tesseract OCR.
# Needs: poppler (pdfinfo, pdftotext, pdftoppm) and tesseract. OCR_LANG=deu (or eng+fra) for other languages.
# Brasspage, MIT license, https://brasspage.com/search-multiple-pdfs/
set -e
t=$(mktemp -d)
trap 'rm -rf "$t"' EXIT
cat > "$t/in.pdf"
n=$(pdfinfo "$t/in.pdf" 2>/dev/null | awk '/^Pages:/ {print $2}')
i=1
while [ "$i" -le "${n:-0}" ]; do
  pdftotext -f "$i" -l "$i" "$t/in.pdf" "$t/page.txt" 2>/dev/null || : > "$t/page.txt"
  if [ "$(tr -d '[:space:]' < "$t/page.txt" | wc -c)" -lt 20 ]; then
    pdftoppm -f "$i" -l "$i" -r 300 -gray "$t/in.pdf" "$t/img"
    tesseract "$t"/img*.pgm - -l "${OCR_LANG:-eng}" 2>/dev/null > "$t/page.txt" || : > "$t/page.txt"
    rm -f "$t"/img*.pgm
  fi
  tr -d '\f' < "$t/page.txt"
  printf '\f'
  i=$((i + 1))
done
