Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active January 11, 2022 11:51
Show Gist options
  • Save kou1okada/8d14b451abcc25c7183cc7a70c13a686 to your computer and use it in GitHub Desktop.
Save kou1okada/8d14b451abcc25c7183cc7a70c13a686 to your computer and use it in GitHub Desktop.
wpra.sh - Wikipedia REST API utility
#!/usr/bin/env bash
. hhs.bash 0.2.0
function init_wpra_math ()
{
: ${PREVIEW_METHOD:=sixel}
}
function optparse_wpra_math ()
{
case "$1" in
-s|--seesaawiki) #
# For seesaawiki. Set twice for embeding raw eqn.
nparams 0
let OPT_SEESAAWIKI=${OPT_SEESAAWIKI:-0}+1
;;
-p|--preview) # {display|sixel|xdg-open}
# Set preview method. (default: sixel)
nparams 1
optset PREVIEW_METHOD "$2"
;;
*) return 1 ;;
esac
}
function wpra_math () # [<equation>]
{
local rest_base="https://wikimedia.org/api/rest_v1/media/math"
local rest_check="${rest_base}/check"
local rest_render="${rest_base}/render"
local hash
local eqn="$1"
local eqn_pe="$(perl -MURI::Escape -e 'print uri_escape($ARGV[0])' "$eqn")"
local previewer
local preview_format=svg
read hash < <(
wget "${rest_check}/tex" --post-data="q={\displaystyle ${eqn_pe}}" -qSO/dev/null \
|& grep -E "^ *x-resource-location: " \
| awk '$0=$2'
)
[ "$hash" ] || {
error "Failed to get x-resource-location: ${1}"
exit 1
}
case "${OPT_PREVIEW_METHOD:-sixel}" in
display) previewer=(display);preview_format=png;;&
sixel) previewer=(convert - -alpha off -negate sixel:-);;&
xdg-open) previewer=(xdg-open);;&
xdg-open)
"${previewer[@]}" "${rest_render}/${preview_format}/${hash}";;
display|sixel)
wget -qO- "${rest_render}/${preview_format}/${hash}" | "${previewer[@]}";;
*) error "Unknown preview method: ${OPT_PREVIEW_METHOD}"; abort;;
esac
case "${OPT_SEESAAWIKI:-0}" in
0) echo "${rest_render}/svg/${hash}";;
1) echo "&ref(${rest_render}/svg/${hash}#.png,no_link)";;
*) echo "&ref(${rest_render}/svg/${hash}#.png,no_link){\$${eqn}\$}";;
esac
}
has_subcommand_wpra=1
function wpra () # <subcommand>
{
:
}
invoke_command "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment