Created
October 25, 2024 00:13
-
-
Save rkmax/9a48fda621c85700fc4743a0b71f36b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/zsh | |
# | |
# Translate clipboard text using OpenAI's GPT-4 model. | |
# Requires OpenAI API key. | |
# Requires xclip (X11) or wl-clipboard (Wayland) to access clipboard. | |
# Requires jq, curl, sed. | |
default_system="Translate any user input into English, informal and concise." | |
get_content_from_clipboard() { | |
if [[ -v WAYLAND_DISPLAY ]]; then | |
if [[ ! $+commands[wl-paste] ]]; then | |
notify "wl-clipboard must be installed." | |
return 1 | |
fi | |
wl-paste | |
elif [[ -v DISPLAY ]]; then | |
if [[ ! $+commands[xclip] ]]; then | |
notify "xclip must be installed." | |
return 1 | |
fi | |
xclip -o -selection clipboard | |
else | |
notify "No clipboard tool found." | |
return 1 | |
fi | |
} | |
set_content_to_clipboard() { | |
if [[ -v WAYLAND_DISPLAY ]]; then | |
if [[ ! $+commands[wl-copy] ]]; then | |
notify "wl-clipboard must be installed." | |
return 1 | |
fi | |
wl-copy | |
elif [[ -v DISPLAY ]]; then | |
if [[ ! $+commands[xclip] ]]; then | |
notify "xclip must be installed." | |
return 1 | |
fi | |
xclip -selection clipboard | |
else | |
notify "No clipboard tool found." | |
return 1 | |
fi | |
} | |
notify() { | |
local message=$1 | |
local timeout=${2:-2000} | |
if [[ ! -v PS1 ]] || [[ ! $+commands[notify-send] ]]; then | |
echo $message | |
return | |
fi | |
notify-send -t $timeout "Translate" "$1" | |
} | |
gpt() { | |
command=( | |
curl | |
jq | |
sed | |
) | |
for cmd in $command; do | |
if [[ ! $+commands[$cmd] ]]; then | |
notify "$cmd must be installed." | |
return 1 | |
fi | |
done | |
if [[ ! -v OPENAI_API_KEY ]]; then | |
notify "Must set OPENAI_API_KEY to your API key" | |
return 1 | |
fi | |
local escaped_text=$(echo "$*" | sed ':a;N;$!ba;s/\n/\\n/g') | |
curl https://api.openai.com/v1/chat/completions -s \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d '{ | |
"model": "gpt-4o-mini", | |
"messages": [{"role": "system", "content": "'$default_system'"}, {"role": "user", "content": "'"$escaped_text"'"}] | |
}' | jq -r '.choices[0].message.content' | |
} | |
notify "Translating clipboard text..." | |
text_from_wayland_clipboard=$(get_content_from_clipboard) | |
if [[ -z $text_from_wayland_clipboard ]]; then | |
notify "No text found in clipboard." | |
exit 1 | |
fi | |
gpt "$text_from_wayland_clipboard" | set_content_to_clipboard | |
if [[ $? -ne 0 ]]; then | |
notify "Error translating text." | |
exit 1 | |
fi | |
notify "Translation copied to clipboard." 5000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment