Example #1
0
    def __init__(self):

        locale.setlocale(locale.LC_ALL, '')
        self.translator = Translater()
        self.translator.set_key(YANDEX_API_KEY)
        self.mode = 'EN-->RU'
        self.default_markup = rkm([['Exit']])
Example #2
0
 def in_latin(self, text):
     tr = T.Translater()
     tr.set_key(
         'trnsl.1.1.20190614T100357Z.bc5cd3d6c2ce136a.74da88f3d7becf09a42fdedd209fdce78f9c7599'
     )
     tr.set_text(text)
     tr.detect_lang()
     tr.set_to_lang('en')
     return tr.translate()
Example #3
0
def yandex_translate(utterance, source, target, api_key):
    """
    Translate a sentence
    :param utterance: sentence to translate
    :param source: source language
    :param target: target language
    :param api_key: Yandex Translate API token https://translate.yandex.com/developers/keys
    :return Translated utterance 
    """

    tr = yandex_trans.Translater()
    tr.set_key(api_key)
    tr.set_from_lang(source)
    tr.set_to_lang(target)
    tr.set_text(utterance)  #text_to_translate
    response = tr.translate()
    return normalize_text(response)
Example #4
0
from keras.layers import Dense
from keras.layers import Flatten
from keras.layers import Activation
from keras.layers import LSTM
from keras.layers import Dropout
from keras.callbacks import TensorBoard
# from keras import regularizers

# Init random number generator
from tensorflow import set_random_seed

## Translation

# Yandex
from yandex import Translater
tr = Translater.Translater()
tr.set_key('trnsl.1.1.20181209T115802Z.b9993365fecdcbe9.c526178c0a9e8765e4e31fb86c03cd55ff3e646d') # Api key found on https://translate.yandex.com/developers/keys

# Google
from google.cloud import translate
# Import Google translate API
# Set Google credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join(basefolder, "data","TuSCI-594003380750.json")
# Instantiates a client
translate_client = translate.Client()

# Get parameters
## Video
try:
    video_file = sys.argv[1]
except:
Example #5
0
class Translator(Activity):
    def __init__(self):

        locale.setlocale(locale.LC_ALL, '')
        self.translator = Translater()
        self.translator.set_key(YANDEX_API_KEY)
        self.mode = 'EN-->RU'
        self.default_markup = rkm([['Exit']])

    def first_query(self, bot, update):
        self.__init__()
        self.mode = rkm([['EN-->RU'], ['RU-->EN']], one_time_keyboard=True)
        bot.sendMessage(
            chat_id=update.message.chat.id,
            text="Select languages:",
            reply_markup=self.mode
        )

    def process(self, query, bot, update):

        result = ""

        if query == 'RU-->EN':
            self.translator.set_from_lang('ru')
            self.translator.set_to_lang('en')
            self.locale = "ru-RU"
        elif query == 'EN-->RU':
            self.translator.set_from_lang('en')
            self.translator.set_to_lang('ru')
            self.locale = "en-US"
        else:
            ans = update2text(update, self.locale)
            if ans != None:
                self.translator.set_text(ans)
                result = self.translator.translate()

            bot.sendMessage(
                chat_id=update.message.chat.id,
                text=result,
                reply_markup=self.default_markup
            )

        if len(result) == 0:
            result = "What? try again, keep calm speak slowly and clearly."
Example #6
0
def transl(file):
    tr = Translater()
    tr.set_key(
        'trnsl.1.1.20181027T064233Z.3eb896622966c6cb.3685096a854ebdc502d7d01bdecdf7d490e88f9d'
    )  # Api key found on https://translate.yandex.com/developers/keys
    tr.set_text(file)
    tr.set_from_lang('en')
    tr.set_to_lang('hi')
    l = tr.translate()
    print(l)
    talkToMe(l)
