dotfiles/.config/zsh/functions/translate

33 lines
1.0 KiB
Bash
Executable File

#!/usr/bin/env zsh
# Translate text with LibreTranslate
setopt LOCAL_OPTIONS ERR_RETURN NO_UNSET PIPE_FAIL
zmodload zsh/zutil
local -a o_help=()
local -a o_domain=()
local -a o_from=()
local -a o_to=()
zparseopts -D -K -- h=o_help -help=o_help -domain:=o_domain \
-from:=o_from -to:=o_to
if [[ ${#o_help} -ne 0 ]]; then
print "usage: ${0} [-h|--help] [--domain <DOMAIN>]" \
"[--from <LANG>] [--to <LANG>] TEXT …"
print "If no TEXT is supplied, input will be taken from STDIN"
return
fi
local domain="libretranslate.de"
local from="en"
local to="de"
[[ ${#o_domain} -eq 2 ]] && domain=${o_domain[2]}
[[ ${#o_from} -eq 2 ]] && from=${o_from[2]}
[[ ${#o_to} -eq 2 ]] && to=${o_to[2]}
local text="${@}"
[[ ! -v 1 ]] && text=$(cat -)
text=${text//$'\n'/'\n'}
curl --silent -X POST \
--header 'Content-Type: application/json' \
--data '{"q": "'${text}'", "source": "'${from}'", "target": "'${to}'", "format": "text"}' \
https://${domain}/translate | jq --raw-output .translatedText