Exemple #1
0
def respondUserWithWikiTranslated(page,targetLang):
    if page is None:
        print('IMDBot: ' + t.translate_text("Sorry, the page you are looking for is not in wikipedia", targetLang))
    else:
        print('IMDBot: ' + t.translate_text("Wikipedia Page of :",targetLang)  + page.title)
        print('IMDBot: ' + t.translate_text(str(page.summary),targetLang))
        print('IMDBot: ' + t.translate_text("Here\'s the link to the full Wikipedia page: ",targetLang) + page.fullurl)
def add_message():
    """Add meesages to Message database"""

    message = request.form.get("message")
    author_id = g.user.user_id
    timestamp = datetime.now()
    chatroom_id = 1
    new_message = Message(author_id=author_id,
                          timestamp=timestamp,
                          text=message,
                          chatroom_id=chatroom_id)

    db.session.add(new_message)
    # Messages on line 60 will be passed in to be translated.
    # Call detect_language(text) and translate_text(target, text) functions.

    languages = db.session.query(User.language).distinct()
    # Loop over all existing user distinct languages. And translate the original message
    # to each language. Add translated messages to database.
    for language in languages:
        # languages returns a list of tuples. language is still a tuple of one element.
        # index language[0] to fix it.
        trans_text = translate_text(language[0], message).translated_text
        message_id = new_message.message_id
        new_translation = Translation(message_id=message_id,
                                      trans_text=trans_text,
                                      language=language)
        db.session.add(new_translation)

    db.session.commit()

    return ""
Exemple #3
0
def get_audio():
    global language
    global input_text
    translated_text = translate.translate_text(input_text, language)
    result = textToSpeech.get_voice(
        translated_text[0]['translations'][0]['text'], language)

    return result
Exemple #4
0
def parse_request():

    if request.method == 'POST':
        print("receiving")
        url = request.json.get('url')
        raw_string =  OCR(url)
        print(raw_string)
        translated_words = translate_text(raw_string)
        return jsonify(translated_words)
Exemple #5
0
def receving(name, sock):
     while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = sock.recvfrom(1024)


                if data.decode()[:4] == "John":
                    string = translate.translate_text(str(data.decode()), 'es')
                    print (str(string))
                elif data.decode()[:3] == "Ale":
                    string = translate.translate_text(str(data.decode()), 'en')
                    print (str(string))
        except:
            pass
        finally:
            tLock.release()
Exemple #6
0
def translate():
    """ REST API call to translate whatever language text to English """
    query_parameters = request.args
    text = query_parameters.get('text')
    if not text:
        return ''
    translated = translate_text('en', text)
    if not translated:
        return ''
    return translated
def process(sentence, doc_2,
            answer):  # Processes user input and outputs the correct response
    invalid_responses = [
        "I do not understand the question",
        "That question is not in my database", "I cannot answer "
        "that question", "I am not familiar with that question",
        "I am sorry. Could you please ask another question?"
    ]
    similarity_index = 0
    index = 0
    nlp = en_core_web_lg.load()
    foreign_indicator = 0
    #This is where input is translated into English
    detected_lang = translate.detect_language(sentence)
    if (detected_lang != "en"):
        sentence = translate.translate_text("EN", sentence)
        foreign_indicator = 1

    doc_1 = nlp(preprocess(sentence))
    similarity = 0

    for i in range(len(doc_2)):
        if doc_2[i].vector_norm and doc_1.vector_norm:
            similarity = doc_1.similarity(doc_2[i])

        if similarity > similarity_index:
            similarity_index = similarity
            index = i
    if similarity_index > 0.60:
        if (foreign_indicator == 1):
            return translate.translate_text(detected_lang, answer[index])
        else:
            return answer[index]

    else:
        if (foreign_indicator == 1):
            return (translate.translate_text(
                detected_lang, random.choice(invalid_responses)) + "\n" +
                    wikipedia.search(sentence))
        else:
            return (random.choice(invalid_responses) + "\n" +
                    wikipedia.search(sentence))
Exemple #8
0
def echo(update, context):
    # Translate the incoming message text and unescape any escaped HTML characters
    print("User " + str(update.effective_chat.id) + " requested translation")
    translatedObject = translate_text('en', update.message.text)
    translatedText = translatedObject['translatedText']
    cleanedText = html.unescape(translatedText)
    print
    # If the original message was not in English, send the translated response to the user
    if translatedObject['detectedSourceLanguage'] != 'en':
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=cleanedText)
def image():
    import click1
    img_nam = click1.click2()
    destination = "C://Users//Shilpa Bundela//Desktop//ocr//Rachit_GoogleApi_Project//src//" + img_nam
    print(destination)
    l = ocr.detect_text(destination)
    print(l[0])
    for i in l:
        print(i)
    trans = translate.translate_text(l[0])

    return render_template("complete.html", output=l[0], op=trans)
Exemple #10
0
def translation_list(message):
    """Show a list of translations for given message."""
    languages = db.session.query(User.language).distinct()
    # Loop over all existing user distinct languages.
    translation_list = {}
    for language in languages:
        # Languages returns a list of tuples. Language is still a tuple of one
        # element, index language[0] to get the language itself.
        translation_list[language] = translate_text(language[0],
                                                    message).translated_text

    return translation_list
