#!/bin/sh
# refs2bib.sh paper.pdf > paper.bib
# The paper's own BibTeX entry, then one entry for each reference in its list, from GROBID on this computer.
# Nothing leaves your computer: no CrossRef lookup (consolidateHeader=0, consolidateCitations=0).
# A scan with no text layer gets OCR first with OCRmyPDF, because GROBID does no OCR.
# Two fixes to GROBID's BibTeX: a book comes back as @inbook with its title only in booktitle (made @book with
# a title), and two entries can share one key (the second gets _2).
# Needs: curl, pdftotext (poppler), GROBID on port 8070:
#   docker run --rm --init --ulimit core=0 -p 8070:8070 grobid/grobid:0.9.1-crf
# and, for scans only, ocrmypdf (OCR_JOBS=2 limits it to 2 CPU cores). `refs2bib.sh --fix < in.bib` applies only the two fixes.
# Brasspage, Nov 2026. Tested on 8 arXiv papers: https://brasspage.com/pdf-to-bibtex/
set -eu
fix() {
  awk 'BEGIN { RS = ""; ORS = "\n\n" }
  {
    if ($0 ~ /^@inbook\{/ && $0 !~ /\n  title = /) { sub(/^@inbook\{/, "@book{"); sub(/\n  booktitle = /, "\n  title = ") }
    if (match($0, /^@[a-zA-Z]+\{[^,]*/)) {
      head = substr($0, 1, RLENGTH); key = substr(head, index(head, "{") + 1)
      if (key in seen) { seen[key]++; $0 = head "_" seen[key] substr($0, RLENGTH + 1) } else seen[key] = 1
    }
    print
  }'
}
if [ "${1:-}" = "--fix" ]; then fix; exit; fi
pdf=${1:?usage: refs2bib.sh paper.pdf > paper.bib}
url=${GROBID_URL:-http://localhost:8070}
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cp -- "$pdf" "$tmp/in.pdf"
if [ "$(pdftotext -l 3 "$tmp/in.pdf" - 2>/dev/null | wc -w)" -lt 50 ]; then
  echo "refs2bib: little or no text layer, running OCRmyPDF first" >&2
  ocrmypdf -q --force-ocr ${OCR_JOBS:+-j "$OCR_JOBS"} "$tmp/in.pdf" "$tmp/ocr.pdf" >&2
  mv "$tmp/ocr.pdf" "$tmp/in.pdf"
fi
call() {
  curl -sSf -H "Accept: application/x-bibtex" -F "input=@$tmp/in.pdf" "$@"
}
{
  call --form-string consolidateHeader=0 "$url/api/processHeaderDocument"
  echo
  call --form-string consolidateCitations=0 --form-string includeRawCitations=1 "$url/api/processReferences"
} | fix
