This repository has been archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 48f4fb5
Showing
6 changed files
with
214 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
__pycache__ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
import datetime | ||
import os | ||
|
||
import PySimpleGUI as sg | ||
|
||
from Sirius_IT_Round.task import Task | ||
from Sirius_IT_Round.translate import Translator | ||
from Sirius_IT_Round.windows_clipboard import to_clipboard, get_clipboard | ||
|
||
|
||
class Application: | ||
def __init__(self): | ||
self.layout = [ | ||
[ | ||
sg.Submit(button_text='Авто', key="mode=AUTO", disabled=True), | ||
sg.Submit(button_text='Русский -> Английский', key="mode=RU_EN"), | ||
sg.Submit(button_text='Английский -> Русский', key="mode=EN_RU") | ||
], | ||
[ | ||
sg.Multiline(size=(150, 20), key='Input') | ||
], | ||
[ | ||
sg.Submit(button_text='Вставить из буфера', key="Paste"), | ||
sg.Submit(button_text='Очистить', key="Clear") | ||
], | ||
[ | ||
sg.Multiline(size=(150, 20), key='Output', disabled=True) | ||
], | ||
[ | ||
sg.Submit(button_text='Скопировать', key="Copy") | ||
], | ||
] | ||
self.window = sg.Window('UniversalTranslator', self.layout, icon=os.path.join('data', 'icon.ico'), | ||
text_justification='c', element_justification='c') | ||
self.window.finalize() | ||
|
||
self.mode = 'AUTO' | ||
self.last_state = '' | ||
self.last_update = datetime.datetime.now() | ||
self.translated = True | ||
self.translator = Translator() | ||
|
||
self.task = Task(self.work, ()) | ||
self.task.start_runner() | ||
|
||
self.run_event_loop() | ||
|
||
def run_event_loop(self): | ||
while True: | ||
event, values = self.window.read() | ||
if event is None: | ||
break | ||
elif event.startswith('mode='): | ||
self.mode = event.split('mode=')[1] | ||
for btn in self.layout[0]: | ||
if event == btn.Key: | ||
self.window[btn.Key].update(disabled=True) | ||
else: | ||
self.window[btn.Key].update(disabled=False) | ||
elif event == 'Clear': | ||
self.window["Input"].update(value='') | ||
self.window["Output"].update(value='') | ||
elif event == 'Paste': | ||
self.window["Input"].update(value=get_clipboard()) | ||
elif event == 'Copy': | ||
to_clipboard(self.window["Output"].get()) | ||
os._exit(0) | ||
|
||
def work(self): | ||
input_text = self.window["Input"].get().strip() | ||
check_state = input_text + self.mode | ||
if input_text.strip() == '': | ||
self.last_state = '' | ||
if self.window["Output"].get().strip() != '': | ||
self.window["Output"].update(value='') | ||
if self.translator.state.strip() != '': | ||
self.translator.state = '' | ||
return | ||
if check_state != self.last_state: | ||
self.last_state = check_state | ||
self.last_update = datetime.datetime.now() | ||
self.translated = False | ||
if not self.translated and (datetime.datetime.now() - self.last_update).total_seconds() > 0.5: | ||
self.translator.translate(self.mode, input_text) | ||
self.translated = True | ||
if self.window["Output"].get().strip() != self.translator.state.strip(): | ||
self.window["Output"].update(value=self.translator.state) | ||
|
||
|
||
app = Application() |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import traceback | ||
from threading import Thread | ||
|
||
|
||
class Task: | ||
def __init__(self, func, args): | ||
self.func = func | ||
self.args = args | ||
self.runner = None | ||
self.status = 'Stopped' | ||
|
||
def start_runner(self): | ||
if self.runner is not None: | ||
return | ||
self.status = 'Running' | ||
self.runner = Thread(target=self.thread, args=()) | ||
self.runner.start() | ||
|
||
def thread(self): | ||
while True: | ||
if self.status == 'Wait stop': | ||
self.status = 'Stopped' | ||
break | ||
try: | ||
self.func(*self.args) | ||
except BaseException as e: | ||
traceback.print_tb(e.__traceback__) | ||
|
||
def stop_runner(self): | ||
if self.runner is None: | ||
return | ||
self.status = 'Wait stop' | ||
while self.status != 'Stopped': | ||
pass | ||
self.runner = None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import json | ||
from threading import Thread | ||
|
||
import requests | ||
|
||
url = "https://translated-mymemory---translation-memory.p.rapidapi.com/api/get" | ||
|
||
headers = { | ||
'x-rapidapi-key': "95f7464936mshaa12257cee57890p12e68fjsnd52d3eb4b848", | ||
'x-rapidapi-host': "translated-mymemory---translation-memory.p.rapidapi.com" | ||
} | ||
|
||
|
||
class Language: | ||
ENGLISH = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | ||
RUSSIAN = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' | ||
|
||
|
||
class Mode: | ||
EN_RU = 'EN_RU' | ||
RU_EN = 'RU_EN' | ||
AUTO = 'AUTO' | ||
|
||
|
||
def detect_language(text): | ||
ru, en = 0, 0 | ||
for item in text: | ||
if item in Language.ENGLISH: | ||
en += 1 | ||
elif item in Language.RUSSIAN: | ||
ru += 1 | ||
if ru + en > 20: | ||
break | ||
return Mode.EN_RU if en > ru else Mode.RU_EN | ||
|
||
|
||
def translate_chunk(mode, text): | ||
if mode == Mode.RU_EN: | ||
querystring = {"q": text, "langpair": "ru|en", "de": "[email protected]", "onlyprivate": "0", "mt": "1"} | ||
query_res = requests.request("GET", url, headers=headers, params=querystring).text | ||
return json.loads(query_res)['responseData']['translatedText'] | ||
if mode == Mode.EN_RU: | ||
querystring = {"q": text, "langpair": "en|ru", "de": "[email protected]", "onlyprivate": "0", "mt": "1"} | ||
query_res = requests.request("GET", url, headers=headers, params=querystring).text | ||
return json.loads(query_res)['responseData']['translatedText'] | ||
|
||
|
||
class Translator: | ||
def __init__(self): | ||
self.state = '' | ||
|
||
def translate(self, mode, text): | ||
Thread(target=self.translate_threaded, args=(mode, text)).start() | ||
|
||
def translate_threaded(self, mode, text): | ||
if mode == Mode.AUTO: | ||
mode = detect_language(text) | ||
def_text = 'Идет перевод...' if mode == Mode.RU_EN else 'Translation in progress...' | ||
self.state = def_text | ||
paragraphs = text.split('\n') | ||
for paragraph in paragraphs: | ||
paragraph_res = [] | ||
chunks = [] | ||
for word in paragraph.split(): | ||
if len(chunks) == 0 or len(chunks[-1]) > 900: | ||
chunks.append(word) | ||
else: | ||
chunks[-1] += ' ' + word | ||
for chunk in chunks: | ||
paragraph_res.append(translate_chunk(mode, chunk)) | ||
if self.state == def_text: | ||
self.state = '' | ||
self.state += ' '.join(paragraph_res) + '\n' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import win32clipboard | ||
|
||
|
||
def to_clipboard(text): | ||
win32clipboard.OpenClipboard() | ||
win32clipboard.EmptyClipboard() | ||
win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT) | ||
win32clipboard.CloseClipboard() | ||
|
||
|
||
def get_clipboard(): | ||
win32clipboard.OpenClipboard() | ||
data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT) | ||
win32clipboard.CloseClipboard() | ||
return data |