Exemple #11
0
def translate_image():
    image_base64_str = request.get_json()['image_base64']
    lang = request.get_json()['language']
    print(lang)
    image_name = 'image.jpg'
    binary_img = base64.b64decode(image_base64_str)
    g = open(image_name, "wb")
    g.write(binary_img)
    g.close()
    default_text = jpg_to_text('image.jpg')
    os.remove('image.jpg')
    translated_text = translate_text(default_text, lang)
    print(translated_text)

    return jsonify({'word': translated_text})
Exemple #12
0
def Enter_pressed():

    input_get = You.get()
    input_test = input_get.lower()
    if (translate.detect_language(input_test) != "en"):
        input_test = translate.translate_text("EN", input_test)
    if input_test in bye_synonyms:
        quit()
    else:
        messages.insert(END, "You: " + '%s\n' % input_get)
        # this gets the response from the Processor.py file and then prints them out
        get_response = Processor.process(input_get, question_list, responses)
        messages.insert(INSERT, "Nova: " + '%s\n' % get_response)
        You.set('')
        messages.see(END)
        return "break"
Exemple #13
0
def message_all(message):
    """Send a message to all active client connections.

    The message is formatted as JSON before sending.
    """

    original = message['message']
    for connection in client_connections:
        if connection.lang:
            message['message'] = translate_text(original, connection.lang)
            print("Translated message before sending to ", message)
        else:
            message['message'] = original
        m = json.dumps(message)
        connection.write_message(m)
    print("messaged {} clients".format(len(client_connections)))
def upload():
    target = os.path.join(APP_ROOT, 'images/')
    print("target =     ", target)

    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("file"):
        print("file =     ", file)
        filename = file.filename
        destination = "/".join([target, filename])
        print("destination =    ", destination)
        file.save(destination)
    l = ocr.detect_text(destination)
    print(str(l))
    trans = translate.translate_text(
        "HOW TO WRITE ALT TEXT AND IMAGE DESCRIPTIONS FOR THE VISUALLY IMPAIRED"
    )

    return render_template("complete.html", output=l, op=trans)
Exemple #15
0
    def ask(self, raw_input_string):
        """
        :param raw_input_string: Users question as raw string
        :return: Bots response as string
        """
        query = self.cleaner.clean(raw_input_string)

        if "translate" in query:
            return translate.translate_text(query.replace("translate", ""))
        elif "tweet" in query:
            return twitter.get_tweets()
        elif "wolfram" in query:
            return wolfram.wolfram_query(query.replace("wolfram", ""))
        else:
            results = self.es.search(query)

            if len(results) > 0:
                return results[0]["_source"]["response"]

            from random import randint

            return DEFAULT[randint(0, len(DEFAULT) - 1)]
tweets = []

pages = [1, 2, 3, 4]
fn = ["。", "?", "、、、", ":", "?", "!", "!", "...", "笑"]
for p in pages:
    results = API.user_timeline(screen_name="D_kazuyan", exclude_replies=True, include_rts=False, count=200, page=p)
    for r in results:
        if not r.retweeted:
            text=re.sub(r'https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+', "", r.text)
            text=re.sub('RT', "", text)
            text=re.sub('┃━━━━━━━━━━━━━┃', "", text)
            text=re.sub('お気に入り', "", text)
            text=re.sub('会食恐怖症', "", text)
            text=re.sub('質問箱', "", text)
            text=re.sub(r'(#[^\s]+)', "", text)#ハッシュタグ
            text=re.sub(r"@([A-Za-z0-9_]+)", "", text)#メンション
            text=re.sub(r'[︰-@]', "", text)#全角記号
            text=re.sub('\n', "", text)#改行文字
            if text and text[-1] not in fn:
                text += "。"
            tweets.append(text)
        # tweets.append(translate_text(text))
line = "".join(tweets)
line += translate_text(line)
# print(line)
with open("tweet.txt", "wt", encoding="UTF-8") as f:
    f.write(line)
# print(tweets)
# for page in pages:
#     results = api.user_timeline(screen_name="D_kazuyan", count=200)
# print("Hello world")
Exemple #17
0
def translate_text():
    data = request.get_json()
    input_text = data['text']
    output_language = data['to']
    response = translate.translate_text(input_text, output_language)
    return jsonify(response)
Exemple #18
0
 def setUp(self):
     self.translated_text = translate.translate_text()
     print(self.translated_text)
Exemple #19
0
 def test_too_many_arg(self):
     self.assertRaises(TypeError, translate.translate_text(), ('ru', 'en'))
Exemple #20
0
            print(
                'IMDBot: Whose wikipedia page would you like to find out about?'
            )
            actorName = input(f'{userName}: ')

            # the user can ask to translate the language in wikipedia part.
            # if the user chooses to translate, everything in wikipedia part will be converted to target Language

            if ("translate" in actorName):
                print(
                    'IMDBot: Please enter the language code you need me to translate to (i.e: "de", "ja", etc)'
                )
                targetLang = input(f'{userName}: ')
                print('IMDBot: ' + t.translate_text(
                    "Whose wikipedia page would you like to find out about?",
                    targetLang))
                actorName = input(f'{userName}: ')

            wikipage = w.findPage(wikipedia,
                                  actorName)  # get the page of the actor

            if targetLang != "en":
                w.respondUserWithWikiTranslated(wikipage, targetLang)
            else:
                w.respondUserWithWiki(wikipage)

            if (wikipage is not None):
                print(
                    'IMDBot: Would you like me to print the page as a text file? (y/n)'
                )