qutebrowser: Slightly refactor translate & codegrab

Code grabbing has been slightly refactored to always check for the
existence of the qutebrowser fifo before sending anything.

Translate has been fixed up a little to use lingva for selection
translations, only falling back to google translate for complete page
translations since I do not think any other services support this for
now.
This commit is contained in:
Marty Oehme 2023-08-08 17:12:53 +02:00
parent f7304b8941
commit ae58c1c4ef
Signed by: Marty
GPG Key ID: EDBF2ED917B2EF6A
2 changed files with 11 additions and 10 deletions

View File

@ -14,16 +14,17 @@ else:
PYPERCLIP = True
def parse_text_content(element):
def parse_text_content(element) -> str:
root = ET.fromstring(element)
text = ET.tostring(root, encoding="unicode", method="text")
text = html.unescape(text)
return text
def send_command_to_qute(command):
with open(os.environ.get("QUTE_FIFO"), "w") as f:
f.write(command)
def send_command_to_qute(command) -> None:
if fifo := os.environ.get("QUTE_FIFO"):
with open(fifo, "w") as f:
f.write(command)
def main():
@ -32,7 +33,7 @@ def main():
# https://github.com/qutebrowser/qutebrowser/blob/master/doc/userscripts.asciidoc
element = os.environ.get("QUTE_SELECTED_HTML")
code_text = parse_text_content(element)
if PYPERCLIP:
if pyperclip and PYPERCLIP:
pyperclip.copy(code_text)
send_command_to_qute(
"message-info 'copied to clipboard: {info}{suffix}'".format(

View File

@ -3,6 +3,7 @@
# Translate the page, or if `--text` argument is given the current selection, with google translate.
#
# Adapted code from https://github.com/AckslD/Qute-Translate, with much gratitude.
PAGE="https://lingva.garudalinux.org/SOURCELANGUAGE/TARGETLANGUAGE/TRANSLATETEXT"
while [ $# -gt 0 ]; do
case $1 in
@ -38,14 +39,13 @@ fi
if [ "$QUTE_TRANS_URL" = "false" ]; then
# Translate selected text
PAGE="https://translate.google.com/#view=home&op=translate&"
CONT_KEY="text"
CONTENT=$QUTE_SELECTED_TEXT
PAGE=$(echo "$PAGE" | sed -e "s/SOURCELANGUAGE/$QUTE_TRANS_SOURCE/" -e "s/TARGETLANGUAGE/$QUTE_TRANS_TARGET/" -e "s/TRANSLATETEXT/$QUTE_SELECTED_TEXT/")
echo "open -t ${PAGE}" >>"$QUTE_FIFO"
else
# Default translate URL
PAGE="https://translate.google.com/translate?"
CONT_KEY="u"
CONTENT=$QUTE_URL
CONTENT="$QUTE_URL"
echo "open -t ${PAGE}sl=${QUTE_TRANS_SOURCE}&tl=${QUTE_TRANS_TARGET}&${CONT_KEY}=\"${CONTENT}\"" >>"$QUTE_FIFO"
fi
echo "open -t ${PAGE}sl=$QUTE_TRANS_SOURCE&tl=$QUTE_TRANS_TARGET&$CONT_KEY=$CONTENT" >>"$QUTE_FIFO"