同时适用于 Wayland 和 X11 的百度 OCR 脚本

** 使用前先把 client_id 和 client_secret 改成自己的值。**
百度 OCR API 文档见 https://ai.baidu.com/tech/ocr
使用到的额外程序:spectacle, wl-clipboard
(由于 Wayland 下的屏幕截图程序大多无法自动复制图片到剪贴板,所以采用 spectacle 保存到临时文件的方式缓解该问题)

使用方法:绑定该脚本至某快捷键,按下快捷键后,spectacle 会提示框选屏幕区域,框选需要进行文字识别的区域并双击,等待图片发送至百度服务器进行识别,识别结果返回后会自动复制到剪贴板上,并通过 kdialog 提示。

#!/usr/bin/env bash
client_id="5P*************************qL"
client_secret="fR*************************kZ"

TMPFILE=$(mktemp)
TMPFILE2=$(mktemp)
trap 'rm -f "$TMPFILE";rm -f "$TMPFILE2"' EXIT
spectacle -r -o $TMPFILE -b -n
# [ "$XDG_SESSION_TYPE" = "x11" ] && xclip -selection clipboard -t image/png -o 2>/dev/null > $TMPFILE
# [ "$XDG_SESSION_TYPE" = "wayland" ] && wl-paste -n -t image/png 2>/dev/null > $TMPFILE
if [ -s "$TMPFILE" ]; then
    base64 -w0 ${TMPFILE} > ${TMPFILE2}
    auth_host="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="${client_id}"&client_secret="${client_secret}
    json_response=$(curl -s --retry-delay 1 --connect-timeout 10 --max-time 10 $auth_host)
    token=$(perl -MCpanel::JSON::XS -ne 'print decode_json($_)->{access_token}' <<< $json_response)
    if [ -n "$token" ]; then
        ocr_host="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="${token}
        result=$(curl -s --retry-delay 1 --connect-timeout 10 --max-time 30 $ocr_host --data-urlencode image@${TMPFILE2} -H 'Content-Type:application/x-www-form-urlencoded')
        words_result_num=$(perl -MCpanel::JSON::XS -ne 'print decode_json($_)->{words_result_num}' <<< $result)
        [ "$XDG_SESSION_TYPE" = "x11" ] && [ "$words_result_num" -gt 0 ] && perl -MCpanel::JSON::XS -ne 'my $arrayref=decode_json($_)->{words_result};foreach my $i(@$arrayref){print $i->{words}}' <<< $result | xclip -selection clipboard
        [ "$XDG_SESSION_TYPE" = "wayland" ] && [ "$words_result_num" -gt 0 ] && perl -MCpanel::JSON::XS -ne 'my $arrayref=decode_json($_)->{words_result};foreach my $i(@$arrayref){print $i->{words}}' <<< $result | wl-copy
        kdialog --passivepopup "OCR finished" 7 --title "OCR"
    fi
fi
4赞