def translate(self): #prepare the translate environment translator = Translator(self.client_id, self.client_secret) #prepare the phantom server driver = webdriver.PhantomJS() print("server ready") for i in range(1, self.linkcount + 1): link = self.weblinkdic[i] driver.get(link) time.sleep(3) print("get link") description = driver.find_element_by_tag_name("body").text print(link) g = open("../translate/" + str(i) + ".txt", 'w+') for line in description.split('\n'): if len(line) > 5: line = line.strip() try: trans_line = translator.translate(line, 'zh-CHS', 'en') except: sys.exit("Error message") g.write(line + '\n') g.write(trans_line + '\n') g.close() driver.close() return
def translate(entities): message = "" try: text_for_translation = entities['phrase_to_translate'][0]['value'] lang = entities['language'][0]['value'].lower() language = "" if lang == "spanish": language = "es" elif lang == "french": language = "fr" elif lang == "german": language = "de" elif lang == "chinese": language = "zh-CHS" else: message = "We don't support translation to " + lang + " as of now. Check back later as support is being added." return message message = "\"" + text_for_translation + "\" in " + lang + " is \'" translator = Translator( 'SMSAssistant', 'fhV+AdYFiK0QfQ4PFys+oQ/T0xiBBVQa32kxxbP55Ks=') message += translator.translate(text_for_translation, language) + "\'" if test_mode: send_sms_to_admin(message) except: message = technical_issues() return message
def translate_text(request): language_from = request.GET.get('from', None) language_to = request.GET.get('to', None) text = request.GET.get('text', None) if language_from == language_to: data = {'success': True, 'translation': text} else: # run the translation: if getattr(rosetta_settings, 'GOOGLE_TRANSLATE', False): import goslate translator = goslate.Goslate() else: AZURE_CLIENT_ID = getattr(settings, 'AZURE_CLIENT_ID', None) AZURE_CLIENT_SECRET = getattr(settings, 'AZURE_CLIENT_SECRET', None) translator = Translator(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET) try: translated_text = translator.translate(text, language_to, language_from) data = {'success': True, 'translation': translated_text} except TranslateApiException as e: data = { 'success': False, 'error': "Translation API Exception: {0}".format(e.message) } return HttpResponse(json.dumps(data), content_type='application/json')
def translate(self): #prepare the translate environment client_id = self.variable.get() client_secret = self.userpasswd[client_id] translator = Translator(client_id, client_secret) #prepare the phantom server driver = webdriver.PhantomJS() for i in range(1,2): link = self.weblinkdic[i] driver.get(link) time.sleep(3) description = driver.find_element_by_tag_name("body").text #find_element_by_id #find_element_by_css_selector print(link) g = open("../translate/" +str(i)+".txt", 'w+') for line in description.split('\n'): if len(line)>5: line = line.strip() try: trans_line = translator.translate(line, 'zh-CHS', 'en') except: sys.exit("Error message") g.write(trans_line + '\n') g.close() driver.close() return
def run(): """Main function to query Microsoft Translator API and translate words :return: """ try: client_id = getenv('MS_TRANSLATOR_CLIENT_ID', None) api_key = getenv('MS_TRANSLATOR_API_KEY', None) if not api_key: client_id = str(raw_input('Microsoft Translator Client ID: ')) api_key = str(raw_input('Microsoft Translator API Key: ')) if client_id and api_key: translator = Translator(client_id, api_key) en_word_list = read_word_list() result_matrix = [] for lang in translator.get_languages(): # result = get_translated_text(en_word_list, lang, client_id, api_key) result_matrix.append(result) # Transpose the matrix for csv writer to_write_matrix = [list(i) for i in zip(*result_matrix)] write_result(to_write_matrix) except: sys.exit(2)
def __init__(self, client_key, language, low, high, language_blacklist): self.language = language self.translator = Translator(client_key) self.languages = set(self.translator.get_languages()) - language_blacklist self.low = low self.high = high
def translate_text(request): language_from = request.GET.get('from', None) language_to = request.GET.get('to', None) text = request.GET.get('text', None) if language_from == language_to: data = {'success': True, 'translation': text} else: # run the translation: AZURE_CLIENT_ID = getattr(settings, 'AZURE_CLIENT_ID', None) AZURE_CLIENT_SECRET = getattr(settings, 'AZURE_CLIENT_SECRET', None) translator = Translator(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET) try: translated_text = translator.translate(text, language_to, language_from) data = {'success': True, 'translation': translated_text} except TranslateApiException as e: data = { 'success': False, 'error': "Translation API Exception: {0}".format(e.message), } return JsonResponse(data)
def translate_text(request): if RosettaSettings.instance().readonly: data = {'success': False, 'error': 'System in readonly mode. Please try later.'} else: language_from = request.GET.get('from', None) language_to = request.GET.get('to', None) text = request.GET.get('text', None) if language_from == language_to: data = {'success': True, 'translation': text} else: # run the translation: AZURE_CLIENT_ID = getattr(settings, 'AZURE_CLIENT_ID', None) AZURE_CLIENT_SECRET = getattr(settings, 'AZURE_CLIENT_SECRET', None) translator = Translator(AZURE_CLIENT_ID, AZURE_CLIENT_SECRET) try: translated_text = translator.translate(text, language_to, language_from) data = {'success': True, 'translation': translated_text} except TranslateApiException as e: data = {'success': False, 'error': "Translation API Exception: {0}".format(e.message)} return HttpResponse(json.dumps(data), content_type='application/json')
def run_command(msg, *args): """Displays a 'enjoy your meal' message in a random language""" lang_code, country = jabberbot.locale.random() meal = 'Enjoy your meal' translator = Translator(trans_client_id, trans_client_sec) translated = translator.translate(meal, lang_code) meal = '{} (translated to {})'.format(translated, country) return 'groupchat', meal
def example_mstranslator(): """ Ref: https://github.com/wronglink/mstranslator/blob/master/mstranslator.py """ from mstranslator import Translator translator = Translator('ecnu_translator', 'sc6x4pJQDBtyqmGhhRmOknjeeXcL1YGBUTkvZLtn62k=') print(translator.translate('Привет, мир!', lang_from='ru', lang_to='en'))
def C3POTranslate(c3pouser, c3pomessage, c3pochannel): translator = Translator('c3po', 'KgKKwR+UILpk0IUlZ0VaZTtBbOrXFqzsgit8y8jNK3M=') message = c3pomessage.split(' ', 1)[1] language = 'en' translated = translator.translate(message, language) print sc.api_call("chat.postMessage", as_user="******", channel=c3pochannel, text=translated)
def translate_bing(text, in_lang, out_lang, bot): if not bot.config.has_option('translate', 'bing_user') or not bot.config.has_option('translate', 'bing_pass'): return 'No se ha habilitado el uso de bing en este bot!' else: user = bot.config.translate.bing_user password = bot.config.translate.bing_pass translator = Translator(user, password) if in_lang == 'auto': return translator.translate(text, out_lang) else: return translator.translate(text, out_lang, in_lang)
def run_command(msg, *args): """Sends a happy birthday in an random language greeting You can add a nickname: bday <nick> """ lang_code, country = jabberbot.locale.random() greet = 'Happy birthday to you' translator = Translator(trans_client_id, trans_client_sec) translated = translator.translate(greet, lang_code) mtype = 'groupchat' if args: return mtype, '{} @{} (translated to {})'.format( translated, ' '.join(args), country) return mtype, '{} (translated to {})'.format(translated, country)
def read_entry(entry): session_attributes = {} reprompt_text = None should_end_session = True speech_output = '' translator = Translator('wykopalexa', 'Y3ThYcaJRUm0Y2zfF0oTlz92c3UDIaDKup+KD7Ror3k=') entryText = re.sub('<[^<]+?>', '', entry['body']) speech_output = translator.translate(entryText, 'en-us', 'pl') return build_response( session_attributes, build_speechlet_response('wykop', speech_output, reprompt_text, should_end_session))
def init_translate(): aBasePath = os.getcwd() sourcePath = aBasePath + "/assets/BingCredentials" fileObj1 = open(sourcePath + '/bingClientId.txt', 'r') client_id = fileObj1.read().strip("\n\r") fileObj1.close() # print (type(client_id), client_id) fileObj2 = open(sourcePath + '/bingClientSecret.txt', 'r') client_secret = fileObj2.read().strip("\n\r") fileObj2.close() # print (type(client_secret), client_secret) client = Translator(client_id, client_secret, debug=False) return client
def translate_Bing(text): ''' This method translates a text string to english with the Microsoft Bing_translator. Note that this translator only translates 2.000.000 Letters / Month for free using a Microsoft account and the registered client with secret. :param text: String that is to be translated :return: english translation of the text ''' client_id = 'EuropenaTranslator' client_secret = 'iAcywBlP37WpSs/qxNVdlCOjVXYSti+L9YTUvBx4ets=' translator = Translator(client_id, client_secret) text4translation = translator.translate(text, 'en') return text4translation
def init(recordToSkip=0): global translator translator = Translator('shalabh', '6Af7+rQSZl+Jqb/y4W0/QP196VkT+fiSMyoKRXBp8Y8=') client=MongoClient() db=client['yelp'] reviewTable=db['reviewData'] collection = db['converted_reviews'] count=0 #gs = goslate.Goslate() for line in file: count+=1 print count if count<=recordToSkip: continue record={} arr=line.replace("\n","").split(':') id=str(arr[0]) lng=str(arr[1]) if lng in langList: time.sleep(1) #print count find={"review_id":id} for review in reviewTable.find(find): text=review["text"] stars=review["stars"] #print text.encode('utf-8') time.sleep(1) if(len(text)>546): arr1=text.split(".") translated_text="" for item in arr1: translated_text= translated_text+". "+MyTranslator.translate(item.replace("\n","").encode('utf-8'), "en", lng) else: translated_text= MyTranslator.translate(text.replace("\n","").encode('utf-8'), "en", lng) print "===========================" #translated_text= MyTranslator.translate(text.replace("\n","").encode('utf-8'), "en", lng) time.sleep(1) #print translated_text record.update({'review_id':id}) record.update({'lng':lng}) record.update({'translation':translated_text}) record.update({'stars':stars}) collection.insert_one(record).inserted_id print count," record inserted" print "============================="
def translate(): if not request.json: abort(make_response(jsonify(message="Bad zapros"), 400)) # sanitize html data = bleach.clean(request.json['text']) if len(data) > 400: abort(make_response(jsonify(message="Slishkom long stroka"), 400)) splitted_original = re.split('(\W+)', data, flags=re.UNICODE) # transliterate flag. if true - the world will be transliterated transliterate_flag = True word_regex = re.compile('\w+', re.U) # array indexes of the words that will be really translated # used to put the translated words back in their places to_translate_indexes = [] # array of the words that will be translated to_translate = [] for i in range(0, len(splitted_original)): # if is's a word, not a comma, or space or whatever if re.match(word_regex, splitted_original[i]): # transliterate it or push in array for translation if transliterate_flag: splitted_original[i] = translit(splitted_original[i], 'ru', reversed=True) else: to_translate_indexes.append(i) to_translate.append(splitted_original[i]) transliterate_flag = not transliterate_flag translated = [{}] try: # translate the words translator = Translator(app.config['TRANSLATOR_ID'], app.config['TRANSLATOR_SECRET']) translated = translator.translate_array(to_translate, 'en', 'ru') except Exception as e: abort(make_response(jsonify(message="Try again popozhe"), 500)) # put the translated words back using the to_translate_indexes array for z in range(0, len(to_translate_indexes)): t = translated[z]['TranslatedText'] splitted_original[to_translate_indexes[z]] = t res = ''.join(splitted_original) return jsonify(translation=res, status=200)
def speakCaption(): filename = str(datetime.now()) + ".png" os.rename("./pepper_picture/now.png", "./pepper_picture/" + filename) print "Creating caption..." script = 'curl -F "file=@./pepper_picture/' + filename + '" localhost:8000' result = commands.getoutput(script).split("\n")[3] print result print "Translating..." translator = Translator('Your client ID', 'Your client secret') #change this line result = translator.translate(result, "ja") print result print "Creating wav.file with Rospeex and preparing speech..." tts_command = { "method": "speak", "params": [ "1.1", { "language": "ja", "text": result, "voiceType": "*", "audioType": "audio/x-wav" } ] } obj_command = json.dumps(tts_command) # string to json object req = urllib2.Request(tts_url, obj_command) received = urllib2.urlopen(req).read() # get data from server obj_received = json.loads(received) tmp = obj_received['result']['audio'] # extract result->audio speech = base64.decodestring(tmp.encode('utf-8')) f = open("./result_voice/out.wav", 'wb') f.write(speech) f.close commands.getoutput('aplay ./result_voice/out.wav')
def translate(text, language): global translator for i in range(5): try: translation = translator.translate(text, language) if 'ArgumentException' in translation: raise Exception(translation) return re.sub(u'peer.fm', u'Peer.fm', translation, flags=re.IGNORECASE) except Exception, e: f = open('translate.log', 'w+') f.write(str(e)) f.close() time.sleep(20) translator = Translator( 'peerfm', 'bJHtNJK4zTLAGtaoyxnO5wI1N3XHN8Fygz2pEn11WTQ=')
def translate(self): #prepare the translate environment client_id = self.variable.get() client_secret = self.userpasswd[client_id] translator = Translator(client_id, client_secret) #prepare the phantom server #driver = webdriver.PhantomJS() #print("server ready") for i in range(1, 20): link = self.weblinkdic[i] try: html = urlopen(link) bsObj = BeautifulSoup(html.read()) description = bsObj.p.get_text().encode('utf-8') print(description) print(link) g = open("../translate/" + str(i) + ".txt", 'w+') for line in description.split('\n'): if len(line) > 5: line = line.strip() try: trans_line = translator.translate( line, 'zh-CHS', 'en') g.write(trans_line + '\n') except: sys.exit("Error message") g.close() except: sys.exit("Error Message") return
def __init__(self): self.translator = Translator(client_id, client_secret) self.langs = self.translator.get_languages()
#!/usr/bin/env python # -*- coding: utf-8 -*- from microsofttranslator import Translator # if this fails, do: # sudo easy_install microsofttranslator from ref_definitions2 import read_all_the_files translator = Translator('finalproj', 'LZTVKNyxQEjmIUbMWp1HhkN4x9XkIbnT6fHhaJfLFmo=') #print translator.translate('你好'.decode('utf8'), 'en', 'zh-CHT') (chinese_sentences, english_sentences) = read_all_the_files() of = open('bing_translations.txt', 'w') for chinese_sent in chinese_sentences: chinese_sent = ''.join([x for x in chinese_sent if x != ' ']) print >> of, chinese_sent print >> of, translator.translate(chinese_sent.decode('utf8'), 'en', 'zh-CHT').encode('utf-8') print >> of, '=========='
from microsofttranslator import Translator import csv t = Translator("WWEB", "ml7-win-wilson-eric-bernie") # ClientID,Client Secret words = open("words.csv").readlines() words = [word.strip() for word in words] with open("engToSpan.csv", "w") as csvfile: writer = csv.writer(csvfile, delimiter="\n") for w in words: try: writer.writerow([w + "," + t.translate(w, "es").encode("utf-8")]) except: pass
# -*- coding: utf-8 -*- from microsofttranslator import Translator translator = Translator('celiacPass', '+gpq62pRXYbq0eAQVb6RhvO4qUpCZKGdaSi+Prov/og=') languages = translator.get_languages() f = open('country_codes_to_countries.txt') codeToTranslation = {} for line in f: code = line.split(' ')[0] codeToTranslation[code] = translator.translate('I have Celiac Disease, a very serious intolerance to gluten, which is found in wheat, oats, barley and rye.', code) print codeToTranslation
import urllib3 urllib3.disable_warnings() from urllib.parse import urlencode client = MongoClient("mongodb://localhost:27017/") MEDIA = "media" RNR = "ratingsAndReviews" from microsofttranslator import Translator CLIENTID = "rakeshthakurcmtoumtpmmm" CLIENTSECRETKEY = "YbssQ38GPYmB+cHTSjvIIBfsnWsqbWR66ehyqzfaors=" #CLIENTID="rinkyrakeshmmm" #CLIENTSECRETKEY="jVKqkdvFBh/l4VqODl9t+GF1LPCh+e0ZNfc4J2QlKik=" translator = Translator(CLIENTID, CLIENTSECRETKEY) LOG_FILENAME = './logs/RnRSentimentAnalysis.log' #FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) logging.info('Initialization done...') def arrayDump(arr, filename): jarr = [] for rec in arr: jarr.append({"text": rec}) print(jarr) with open(filename, 'w') as f: json.dumps(jarr, f)
import os import re from microsofttranslator import Translator import sys client_id = "boliu" client_secret = "pwfbBe660uJoi0yQrfyCurzfhoXYsNRkXhmaocNKInY=" translator = Translator(client_id, client_secret) def translate(filename): print(filename) f = open("./detail_org/" + filename, 'r+') g = open("./detail_org_ch/ch_" + filename, 'w+') for line in f.readlines(): line = line.strip() trans_line = translator.translate(line, 'zh-CHS', 'en') g.write(trans_line + '\n') f.close() g.close() def get_file(): filelist = os.listdir("./detail_org") for item in filelist: if item.endswith(".txt"): translate(item)
def processRequest(req): #for wolfram alpha if req.get("result").get("action") == "fact": client = wolframalpha.Client("4393W5-W6E838H957") john = client.query(req.get("result").get("resolvedQuery")) answer = next(john.results).text return { "speech": answer, "displayText": answer, "source": "From wolfram_alpha" } #translator #uses microsoft translator api USE your key here elif req.get("result").get("action") == "tran": translator = Translator( '''jkthaha''', '''syosNIlEOJnlLByQGcMS+AIin0iaNERaQVltQvJS6Jg=''') try: s = translator.translate( req.get("result").get("parameters").get("question"), req.get("result").get("parameters").get("language")) res = makeWebhookResult(s) return res except: res = makeWebhookResult("Server busy, please try again later") return res #for news #takes news randomly from different sources use newsapi docs for more info elif req.get("result").get("action") == "news": y = random.randint(1, 6) if y == 1: r = requests.get( 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 2: r = requests.get( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 3: r = requests.get( 'https://newsapi.org/v1/articles?source=independent&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 4: r = requests.get( 'https://newsapi.org/v1/articles?source=bbc-sport&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines from bbc sports: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 5: r = requests.get( 'https://newsapi.org/v1/articles?source=ars-technica&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 6: r = requests.get( 'https://newsapi.org/v1/articles?source=the-hindu&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res #for wikipedia elif req.get("result").get("action") == "wiki": param = req.get("result").get("parameters").get("any") fin = wikipedia.summary(param, sentences=2) res = makeWebhookResult(fin) return res #for local time elif req.get("result").get("action") == "time": app_id = "4393W5-W6E838H957" client = wolframalpha.Client(app_id) john = client.query("time in bangalore") answer = next(john.results).text res = makeWebhookResult(answer) return res #for weather (yahoo api) elif req.get("result").get("action") == "yahooWeatherForecast": baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = makeYqlQuery(req) if yql_query is None: return {} yql_url = baseurl + urllib.urlencode({'q': yql_query}) + "&format=json" result = urllib.urlopen(yql_url).read() data = json.loads(result) res = makeWebhookResult1(data) return res #for dictionary else: dictionary = PyDictionary() ch = req.get('result').get('parameters').get('word') test = req.get('result').get('parameters').get('dictionary') if test == 'antonym': res = dictionary.antonym(ch) try: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}, {3}, {4}.".format( res[0], res[1], res[2], res[3], res[4]) except: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}, {3}.".format( res[0], res[1], res[2], res[3]) except: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}.".format( res[0], res[1], res[2]) except: answer = "Antonym for the word " + ch + " are: {0}, {1}.".format( res[0], res[1]) except: answer = "There is no antonym for this word" return makeWebhookResult(answer) elif test == 'definition': re1s = dictionary.meaning(ch) try: try: answer = "The word {0} is a verb and its meaning is {1}".format( ch, re1s['Verb']) except: try: answer = "The word {0} is a noun and its meaning is {1}".format( ch, re1s['Noun']) except: answer = "The word {0} is an adjective and its meaning is {1}".format( ch, re1s['Adjective']) except: answer = re1s return makeWebhookResult(answer) elif test == 'synonym': res = dictionary.synonym(ch) try: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}, {3}, {4}.".format( res[0], res[1], res[2], res[3], res[4]) except: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}, {3}.".format( res[0], res[1], res[2], res[3]) except: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}.".format( res[0], res[1], res[2]) except: answer = "Synonym for the word " + ch + " are: {0}, {1}.".format( res[0], res[1]) return makeWebhookResult(answer) except: answer = "There is no Synonym for this word" return makeWebhookResult(answer)
def __init__(self, logger): self.bing = Translator('l2a', '9W6zDb3DBJ77SCjWPOHZsp5y75j5gJvu0z0pjn9zdHk=') self.logger = logger.getChild(__name__)
def translate(tag, language): """ returns lower-case tag translated into language """ translator = Translator(MS_CLIENT_ID, MS_SECRET_KEY) return translator.translate(tag, language).lower()