def test_logging_level_error(self, capture): logger = logging.getLogger('TSE LOGGER') logger.setLevel('ERROR') google('Test massage', 'en', 'ru') for log in capture.actual(): self.assertNotEqual(log[0] + ' ' + log[1], 'TSE LOGGER ERROR') logger.setLevel('INFO')
def tran_line(en): if (len(en) == 0): return '' # en中不能存在&,所以我们把en的&直接去除 # en中的#号也是没有意义的,不需要翻译 en = en.replace('&', '') en = en.replace('#', '') en = en.replace('**', '') en = en.replace('`', '') en = en.replace('"', '') en = en.replace('\n', ' ') len_en = len(en) if (len_en > 5000): print('len_en = %d' % len_en) print(en) ens = en.split('.') ch = '' for elem in ens: ch = ch + ts.google(elem, 'en', 'zh') return ch while (True): try: ch = ts.google(en, 'en', 'zh') return '<font color=#00ffff size=3> ' + ch + ' </font>' except Exception as e: print(en, e)
def load_key_words(self, country, translated=True): """ Load the key words for a specific country :param country: country of set {NL, DE, ES} :param translated: True if you also want the english word :return: data frame with keywords """ folder_path = Path.cwd().absolute().parents[0].as_posix() + "/Data/KeyWords" file_name = country + ('_EN' if translated else '') + '.txt' file_path = folder_path + "/" + file_name if os.path.exists(file_path): self.df_kws = pd.read_csv(file_path, index_col=0) else: self._create_folder(folder_path) key_words = self._key_words_UF(country) if translated: print("Translating keywords...") key_words_trans = [[key_word, ts.google(key_word, from_language=country.lower(), to_language='en') if country != 'ZA' else ts.google(key_word, to_language='en')] for key_word in key_words] self.df_kws = pd.DataFrame(key_words_trans) self.df_kws.columns = [country, 'EN'] else: self.df_kws = pd.DataFrame(key_words) self.df_kws.columns = [country] self.df_kws.to_csv(file_path, sep=',', mode='w') return self.df_kws
def translate_to_ru(): print("start translate_to_ru") text = Quester.get_text() answ = ts.google(text, 'en', 'ru') try: if en_ru[text] == 'None': answ = ts.google(text, 'en', 'ru') en_ru[text]=answ else: answ = en_ru[text] print("\tI know the answer on" + str(text) + ' is: ' + str(answ)) except KeyError: pass pyautogui.click(685, 672) pyperclip.copy(answ) pyautogui.hotkey('ctrl', 'v') if not Checker.check(): pyautogui.moveTo(576, 955) pyautogui.dragTo(1156, 971, duration=0.5) # drag mouse to XY time.sleep(0.5) pyautogui.hotkey('ctrl', 'c') time.sleep(0.2) ru_en[text] = (str)(pyperclip.paste()) print("\tI don't know the answer,but at the next time i will answer: " + str(ru_en[text])) File_Magager.write(en_ru,'en_ru') pyautogui.click(1358, 967) else: pyautogui.click(1358, 967)
def multi_translate(text, language_stack): prev_lang = 'en' for lang in language_stack: text = ts.google(text, from_language=prev_lang, to_language=lang) prev_lang = lang text = ts.google(text, from_language=prev_lang, to_language='en') return text
def read(): Speak("In which Language?") lan = takecommand() if 'marathi' in lan: Speak("Select the Pdf") book = askopenfilename() book1 = open(book, 'rb') pdfreader = PyPDF2.PdfFileReader(book) pages = pdfreader.numPages Speak("Page number") print("Enter the Page number and press") panu = int(input('')) page = pdfreader.getPage(panu) text = page.extractText() print(text) Speak("Name the file") ask = input('') ty = gTTS(ts.google(text, from_language='en', to_language="mr")) print("Please Wait...") ty.save(f"{ask}.mp3") Speak("done sir") os.startfile(book) if 'hindi' in lan: Speak("Select the Pdf") book = askopenfilename() book1 = open(book, 'rb') pdfreader = PyPDF2.PdfFileReader(book) pages = pdfreader.numPages Speak("Page number") print("Enter the Page number and press") panu = int(input('')) page = pdfreader.getPage(panu) text = page.extractText() print(text) Speak("Name the file") ask = input('') ty = gTTS(ts.google(text, from_language='en', to_language="hi")) print("Please Wait...") ty.save(f"{ask}.mp3") Speak("done sir") os.startfile(book) if 'Normal' in lan: Speak("Select the Pdf") book = askopenfilename() book1 = open(book, 'rb') pdfreader = PyPDF2.PdfFileReader(book) pages = pdfreader.numPages Speak("Page number") print("Enter the Page number and press") panu = int(input('')) page = pdfreader.getPage(panu) text = page.extractText() player = pyttsx3.init() player.say(text) player.runAndWait() os.startfile(book)
def test_on_logging(self, capture): google('Test massage', 'en', 'ru') self.assertEqual(capture.actual()[3][0], 'TSE LOGGER') self.assertEqual(capture.actual()[3][1], 'INFO') self.assertEqual( capture.actual()[3][2][:len('UseTimeSeconds(fn: google_api):')], 'UseTimeSeconds(fn: google_api):')
def translate_text_to(text_to_translate: str, language_to: str, language_from: str = None): correct_language_to = language_to if language_to == "cn": correct_language_to = "zh-CN" if language_from: translation = ts.google(query_text=text_to_translate, from_language=language_from, to_language=correct_language_to, is_detail_result=True) else: translation = ts.google(query_text=text_to_translate, to_language=correct_language_to, is_detail_result=True) return translation
def translate(self, layout, program): sentence = str(program.findChild(QWidget, "Sentence").text()) words = str(program.findChild(QWidget, "Words").text()) tr_sentence = ts.google( sentence, to_language='en' ) tr_words = ts.google( words, to_language='en' ) program.findChild(QWidget, "Translated Sentence").setText(tr_sentence) program.findChild(QWidget, "Translated Words").setText(tr_words)
def translate(text, country): """ Translate the text to the languages originating from the country :param text: english text :param country: country abbreviation :return: list of translations """ lang = country.lower() if lang == 'es': # Spanish, Basque, Catalan, Galician, langs = ['es', 'eu', 'ca', 'gl'] translations = [ts.google(text, from_language='en', to_language=lang) for lang in langs] else: translations = [ts.google(text, from_language='en', to_language=lang)] return translations
def index(): if request.method == 'POST': url = "http://www.essaytyper.com/lookup" essay = request.form['essay'] res = requests.post( url, data={'subject': ts.google(essay, to_language='en')}) if res.status_code == 200: go = json.loads(res.text) result = """<div class="t-area">Ucup Setiawan<br>[jurusan/mata kuliah],Semester II, Class 2A<br>Bambang Suratman S.Sos <br>Institute Teknologi Surabaya<br>""" + tanggal( ) + """<br><br><center>""" + html.escape(essay).upper( ) + """</center><br>   """ + go['text'] + """<div>""" return render_template('index.html', result=result) else: try: wikipedia.set_lang("id") result = """<div class="t-area">Ucup Setiawan<br>[jurusan/mata kuliah],Semester II, Class 2A<br>Bambang Suratman S.Sos <br>Institute Teknologi Surabaya<br>""" + tanggal( ) + """<br><br><center>""" + html.escape(essay).upper( ) + """</center><br>   """ + wikipedia.summary( essay) + """ <div>""" return render_template('index.html', result=result) except: result = """<div class="t-area"> <div class="alert alert-danger" role="alert">OOops sorry we don't find anything about """ + html.escape( essay) + """</div><div>""" return render_template('index.html', result=result) else: return render_template('index.html')
def write_smth(arr): print("start write somthing") r1 = re.sub('Напишите',"", arr) r1 = re.sub(' на',"", r1) r1 = re.sub(' английском',"", r1) r1 = re.sub(r'[""]',"", r1) #choose a word r2 = ts.google(r1, 'ru', 'en').lower() try: answ = write[r1] print("\tI know the answer on" + str(r1) + ' is: ' + str(answ)) pyautogui.click(928, 566) pyperclip.copy(answ) pyautogui.hotkey('ctrl', 'v') pyautogui.click(1362, 972) except KeyError: print("\ti trying by myslef") pyautogui.click(928, 566) pyperclip.copy(r2) pyautogui.hotkey('ctrl', 'v') pyautogui.click(1362, 972) time.sleep(.5) if not Checker.check(): pyautogui.moveTo(576, 955) pyautogui.dragTo(1156, 971, duration=0.5) # drag mouse to XY time.sleep(0.5) pyautogui.hotkey('ctrl', 'c') time.sleep(0.2) ru_en[text] = (str)(pyperclip.paste()) print("\tI don't know the answer,but at the next time i will answer: " + str(ru_en[text])) File_Magager.write(write,'write') pyautogui.click(1358, 967) else: pyautogui.click(1358, 967)
def choose(arr): print("start choose") r1 = re.sub('Отметьте слово ',"", arr) r2 = re.sub(r"[«»]","", r1) #choose a word r2 = ts.google(r2, 'ru', 'en').lower() pyautogui.moveTo(1319, 677) pyautogui.dragTo(703, 617, duration=0.3) # drag mouse to XY time.sleep(0.5) pyautogui.hotkey('ctrl', 'c') time.sleep(0.2) text = (str)(pyperclip.paste()) result2 = re.sub('\d'," ", text) result3 = result2.split() if(result3[0] == r2): pyautogui.click(771, 563) elif(result3[1] == r2): pyautogui.click(970, 589) else: pyautogui.click(1146, 576) if Checker.check(): pyautogui.click(1358, 967) else: pyautogui.click(1358, 967)
def do_trans(to_trans): for zh in to_trans: print(zh) if zh in done_trans: print('in done trans, continue') continue res = es.search(index='pekall-py-trans-zh-en', body={"query": { "term": { "zh": { "value": zh } } }}) if res['hits']['hits']: print("found in es, continue") else: print(f"no hits, google trans: {zh}") # time.sleep(1) en = ts.google(zh, 'zh', 'en') print(f'en is {en}') res = es.index( index='pekall-py-trans-zh-en', body={ 'zh': zh, # 'en': translator.translate(zh) 'en': en }) done_trans.add(zh)
def sort_data(rockets: list, mode: bool): """ Сортировать данные по опр. моду, который передаётся в функции get_data, если mode равен True, то сортировка происходит по алгоритму для json формата, если mode равен False, то сортировка происходит по алгоритму для бд формата Json сортировка: [(*name*,..., *перевод описания ракеты*,...),(*name*,..., *перевод описания ракеты*,...),...] Бд сортировка: из [<Rocket(*name*,...)>, <Rocket(*name*,...)>,...] в [(*name*,...),(*name*,...),...] """ sort_rockets = [] if mode: for rocket in rockets: # sort_rocket = name, height, diam, mass, fuel, desc, wiki sort_rocket = (rocket['name'], rocket['height']['meters'], rocket['diameter']['meters'], rocket['mass']['kg'], rocket['engines']['propellant_1'] + '\n' + rocket['engines']['propellant_2'], translators.google(rocket['description'].lower(), from_language='en', to_language='ru'), rocket['wikipedia']) sort_rockets.append(sort_rocket) ui.create_table(sort_rockets, False) else: for rocket in rockets: local_sort = (rocket.name, rocket.height, rocket.diam, rocket.mass, rocket.fuel, rocket.desc, rocket.wiki) sort_rockets.append(local_sort) ui.create_table(sort_rockets, True)
def post(self): post_data = request.get_json() input_text = post_data.get('text', None) text = ts.google(input_text) return {'result': text}, 200
def trans(list1): mylist = [] for i in range(len(list1)): chi_eng_google = ts.google(list1[i], 'zh-CN', 'en') mylist.append(chi_eng_google) result = str(" ".join(mylist)) + '\n' return result
def translate_to_cn(self, input:str) -> str: if self._translator == 'google': return (tl.google(input, if_use_cn_host=False, to_language='zh-CN')) if self._translator == 'bing': return (tl.bing(input, if_use_cn_host=False, to_language='zh-CN')) else: print("Error: no translator claimed!")
def translate_text(self, text): if self.translator == "google": return ts.google(text, to_language=self.to_language) elif self.translator == "bing": return ts.bing(text, to_language=self.to_language) elif self.translator == "google_separate": return self.google_separate.translate(text=text, dest=self.to_language).text elif self.translator == "microsoft": params = {'appid': 'Bearer ' + self.token, 'text': text, 'to': self.to_language} requestHeader = {'Accept': 'application/xml'} responseResult = requests.get(self.translateUrl, params=params, headers=requestHeader) soup = BeautifulSoup(responseResult.text, "lxml") return colored(soup.get_text()) elif self.translator == "sogou": return ts.sogou(text, to_language=self.to_language) elif self.translator == "baidu": return ts.baidu(text, to_language=self.to_language) elif self.translator == "alibaba": return ts.alibaba(text, to_language=self.to_language) elif self.translator == "tencent": return ts.tencent(text, to_language=self.to_language) elif self.translator == "youdao": return ts.youdao(text, to_language=self.to_language) elif self.translator == "deepl": return ts.deepl(text, to_language=self.to_language)
def trans(): Speak("Speak to translate") text = takecommand() Speak("In which language") lan = takecommand() if 'hindi' in lan: ty = gTTS(ts.google(text, from_language='en', to_language="hi")) # you can add any language ty.save(f"{text}.mp3") playsound.playsound(f"{text}.mp3") os.remove(f"{text}.mp3") if 'marathi' in lan: ty = gTTS(ts.google(text, from_language='en', to_language="mr")) ty.save(f"{text}.mp3") playsound.playsound(f"{text}.mp3") os.remove(f"{text}.mp3")
def translate_the_string(text, to, from_what, server): try: if server == 'b': return ts.bing(text, from_what, to) else: return ts.google(text, from_what, to) except Exception as e: return 'Sorry, Following Error Occured\n{}'.format(e)
def auto(self, text) -> str: self.text = text return str( ts.google( self.text, from_language=self.from_language, to_language=self.to_language, ))
def tr_cmd(cls, ctx): chat = cls.bot.get_chat(ctx.msg) if not ctx.text: chat.send_text(cls.description) else: l1, l2, text = ctx.text.split(maxsplit=2) chat.send_text(ts.google(text=text, from_language=l1, to_language=l2, host='https://translate.google.com'))
def write_ui(): eng_txt = st.text_input( 'Enter any sentence below and hit Enter', value= "India's national language Hindi, and Pakistan's national language Urdu are almost the same." ) if not eng_txt: return converters = get_converters() outputs = { 'hi': ts.google(eng_txt, from_language='auto', to_language='hi'), 'ur': ts.google(eng_txt, from_language='auto', to_language='ur'), } outputs['h2u'] = converters['hi2ur'].transform(outputs['hi']) outputs['u2h'] = converters['ur2hi'].transform(outputs['ur']) outputs['h2e'] = converters['hi2en'].transform(outputs['hi']) outputs['u2e'] = converters['ur2en'].transform(outputs['ur']) write_matrix(outputs)
def google_block(eng_qns): # translate the English question to Chinese using Google eng_chi_google = ts.google(eng_qns, 'en', 'zh-CN') # the list of questions translated from Chinese to English the_list = [] # Google chi_eng_google = ts.google(eng_chi_google, 'zh', 'en') the_list.append(chi_eng_google) # Bing translator = Translator(from_lang="zh", to_lang="en") chi_eng_bing = translator.translate(eng_chi_google) the_list.append(chi_eng_bing) # Youdao chi_eng_youdao = ts.youdao(eng_chi_google, 'zh', 'en') the_list.append(chi_eng_youdao) # Tencent chi_eng_tencent = ts.tencent(eng_chi_google, 'zh', 'en') the_list.append(chi_eng_tencent) return the_list
def translate(text='hello', to_lang='english'): lang_key = { 'english': 'en', 'tamil': 'ta', 'french': 'fr', 'spanish': 'es' } return translators.google(text, if_use_cn_host=True, to_language=lang_key[to_lang])
def translate(text): try: # print(text) t = ts.google(text, to_language='hi') t = t.replace("\n", " ") # print(t) return t except: print( "--------------------OOPS (stop and try again)---------------------" ) return ""
def send_indicators(message): text = message.text if text[0] == '.': text = text.split('.') with rq.Session() as se: se.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36", "Accept-Encoding": "gzip, deflate", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Language": "en" } # ticker = input("Enter ticker: ") link = 'https://finviz.com/quote.ashx?t=' + str(text[1]) response = se.get(link) soup = BeautifulSoup(response.text, 'lxml') print(soup.title.text, '\n') marketCap = soup.find('td', text='Market Cap').find_next() PE = soup.find('td', text='P/E').find_next() PS = soup.find('td', text='P/S').find_next() PB = soup.find('td', text='P/B').find_next() ROE = soup.find('td', text='ROE').find_next() ROA = soup.find('td', text='Debt/Eq').find_next() shortFloat = soup.find('td', text='Short Float').find_next() recom = soup.find('td', text='Recom').find_next() recom = float(recom.text) if recom >=1 and recom <3: recom = "ПОКУПАТЬ" elif recom >=3 and recom <4: recom = "ДЕРЖАТЬ" elif recom>=4 and recom <=5: recom = "ПРОДАВАТЬ" introAboutComp = soup.find('td', attrs={'class': 'fullview-profile'}) link = soup.find('table', attrs={'class': 'fullview-title'}).find('a', attrs={'class': 'tab-link'}) marketCap = 'Market Cap: ' + marketCap.text print(marketCap) pe = 'P/E: ' + PE.text + '\n' ps = 'P/S: ' + PS.text + '\n' pb = 'P/B: ' + PB.text + '\n' roe = 'ROE: ' + ROE.text + '\n' roa = 'ROA: ' + ROA.text + '\n' shortFloat = 'Short Float: ' + shortFloat.text + '\n' recom = 'recom: ' + recom + '\n' link = 'link: ' + link['href'] + '\n' introAboutComp = '\n' + ts.google(introAboutComp.text, to_language='ru') + '\n' text = marketCap + pe + ps + pb + roe + roa + shortFloat + recom + link bot.send_message(message.chat.id, text)
def trans_late(_, msg): #new_text = '' orig_text = msg.text.split(".translate ", maxsplit=1)[1] #new_text = translator.translate(orig_text, dest='ru') new_text = ts.google(orig_text, to_language=tr_lang) #print(tr_lang) ret_str = "**Original:**\n" ret_str += orig_text ret_str += '\n' ret_str += "**Translation:**\n" ret_str += str(new_text) #print(ret_str) msg.edit(ret_str)
def translate(text, mc_locale): locale_code = mc_to_google_locale_dict[mc_locale] if locale_code == "": print("No translation available") return "No translation available" else: split_text = camel_case_split(text) translated_text = ts.google(split_text, from_language="en", to_language=locale_code) translated_text = camel_case_join(translated_text) print(f"{split_text} translated to {translated_text}") return translated_text