def search_by_phrase(input_phrase, language, transDict, Greek_word_num, Greek_search_dict, Greek_text, max_scoreboard_size, min_score):

	if not (valid_search(input_phrase)):
		return ERROR
	else:
		output_translation_matrix = []
		output_translation_matrix.append([""])

		# Save lemma to translations found
		found_translist = {}

		scoreKeeper = scoreboard(max_scoreboard_size, min_score)

		search = search_phrase(input_phrase, language)

		# Find all the translations of the given words
		for i in range(search.search_len):
			search.has_translation[i] = trn.get_translation(search.text[i], transDict, found_translist)
		
		xls.try_all_search_combos(search, scoreKeeper, Greek_word_num, Greek_search_dict, Greek_text, output_translation_matrix)

		#translations_of_search = translation_matrix_to_string(output_translation_matrix)
		output_translation_matrix.pop(0)

		return scoreKeeper, output_translation_matrix
Esempio n. 2
0
def translate_text():
    data = request.get_json()
    text_input = data['text']
    print(text_input)
    translation_output = data['to']
    response = translate.get_translation(text_input, translation_output)
    return jsonify(response)
def main():

	transDict, Greek_word_num, Greek_search_dict, Greek_text = preprocessing()

	# Save lemma to translations found
	found_translist = {}

	try:
		while (True):

			scoreKeeper = scoreboard(MAX_SCOREBOARD_SIZE, MIN_SCORE)

			input_phrase = input("Enter Search Phrase>  ")

			if re.sub(" ", "", re.sub("q", "", input_phrase)) == "" or re.sub(" ", "", re.sub("quit", "", input_phrase)) == "":
				exit(0)

			if (valid_search(input_phrase)):
				
				search = search_phrase(input_phrase, "Latin")

				# Find all the translations of the given words
				for i in range(search.search_len):
					search.has_translation[i] = trn.get_translation(search.text[i], transDict, found_translist)
		
				xls.try_all_search_combos(search, scoreKeeper, Greek_word_num, Greek_search_dict, Greek_text)

				print(scoreKeeper)

			else:
				print('Please enter a valid string\n')

	except KeyboardInterrupt:
		print('\nProgram Terminated\n')
		sys.exit(0)
Esempio n. 4
0
def translate_text():
    data = request.get_json()
    text_input = data['text']
    translation_output = data['to']
    response = translate.get_translation(text_input, translation_output)
    ##return jsonify(response)   ##if this does not work, try return response (not jsonify)
    return jsonify(response)
Esempio n. 5
0
def translate_route():
	phrase = request.args.get("text")
	fro = request.args.get("from")
	to = request.args.get("to")

	translated_text = translate.get_translation(phrase, lang=fro + "-" + to)
	if translated_text == None:
		return "Failed to translate", 404

	return translated_text
Esempio n. 6
0
def text_func(msg):
    """ 测试 """
    # 这里 需要对方TO me, 然后我要回复FromUser
    if msg['ToUserName'] == get_friend('ZmJ'):
        if msg.Content[-2:] == '天气':
            weather = get_weather(msg.Content[:-2])
            itchat.send(weather, toUserName=msg['FromUserName'])

        elif msg.Content[:2] == 'fy':
            translation = get_translation(msg.Content.split(' ')[1])
            itchat.send(translation, toUserName=msg['FromUserName'])
Esempio n. 7
0
def make_translation(text):
    loaded_from_cache = False
    last = text.split('\n')[-1]
    if db.exists(last):
        translation = db.get(last)
        loaded_from_cache = True
    else:
        translation = translate.get_translation(text)
        if translation != 'Not recognized':
            # for simplicity one text row of textarea is considered as one query and the last sentence saved
            add_row(text, translation)
    return translation, loaded_from_cache
Esempio n. 8
0
def auto_reply_message(msg):
    if get_group(
            Username.FRIEND_GROUP) in [msg['ToUserName'], msg['FromUserName']]:
        if msg.Content[-2:] == '天气':
            weather = get_weather(msg.Content[:-2])
            itchat.send(weather, toUserName=get_group(Username.FRIEND_GROUP))

        elif msg.Content[:2] == 'fy':
            translation = get_translation(msg.Content.split(' ')[1])
            itchat.send(translation,
                        toUserName=get_group(Username.FRIEND_GROUP))

    elif msg['ToUserName'] == get_group(Username.OTHER_GROUP):
        pass