def translate():
    """
    translate Russian okpd category descriptions to English
    """
    f = codecs.open("okpd2.csv", "r", "cp1251")
    reader = csv.reader(f, delimiter=";")
    okpd_dict = {l[3]: l[1] for l in reader}

    names = {okpd_dict[k] for k in okpd_dict}

    names_eng = dict()
    names_eng_yandex = dict()

    try:
        names_eng = pickle.load(open("okpd_eng.pcl", 'rb'))
    except Exception as ex:
        print(ex)
    try:
        names_eng_yandex = pickle.load(open("okpd_eng_yandex.pcl", 'rb'))
    except Exception as ex:
        print(ex)

    translator = Translator()
    yandex_translator = Translater()
    yandex_translator.set_from_lang('ru')
    yandex_translator.set_to_lang('en')
    yandex_translator.set_key('trnsl.1.1.20170307T175252Z.243ee3f0dfd2721a.'
                              '7af76b883f12f9f4fc2d861bab7d733112aeb66d')

    texts = []
    total_len = 0

    for n_i, n in enumerate(names):
        if n in names_eng or n in names_eng_yandex:
            continue
        else:
            yandex_translator.set_text(n)
            translation = yandex_translator.translate()
            names_eng_yandex[n] = translation
            print(n, translation)
            # time.sleep(1)

    for n_i, n in enumerate(names):
        if n in names_eng:
            continue
        else:
            if total_len > 14000:
                try:
                    translations = translator.translate(texts)
                    time.sleep(2)
                    for t_i, t in texts:
                        names_eng[t] = translations[t_i]
                        print(len(names_eng), len(names))
                except Exception as ex:
                    pickle.dump(names_eng, open("okpd_eng.pcl", 'wb'))
                    translator = Translator()
                    time.sleep(1)
                texts = [n]
                total_len = len(n)
            else:
                texts.append(n)
                total_len += len(n)

    pickle.dump(names_eng, open("okpd_eng.pcl", 'wb'))
    pickle.dump(names_eng_yandex, open("okpd_eng_yandex.pcl", 'wb'))
Example #8
0
def test():
    os.chmod("/home/ubuntu/flaskapp/Img1.png", 0777)
    uid = pwd.getpwnam("nobody").pw_uid
    gid = grp.getgrnam("nogroup").gr_gid
    #os.chown("/home/ubuntu/flaskapp/static/Img1.png", uid, gid)
    im = Image.open("/home/ubuntu/flaskapp/Img1.png")
    im.save("/home/ubuntu/flaskapp/Img1.png", dpi=(300, 300))
    ref = cv2.imread("/home/ubuntu/flaskapp/Img1.png")
    height, width, channels = ref.shape
    max_height = 1000
    max_width = 700
    scaling_factor = 1
    print(height, width)
    # only shrink if img is bigger than required
    if max_height < height or max_width < width:
        # get scaling factor
        scaling_factor = max_height / float(height)
        if max_width / float(width) < scaling_factor:
            scaling_factor = max_width / float(width)
    # resize image
    ref = cv2.resize(ref,
                     None,
                     fx=scaling_factor,
                     fy=scaling_factor,
                     interpolation=cv2.INTER_AREA)
    ref = cv2.resize(ref, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_AREA)
    morph = ref.copy()

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
    morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
    morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))

    gradient_image = cv2.morphologyEx(morph, cv2.MORPH_GRADIENT, kernel)

    image_channels = np.split(np.asarray(gradient_image), 3, axis=2)
    channel_height, channel_width, _ = image_channels[0].shape

    for i in range(0, 3):
        _, image_channels[i] = cv2.threshold(
            ~image_channels[i], 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY)
        image_channels[i] = np.reshape(image_channels[i],
                                       newshape=(channel_height, channel_width,
                                                 1))

    image_channels = np.concatenate(
        (image_channels[0], image_channels[1], image_channels[2]), axis=2)

    ref = image_channels

    ref = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
    ref = cv2.equalizeHist(ref)
    # create a CLAHE object (Arguments are optional).
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    ref = clahe.apply(ref)
    #cv2.imshow("Image", ref)
    os.environ[
        "TESSDATA_PREFIX"] = "/usr/share/tesseract-ocr/tessdata/tesseract-ocr/tessdata"

    ref = Image.fromarray(ref)

    text = pytesseract.image_to_string(ref)

    print('Orginal Text Extracted from Image:', text)

    if not text:
        text = "No Text Available"
    tr = Translater()
    tr.set_key(
        'trnsl.1.1.20180215T092213Z.aa1fc0e95288ebd7.dab36b649144ed25babf6247bcabd9885b5bb63f'
    )
    tr.set_from_lang('en')
    tr.set_to_lang('hi')
    tr.set_text(text)
    TransText = tr.translate()
    #TransText="Not Available"
    print('Translated Text', TransText)
    return text, TransText
