Greetings habrazhitel!
Quite a long time ago there was a need for a multilingual online translator with a closed browser.
No, I don’t disdain to use the dictionary in “especially difficult” cases, but sometimes I have to read a rather big text, and not all words I know how the context is lost.
At the beginning there was a translate-shell ...
The Translate-shell thing is quite convenient, especially if you write, say, in Vi / vim . Switch to the next console and translate.
The keys are simple and easy to remember.
$ trans -b -e yandex -t en " ." Simple keys. $ echo -e "\n .\n"|trans -b -e yandex -t en With redirection.
But this, as usual, was not enough. I wanted graphics.
Working in SublimeText and Zeal is somewhat more convenient than a bare console.
Hmm ... Thought, thought, and decided to fasten the translator to a hot key.
The choice fell on gxmessage . Zenity did not suit me, I don’t remember why.
The code was written:
#!/bin/bash # Name script trans.sh TEXT=$(xclip -selection primary -o) TRANS=$(trans -e yandex -hl en -tl ru -b "$TEXT") if [ "$TRANS" ]; then gxmessage -geometry 1000x800 -bg "#aaaaaa" -title "Translate" -wrap -center -font "Menlo Regular 24" "$TRANS" else gxmessage -geometry 1000x800 -bg "#aaaaaa" -title "Translate" -wrap -center -font "Menlo Regular 24" " " fi
And assigned to Ctrl + 1. In IceWm, this is easy. Edit $ HOME / .icewm / keys
key "Ctrl+1" $HOME/progs/trans.sh
It suited me for a while. To "control + 1" from English, "control + 2" to English. Good...
But then the translate-shell started to fail.
I don’t know what happened to the developers, but it really upset me.
I decided it’s time, I haven’t written in python for a long time.
A short Google search led me to Yandex.API , Python, and GTK + 3 in the form of a gi module.
Why gi , because you usually wrote in PyQt5 ? It works much faster on my car. The machine is not new, memory, too (by modern standards) is not so hot.
The GTK + 3 module for python was new to me. I spent a whole evening sorting out the syntax on sites once , twice, and three .
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- import sys import requests import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk from gi.repository import Pango import warnings warnings.filterwarnings("ignore") import os CURRDIR = os.path.dirname(os.path.abspath(__file__)) ICON = os.path.join(CURRDIR, 'yandex-48.xpm') headers = { 'User-Agent': ('Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 ' 'Firefox/14.0.1'), 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'DNT': '1' } URLDETECT = "https://translate.yandex.net/api/v1.5/tr.json/detect" URLTRANS = "https://translate.yandex.net/api/v1.5/tr.json/translate" KEY = "you-API-key" def clip(): clipboard = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY) clip = clipboard.wait_for_text() return clip def detect(): params = {"key": KEY, "text": clip(), "lang": 'ru'} respdetect = requests.get(URLDETECT, params=params, headers=headers).json() if 'lang' in respdetect.keys(): respdetect = respdetect else: respdetect = {'code': 200, 'lang': 'en'} langtetect = respdetect["lang"] if langtetect != 'ru': langout = langtetect + '-ru' else: langout = 'ru-en' return langout def translate(): params = {"key": KEY, "text": clip(), "lang": detect()} response = requests.get(URLTRANS, params=params, headers=headers).json() if 'text' in response.keys(): response = response else: response = {'code': 200, 'lang': 'en-ru', 'text': ['the buffer is empty'] } output = ''.join(response["text"]) return output class TextViewWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title=f"Yandex Translator {detect()}") self.set_default_size(1000, 350) self.set_position(Gtk.WindowPosition.CENTER_ALWAYS) self.grid = Gtk.Grid() self.add(self.grid) self.create_textview() self.create_toolbar() self.key_Esc = Gdk.keyval_from_name("Escape") self.connect("key-press-event", self._key) def create_toolbar(self): toolbar = Gtk.Toolbar() self.grid.attach(toolbar, 1, 1, 1, 1) new_button = Gtk.ToolButton.new_from_stock(Gtk.STOCK_CLOSE) new_button.set_is_important(True) toolbar.insert(new_button, 0) new_button.connect("clicked", self.on_button_clicked, self.tag_bold) new_button.show() def on_button_clicked(self, widget, tag): Gtk.main_quit() def create_textview(self): scrolledwindow = Gtk.ScrolledWindow() scrolledwindow.set_hexpand(True) scrolledwindow.set_vexpand(True) self.grid.attach(scrolledwindow, 0, 0, 2, 1) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textbuffer.set_text(f"{translate()}") scrolledwindow.add(self.textview) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) self.tag_bold = self.textbuffer.create_tag("bold", weight=Pango.Weight.BOLD) self.textview.modify_font(Pango.FontDescription('Menlo Regular 24')) def _key(self, widg, event): if event.keyval == self.key_Esc: Gtk.main_quit() win = TextViewWindow() win.connect("destroy", Gtk.main_quit) win.set_icon_from_file(ICON) win.show_all() Gtk.main()
As a result, I have an auto-translator on a hot key.
Thank you all for your attention.
The project is completely on github .
PS: I will be glad to criticize the code.