Esempio n. 9
0
def translate():
    if request.method == 'POST':
        from_lang = request.form['from']
        sentence = request.form['sentence']
        if from_lang != 'en':
            to_lang = 'en'
            input_word = trans.get_translation(sentence, to_lang)
            # print(input_word, 'IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII')
        else:
            input_word = sentence

        trans.translate_word(input_word)
        return render_template("pages/try.html",
                               sentence=sentence,
                               translated=input_word)
    async def translate(self, msg, *args):
        params = args[0]
        if len(params) < 3:
            format_err_msg = "Oh! That's not how you format ~translate! >_<\n"
            #await self.ntsk.send_message(msg.channel, format_err_msg + data.TRANSLATE_FORMAT)
            await self.ntsk.send_message(msg.channel, format_err_msg)

        text = ' '.join(params[2:])
        success, trans = translate.get_translation(params[1], text)

        trans = trans[0]

        if len(trans) > 2000:
            lth_err_msg = "The translation is too loong~!"
            await self.ntsk.send_message(msg.channel, lth_err_msg)
            return False

        await self.ntsk.send_message(msg.channel, trans)
Esempio n. 11
0
def traductor_text():
    data = request.get_json()
    text_input = data['text']
    text_input2 = data['text2']
    text_input3 = data['text3']
    text_input4 = data['text4']
    text_input5 = data['text5']
    text_input6 = data['text6']
    text_input7 = data['text7']
    text_input8 = data['text8']
    text_input9 = data['text9']
    translation_output = data['to']
    response = translate.get_translation(text_input, text_input2, text_input3,
                                         text_input4, text_input5, text_input6,
                                         text_input7, text_input8, text_input9,
                                         translation_output)
    print(response)
    return jsonify(response)
Esempio n. 12
0
def handle_dialog(res, req):
    global listening, action
    user_id = req['session']['user_id']
    if listening:
        txt = req['request']["original_utterance"]

        if action == 't':
            answer = get_translation(txt)
        else:
            answer = get_mistakes(txt)

        if answer != 'Ой, я не знаю этот язык! не могли бы вы написать что-либо на русском/английском?':
            listening = False
            action = None

        res['response']['text'] = answer
        return

    if req['session']['new']:
        sessionStorage[user_id] = {
            'suggests': [
                "Алиса, переведи мне текст",
                "Алиса, проверь мое предложение",
            ]
        }

        res['response'][
            'text'] = 'Привет! Я - Алиса-лингвист. Что тебя интересует?'
        res['response']['buttons'] = get_suggests(user_id)

        return

    if 'возможности' in req['request']['nlu']['tokens'] or "команды" in req[
            'request']['nlu']['tokens']:
        sessionStorage[user_id] = {
            'suggests': [
                "Переведи мне текст",
                "Проверь мое предложение",
            ]
        }

        res['response']['text'] = 'Я умею переводить текст с анлийского на русский и с русского на английский!\n' \
                                  'А также проверять твои предложения на грамматические ошибки.\n' \
                                  'Что тебя интересует? :P'
        res['response']['buttons'] = get_suggests(user_id)

        return

    tokens = get_command(req)

    if len(tokens) == 0:
        res['response'][
            'text'] = 'Прости, я не могу понять тебя. Не мог бы ты повторить?'

    elif len(tokens) > 1:
        res['response']['text'] = 'Хей, не все сразу.'

    elif len(tokens) == 1:
        res['response']['text'] = "Я вас внимательно слушаю."
        listening = True
        if tokens[0] == 'переведи':
            action = 't'
        else:
            action = 'g'
Esempio n. 13
0
def speech_translator():
    data = request.get_json()
    text_input = data['text']
    translation_output = data['to']
    response = translate.get_translation(text_input, translation_output)
    return jsonify(response)
Esempio n. 14
0
 def update(self, cur_text):
     con.clip_changed.emit(get_translation(cur_text))
Esempio n. 15
0
 layout, size = re.findall(
     r"[0-9+k]+",
     flat.find("p", "product__note").string)
 status = flat.find("span", "badge")
 datetime_now = datetime.now().isoformat()
 is_new = 0
 if status:
     status = status.string
     if "Nová nabídka" in status.string:
         is_new = 1
 select_sql = "SELECT * FROM flats WHERE id=?"
 c.execute(select_sql, (flat_id, ))
 selected_flat = c.fetchone()
 if selected_flat:
     if selected_flat[4] != description:
         description_pl = get_translation(
             translator, description)
         update_description_sql = """UPDATE flats
                  SET description = ?, description_pl = ?
                  WHERE id = ?"""
         c.execute(
             update_description_sql,
             (description, description_pl, flat_id),
         )
     update_sql = """UPDATE flats
                  SET is_new = ?, layout = ?, size = ?, price = ?, status = ?, district = ?, updated = ?
                  WHERE id = ?"""
     update_parameters = (
         is_new,
         layout,
         size,
         total_price,