Example #9
0
def main():
    from yandex import Translater
    tr = Translater()
    tr.set_key(
        'trnsl.1.1.20180513T075008Z.0977a7606fc0921a.5fa98626b8990514e07e29aa73211e45f42e934f'
    )
    tr.set_from_lang('en')
    tr.set_to_lang('fa')
    #tr.set_text('hello,this is me you looking for ;)')
    tr.set_text(input("enter your word!\n"))
    print(tr.translate())
Example #10
0
def talk_to_me(update, context):
    user_text = f'Привет {update.message.from_user.first_name} (@{update.message.from_user.username})! ' \
                f'Ты написал "{update.message.text}".'
    comm_text = 'Добавьте "/" перед названием команды'

    dict_words = {
        'Тест': [update.message.reply_text, user_text],
        'тест': [update.message.reply_text, user_text],
        'start': [update.message.reply_text, comm_text],
        'help': [update.message.reply_text, comm_text],
        'resp': [update.message.reply_text, comm_text]
    }
    if update.message.text in dict_words:
        dict_words.get(update.message.text)[0](dict_words.get(
            update.message.text)[1])
    else:
        request = apiai.ApiAI(
            str(DF_TOKEN)).text_request()  # Токен для авторизации в Dialogflow
        request.lang = 'ru'  # Указвыаем язык запроса
        request.session_id = 'BotNameST'  # Id сессии диалога
        text = update.message.text
        if context.bot.name in text:
            request.query = text
            responseJson = json.loads(
                request.getresponse().read().decode('utf-8'))
            print(responseJson)
            response = responseJson.get('result').get('parameters').get(
                'address').get('city')
            data_time = responseJson.get('result').get('parameters').get(
                'date-time')
            print(response)
            print(data_time)

            if response:  # Если есть ответ выводим
                owm = OWM(str(OWM_TOKEN))
                owm.set_language(language='ru')
                tr = Translater.Translater()
                tr.set_key(str(YAND_TOKEN))
                tr.set_text(response)
                tr.set_from_lang('ru')
                tr.set_to_lang('en')
                t_city = tr.translate()
                fc = owm.three_hours_forecast(t_city)
                print(fc)

                print(t_city)
                obs = owm.weather_at_place(t_city)
                print(owm.weather_at_place(t_city))
                w = obs.get_weather()
                t = w.get_temperature(unit='celsius')
                context.bot.send_message(chat_id=update.message.chat.id,
                                         text=response)
                context.bot.send_message(
                    chat_id=update.message.chat.id,
                    text=f'Сегодня ожидается: {w.get_detailed_status()}.\n'
                    f'Диапазон температу: от {t["temp_min"]}°С до '
                    f'{t["temp_max"]}°С. Текущая температура: '
                    f'{t["temp_max"]}°С\n')
            else:  # Если нет говорим что запрос не понятен
                context.bot.send_message(chat_id=update.message.chat.id,
                                         text='Не совсем понял Ваш запрос')
Example #11
0
#! /usr/bin/python3

from yandex import Translater  # install Translater from https://pypi.org/project/yandex-translater/

import os

tr = Translater()

tr.set_default_ui('ru')
tr.set_key(
    'trnsl.1.1.20180blah-BLAH-blah'
)  # get your own free key here https://translate.yandex.com/developers/keys (press Create key)

tr.set_from_lang('en')
tr.set_to_lang('ru')

files = "/path/to/folder/with/texts/to/be/translated/"  # provide a real path to the input texts
fh = [f for f in os.listdir(files) if f.endswith('.split')]

for f in fh:
    print(f)
    lines_in = open(files + f.strip(), 'r').readlines()
    file_out = open(
        files + f + '.yt', 'w'
    )  # the output texts with a different extension are stored to the input folder
    for line in lines_in:
        # try:
        tr.set_text(line)
        trans = tr.translate()
        print(trans)
        file_out.write(trans)
Example #12
0
from config import YANDEX_TOKEN
from yandex import Translater

tr = Translater()
tr.set_key(YANDEX_TOKEN)


