Skip to content

Instantly share code, notes, and snippets.

@imaami
Created September 12, 2023 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imaami/f92512ac8a04231c40e5610027895e7c to your computer and use it in GitHub Desktop.
Save imaami/f92512ac8a04231c40e5610027895e7c to your computer and use it in GitHub Desktop.
QuizGPT
#!/usr/bin/env bash
#
# IMPORTANT: The HTTP authorization header must be found
# in ~/.openai in full, not just the API key.
#
# Usage: ./quizgpt.sh <windowtitle> <expertrole>
#
# Example:
# ./quizgpt.sh 'Online C quiz' 'a C programmer'
#
# Required Debian packages:
# - curl
# - imagemagick
# - jq
# - scrot
# - tesseract-ocr
# - xdotool
#
run_ocr()
{
{ convert "$1" -crop "$2" -format png - \
| tesseract - - --dpi 300 \
| tr -d $'\x0c'; } 2>/dev/null
}
read_window()
{
local dtop vars img
dtop=$(xdotool get_desktop) &&
vars=$(xdotool search --desktop "$dtop" \
--name "$1" \
getwindowgeometry --shell \
windowactivate --sync) &&
local $vars &&
xdotool mousemove --window "$WINDOW" \
--sync 0 0 &&
img="/tmp/$(date +%s%N).png" &&
scrot -a "$X,$Y,$WIDTH,$HEIGHT" "$img" &&
local -i w=WIDTH/2 h=HEIGHT-200 &&
run_ocr "$img" "${w}x$h+0+100" &&
echo &&
run_ocr "$img" "${w}x$h+$w+100"
}
(return 0 2>/dev/null) ||
{
{ command -v i3-msg &&
i3-msg '[class="Firefox" title="'"${1//\"/\\\"}"'"] resize set 1440 1200'; } >/dev/null 2>&1
prompt=$(read_window "$1") && [[ "$prompt" ]] &&
printf '%s\n----\n\n\e[38;5;195m' "$prompt" &&
jq --rawfile user <(
printf '%s\n' "$prompt"
) -Mnc --rawfile system <(cat << EOF
You are"${2:+ $2}" responding to a questionnaire. Your response must contain at most the verbatim text of the choice you selected. For true or false questions, respond with a single word.
EOF
) '{
"model": "gpt-4",
"stream": false,
"messages": [
{"role":"system","content":$system},
{"role":"user","content":$user}
]
}' \
| curl https://api.openai.com/v1/chat/completions -s -S -d @- \
-H @"$HOME/.openai" -H Content-Type:\ application/json \
| jq -r '.choices[0].message.content'; printf '\e[m\n'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment