分享自用百度图片文字识别 Shell 脚本

** 使用前先把 client_id 和 client_secret 改成自己的值。**
百度 OCR API 文档见 https://ai.baidu.com/tech/ocr
脚本中用到了 openSUSE 不知道哪个软件包安装的 perl Cpanel::JSON::XS 模块(仓库中的软件包名为 perl-Cpanel-JSON-XS),解析 JSON 还挺好用。
结合 Meta+Shift+PrintScr 区域截取屏幕图像自动复制到剪贴板,配合 鼠标手势 食用更佳。

(Win) StrokesPlus.net 脚本传送门:https://forum.strokesplus.net/posts/t8306-A-script-to-snip-screen-area-and-use-Baidu-OCR-API-to-recognize-the-text

#!/bin/bash
TMPFILE=$(mktemp)
xclip -selection clipboard -t image/png -o 2>/dev/null > $TMPFILE
if [ -s "$TMPFILE" ]; then
    base64_image=$(base64 -w0 ${TMPFILE})
    client_id="5Pkb*****************CqL"
    client_secret="fRo*************************************kZ"
    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='${base64_image} -H 'Content-Type:application/x-www-form-urlencoded')
        words_result_num=$(perl -MCpanel::JSON::XS -ne 'print decode_json($_)->{words_result_num}' <<< $result)
        [ "$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
    fi
fi
rm $TMPFILE
4赞