Translate Text via Command Line through Tor

I sometimes use a shortcut to quickly translate snippets of highlighted text, via google translate. I hate to admit it, but it does this best. It auto-detects the input language and defaults to english for output, which is what I need in most cases.

There's a few applications for translating text snippets like this, but one got buggy over time, and while I was troubleshooting it I installed another, by which time Google kicked me out because of "suspicious activities".

Enter crow-translate.

A lightweight Qt application that defaults to sitting in your system tray, listening to shortcuts or clicks. The pop-up window looks a lot like Google Translate's page. And although other utilities just got blocked from Google, crow-translate is not affected.

But, what's even better: I can use it on the command line, in which case I do not need to have it in my system tray. The functionality isn't quite there yet, it's either GUI or CLI, meaning: text entered on the command line also gets translated to the command line, there's no way to make crow pop up its window just to show the output in that case.

But a quick wrapper script with xclip and yad fixes that:

sh
#!/bin/sh xclip -o | crow -i | yad --geometry=500x300 --text-info --wrap exit 0

Here's another good thing: crow can be told to use a SOCKS5 proxy. I could use that wrapper script to start tor on demand, translate stuff, then close it again.

First I have to install the tor package (?). I don't want it to interfere with my setup, so I check: It does not automatically start any system daemons. It is possible to start & stop tor on demand, not interfering with my internet habits.

Now configure crow-translate to listen to a SOCKS5 proxy on 127.0.0.1, port 9050 (these are tor's default - one could change that if so desired).

Now expand the wrapper script thusly:

sh
#!/bin/sh datadir="$HOME/.config/tor/crow" torrc="$datadir/torrc" title="Translate to English" if pidof tor; then # use existing tor connection torpid=FALSE else # start tor mkdir -p "$datadir" test -s "$torrc" || printf "DataDirectory \"$datadir\"\nRunAsDaemon 0\n" > "$torrc" tor -f "$torrc" & torpid=$! fi # sed magic to remove all trailing newlines: stackoverflow.com/a/7359879 xclip -o | crow -i | sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' | yad --title="$title" \ --window-icon crow-translate --geometry=750x300 --tail --text-info --wrap --no-buttons # if tor was started for this, close it [ "$torpid" != FALSE ] && kill $torpid exit 0

Explanation:

  • if tor isn't already running, start it.
  • xclip pipes the contents of the clipboard to crow
  • the translation is piped into a suitable yad window.
  • if tor wasn't running yet, kill it again, else leave it be