#!/bin/bash

# Packages needed: sane-utils cuneiform|tesseract mbrola-de

# Parameter for scanimage (see: scanimage -A)

# Device name (e.g. epson, plustek)
SCANNER=epson
# Scan mode (lineart/monochrome/color)
MODE=gray
# Select resolution
RESOLUTION=300
# Top-left x position of scan area (0..607pel)
TOP_LEFT_X_POS=0
# Top-left x position of scan area (0..391pel)
TOP_LEFT_Y_POS=0
# Width of scan area (160..767pel)
WIDTH=767
# Height of scan area (120..511pel)
HEIGHT=511

# OCR software (cuneiform or tesseract)
OCR=tesseract

# Miscellaneous
KEEP_DATA="no"
VERBOSE="no"

[ -e /etc/mbrola/readtext.conf ] && . /etc/mbrola/readtext.conf ]
[ -e ~/.readtext ] && . ~/.readtext ]

error() {
  echo "## ERROR: $1"
  [ "$KEEP_DATA" = "yes" ] || rm -f /tmp/image-$TIMESTAMP.pnm /tmp/image-$TIMESTAMP.txt
  sayit "Es ist ein Fehler aufgetreten."
  exit 1
}

TIMESTAMP=$(date +%Y-%M-%d_%H:%M:%S)

if [ "$VERBOSE" = "yes" ]
then
  echo "## scanning image"
  sayit "Das Dokument wird eingescännt."
fi
scanimage -d $SCANNER --mode $MODE --resolution $RESOLUTION \
-l $TOP_LEFT_X_POS -t $TOP_LEFT_Y_POS -x $WIDTH -y $HEIGHT >/tmp/image-$TIMESTAMP.pnm || error "scanning failed"

[ -e /tmp/image-$TIMESTAMP.pnm ] || error "no image"

if [ "$VERBOSE" = "yes" ]
then
  echo "## text recognition"
  sayit "Der Text wird analysiert."
fi

if [ "$OCR" = "cuneiform" ]
then
  $OCR -l ger -o /tmp/image-$TIMESTAMP.txt /tmp/image-$TIMESTAMP.pnm &>/dev/null || error "ocr failed"
fi

if [ "$OCR" = "tesseract" ]
then
  $OCR /tmp/image-$TIMESTAMP.pnm /tmp/image-$TIMESTAMP -l deu &>/dev/null || error "ocr failed"
fi

[ -e /tmp/image-$TIMESTAMP.txt ] || error "no text"

if [ "$VERBOSE" = "yes" ]
then
  echo "## speech output"
  sayit "Folgender Text wurde erkannt."
  sleep 1
fi
cp -f /tmp/image-$TIMESTAMP.txt /tmp/last_document.txt
say /tmp/image-$TIMESTAMP.txt

if ! [ "$KEEP_DATA" = "yes" ]
then
  rm -f /tmp/image-$TIMESTAMP.pnm /tmp/image-$TIMESTAMP.txt
fi
