#!/bin/sh SCRIPT_NAME="$0" SOURCES="lp101,lp101_alt,jisho,nhk" KANJI="" KANA="" urlencode() { printf '%s' "$1" | od -An -tx1 | tr ' ' '%' | tr '[:lower:]' '[:upper:]' } lp101() { URL="https://assets.languagepod101.com/dictionary/japanese/audiomp3.php?kanji=$KANJI&kana=$KANA" # 52288 is the content-length of the "the audio for this clip is currently # not available. it will be recorded and uploaded shortly. thank you for your # patience" message (404, but server sends 200 anyways) curl -X HEAD -iso - "$URL" | awk '/^Content-length:/ { exit $2 == 52288 }' [ $? -ne 0 ] && return curl -sLo - "$URL" exit 0 } lp101_alt() { HTML="$(curl -s -X POST \ "https://www.japanesepod101.com/learningcenter/reference/dictionary_post" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "post=dictionary_reference&match_type=exact&search_query=$KANJI&vulgar=true" \ )" [ $? -ne 0 ] && return URL="$(echo "$HTML" | pup "audio source attr{src}" | head -n1)" [ -z "$URL" ] && return curl -sLo - "$URL" exit 0 } jisho() { HTML="$(curl -s "https://jisho.org/search/$KANJI")" [ $? -ne 0 ] && return URL="$(echo "$HTML" | pup "audio[id=\"audio_$KANJI:$KANA\"] source attr{src}" | head -n1)" [ -z "$URL" ] && return curl -sLo - "https:$URL" exit 0 } nhk() { BASE_URL="https://sakura-paris.org" HTML="$(curl -s "$BASE_URL/dict/NHK日本語発音アクセント辞典/prefix/$KANJI")" [ $? -ne 0 ] && return URL="$(echo "$HTML" | pup "#$(urlencode $KANJI) audio source[src\$=\".mp3\"] attr{src}" | head -n1)" [ -z "$URL" ] && return curl -sLo - "$BASE_URL$URL" exit 0 } usage() { cat << EOF usage: $SCRIPT_NAME [OPTIONS] > attempt to download a native Japanese recording of word written as KANJI and read as KANA. outputs mp3 to stdout. return value is 0 if OUTPUT was written (clip was found), and 1 if no clip could be found. options: -s set source order (default: $SOURCES) -h show help sources: lp101 JapanesePod101 lp101_alt JapanesePod101 (Alternate) jisho Jisho.org nhk NHK日本語発音アクセント辞典 EOF exit ${1:-0} } while getopts 'hs:' OPT; do case "$OPT" in h) usage ;; s) SOURCES="$OPTARG" ;; \?|*) usage 1 ;; esac done shift $(($OPTIND - 1)) [ $# -ne 2 ] && usage 1 >&2 KANJI="$1" KANA="$2" $(printf '%s;' "$SOURCES" | sed -z 's/[;,\n]/ ; /g') # if none were succesful, delete output file and exit with error rm -f "$OUTPUT" exit 1