def series(tunombre): msg_salida = None msg_salida = random.choice(["¿Que tipo de series te gustan?, tengo\n", "Genial!, tengo estas categorías\n", "Muy bien, series, podríamos empezar por: \n"]) categorias_series = " - Crimen\n - Novela\n - Infantil\n - Documentales\n - Clásicos\n - Reality Shows" # msg_salida = msg_salida + categorias_entretenimiento print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) print("\n"+chr(27)+"[1;34m"+'CHATBOT:\n'+categorias_series) msg = leer_mensaje(tunombre) name = encontrar_en_lista(msg, LEER_SERIES) if name: select = random.choice(DIC_SERIES[name]) ran = np.random.randint(0,len(Netflix_s[Netflix_s['listed_in']==select])) datos = Netflix_s[Netflix_s['listed_in']==select][['title', 'duration','description']].iloc[ran] msg_salida = ( 'Si te gusta la categoría de {} yo te recomendaría la serie "{}", que tiene {}, trata de: {}'.format(name, datos[0], GoogleTranslator(source='auto', target='es').translate(datos[1]), GoogleTranslator(source='auto', target='es').translate(datos[2]))) else: msg_salida = "Hum... creo que no capté algo de lo que dijiste, ¿podrías repetirlo?" print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) series(tunombre) msg_salida = [] print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) return
def wikis(tunombre): msg_salida = None msg_salida = random.choice(["¿Que te gustaría saber?, preguntame algún concepto\n", "Genial!, ¿te interesa saber la definición de algo en particular?\n", "Muy bien, podríamos empezar por algo que quieras saber... \n"]) print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) w = leer_mensaje(tunombre,w=True) w = GoogleTranslator(source='auto', target='en').translate(lista_a_cadena(w, '')) w = w.split() name = encontrar_en_lista(w, name_wikis) if name: ran = np.random.randint(0,len(Wikis[Wikis['Name']==name])) title = Wikis[Wikis['Name']==name][['Name', 'WikiDescription','WikiUrl']] msg_salida = ( 'Aquí esta la definición de {} que encontré para ti: {}'.format( GoogleTranslator(source='auto', target='es').translate(title.iloc[ran][0]), GoogleTranslator(source='auto', target='es').translate(lista_a_cadena(contar_puntos(title.iloc[ran][1]), ''))) + ' Puedes leer más de ello en: {}'.format( title.iloc[ran][2])) else: msg_salida = "Hum... creo que no capté algo de lo que dijiste, ¿podrías repetirlo?" print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) wikis(tunombre) msg_salida = [] print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) return
def getTweets(api, cuentaDeDiputado): translator = GoogleTranslator(source="es", target="en") count = 0 botPercentageAvg = 0 MAX = 1000 for tweet in tweepy.Cursor(api.user_timeline, id=cuentaDeDiputado, tweet_mode="extended").items(): tweetJSON = tweet._json fullText = tweetJSON["full_text"] if "RT @" not in fullText and fullText[0] != '@': cleanText = cleanTweet(fullText) try: sentiment = TextBlob(str( translator.translate(cleanText))).sentiment botPercentageAvg += sentiment.polarity count += 1 print(count) except Exception as e: print(e) continue if count == MAX: break print("PolarityAvg = " + str(botPercentageAvg / count))
def translate_chunk(text, code): text = text.replace("\\n", "\n") translated = GoogleTranslator( source="auto", target=code).translate(text) if len(text) <= CHARS_MAX else text translated = translated.replace("\n", "\\n") return translated
async def on_message(message): global step ou = re.search(r"\best\s(où|ou) ?", message.content) calendar = re.search(r"calendrier|calend", message.content) appel = re.search(r"appel|apel", message.content) cafe = re.search(r"caf|cof", message.content) reprend = re.search(r"reprend|fait", message.content) boulot = re.search(r"boulot|boulo|taf", message.content) deplacement = re.search( r"deplacement|etrangé|étranger|etranger|déplacement", message.content) postuler = re.search(r"postul", message.content) if postuler: await message.channel.send( "Non mais je soummet ma candidature à ce qui me plait en faite ? J'ai le droit ? " ) if deplacement: await message.channel.send( "ça c'est un problème, je deteste voyager ! Pas envie de me retrouver à New York ou en Chine" ) if boulot: await message.channel.send( "Toujours au chômage, je commence à regarder les cdi en alternance pour technicien de maintenance " ) if reprend: await message.channel.send("ouais, ce que j'ai fais ") if appel: await message.channel.send( "Flemme, j'ai le nez bouché, j'respire par la bouche, flemme de parler" ) if calendar: await message.channel.send( "Pas besoin de ça! Je vois pas l'interêt d'un calendrier, le sapin c'est festif ! Pas le calendrier ! " ) if ou: await message.channel.send('Oh putain ! Totalement zappé') elif message.content.startswith('*'): print(message.content) text = message.content transl = GoogleTranslator(source='auto', target='en').translate( text) # output -> Weiter so, du bist großartig to_send = chatbot_response_b(step=step, user=transl) to_send = GoogleTranslator(source='auto', target='fr').translate(to_send) print(to_send) try: await message.channel.send(to_send) except: await message.channel.send("no response...") if message.author == client.user: return if message.content.startswith('$'): if message.content == '$spam': pass print(message.content)
def __init__(self,file ,args): self.df = pd.read_csv(file) self.kwargs = args self.stemmer = PorterStemmer() # self.translator = GoogleTranslator( # source='auto', target='en')#args['language'] self.translate = GoogleTranslator(source='auto', target='en') self.df['cleanTweet'] = self.df['tweet'].apply(self.execute) self.df.to_csv(file)
def translate_word(eng_word: str) -> str: for _ in range(4): translator = GoogleTranslator(source='en', target='ru') try: ru_word = translator.translate(eng_word) if eng_word == eng_word.lower(): ru_word = ru_word.lower() return ru_word except TooManyRequests: sleep(5) return 'не найдено'
def test_inputs(): with pytest.raises(exceptions.LanguageNotSupportedException): GoogleTranslator(source="", target="") with pytest.raises(exceptions.LanguageNotSupportedException): GoogleTranslator(source="auto", target="nothing") # test abbreviations and languages g1 = GoogleTranslator("en", "fr") g2 = GoogleTranslator("english", "french") assert g1._source == g2._source assert g1._target == g2._target
def numbers(lan): language = extras.get_language_long(lan) print("\n\nNumbers in " + language) print("---------------------------------------------------------") numEn = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ] numL = [] for n in numEn: numOth = GoogleTranslator(source='en', target=lan).translate(text=n) numOth = numOth.lower() numL.append(numOth) newP = 0 i = 0 while i < 11: correct = False mike.mike(numEn[i] + " in " + language + " is ") mike.mike(numL[i], lan) mike.mike("Say " + numEn[i] + " in " + language) user_input = mike.record_audio(lang=lan) attempt = 0 while correct == False: print("You said: " + user_input) if numL[i] in user_input: print("Correct!") newP = newP + 1 correct = True elif str(i) in user_input: print("Correct!") newP = newP + 1 correct = True elif "quit" in user_input: main.save_progress() exit() else: if attempt < 3: mike.mike("Let's try again, say ") user_input = mike.record_audio(numL[i], lan) else: print("Let's move on") correct = True attempt = attempt + 1 i = i + 1 return newP
def colours(lan): language = extras.get_language_long(lan) print("\n\nColours in " + language) print("---------------------------------------------------------") clrEn = [ "white", "grey", "black", "brown", "red", "green", "blue", "yellow", "pink", "purple", "orange" ] clrL = [] for n in clrEn: clrOth = GoogleTranslator(source='en', target=lan).translate(text=n) clrOth = clrOth.lower() clrL.append(clrOth) i = 0 newP = 0 while i < 11: correct = False mike.mike(clrEn[i] + " in " + language + " is ") mike.mike(clrL[i], lan) mike.mike("Say " + clrEn[i] + " in " + language) user_input = mike.record_audio(lang=lan) user_input = user_input.lower() attempt = 0 while correct == False: print("You said: " + user_input) if clrL[i] in user_input: print("Correct!") newP = newP + 1 correct = True elif "quit" in user_input: main.save_progress() exit() else: if attempt < 3: mike.mike("Let's try again, say ") user_input = mike.record_audio(clrL[i], lan) else: print("Let's move on") correct = True attempt = attempt + 1 i = i + 1 return newP
def translate_subtitles_file(video_path, source_srt_file, to_lang, forced, hi): to_lang = alpha3_from_alpha2(to_lang) lang_obj = Language(to_lang) if forced: lang_obj = Language.rebuild(lang_obj, forced=True) if hi: lang_obj = Language.rebuild(lang_obj, hi=True) logging.debug('BAZARR is translating in {0} this subtitles {1}'.format(lang_obj, source_srt_file)) max_characters = 5000 dest_srt_file = get_subtitle_path(video_path, language=lang_obj, extension='.srt', forced_tag=forced, hi_tag=hi) subs = pysubs2.load(source_srt_file, encoding='utf-8') lines_list = [x.plaintext for x in subs] joined_lines_str = '\n\n\n'.join(lines_list) logging.debug('BAZARR splitting subtitles into {} characters blocks'.format(max_characters)) lines_block_list = [] translated_lines_list = [] while len(joined_lines_str): partial_lines_str = joined_lines_str[:max_characters] if len(joined_lines_str) > max_characters: new_partial_lines_str = partial_lines_str.rsplit('\n\n\n', 1)[0] else: new_partial_lines_str = partial_lines_str lines_block_list.append(new_partial_lines_str) joined_lines_str = joined_lines_str.replace(new_partial_lines_str, '') logging.debug('BAZARR is sending {} blocks to Google Translate'.format(len(lines_block_list))) for block_str in lines_block_list: try: translated_partial_srt_text = GoogleTranslator(source='auto', target=lang_obj.basename).translate(text=block_str) except: return False else: translated_partial_srt_list = translated_partial_srt_text.split('\n\n\n') translated_lines_list += translated_partial_srt_list logging.debug('BAZARR saving translated subtitles to {}'.format(dest_srt_file)) for i, line in enumerate(subs): line.plaintext = translated_lines_list[i] subs.save(dest_srt_file) return dest_srt_file
async def translate(self, ctx, *args): lang = args[0] msg = " ".join(args[1:]) if lang.lower() == 'list': await ctx.send( GoogleTranslator.get_supported_languages(as_dict=True)) return try: translated = GoogleTranslator(source='auto', target=lang).translate(msg) await ctx.send(translated) except: await ctx.send("지원되지 않는 언어입니다.")
def translate(word): # p = {'key': 'trnsl.1.1.20190115T093726Z.65e1460d8d95bd06.р45ор345о3р4о53р45о345р3о', # 'lang': LANGUAGE, 'text': word} # # response = get('https://translate.yandex.net/api/v1.5/tr.json/translate', params=p) # print(response.status_code) # if not response.__bool__(): # return # trans_text = response.json()['text'][0] try: trans = GoogleTranslator(source='auto', target=LANGUAGE) text = trans.translate(word) return text except Exception: return
def lyrics(cancion, artista, trans): artista = artista.lower() cancion = cancion.lower() artista = re.sub('[^A-Za-z0-9]+', "", artista) cancion = re.sub('[^A-Za-z0-9]+', "", cancion) url = f"http://azlyrics.com/lyrics/{artista}/{cancion}.html" try: content = urllib.request.urlopen(url).read() soup = BeautifulSoup(content, 'html.parser') lyrics = str(soup) inicio = '<!-- Usage of azlyrics.com content by any third-party lyrics provider is prohibited by our licensing agreement. Sorry about that. -->' fin = '<!-- MxM banner -->' lyrics = lyrics.split(inicio)[1] lyrics = lyrics.split(fin)[0] lyrics = re.sub('(<.*?>)', "", lyrics) if trans == 0: return lyrics elif trans == 1: ln = 'es' # <-----------------------------Assign the language using its abbreviation lyrics = GoogleTranslator(source='auto', target=ln).translate(text=lyrics) return lyrics else: return 'Error: You got the wrong number' except Exception as e: return "Exception occurre: " + str(e)
def translate(text, source, dest): if text is None: print("Invalid Text") elif text != "": translation = GoogleTranslator(source='en', target=desti_lang).translate(text=text) pyperclip.copy(translation) return translation
def test_l1(lan): language = extras.get_language_long(lan) count = 0 tPoints = 0 # Five questions to test the most basic words while count < 3: if count % 2 == 0: phrase = random_test.easy_noun() else: phrase = random_test.easy_adj() userAnswer = mike.record_audio( "What is " + phrase + " in " + language + "?", lan) translated = GoogleTranslator(source='auto', target=lan).translate(text=phrase) print("You said: " + userAnswer + "\n The correct answer was: " + translated) count = count + 1 if len(userAnswer) > 0: if userAnswer in translated: print("+1") tPoints = tPoints + 1 if tPoints > 2: tPoints = 2 percent = (tPoints / 2) * 100 return percent
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # print(tracker.latest_message) # print(tracker.events) intent = tracker.latest_message['intent'].get('name') input_text = tracker.latest_message['text'] lang = language_detection.predict_lang(input_text) response = multilingual_response.predict_response(intent=intent, lang=lang) if response: logger.info('Multilingual Response:{0}'.format(response)) dispatcher.utter_message(text=response) else: utter_intent = "utter_{}".format(intent) response_default = domain.get('responses').get( utter_intent)[0].get('text') if response_default: if lang == 'en': logger.info('Setting default response for the intent:{0}, ' 'in language:{1}.'.format(intent, lang)) dispatcher.utter_message(text=response_default) else: logger.info( 'There is no multilingual response for intent:{0}, ' 'in language:{1}. Running online translation.'.format( intent, lang)) if lang == 'zh': # Change the language from 'zh' to 'zh-cn', as google translate is not supported with zh lang = "{}-cn".format(lang) response_translated = GoogleTranslator( source='en', target=lang).translate(response_default) dispatcher.utter_message(text=response_translated) return []
def peliculas(tunombre): msg_salida = None msg_salida = random.choice(["¿Qué clase de películas te gustan?, tengo\n", "Genial!, tengo estas categorías\n", "Muy bien, entretenimiento, podríamos empezar por: \n"]) opciones_peliculas = " - documentales\n - accion\n - comedia\n - palomera\n - drama\n - terror\n - clasicos\n - ficcion\n - infantil" # msg_salida = msg_salida + opciones_peliculas print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) print("\n"+chr(27)+"[1;34m"+'CHATBOT:\n'+opciones_peliculas) msg = leer_mensaje(tunombre) name = encontrar_en_lista(msg, LEER_PELIS) if name: select = random.choice(DIC_PELIS[name]) ran = np.random.randint(0,len(Netflix_p[Netflix_p['listed_in']==select])) datos = Netflix_p[Netflix_p['listed_in']==select][['title', 'duration','description']].iloc[ran] msg_salida = ( 'Si te gusta la categoría de {} yo te recomendaría la película "{}", que dura {}, trata de: {}'.format(name, datos[0], GoogleTranslator(source='auto', target='es').translate(datos[1]), GoogleTranslator(source='auto', target='es').translate(datos[2]))) else: msg_salida = "Hum... creo que no capté algo de lo que dijiste, ¿podrías repetirlo?" print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) peliculas(tunombre) msg_salida = [] print(chr(27)+"[1;34m"+'CHATBOT:') for i in textwrap.wrap(str(msg_salida), 130): print(chr(27)+"[1;34m"+ i) return
def read_pdf(storage_directory, pdf_files): # Fonction permettant de gérer l'extraction d'information des PDF # taille = len(pdf_files) # compteur = 1 for pdf_file in pdf_files: # Lecture du CV doc = fitz.open(storage_directory + pdf_file) print(pdf_file) # on recupère tout le texte content = "" for page in doc: content = content + str(page.getText()) # élimine les retour à la ligne tx = " ".join(content.split('\n')) # On Supprime les caractères non désirable tx = unidecode.unidecode(tx) # On traduit le texte en francais tx = GoogleTranslator(source='auto', target='fr').translate(tx) # Extraction des informations des CV parse_string(storage_directory, pdf_file, tx)
def learn_word(self, message): if random.choice([True, False]): tr = GoogleTranslator(source=self.current_learning_words[ self.learning_word]["languages"]["src"], target=self.current_learning_words[ self.learning_word]["languages"]["dest"]) print(self.__get_uqicues(count=2)) self.wrong_answers = self.__get_uqicues(count=2) answers = [ f"types.InlineKeyboardButton('{tr.translate(el)}', callback_data=\"{tr.translate(el)}_answer\")" for el in self.wrong_answers ] answers.append( f"types.InlineKeyboardButton('{self.current_learning_words[self.learning_word]['values']['dest']}', callback_data=\"{self.current_learning_words[self.learning_word]['values']['dest']}_answer\")" ) answers_keyboard = types.InlineKeyboardMarkup() random.shuffle(answers) print(answers) exec(f"answers_keyboard.add({','.join(answers)})") print(answers_keyboard) bot.send_message( message.chat.id, f'choose correct translation of "**{self.current_learning_words[self.learning_word]["values"]["src"]}**"', parse_mode='Markdown', reply_markup=answers_keyboard) else: bot.send_message( message.chat.id, f'enter correct translation of "**{self.current_learning_words[self.learning_word]["values"]["src"]}**"', parse_mode='Markdown') bot.register_next_step_handler(message, self.input_truth_answer)
def translate_word(request): if request.method == 'POST': data = json.loads(request.body) if data["source_lang"] == 'zh': data["source_lang"] = "zh-cn" if data["dest_lang"] == 'zh': data["dest_lang"] = "zh-cn" if data["source_lang"] == 'po': data["source_lang"] = "portuguese" if data["dest_lang"] == 'po': data["dest_lang"] = "portuguese" if data["source_lang"] == 'ge': data["source_lang"] = "de" if data["dest_lang"] == 'ge': data["dest_lang"] = "de" raw_data = data["content"].replace('\n', '\n ') raw_data = data["content"].replace(',', ', ') raw_data = raw_data.split(' ') try: for count, item in enumerate(raw_data): word_to_translated = raw_data[count] if word_to_translated != ',' and word_to_translated != '' and word_to_translated != ' ' and word_to_translated != '\n' and word_to_translated != '\n ': translated_word = GoogleTranslator( source=data["source_lang"], target=data["dest_lang"]).translate(raw_data[count]) raw_data[count] = translated_word except Exception as e: return JsonResponse(data={"result": e, 'error': "1"}, safe=False) return JsonResponse( data={"result": ' '.join([str(elem) for elem in raw_data])}, safe=False)
def save_countries(): Country.objects.all().delete() url = 'https://restcountries.eu/rest/v2/all' response = requests.request('GET', url) countries = response.json() available_countries = [] for country in countries: country_name_en = country['name'] #Se utiliza Google Translator para traducir el nombre del país #En caso de error en la traducción, el nombre del país queda igual que el original try: country_name_es = GoogleTranslator( source='en', target='es').translate(country_name_en) except Exception as e: country_name_es = country_name_en new_country = Country() new_country.name_spanish = country_name_es new_country.name_english = country_name_en new_country.slug_spanish = slugify(country_name_es) new_country.slug_english = slugify(country_name_en) new_country.code_alpha_two = country['alpha2Code'] new_country.code_alpha_three = country['alpha3Code'] available_countries.append(new_country) #Se crean los países de forma masiva Country.objects.bulk_create(available_countries) return True
def run(path, ext): ff = [] for root, directories, files in os.walk(path, topdown=False): for name in files: f_name = os.path.join(root, name) if f_name.endswith(ext): ff.append(f_name) for name in directories: f_name = os.path.join(root, name) if f_name.endswith(ext): ff.append(f_name) r = re.compile(regexp) i = 0 for fn in ff: with open(fn, "r") as f: new_file = fn + ".new" new_lines = [] for line in f.readlines(): words = r.findall(line) for word in words: ret = GoogleTranslator(source='auto', target='en').translate(word) line = line.replace(word, ret) print("{} {} --> {}".format(i, word, ret)) i = i + 1 new_lines.append(line) with open(new_file, "w+") as nf: nf.writelines(new_lines)
def getInfoWikipedia(self): try: text = wikipedia.summary("Empresa: " + infoAction["nome"], 3) return GoogleTranslator(source="auto", target="pt").translate(text) except: #print("Não conseguiu pegar da Wikipédia/traduzir") return "Nada encontrado...."
def main(): input_file = parser.parse_args().file input_file = open(input_file, 'r') lines = input_file.readlines() with open('ENG_pretty_headers.po', 'w', encoding='utf8') as outfile: for line in lines: if '#: spoonbill/locales/schema.json:1' in lines[lines.index(line)-1]: msgstr = line.replace('/', ' ') msgstr = re.sub(r"(\w)([A-Z])", r"\1 \2", msgstr).replace('msgid ', '').replace('"', '').strip().title() msgstr = f'msgstr "{msgstr}"\n' lines[lines.index(line)+1] = msgstr outfile.writelines(line) outfile.close() with open('ES_pretty_headers.po', 'w', encoding='utf8') as outfile: for line in lines: if '#: spoonbill/locales/schema.json:1' in lines[lines.index(line) - 1]: eng = lines[lines.index(line)+1] eng = eng.replace('msgstr "', '').replace('"', '').replace('\n', '').split(' ') spa = [GoogleTranslator(source='en', target='es').translate(word) for word in eng] translated = 'msgstr "' for word in spa: translated += word + ' ' translated = translated.strip() + '"\n' lines[lines.index(line) + 1] = translated outfile.writelines(line) outfile.close() input_file.close()
def sns(query, num_tweets=10): output = [] # We decode the parameter since we are calling the function from a separate server and parameters info is binary-enconded engine_query = '#' + query.decode('utf-8') + ' -filter:retweets' for i, tweet in enumerate(sntwitter.TwitterSearchScraper(engine_query).get_items()): # We need to limit the no. of tweets manually since the sns Python wrapper doesn't include the functionality if i > num_tweets-1: break try: to_translate = tweet.content translated = GoogleTranslator(source='auto', target='en').translate(to_translate) sentimiento = TextBlob(translated).sentiment except Exception as e: sentimiento = 0.0 output.append({ 'Tweet_No': str(i+1), 'Date': str(tweet.date), 'ID': tweet.id, 'Content': tweet.content, 'Username': tweet.username, 'Sentiment': round(sentimiento.polarity, 2) }) return json.dumps(output, indent=3)
def main(): print('Number of arguments:', len(sys.argv), 'arguments.') print('Argument List:', sys.argv) f = open(sys.argv[1], "r", encoding="utf8") all_data = "" for x in f.readlines(): all_data += x f.close() all_data = split(["Chapter"], all_data) newTxt = split(["."], sys.argv[1]) newTxt = newTxt[0] + "_thai." + newTxt[1] f = open(newTxt, "w", encoding="utf8") for x in all_data: if len(x) > 6: x = "Chapter" + x #print(x) #print("-------------- " + str(len(x)) + "-------------- ") f.writelines(x) translated = GoogleTranslator(source='en', target='th').translate(x) print(translated) f.writelines(translated)
async def _(event): if event.fwd_from: return if "trim" in event.raw_text: return input_str = event.pattern_match.group(1) if event.reply_to_msg_id: previous_message = await event.get_reply_message() text = previous_message.message lan = input_str or "gu" elif "|" in input_str: lan, text = input_str.split("|") else: await edit_or_reply(event, "`.tr LanguageCode` as reply to a message") return text = emoji.demojize(text.strip()) lan = lan.strip() try: lmao = detect(text) after_tr_text = lmao to_translate = text translated = GoogleTranslator(source="auto", target=lan).translate(to_translate) output_str = """**Translated By FridayUserbot** Source **( {} )** Translation **( {} )** {}""".format(after_tr_text, lan, translated) await edit_or_reply(event, output_str) except Exception as exc: await edit_or_reply(event, str(exc))
def ko_translate(self, text, lan): try: res = GoogleTranslator(source='ko', target=lan).translate(text) except Exception as e: print('Failed to Translate text. Reason: %s' % e) res = '' return res
def choose_language(): valid = False chosen = False langs_dict = GoogleTranslator.get_supported_languages(as_dict=True) print("Languages available: ") for key in langs_dict: if langs_dict[key] in tts_langs(): print(key) while valid == False: while chosen == False: choice = mike.record_audio("Please select a new language to learn") try: languageToLearn = extras.get_language_short(choice) if languageToLearn in tts_langs(): valid = True if valid == True: response = mike.record_audio( "You have chosen " + choice + ", say yes to start learning this language.") if 'yes' in response: chosen = True return languageToLearn except: return 0