Last active
July 22, 2023 18:01
-
-
Save amane-katagiri/629063645b49eddf5627c069756a4df7 to your computer and use it in GitHub Desktop.
A tiny script to print proofreading suggestions for your sentences with OpenAI API.
This file contains hidden or 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/bash -eu | |
# https://blog.jxck.io/entries/2023-03-24/proofreading-via-openai.html | |
PROMPT='バッククォートで囲まれた以下の文章の誤字、脱字、スペルミスを、原文をできるだけ尊重しつつ修正してください。返答は修正後の文章のみを簡潔に返すこと。' | |
QUOTE='```' | |
CONF="$HOME/.correct" | |
CACHE="$HOME/.correct_cache" | |
FORCE='' | |
PRIVACY='' | |
while getopts fpc OPT | |
do | |
case $OPT in | |
f) FORCE="force" | |
;; | |
p) PRIVACY="privacy" | |
;; | |
c) rm -f "$CACHE" | |
echo "Cleared all cache." >&2 | |
exit 0 | |
;; | |
*) echo "Usage: $0 [-fpc]" >&2 | |
echo "-f: overwrite cache, -p: do not cache, -c: clear cache and quit" >&2 | |
exit 1 | |
;; | |
esac | |
done | |
if [ ! -f "$CONF" ] || ! grep -q '^OPENAI_API_KEY=' "$CONF"; then | |
echo "Set your API key: echo 'OPENAI_API_KEY=XXXXX' > '${CONF}'" >&2 | |
exit 1 | |
fi | |
if [ -z "$(type -t jq)" ]; then | |
echo 'install jq' >&2 | |
exit 1 | |
fi | |
source "$CONF" | |
cat - | tr "$(printf '\t')" ' ' | while read -r LINE; do | |
if [ -z "$LINE" ]; then | |
echo | |
continue | |
fi | |
RESULT="" | |
if [ -f "$CACHE" ]; then | |
RESULT=$(tac "$CACHE" | grep -m1 "^${LINE}" | cut -f2 -d"$(printf '\t')") | |
fi | |
if [ -n "$FORCE" ] || [ -z "$RESULT" ]; then | |
RESULT=$(curl -Ss 'https://api.openai.com/v1/chat/completions' \ | |
-H "Content-Type: application/json" \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-d "{ | |
\"model\": \"gpt-3.5-turbo\", | |
\"messages\": [ | |
{\"role\": \"user\", \"content\": \"${PROMPT}\n${QUOTE}\n${LINE}\n${QUOTE}\"} | |
] | |
}" | jq -r .choices[0].message.content | tr -d '\n') | |
if [ -z "$PRIVACY" ]; then | |
printf '%s\t%s\n' "$LINE" "$RESULT" >> "$CACHE" | |
fi | |
fi | |
echo "$RESULT" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment