audiogame-manager/speech/clipboard_translator.sh

44 lines
1.5 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
cleanup() {
sort -uo "$dictionaryFile" "$dictionaryFile"
}
trap cleanup EXIT
# Clear the clipboard so you don't accidently send personal info to the translator.
echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null
export dictionaryFile="${XDG_CONFIG_HOME:-$HOME/.config}/storm-games/audiogame-manager/translations.txt"
if [[ ! -r "$dictionaryFile" ]]; then
touch "$dictionaryFile"
fi
while : ; do
newText=""
translatedText=""
newText="$(xclip -d "${DISPLAY:-:0}" -selection clipboard -o 2> /dev/null)"
sleep 0.01
if [[ "${#newText}" -lt 1 ]]; then
continue
fi
if [[ "${newText}" =~ ^[0-9A-Za-z[:space:][:punct:]]+$ ]]; then
spd-say "$newText"
echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null
continue
fi
export newText
translatedText="$(awk -v originalText="${newText})==:" 'BEGIN { exitCode = 1; FS = "\\)==:\\[" }
$0~originalText { print $2; exitCode = 0; exit}
END { exit exitCode }' "$dictionaryFile")"
if [[ "${#translatedText}" -ge 1 ]]; then
spd-say "$translatedText"
echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null
continue
fi
translatedText="$(trans -b -- "$newText")"
if ! [[ "${newText}" =~ ^[0-9[:punct:]]+$ ]]; then
echo "${newText})==:[${translatedText}" >> "$dictionaryFile"
fi
spd-say "$translatedText"
echo "" | xclip -d "${DISPLAY:-:0}" -selection clipboard 2> /dev/null
done