OCR for Spectacle

This version uses kate to display the text instead of using the dialog. I find it more convenient plus you don’t need wl-clipboard nor kdialog dependencies.

#!/usr/bin/env bash

PICTURE="$HOME/_temp_Screenshot_$(date +%Y%m%d_%H%M%S)_OCR.png"
PICTURE_RESIZED="$HOME/_temp_Screenshot_$(date +%Y%m%d_%H%M%S)_OCR_resized.png"
CR=$(printf '\r')

spectacle -r -o "$PICTURE" -b -n 2>/dev/null

if [ -s "$PICTURE" ]; then
  # Resize picture for better OCR processing (optional)
  magick "$PICTURE" -resize 400% "$PICTURE_RESIZED"

  # Perform OCR and format text for Windows compatibility
  TEXT="$(tesseract --psm 6 "$PICTURE_RESIZED" - | sed "s/$/$CR/")"

  # Cleanup temporary files
  rm -f "$PICTURE" "$PICTURE_RESIZED"

  # Open text in Kate
  echo "$TEXT" | kate -i
fi