def do_translate(in_text, out_lang, in_lang=""):
    print(in_text, out_lang, in_lang)
    tr.set_text(in_text)
    if in_lang is "":
        tr.set_from_lang(tr.detect_lang())
    else:
        tr.set_from_lang(in_lang)
    tr.set_to_lang(out_lang)
    return tr.translate()


def get_valid_langs():
    return tr.valid_lang
Example #13
0
def multi_translate(utterance,api_key,pivot_level):
  """
  Translate sentence
  :param utterance: sentence to translate
  :param api_key: Yandex Translate API token https://translate.yandex.com/developers/keys
  :param pivot_level: integer that indicate the pivot language level, single-pivot or multi-pivot range,1 =single-pivot, 2=double-pivot, 0=apply single and double
  :return list of utterance translations
  """

  tr = yandex_translate.Translater() # load yandex translator
  tr.set_key(api_key) # set the api token

  response = set()
  text = utterance
  if pivot_level == 0 or pivot_level == 1:
    tmp = translate(text,'en','it',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'it','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ru',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ru','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ar',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ar','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','fr',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'fr','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ja',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ja','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','zh',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'zh','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','de',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'de','en',tr)
    response.add(tmp)
    
  if pivot_level == 0 or pivot_level == 2:
    tmp = translate(text,'en','de',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'de','ru',tr)
    tmp = translate(tmp,'ru','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','fr',tr)
    tmp = translate(tmp,'fr','ru',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ru','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ar',tr)
    tmp = translate(tmp,'ar','fr',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'fr','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','it',tr)
    tmp = translate(tmp,'it','ru',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ru','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ru',tr)
    tmp = translate(tmp,'ru','ar',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ar','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ru',tr)
    tmp = translate(tmp,'ru','zh',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'zh','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ru',tr)
    tmp = translate(tmp,'ru','ja',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ja','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ar',tr)
    tmp = translate(tmp,'ar','zh',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'zh','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','ar',tr)
    tmp = translate(tmp,'ar','ja',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'ja','en',tr)
    response.add(tmp)

    tmp = translate(text,'en','de',tr)
    tmp = translate(tmp,'de','fr',tr)
    response.add(google.translate_wrapper(tmp,'en'))
    tmp = translate(tmp,'fr','en',tr)
    response.add(tmp)
  return response
Example #14
0
def donusturme(img):
    img = Image.open(img)
    pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'
    result = pytesseract.image_to_string(img)
    tr = Translater()
    tr.set_key(
        'KEY')  # Api key found on https://translate.yandex.com/developers/keys
    tr.set_from_lang('en')
    tr.set_to_lang('tr')
    tr.translate()
    tr.set_text(result)
    with open("magic.txt", mode="w") as file:
        file.write(tr.translate())
        file.close()
        print(">ceviri tamamlandı...")
    return
Example #15
0
def translate(values):
    # TODO: исправить перевод. Сейчас переводит только с русского на англ
    # message = getTranslatedText(values.message[values.message.find(' '):])
    # fixme: временный переводчик
    tr = Translater()
    tr.set_key(os.environ['YANDEX_TRNSL_KEY'])
    tr.set_text(values.message[values.message.find(' '):])
    fromLang = tr.detect_lang()
    if fromLang == 'ru':
        tr.set_from_lang('ru')
        tr.set_to_lang('en')
    else:
        tr.set_from_lang('en')
        tr.set_to_lang('ru')
    message = tr.translate()

    return message, None, None
Example #16
0
def translator(string, words):
    tr = Translater()
    for i in range(0, len(words)):
        if (words[i] == 'перевод') or (words[i] == 'переведи') or (words[i] == 'translate') or (words[i] == 'translator'):
            string = string.replace(words[i], '')
    tr.set_key(data.TRANSLATOR_KEY)
    tr.set_text(string)
    tr.set_from_lang('ru')
    tr.set_to_lang('en')
    return tr.translate()
Example #17
0
    def translate(self, text, toLang, fromLang=None):
        tr = Translater()
        tr.set_key(self.api_key)
        tr.set_text(text)

        if fromLang is None:
            fromLang = tr.detect_lang()
            if fromLang is None:
                fromLang = 'de'

        tr.set_from_lang(fromLang)
        tr.set_to_lang(toLang)
        return tr.translate()