def doTranslate(self):
        openDirName = self.getOpenFileName()
        trans = Translator(to_lang="ko")
        trans.from_lang = self.lang_code[str(self.cb_fromLang.currentText())]
        self.label.setText("Under translating")
        for langCode in self.lang_code.keys():
            try:
                writeFile = open(openDirName+"\\"+langCode+"_"+self.originalFileName,'w')
                transResult=''
                trans.to_lang = self.lang_code[langCode]
                for line in self.readText:
                    try:
                        transResult += trans.translate(line).encode('utf-8')+"\n"
                    except:
                        transResult += trans.translate(line)+'\n'
                writeFile.write(transResult)
                writeFile.close()
            except:
                print langCode
                print self.readText
                break

        self.label.setText("Working done")
示例#2
0
	def twist(self, in_message):
		start_lang = 'en'
		last_lang = 'en'
		sentence =  in_message
		turns = 20

		first_step = ''

		for lang in range(len(lang_array)):
			if start_lang == lang_array[lang][1]:
				first_step += (lang_array[lang][0])

		steps = []
		for turn in range(turns):
			rand_int = r.randint(0,len(lang_array)-1)
			rand_lang = lang_array[rand_int][1]
			translator = Translator(to_lang = rand_lang, from_lang = last_lang)
			sentence = translator.translate(sentence)
			if sys.version_info.major == 2:
				sentence =sentence.encode(locale.getpreferredencoding())
			steps.append([sentence, rand_lang])
			print(str(turn + 1)+ '/' + str(turns) + ' (' + lang_array[rand_int][0] + ')')
			last_lang = rand_lang
		translator = Translator(to_lang = start_lang, from_lang = last_lang)
		sentence = translator.translate(sentence)
		sentence = sentence.capitalize()
		sentence = sentence.replace(' ,', ',')
		sentence = sentence.replace(' .', '.')
		sentence = sentence.replace(' \'', '\'')
		if sentence[len(sentence) - 1] != '.':
			sentence += '.'
		# print('\n' + steps)
		# print('\n' + sentence)
		return [steps, sentence]
示例#3
0
def translate_excel():
    outfile = open("english_cv.md",'w')
    
    translator= Translator(from_lang="zh",to_lang="en")

    # sXXX for SOURCExxx
    sbook = open_workbook('source.xls',formatting_info= False )
    # tXXX means translatedXXX
    tbook = Workbook(encoding='utf-8')#write
    
    # read and write per sheet
    book_content = []
    for s in sbook.sheets():# s is a source sheet handle for read
        
        #add sheet
        try:
            utf_name = s.name.encode('utf8') #sheet names are all in unicode, translation need utf8
            tsheet_name = translator.translate(utf_name) #translator.translate method only accepts utf-8
            print s.name,tsheet_name
            tsheet = tbook.add_sheet(tsheet_name) # write sheet in tbook, name in english
            print_title(tsheet_name,outfile)#write
        except:
            print "error in sheet:",s.name,"\n"
            print_title(s.name,outfile)
            
        #add content
        
        rows_content = []
        for row in range(s.nrows):
            print "row:",row
            col_content = []
            for col in range(s.ncols):
                try:
                    utf_cell = s.cell(row,col).value.encode('utf8')
                    tcell_value = translator.translate(utf_cell)
                    tsheet.write(row,col,tcell_value)
                    col_content.append(tcell_value)
                except: #the value might be float
                    # print "row:",row,"col:",col,s.cell(row,col).value
                    # tsheet.write(row,col,s.cell(row,col).value)
                    
                    nontexts = s.cell(row,col).value
                    col_content.append(str(nontexts))
            row_value = "\t".join(col_content)
            rows_content.append(row_value)
            tsheet.flush_row_data()
            
        try:
            sheet_txt = "\n".join(rows_content).encode('utf8')
        except:
            sheet_txt = "\n".join(rows_content)
        all_lines = invert_txt_table(sheet_txt)
        print_table(all_lines,outfile)

    outfile.close()
    
    print "saving..."
    tbook.save('english_output.xls')
    print "saved."
示例#4
0
def main():
    arguements = docopt(
        data_io.set_up_doc(__doc__),
        version='0.1'
    )

    record = Record(debug=arguements['--debug'])
    if arguements['<data>']:
        # translation
        from_lang, to_lang, data = _extract(arguements)

        # translate data
        translator = Translator(from_lang, to_lang, data,
                                debug=arguements['--debug'])
        # result is a dictionary contains decoded infomation of the
        # trnaslation.
        result = translator.translate()
        translator.display_result(result)
        # add record
        record.add(from_lang, to_lang,
                   data, result)

    elif arguements['--record']:
        # display record
        record.display()
    else:
        raise Exception('No Implemented Yet.')
示例#5
0
def trans(flag,lang,word,delim):
  try:
    langNAme,langReq = word.split(delim,1)
    length=len(langReq)
    if ( length > maxLength):
      sc.api_call('chat.postMessage', 
                   username='******', 
                   icon_url=flag,  
                   as_user='******', 
                   channel=evt["channel"], 
                   text='Don\'t be a dick <@'+evt["user"]+'>')
    else:
      translator= Translator(to_lang=lang)
      l = translator.translate(langReq)
      sc.api_call('chat.postMessage', 
                   username='******', 
                   icon_emoji=flag,
                   as_user='******', 
                   channel=evt["channel"], 
                   text=l)
  except ValueError:
    sc.api_call('chat.postMessage', 
                 username='******', 
                 icon_url=flag,
                 as_user='******', 
                 channel=evt["channel"], 
                 text='Vhy try to anger botiana <@'+evt["user"]+'>?')
示例#6
0
def process(source, outfile, _filter):
    if os.path.isfile(source):
        deny = []
        with open(_filter, 'r') as filter:
            for line in filter:
                deny.append(line.replace('\n', '').replace('\r', ''))
        tmp = []
        words = {}
        with open(source, 'r') as source:
            with open(outfile, 'w') as dic:
                for str in source:
                    tmp = normalize(str).split(' ')
                    for word in tmp:
                        if len(word) > 2:
                            if words.get(word):
                                words[word] += 1
                            else:
                                words[word] = 1
                # print words
                translator = Translator(to_lang="ru")
                for key, value in sorted(words.iteritems(), key=lambda (k, v): (v, k)):
                    if key not in deny:
                        dic.write(key + ' - ' + translator.translate(key).encode("utf8") + '\n')
                        # print "%s: %s" % (key, value)
    else:
        print 'Plese input correctly data for <source>!'
示例#7
0
def ask_mapping(token_list):
    "Asks the user for a mapping"
    translation_name = input('Enter code of target language("hi" for hindi): ')
    translation_name = translation_name.upper().strip()
    translator = Translator(to_lang=translation_name)
    mapping = {}
    for token in token_list:
        internal = False
        if token[:2] + token[-2:] == '____':
            token = token[2:-2]
            internal = True
        try:
            translation = translator.translate(token)
        except:
            print('>'*10, 'Token failed to translate :|', token + '|')
        translation = translation.replace(' ', '_').strip()
        if internal:
            token = '__' + token + '__'
            translation = '__' + translation + '__'
        mapped = {translation: token}
        print(mapped)
        mapping.update(mapped)
    f = open(translation_name, 'w')
    f.write(json.dumps(mapping,
                       ensure_ascii=False,
                       indent=4))
    f.close()
示例#8
0
class TestTranslator(unittest.TestCase):

    client_id = "<CLIENT_ID>"
    client_secret = "<CLIENT_SECRET>"

    def setUp(self):
        self.t = Translator(self.client_id, self.client_secret)

    def test_get_access_token(self):
        self.assertNotEqual(self.t.get_access_token(), "", "The access token is empty!")

    def test_translate(self):
        translated = self.t.translate("day", "en", "it")
        self.assertEqual(translated.lower(), "giorno", "The translated word is incorrect!")

        translated = self.t.translate("summer", "en", "ro")
        self.assertEqual(translated.lower(), "vara", "The translated word is incorrect!")
示例#9
0
def translate(string, fromlang, tolang):
    translator = Translator(from_lang=fromlang, to_lang=tolang)
    print "Translating from " + fromlang + " to " + tolang
    try:
        return translator.translate(string).encode("UTF-8")
    except Exception as e:
        print "HTTP Error. Translation failed. Please run the script again."
        sys.exit()
def trans_to_english(sentence, language):
    """
    Translate a sentece to English.
    """
    translator= Translator(from_lang=language, to_lang="en")
    translation = translator.translate(sentence)
    print(translation)
    return translation
示例#11
0
def index(request, source, target, text):
    trans = Translator(to_lang=target, from_lang=source)
    translation = trans.translate(text)
    # return HttpResponse(translation)

    return HttpResponse("""{ "data": { "translations": [ { "translatedText": "%s" } ] } }""" % translation)

# def index(request, text, source, target):
#     return HttpResponse("Hello, world. You're at the polls index.")
示例#12
0
def trans(request):
    if request.method == 'POST':
        inpu = request.POST.get('intext', '')
        translator= Translator(to_lang="fr")
        out = translator.translate(str(inpu))
        print out
        return HttpResponse(out)
    else:
         return render(request, 'personal/header.html')
示例#13
0
def __trans(flag, lang, message):
    try:
        if len(message) > MAX_TRANSLATE_LENGTH:
            resp = "Don't be a dick <@{}>".format(evt["user"])
            __send_response(resp, icon_ru)
        else:
            translator = Translator(to_lang=lang)
            l = translator.translate(message)
            __send_response(l, "emoji", flag)
    except ValueError:
        resp = 'Vhy try to anger {} <@{}>?'.format(BOT_NAME, evt["user"])
        __send_response(resp, icon_ru)
示例#14
0
def generate_release_names(num, names, translate=True, show_excluded=False):
    """Generate release names for Montréal Python edition

    num: amount of names to generate
    names: list of English names in format "Adjective Noun"
    translate: query google translate to provide French translation

    returns a tuple of two lists in format: (french names, english names)
    """
    en_names = []
    fr_names = []

    for en_name in sorted(names, key=len):
        if len(en_names) == num:
            break

        if not translate:
            en_names.append(en_name)
            continue

        translator = Translator(from_lang='en', to_lang='fr')
        fr_name = translator.translate(en_name).encode('utf8')

        # allow another run when the translated name
        # produces more than two words for our release name
        if len(fr_name.split(' ')) != 2:
            continue

        en_adj, en_noun = en_name.strip().split(' ')
        fr_adj, fr_noun = fr_name.strip().split(' ')

        # only keep release names for which one of the
        # translation's opposed word is a match.
        s_fr_adj = strip_accents(fr_adj.decode('utf8'))
        s_fr_noun = strip_accents(fr_noun.decode('utf8'))

        save = lambda l, adj, noun: l.append(' '.join([adj, noun]))
        if s_fr_adj == en_noun:
            # TODO: s_fr_adj is really french?
            save(en_names, en_adj, en_noun)
            save(fr_names, fr_adj, fr_noun)
            continue
        elif s_fr_noun == en_adj:
            # TODO: s_fr_noun is really french?
            save(en_names, en_adj, en_noun)
            save(fr_names, fr_adj, fr_noun)
            continue
        elif show_excluded:
            c = lambda c: ' '.join([w.capitalize() for w in c.split(' ')])
            print("excluded: %s (%s)" % (c(en_name), c(fr_name)))

    return fr_names, en_names
示例#15
0
文件: botiana.py 项目: rpkish/botiana
def __trans(flag, lang, message):
    try:
        if len(message) > MAX_TRANSLATE_LENGTH:
            resp = "Don't be a dick <@{}>".format(evt["user"])
            __send_response(resp, icon_ru)
        elif bot_mention in message:
            __send_response(msg_noop, icon_ru)
        else:
          if len(lang) > 2 and lang.find('|')!=-1:
              from_lang = lang.split("|")[0]
              to_lang = lang.split("|")[1]
              if len(from_lang) > 2 or len(to_lang) > 2:
                  __send_response(msg_noop, "emoji", ":flag-ru:")
              else:
                try:
                  translator = Translator(to_lang=to_lang, from_lang=from_lang)
                  if from_lang == "en":
                      flag = ":flag-us:"
                  else:
                      flag = ":flag-" + from_lang + ":"
                  l = translator.translate(message)
                  __send_response(l, "emoji", flag)
                except TypeError:
                  resp = 'hey <@{}>... {} don\'t speak that language.'.format(evt["user"],BOT_NAME)
                  __send_response(resp, icon_ru)
          elif len(lang) > 2:
              __send_response(msg_noop, "emoji", ":flag-ru:")
          else:
            try:
              translator = Translator(to_lang=lang)
              l = translator.translate(message)
              __send_response(l, "emoji", ":earth_americas:")
            except TypeError:
                angry()
    except ValueError:
        resp = 'Vhy try to anger {} <@{}>?'.format(BOT_NAME, evt["user"])
        __send_response(resp, icon_ru)
示例#16
0
    def setTargetCountry(self, targetcountrynames, language='es'):
        path = os.path.join(kmethods.__path__[0], 'new_country_db.json')
        translator = Translator(from_lang='en',to_lang='es')        
        
        hashtable = kgen.jload(path)
        
        targettable = dict()
        if(type(targetcountrynames)==list):            
            for n in targetcountrynames:
                try:
                    if(type(n)==unicode):
                        n = unicodedata.normalize('NFKD', n).encode('ascii','ignore').lower()
                    transn = translator.translate(n).lower()
                    targettable[n] = hashtable.pop(n)
                    if(hashtable.has_key(transn)):
                        targettable[transn] = hashtable.pop(transn)
                except:
                    print "name %s not found" % n
        elif(type(targetcountrynames)==str or type(targetcountrynames)==unicode):
            try:
                if(type(targetcountrynames)==unicode):
                    targetcountrynames = unicodedata.normalize('NFKD', targetcountrynames).encode('ascii','ignore').lower()
                transn = translator.translate(targetcountrynames).lower()
#                transn = u'm\u00e9xico'
                targettable[targetcountrynames] = hashtable.pop(targetcountrynames)
                if(hashtable.has_key(transn)):
                    targettable[transn] = hashtable.pop(transn)
            except:
                print "name %s not found" % targetcountrynames
        else:
            print "please input list or string"
            return
            
        allterms = [k for t in hashtable.values() for k in t.values()]
        self.NonTargetCountries = dict(zip(allterms, range(len(allterms))))
        alltargets = [k for t in targettable.values() for k in t.values()]
        self.TargetCountries = dict(zip(alltargets, range(len(alltargets))))
示例#17
0
def sms():
    text = request.form.get('Body', '')
    response = twiml.Response()
    text = text.strip()
    if text == 'HelpMe':
      response.sms("use 2 letter language code in this format for from and to ' from @to @message'")
    else: 
      text = text.split('@')  
      text[0] = text[0].strip()
      text[1] = text[1].strip()
      text[2] = text[2].strip()
      translator = Translator(to_lang=text[1], from_lang=text[0])
      translation = translator.translate(text[2])
      response.sms(translation)
    return str(response)
示例#18
0
def autotranslate(path, source_language, target_language,
                  ignore_already_translated=True):
    """Given a po file which is opened using polib and processed through
       Google Translator for all untranslated items by default
    """

    try:
        catalog = polib.pofile(path)
    except UnicodeDecodeError:
        raise Exception(("Encoding problem while parsing {0}, are you "
                         "sure that's a PO file?").format(path))

    translator = Translator(to_lang=target_language, from_lang=source_language)
    try:
        for idx, entry in enumerate(catalog):

            if ignore_already_translated and entry.translated():
                continue

            default_text = DEFAULT.match(entry.comment)
            if default_text:
                to_translate = default_text.group(1)
            else:
                to_translate = entry.msgid

            # Do we have to handle variables?
            variables = VAR_REGEX.search(to_translate)
            try:
                translated = translator.translate(to_translate.encode('utf-8'))
            except urllib2.HTTPError as e:
                log(ERROR, 'Error', u'{0:s} raised {1}: {2:s}'.format(
                    entry, e.__class__, e))
                continue

            if variables is not None:
                log(INFO, 'Found variable(s)', ', '.join(variables.groups()))

            log(SUCCESS, 'Success', u'{0} -> {1}'.format(
                to_translate, translated))

            # Save entry
            catalog[idx].msgstr = translated
            time.sleep(BREATHE)

    except KeyboardInterrupt:
        log(ERROR, 'Quit', '')

    catalog.save()
示例#19
0
    def __get_geocode(self, hospital):
        geolocator = GoogleV3(api_key=self.API_KEY)
        translator = Translator(from_lang='bg', to_lang='eng')

        name_query = self.__filter_only_letters(hospital.name)
        address_query = self.__reverse_abbreviations(self.__filter_only_letters(hospital.address))
        translated_address_query = translator.translate(address_query)

        # `translated address` followed by `address` lead to more accurate matches
        for query in [translated_address_query, address_query, name_query]:
            geocode_result = geolocator.geocode(query=query, exactly_one=True,
                                                timeout=self.API_TIMEOUT,
                                                sensor=False)
            if geocode_result is not None:
                break
        return geocode_result
示例#20
0
    async def translate(self, language, *text):
        """Translates text from English to specified language

        **Use double quotes for each option**

        **Dependencies**: pip install translate
                          (https://github.com/terryyin/google-translate-python)

        Keyword arguments:
        language -- Two-letter code for the languate to translate to
        text -- Text to translate.

        """
        text_to_string = ''.join(text)
        translator = Translator(to_lang=language)
        translation = translator.translate(text_to_string)

        await self.bot.say(translation)
def main(asmfile="",from_lang="cz",to_lang="en"):
  if len(asmfile) > 0 and not isfile(asmfile):
    print "%s is not a file!" % asmfile
    exit(1)
  tl=Translator(from_lang=from_lang,to_lang=to_lang)
  #read from stdin or a file
  if len(asmfile) == 0:
    data=stdin.read()
  else:
    with open(asmfile,'r') as f:
      data=f.read()
  #try translating comments otherwise simply output the line
  for x in data.split('\n'):
    parts=x.split(';',1)
    if len(parts) > 1:
      parts[1]=tl.translate(parts[1])
      print ';'.join(parts)
    else:
      print x
示例#22
0
文件: trans.py 项目: HANNATH/vsm
def transwrapper(text, from_lang, to_lang):
    
    if from_lang == 'en':
        lang = 'english'
    elif from_lang == 'fr':
        lang = 'french'
    elif from_lang == 'de':
        lang = 'german'
    sli = sent_tokenize(text, lang=lang)
    
    out = ''
    for sent in sli:
        sent = cleanup(sent) 
        
        ts = Ts(from_lang=from_lang, to_lang=to_lang)
        target = ts.translate(sent)
        out += target
    
    return out
示例#23
0
def main():
    config = Config('config.yaml')
    config.load() # Loads the configuration file.
    settings = config.get_config() # Stores the settings.

    core = Core(settings['proxy'], settings['server'], settings['listen'])
    core.connect() # Connects with the server over TOR.
    core.login(settings['account']['user'], # Login using nick and password.
               settings['account']['password'])

    # Joins to the channels.
    core.join(settings['transmission']['retransmit'])
    core.join(settings['transmission']['origin'])

    translator = Translator(from_lang=settings['translate']['from'],
                            to_lang=settings['translate']['to'])

    while True: # Main loop.
        output = core.read() # Reads data from the server.
        if core.ismessage(output): # If data is a message...
            # Get the nick of the owner.
            emitter = core.isemitter(output) if core.filter() \
            else output.split(' ')[0].split('!')[0][1:]

            # Get the name of the channel.
            channel = output.split(':')[1].split('#')[1][:-1]
            # If user and channel are allowed...
            if emitter and channel == settings['transmission']['origin']:
                # Builds a response.
                text = '@' + emitter + '#' + channel + ': ' + \
                       translator.translate(output.split(':')[2])
                # Sends the translated message to the desired channel.
                core.msg(settings['transmission']['retransmit'], text)
                print(text) # Shows the message.

        # If data is a PING...
        if output.find('PING') == 0: # Prevent timeout
            core.pong(output) # Sends a PONG.

        time.sleep(0.2) # Waits for 0.2 seconds.
示例#24
0
def translate_video_title(what):
	to_language = g.lang_code

	if to_language == "en":
		return what

	key = "{0}_{1}".format(what, to_language)

	translation = redis.get(key)

	if translation:
		return translation

	translator = Translator(to_lang=to_language)
	
	try:
		translation = translator.translate(what)
		redis.set(key, translation)
	except:
		translation = what

	return translation
示例#25
0
def ask_mapping(token_list):
    "Asks the user for a mapping"
    translation_name = input('Enter code of target language("in" for hindi): ')
    translation_name = translation_name.upper().strip()
    translator = Translator(to_lang=translation_name)
    mapping = {}
    for token in token_list:
        internal = False
        if token[:2] + token[-2:] == '____':
            token = token[2:-2]
            internal = True
        translation = translator.translate(token)
        translation = translation.replace(' ', '_').strip()
        if internal:
            token = '__' + token + '__'
            translation = '__' + translation + '__'
        mapped = {translation: token}
        print(mapped)
        mapping.update(mapped)
    f = open(translation_name, 'wb')
    pickle.dump(mapping, f)
    f.close()
示例#26
0
class Plugin(plugin.Plugin):
    def prepare(self):
        self.translator = Translator(self.conf.conf['bing_app_id'])

    def register_commands(self):
        self.commands = [
                ('party <<phrase>>', self.party)
                ]

    def party(self, message, args):
        """ A recreation of <a href="http://translationparty.com/">Translation Party</a> using the Bing translate API.
        $<comchar>party scissor me timbers
        >I have a tree.\x03# |\x03 \x027\x02 attempts\x03# |\x03 http://woof.bldm.us/party/<network>/Derasonika-120213-235608 """
        transvia = self.conf.conf['party_via']
    

        party = [args['phrase']]
        while dupes(party) == False:
            party.append(self.translator.translate('en', transvia, party[-1]))
            party.append(self.translator.translate(transvia, 'en', party[-1]))
        
        filename = '%s-%s' % (message.nick, time.strftime('%y%m%d-%H%M%S'))
        filepath = path.expanduser(self.conf.conf['party_dir']+self.conf.alias+'/')
        if not path.exists(filepath):
            mkdir(filepath)
        elif path.exists(filepath) and not path.isdir(filepath):
            raise OSError('\'party_dir\' is not a directory')
        filepath = filepath+filename+'.txt'

        print ' -- Writing to %s...' % filepath
        file = open(filepath, mode='w')
        sup = '\n'.join(party)
        file.write(sup)
        file.close()
        
        attempts = (len(party)-1)/2
        self.irc.privmsg(message.source, '%s | \x02%i\x02 attempts | %sparty/%s/%s/' % (party[-1], attempts, self.conf.conf['web_url'], self.conf.alias, filename), pretty=True)
示例#27
0
 def on_hypothesis(self, hypothesis):
     print(hypothesis + '\n')
     translate = Translator(to_lang='hi')
     translation = translate.translate(hypothesis)
     print(translation)
     print('')
 async def en_ru(self, ctx, *args):
     txt = str(" ".join(args))
     translator = Translator(to_lang="Russian")
     translation = translator.translate(txt)
     await ctx.send(translation)
示例#29
0
from translate import Translator

translator = Translator(to_lang="ja")
translation = translator.translate("This is a pen.")

try:
    translation = translator.translate("Engineering is the use of scientific principles to design and build machines, "
                                       "structures, and other items, including bridges, tunnels, roads, vehicles, "
                                       "and buildings. The discipline of engineering encompasses a broad range of "
                                       "more specialized fields of engineering, each with a more specific emphasis on "
                                       "particular areas of applied mathematics, applied science, and types of "
                                       "application. See glossary of engineering.")
    print(translation)
    # with open('./test.txt', mode='r') as my_file: #You can load a file to convert here using python I/O
    #     text = my_file.read()
    #     translation = translator.translate(text)
except FileNotFoundError as e:
    print('check your file path')
示例#30
0
def detected():
    global latest
    command = given_command()
    if command['success']:
        message = command['transcription']
    else:
        talk("I don't understand")
        return
    print(f"You: {message}")
    message = message.lower()

    if 'changes' in message:
        talk('Sure')
        talk('Sending...')
        send_changes()

    elif "roll the dice" == message:
        talk("Rolling...")
        cube_1 = random.randint(1, 6)
        cube_2 = random.randint(1, 6)
        talk(f"The dice have rolled: {cube_1}, {cube_2}")

    elif "how do i say" in message:
        rex = re.search("how do i say (.*) in (.*)", message)
        lang = rex.group(2)
        phrase = rex.group(1)
        translator = Translator(to_lang=lang)
        translation = translator.translate(phrase)
        talk(translation)

    elif "how much is" in message:
        rex = re.search("how much is (.*)", message.replace("^", "**"))
        talk(str(eval(rex.group(1))))

    elif "timer" in message and ("set a" in message or "start a" in message):
        rex = re.search(" a (.*) (.*) timer", message)
        unit = 1
        if "minute" in rex.group(2):
            unit = 60
        elif "hour" in rex.group(2):
            unit = 3600
        try:
            interval = int(rex.group(1)) * unit
        except ValueError:
            interval = w2n.word_to_num(rex.group(1)) * unit
        time = f"{rex.group(1)} {rex.group(2)}"
        Timer(interval, alarm, args=f"your {time} timer is up").start()
        talk("set")

    elif 'open' in message and 'website' in message:
        talk('Sure')
        reg_ex = re.search('open (.*) website', message)
        if reg_ex:
            domain = reg_ex.group(1).replace(" ", "")
            if '.com' not in domain:
                domain += ".com"
            url = 'https://www.' + domain
            webbrowser.open(url)
            talk("done")
        else:
            talk("not found")

    elif 'open' in message:
        reg_ex = re.search('open (.*)', message)
        app_name = ""
        try:
            if reg_ex:
                app_name = reg_ex.group(1)
                app_name1 = app_name + ".exe"
                subprocess.call(app_name1)
                talk("done")
            else:
                talk("not found")
        except FileNotFoundError:
            if '.com' not in app_name:
                app_name += ".com"
            url = 'https://www.' + app_name
            webbrowser.open(url)
            talk("done")

    elif 'tell me about' in message:
        reg_ex = re.search('tell me about (.*)', message)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                talk('How long?')
                length = given_command()
                talk(get_summary(topic, length))
        except Exception as e:
            talk(str(e))

    elif 'current weather' in message:
        reg_ex = re.search('current weather in (.*)', message)
        if reg_ex:
            talk(get_weather(reg_ex.group(1)))
        else:
            talk("not found")

    elif 'who is' in message:
        talk('Searching...')
        rex = re.search("who is (.*)", message)
        name = rex.group(1).replace(" ", "+")
        webbrowser.open('https://www.google.com/search?q=' + name)
        try:
            outputs = wikipedia.summary(message, sentences=3)
            talk('Gotcha')
            talk(outputs)

        except wikipedia.DisambiguationError:
            talk("Searching on google for " + message)
            webbrowser.open('https://www.google.co.il/search?q=' + message)

    elif 'email summary' in message:
        reg_ex = re.search('email summary (.*)', message)
        if reg_ex:
            topic = reg_ex.group(1)
            talk('How long?')
            length = given_command()
            content = get_summary(topic, length)
            msg = MIMEText(content)
            msg['To'] = "*****@*****.**"
            msg['From'] = username
            msg['Subject'] = message
            server.sendmail(username, "*****@*****.**",
                            msg.as_string())
            talk("sent")
        else:
            talk("not found")

    elif 'email news' in message:
        page = BeautifulSoup(requests.get(
            'https://www.ynet.co.il/home/0,7340,L-8,00.html').text,
                             features='html.parser')
        content = page.select_one('.title').get_text(
        ) + ':\n' + page.select_one('.sub-title').get_text() + '.\n '
        titles = page.select('.title')
        sub_titles = page.select('.sub_title.sub_title_no_credit')

        i = 0
        while i < len(sub_titles):
            content += '\n' + titles[
                i + 1].get_text() + ':\n' + sub_titles[i].get_text() + '.\n'
            i += 1

        msg = MIMEText(content)
        msg['To'] = "*****@*****.**"
        msg['From'] = username
        msg['Subject'] = "News"
        server.sendmail(username, "*****@*****.**", msg.as_string())
        talk("sent")

    elif "whats the error" in message:
        talk("Checking...")
        reg_ex = re.search("whats the error (.*)", message)
        error = reg_ex.group(1)
        links = ask_stack(error)
        links_amount = len(links)
        if links_amount == 0:
            talk("could not find anything about that")
        else:
            talk(
                f"I found {links_amount} questions about that on stackoverflow, how many do you want me to open?"
            )
            index = get_number(links)
            for link in links[:index]:
                webbrowser.open(link)

    elif "news flash" in message:
        response = requests.get("https://www.theverge.com")
        page = BeautifulSoup(response.text, "html.parser")
        title_boxes = page.find_all("h2",
                                    {"class": "c-entry-box--compact__title"})
        articles = []
        for title_box in title_boxes:
            articles.append(title_box.findChildren("a")[0].text)
        talk(f"I found {len(articles)-1} articles, how many do you want?")
        talk(".\n".join(articles[:get_number(len(articles)):]))

    elif 'email' in message:
        talk('Who is the recipient? ')
        recipient = given_command()['transcription']

        if 'me' in recipient:
            try:
                talk('What should I say? ')
                content = given_command()['transcription']
                server.sendmail(username, "*****@*****.**", content)
                talk('Email sent!')

            except Exception as e:
                print(type(e))
                talk(
                    'Sorry ! I am unable to send your message at this moment!')

    elif 'abort' in message or 'stop' in message or 'bye' in message:
        talk('Okay')
        talk('Bye, have a good day.')
        sys.exit()

    elif 'search for' in message:
        talk('Searching...')
        message = message.split("search for")[-1]
        message = message.replace(' ', '+')
        webbrowser.open('https://www.google.co.il/search?q=' + message)

    elif "repeat" in message:
        talk(latest)

    elif "should i watch" in message:
        talk("Checking...")
        reg_ex = re.search('should i watch (.*)', message)
        opinion = estimate_quality(reg_ex.group(1))
        if "bad" in opinion:
            opinion += ", so I don't recommend you watch it."
        else:
            opinion += ", so I recommend you watch it"
        talk(opinion)

    else:
        try:
            page = subprocess.getoutput(
                'curl "https://miapi.pandorabots.com/talk" -H "Sec-Fetch-Mode: cors" -H '
                '"Referer: https://www.pandorabots.com/mitsuku/" -H "Origin: '
                'https://www.pandorabots.com" -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; '
                'Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 '
                'Safari/537.36" -H "Content-type: application/x-www-form-urlencoded" --data '
                f'"input={message}&sessionid={sessionID}&channel=6&botkey'
                '=n0M6dW2XZacnOgCWTp0FRYUuMjSfCkJGgobNpgPv9060_72eKnu3Yl-o1v2nFGtSXqfwJBG2Ros'
                '~&client_name=cw16d8c77ebdd"').split("\n")[-1]
            talk(
                eval(page)['responses'][0].replace("Mitsuku",
                                                   "Jarvis").replace(
                                                       "Mitsuku", "Jarvis"))
        except UnicodeDecodeError:
            talk("Something went wrong, please try something else.")
示例#31
0
from translate import Translator
to_lang = 'it'
translator = Translator(to_lang=to_lang)

with open(f'translate-{to_lang}.txt', mode='w') as writer:
    writer.write('')

try:
    with open('translate.txt', mode='r') as reader:
        # print(reader.read())
        while True:
            line = reader.readline()
            if line is '':
                break
            translated_text = translator.translate(line)
            print(line, translated_text)
            with open(f'translate-{to_lang}.txt', mode='a') as writer:
                print(translated_text, file=writer)
except Exception as err:
    print(err)
import pyjokes
import io
from translate import Translator

try:

    translator = Translator(to_lang="ja")
    file = open('./input/input.txt', 'r')
    content = file.read()
    converted = translator.translate(content)

    with io.open('./translated file/converted.txt', "w",
                 encoding="utf-8") as my_file:
        my_file.write(converted)

except FileNotFoundError as err:

    print("Please check the path of your input file")
    print("Here's a joke for you")
    print(pyjokes.get_joke('en', 'neutral'))
示例#33
0
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from translate import Translator
import numpy as np

translator = Translator(to_lang='en')

df = pd.read_excel(r'/Users/jaeeun/Desktop/trans_5.xlsx')
# print(df)
wr = pd.DataFrame({'kr': [], 'en': []})

kor = []
eng = []

for index, row in df.iterrows():
    kor.append(str(row[0]))
    eng.append(translator.translate(str(row[0])))

append = pd.DataFrame({'kr': kor, 'en': eng})
wr = wr.append(append, ignore_index=True)
print(wr)
writer = ExcelWriter('translated_5.xlsx')
wr.to_excel(writer, 'Sheet1', index=False)
writer.save()
示例#34
0
# Language Translator
from translate import Translator
translator = Translator(From_lang="English", to_lang="Hindi")
username = input("Enter your name : ")
translation = translator.translate(username)
print(translation)
示例#35
0
    voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"

    # Use female voice
    engine.setProperty('voice', voice_id)
    engine.runAndWait()


### CONTENT FOR SPEAKING

now = datetime.now()
output = tamilSpeechToText()

if "உன் பெயர் என்ன" in output:
    tamilTextToSpeech("என் பெயர் நிலா")
    print("என் பெயர் நிலா")
elif "ஹாய்" in output:
    tamilTextToSpeech("வணக்கம், நீ் எப்டி இருக்க")
    print("வணக்கம், நீ் எப்டி இருக்க")
elif "வணக்கம்" in output:
    tamilTextToSpeech("வணக்கம், நீங்கள் எப்படி இருக்கிறீர்கள்")
    print("வணக்கம், நீங்கள் எப்படி இருக்கிறீர்கள்")
elif "நாள்" in output:
    today = datetime.today()
    current_day = today.strftime("%A")
    translation = Translator.translate(current_day)
    tamilTextToSpeech("இன்று" + translation + "கிழமை")
    print("இன்று", translation, "கிழமை")

else:
    tamilTextToSpeech(output)
示例#36
0
def google_translate(text, langc="zh-CN", langc_f="en"):
    import translate
    from translate import Translator
    translator= Translator(to_lang=langc, from_lang=langc_f)
    return translator.translate(text)
示例#37
0
文件: main2.py 项目: Poggergg/verrus2
async def translate(ctx, anguage, *, argument):
    translator = Translator(to_lang=f"{anguage}")
    translation = translator.translate(f"{argument}")
    print(translation)
    await ctx.send(translation)
示例#38
0
def google(text):
    translator = Translator()
    print(translator.detect(text))
    print(translator.translate(text, dest='en').text)
    return (translator.translate(text, dest='en').text)
from translate import Translator
print('HEEEELLOOOOOOOO')
translator = Translator(to_lang='fr')
translation = translator.translate('This is a boy: Ibrahim Olawale')
print(translation)
print(Translator)

with open('scared.txt', mode='r') as my_story:
    story = my_story.read()
    print(story)
    translated_story = translator.translate(story)
    print(translated_story)

with open('translated_story.txt', mode='w') as my_translated_story:
    text = my_translated_story.write(translated_story)
    print(text)

    #text = my_story.write('The End.')
    #translated_text = translator.translate(my_story)
    # print(text)
    # print(my_story.readlines())
    # print(my_story)
示例#40
0
 def translate(self, word, from_lang, to_lang='english'):
     translator= Translator(from_lang=from_lang,to_lang=to_lang)
     return translator.translate(word)
示例#41
0
                total_word_count += word_count
            except:
                continue

            if total_char_count > TRANSLATION_CHAR_LIMIT or total_word_count > TRANSLATION_WORD_LIMIT:
                print(
                    f'TRANSLATION_CHAR_LIMIT= {TRANSLATION_CHAR_LIMIT} or TRANSLATION_WORD_LIMIT= {TRANSLATION_WORD_LIMIT} reached --> {total_char_count} or {total_word_count}'
                )
                break

            print(
                f'Tranlating text into {TRANSLATE_LANG} --> {text2translate} -->',
                end=' ')

            try:
                translated_text = translator.translate(text2translate)
                print(translated_text)
                print(
                    f'Translated count -> chars= {total_char_count} words= {total_word_count}'
                )

                if 'MYMEMORY WARNING' in translated_text or 'IS AN INVALID TARGET LANGUAGE' in translated_text:
                    print(translated_text)
                    update_translated = False
                    break
                mlt_df.loc[i, translated_column] = translated_text
            except Exception as e:
                print('Translation exception occured')
                print(e)
                update_translated = False
                break
示例#42
0
# 抓取網站
resource_url = 'http://www.indiaculture.nic.in/press-release'
re = requests.get(resource_url)
print(re.status_code)
soup = BeautifulSoup(re.text, 'html.parser')
data = soup.find_all('span', class_='field-content')

# 分類資訊
translator = Translator(to_lang='chinese')
title = []
title_zh = []
date = []
link = []
for i in range(0, len(data), 3):
    title.append(data[i].text.strip())
    zh_title = translator.translate(data[i].text.strip())
    title_zh.append(zh_title)
    try:
        link.append(data[i].a.get('href'))
    except:
        link.append('無連結')
for i in range(2, len(data), 3):
    date.append(data[i].text.strip())

# 組成表格
today = datetime.date.today()
dict = {'搜尋日期': today,
        '新聞日期': date,
        '地區別':'',
        '國家':'',
        '發布機構':'印度文化部',
示例#43
0
from translate import Translator
translator = Translator(to_lang="es")
try:
    with open('app/test.txt', mode='r') as my_file:
        text = my_file.read()
        translation = translator.translate(text)
        with open('app/test.ja.txt', mode='w') as my_file2:
            my_file2.write(translation)
except FileNotFoundError as e:
    print('please check path')
示例#44
0
            engine.say(user_translation_text)
            engine.runAndWait()
            user_translation_text_X = str(input(""))
            engine.say(user_translation_text_X)
            engine.runAndWait()
            user_language_code = f"Sorry {getting_user_name_storing} but you have to manually input the language code: "
            print(f"{user_language_code} ", end="")
            engine.say(user_language_code)
            engine.runAndWait()
            user_language_code_in = str(input())
            user_language_code_dec = "NOTE: If language code is appropriate then you'll get the result!"
            print(user_language_code_dec)
            engine.say(user_language_code_dec)
            engine.runAndWait()
            translator = Translator(to_lang=user_language_code_in)
            user_translated_data = translator.translate(user_translation_text_X)
            engine.say("Here you go...")
            engine.runAndWait()
            print(f"The translated data in language code '{user_language_code_in}': ", end="")
            print(user_translated_data)
        
            # return user_action_on_fire

            # Google News

        elif user_action_on_fire == 'news' or user_action_on_fire == 'google' or user_action_on_fire == 'breaking':
            user_wish_news = "Say, 'RSS' to check Top News or say, 'Search a News' to search your choice"
            print(user_wish_news)
            engine.say(user_wish_news)
            engine.runAndWait()
            with sr.Microphone() as source:
示例#45
0
# pip install translate
#pip install -i https://pypi.tuna.tsinghua.edu.cn/simple translate

from translate import Translator

# 以下是将简单句子从英语翻译中文
translator = Translator(to_lang="chinese")
translation = translator.translate("Good night!")
print(translation)

# 在任何两种语言之间,中文翻译成英文
translator = Translator(from_lang="chinese", to_lang="english")
translation = translator.translate("我想你")
print(translation)

mylist = ['网页', '类别', '片名', '女优', '大小', '步骑', '时间', '磁力', '预览', '预览', '预览']

my_english_list = []
for one in mylist:
    translator = Translator(from_lang="chinese", to_lang="english")
    translation = translator.translate(one)
    my_english_list.append(translation.replace(" ", "_").lower())  #空格替换成下划线

print(mylist)
print(my_english_list)

mylist_len = len(mylist)
for i in range(0, mylist_len):
    one = """
    %s = models.CharField(max_length=100, default="", verbose_name=u"%s")""" % (
        my_english_list[i], mylist[i])
示例#46
0
#from googletrans import Translator
import speech_recognition as sr
import pyttsx3
from translate import Translator
#translator = Translator()

translator = Translator(to_lang="cs")

r = sr.Recognizer()
engine = pyttsx3.init()

with sr.Microphone() as source:
    print("Please wait. Calibrating microphone...")
    r.adjust_for_ambient_noise(source, duration=5)
    print("Akshat say something!")
    audio = r.listen(source)
check = str(r.recognize_google(audio))

print(check)
translation = translator.translate(check)
print(translation)
engine.say(translation)
engine.runAndWait()

#answer = translator.translate(check, dest='hi')
#s = str(answer)
#ansr = eval(str)
#fan = ansr['pronunciation']
#engine.say(answer)
#engine.runAndWait()
示例#47
0
文件: server.py 项目: tomekd/nematus
class NematusServer(object):
    """
    Keeps a Nematus model in memory to answer http translation requests.
    """

    STATUS_LOADING = 'loading'
    STATUS_OK = 'ok'

    def __init__(self, server_settings, decoder_settings):
        """
        Loads a translation model and initialises the webserver.

        @param startup args: as defined in `console.py`
        """
        self._style = server_settings.style
        self._host = server_settings.host
        self._port = server_settings.port
        self._debug = decoder_settings.verbose
        self._models = decoder_settings.models
        self._num_processes = decoder_settings.num_processes
        self._device_list = decoder_settings.device_list
        self._status = self.STATUS_LOADING
        # start webserver
        self._server = Bottle()
        self._server.config[
            'logging.level'] = 'DEBUG' if decoder_settings.verbose else 'WARNING'
        self._server.config['logging.format'] = '%(levelname)s: %(message)s'
        self._server.install(LoggingPlugin(self._server.config))
        logging.info("Starting Nematus Server")
        # start translation workers
        logging.info("Loading translation models")
        self._translator = Translator(decoder_settings)
        self._status = self.STATUS_OK

    def status(self):
        """
        Reports on the status of this translation server.
        """
        response_data = {
            'status': self._status,
            'models': self._models,
            'version': pkg_resources.require("nematus")[0].version,
            'service': 'nematus',
        }
        response.content_type = "application/json"
        return json.dumps(response_data)

    def translate(self):
        """
        Processes a translation request.
        """
        translation_request = request_provider(self._style, request)
        logging.debug("REQUEST - " + repr(translation_request))

        translations = self._translator.translate(translation_request.segments,
                                                  translation_request.settings)
        response_data = {
            'status':
            TranslationResponse.STATUS_OK,
            'segments':
            [translation.target_words for translation in translations],
            'word_alignments': [
                translation.get_alignment_json(as_string=False)
                for translation in translations
            ] if translation_request.settings.get_alignment else None,
            'word_probabilities':
            [translation.target_probs for translation in translations]
            if translation_request.settings.get_word_probs else None,
        }
        translation_response = response_provider(self._style, **response_data)
        logging.debug("RESPONSE - " + repr(translation_response))

        response.content_type = translation_response.get_content_type()
        return repr(translation_response)

    def start(self):
        """
        Starts the webserver.
        """
        self._route()
        self._server.run(host=self._host,
                         port=self._port,
                         debug=self._debug,
                         server='paste')
        self._cleanup()

    def _cleanup(self):
        """
        Graceful exit for components.
        """
        self._translator.shutdown()

    def _route(self):
        """
        Routes webserver paths to functions.
        """
        self._server.route('/status', method="GET", callback=self.status)
        self._server.route('/translate',
                           method="POST",
                           callback=self.translate)
示例#48
0
def translate_1():
    read = txt_box.get(0.0, END)
    translator = Translator(from_lang="Russian", to_lang="English")
    translation = translator.translate(read)
    txt_box1.insert(0.0, translation)
示例#49
0
# -*- coding: utf-8 -*-

"""
 Creato da.....: Marco Valaguzza
 Piattaforma...: Python3.6
 Data..........: 30/12/2019
 
 Descrizione...: Dato un testo, lo traduce nella lingua indicata
 
 Note..........: Il layout è stato creato utilizzando qtdesigner e il file traduci_ui.py è ricavato partendo da traduci_ui.ui 
"""

from translate import Translator

o_traduci = Translator(provider='mymemory', from_lang='it', to_lang='en')

s_testo = ''
o_file = open('N:\\smi_job\\It&c\mvalaguz\\01 - Aggiornamenti\\2019\\2019 07 15 2019 09 03 Creazione descrizioni in lingua in base a dizionario su richiesta di AZAMBELL\\Estrazioni per test traduzione tramite automatismo\\TERMINI.txt','r')
o_output = open('N:\\smi_job\\It&c\mvalaguz\\01 - Aggiornamenti\\2019\\2019 07 15 2019 09 03 Creazione descrizioni in lingua in base a dizionario su richiesta di AZAMBELL\\Estrazioni per test traduzione tramite automatismo\\TERMINI_OUT.txt','w')
for linea in o_file:    
    elementi = linea.split('|')
    s_traduci = o_traduci.translate(elementi[0])    
    print(elementi[0] + ' ' + s_traduci)
    #o_output.write(elementi[0] + '|' + elementi[1] + '|' + s_traduci + '\n')    

o_file.close()
o_out.close()
示例#50
0
    def on_play_pause(self):
        if self.player.playing:
            self.player.pause()

            #sergio's code
            def closest_words(pause_time, dictionary, word_count=2):
                '''pause_time (float): time in seconds when video was paused
                    dictionary: Stores timestamps to words as {X.XX:'word'}
                    word_count (int): # of words desired in output
                    
                    returns: dictionary with word_count most recent words at given timestamp
                            {x.xx:'word'}'''

                result = {}
                current = round(pause_time + 0.5, 2)
                list_of_timez = []
                #While we still need more words to output
                while len(result) < word_count:

                    #If we go back to time 0, no more words exist
                    if current <= 0:
                        break
                    #If the current timestamp contains a word, save to output
                    if current in dictionary:
                        result[current] = dictionary[current]

                    #Look at earlier timestamp for more words
                    current = round(current - 0.01, 2)

                list_of_timez = sorted(result.keys())
                return (result, list_of_timez)

            #isaak's code
            def time_to_word(file_name):
                # loading our json file
                with open(file_name, 'r') as f:
                    word_time_dict = json.load(f)

                #getting to a list of dictionaries that contain info about each word
                list_of_dict = word_time_dict['monologues'][0]['elements']

                final_dict = {}
                list_of_time_stamps = []
                articles = ['and', 'the', 'a']
                for a_dict in list_of_dict:
                    if a_dict['type'] == 'text':
                        if a_dict['value'] not in articles:
                            final_dict[a_dict['end_ts']] = a_dict['value']
                            list_of_time_stamps.append(a_dict['end_ts'])
                list_of_time_stamps.sort()
                return (final_dict, list_of_time_stamps)

            #instantiating file name
            #creating final dict using functions defined above
            file_name = 'hack_audio.json'
            time_stamp = self.player.time
            a_dict = time_to_word(file_name)[0]
            list_of_times = closest_words(time_stamp, a_dict)[1]

            final_dict = closest_words(time_stamp, a_dict)[0]

            def corr_dict(L1, L2):
                dict_o = {}
                for t in range(len(L1)):
                    dict_o[L1[t]] = L2[t]
                return dict_o

            #Set Languages Of Translation
            lang_codes = [
                "ar", "bn", "es", "fr", "hi", "id", "pt", "ru", "zh", "ur",
                "en"
            ]
            lang_names = [
                "Arabic", "Bengali", "Spanish", "French", "Hindi",
                "Indonesian", "Portuguese", "Russian", "Chinese", "Urdu",
                "English"
            ]

            lang_dict = corr_dict(lang_codes, lang_names)

            def get_spanish_dict(word):

                app_id = "f253b36c"
                app_key = "05154548fb10d80a43f8705e23a4c4c9"
                language = "es"
                word_id = word
                url = "https://od-api.oxforddictionaries.com/api/v2/entries/" + language + "/" + word_id.lower(
                )
                r = requests.get(url,
                                 headers={
                                     "app_id": app_id,
                                     "app_key": app_key
                                 })
                print((r).json())

                return ((r).json()['results'][0]['lexicalEntries'][0]
                        ['entries'][0]['senses'][0]['definitions'])

            #Find Words Needed
            transcription_dict = final_dict

            times_list = sorted(transcription_dict.keys())

            english_lst = []

            for time in times_list:
                english_lst.append(transcription_dict[time])

            #Translation
            from_l = 'en'
            to_l = 'es'
            #input(lang_names + "Which language would you like? "), TBA
            translator = Translator(from_lang=from_l, to_lang=to_l)

            translation_d = {}

            #translating and grabbing definition
            for word in english_lst:
                inter_list = []

                translation = translator.translate(word)
                inter_list.append(translation)

                try:
                    inter_list.append(get_spanish_dict(translation))
                except:
                    inter_list.append(
                        "Aun no tenemos esta palabra en nuestro diccionario. Lo siento"
                    )

                translation_d[word] = inter_list  #, definition

            #Initialization Of GUI

            window = pyglet.window.Window(1500, 200)
            label = pyglet.text.Label(str(translation_d),
                                      font_name='Times New Roman',
                                      font_size=12,
                                      x=window.width // 2,
                                      y=window.height // 2,
                                      anchor_x='center',
                                      anchor_y='center')

            @window.event
            def on_draw():
                window.clear()
                label.draw()

            pyglet.app.run()

        else:
            if self.player.time >= self.player.source.duration:
                self.player.seek(0)
            self.player.play()
        self.gui_update_state()
示例#51
0
class MainWindowUI(Ui_MainWindow):
    # Initialise the model
    def __init__(self):
        super().__init__()
        self.model = Model()
        self.tr = Translator(to_lang="en", from_lang="ja")

    # Use super function to allow inheritance from GUI
    def setup_ui(self, mw):
        super().setup_ui(mw)
        self.splitter.setSizes([300, 0])

    # Function that performs ocr
    def read_img(self):
        image = cv2.imread(self.model.getFileName())

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        self.debug_print(str(type(gray)))

        image_name = "{}.png".format(os.getpid())
        cv2.imwrite(image_name, gray)

        # run ocr in both languages
        text = pytesseract.image_to_string(Image.open(image_name), config='-l eng+jpn')

        text = self.read_lang(image_name, text)

        os.remove(image_name)
        self.originalTextBrowser.setText(text)

    # Non-deterministic algorithm to read the language present
    def read_lang(self, image_name, text):
        if self.model.readLang(text) == 'en':
            filename = self.model.getFileName()
            text = image_to_string(Image.open(filename))
            text_original = str(text)
            # cleanup text
            text = text_replace(text)

            persons_list = get_persons_list(text)
            ignore_words = persons_list + ["!", ",", ".", "\"", "?", '(', ')', '*', '\'']
            # using enchant.checker.SpellChecker, identify incorrect words
            spell = SpellChecker("en_US")
            words = text.split()
            incorrect_words = [w for w in words if not spell.check(w) and w not in ignore_words]
            # using enchant.checker.SpellChecker, get suggested replacements
            suggested_words = [spell.suggest(w) for w in incorrect_words]
            # replace incorrect words with [MASK]
            text, text_original = replace_incorrect(incorrect_words, text, text_original)

            id_mask, model, segments_tensor, tokenizer, tokens_tensor = evaluate_tokens(text)
            # Predict all tokens
            with torch.no_grad():
                predictions = model(tokens_tensor, segments_tensor)

            # Refine prediction by matching with proposals from SpellChecker
            text = predict_word(id_mask, tokenizer, suggested_words, text_original, predictions)
        else:
            text = pytesseract.image_to_string(Image.open(image_name), config='-l jpn')
            text = re.sub(" ", "", text)
        return text

    # Function to detect text in an image using EAST
    def text_detect(self):
        #                                                 ,  ,
        #                                                / \/ \
        #                                               (/ //_ \_
        #      .-._                                      \||  .  \
        #       \  '-._                            _,:__.-"/---\_ \
        #  ______/___  '.    .--------------------'~-'--.)__( , )\ \
        # `'--.___  _\  /    |             Here        ,'    \)|\ `\|
        #      /_.-' _\ \ _:,_          Be Dragons           " ||   (
        #    .'__ _.' \'-/,`-~`                                |/
        #        '. ___.> /=,| Abandon all hope, ye who enter! |
        #         / .-'/_ )  '---------------------------------'
        #         )'  ( /(/
        #              \\ "
        #               '=='
        # This horrible monstrosity takes what should be normal variables as
        # CLI arguments, but for some reason they don't work as normal variables.
        # It's bloated, confusing, and pretty awful by necessity(for the most part).
        # Due to the extremely volatile nature of this code, it should NOT be edited
        # unless absolutely necessary.

        # Defines an argument parser, which handles command line inputs
        ap = argparse.ArgumentParser()
        ap.add_argument("-east", "--east", type=str,
                        help="me", default="frozen_east_text_detection.pb")
        ap.add_argument("-c", "--min-confidence", type=float, default=0.5,
                        help="these shouldn't even be needed????")
        ap.add_argument("-w", "--width", type=int, default=320,
                        help="magic, do not touch")
        ap.add_argument("-e", "--height", type=int, default=320,
                        help="without this line, the program breaks")
        args = vars(ap.parse_args())

        # Reads image
        image = cv2.imread(self.model.getFileName())
        orig = image.copy()
        (H, W) = image.shape[:2]

        # Resize image based on given parameters
        (newW, newH) = (args["width"], args["height"])
        r_w = W / float(newW)
        r_h = H / float(newH)

        image = cv2.resize(image, (newW, newH))
        (H, W) = image.shape[:2]

        layer_names = [
            "feature_fusion/Conv_7/Sigmoid",
            "feature_fusion/concat_3"]

        # Load EAST
        self.debug_print("[INFO] loading EAST text detector...")
        net = cv2.dnn.readNet(args["east"])

        blob = cv2.dnn.blobFromImage(image, 1.0, (W, H),
                                     (123.68, 116.78, 103.94), swapRB=True, crop=False)
        start = time.time()
        net.setInput(blob)
        (scores, geometry) = net.forward(layer_names)
        end = time.time()

        # Time that the text detection took
        self.debug_print("[INFO] text detection took {:.6f} seconds".format(end - start))
        (numRows, numCols) = scores.shape[2:4]
        rects = []
        confidences = []

        # Generate a probability score for each word to be a word
        probability_score(args, confidences, geometry, numCols, numRows, rects, scores)

        boxes = non_max_suppression(np.array(rects), probs=confidences)
        for (start_x, start_y, end_x, end_y) in boxes:
            # scale the bounding box coordinates based on the respective
            # ratios
            start_x = int(start_x * r_w)
            start_y = int(start_y * r_h)
            end_x = int(end_x * r_w)
            end_y = int(end_y * r_h)

            # draw the bounding box on the image
            cv2.rectangle(orig, (start_x, start_y), (end_x, end_y), (0, 255, 0), 2)

        cv2.imshow("Text Detection", orig)
        self.debug_print("[INFO] detected language " + self.model.readLang(self.originalTextBrowser.toPlainText()))
        cv2.waitKey(0)

    # Setup a hidden debugging log
    def debug_print(self, msg):
        self.debugTextBrowser.append(msg)

    # Basic function to empty the textboxes
    def refresh_all(self):
        self.lineEdit.setText(self.model.getFileName())

    # Function executes when enter is pressed, but only while the file path textbox is focused
    def returnPressedSlot(self):
        file_name = self.lineEdit.text()
        if self.model.isValid(file_name):
            self.model.setFileName(self.lineEdit.text())
            self.refresh_all()
            self.read_img()
            self.text_detect()
        else:
            m = QtWidgets.QMessageBox()
            m.setText("Invalid file name!\n" + file_name)
            m.setIcon(QtWidgets.QMessageBox.Warning)
            m.setStandardButtons(QtWidgets.QMessageBox.Ok
                                 | QtWidgets.QMessageBox.Cancel)
            m.setDefaultButton(QtWidgets.QMessageBox.Cancel)
            ret = m.exec_()
            self.lineEdit.setText("")
            self.refresh_all()
            self.debug_print("Invalid file specified: " + file_name)

    # Function when translate is pressed
    def translateSlot(self):
        text = self.originalTextBrowser.toPlainText()
        if self.model.readLang(text) == 'en':
            self.debug_print("Text already in English.")
            self.translatedTextBrowser.setText(text)
        else:
            text.join(text.split())
            text = re.sub(" ", "", text)
            try:
                tText = self.tr.translate(text)
                self.translatedTextBrowser.setText(tText)
            except HTTPError:
                time.sleep(2)
                try:
                    tText = self.tr.translate(text)
                    self.translatedTextBrowser.setText(tText)
                except HTTPError:
                    self.debug_print("Failed twice.")

    # Function when browse is pressed
    def browseSlot(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        file_name, _ = QtWidgets.QFileDialog.getOpenFileName(
            None,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*);;Jpeg Files (*.jpg)",
            options=options)
        # This comment is self explanatory
        if file_name:
            self.debug_print("setting file name: " + file_name)
            self.model.setFileName(file_name)
            self.refresh_all()
            try:
                self.read_img()
                try:
                    self.text_detect()
                except:
                    m = QtWidgets.QMessageBox()
                    m.setText("Invalid file name!\n" + file_name)
                    m.setIcon(QtWidgets.QMessageBox.Warning)
                    m.setStandardButtons(QtWidgets.QMessageBox.Ok
                                         | QtWidgets.QMessageBox.Cancel)
                    m.setDefaultButton(QtWidgets.QMessageBox.Cancel)
                    ret = m.exec_()
                    self.lineEdit.setText("")
                    self.refresh_all()
                    self.debug_print("Invalid file specified: " + file_name)
            except:
                m = QtWidgets.QMessageBox()
                m.setText("File contains no readable text!\n" + file_name)
                m.setIcon(QtWidgets.QMessageBox.Warning)
                m.setStandardButtons(QtWidgets.QMessageBox.Ok
                                     | QtWidgets.QMessageBox.Cancel)
                m.setDefaultButton(QtWidgets.QMessageBox.Cancel)
                ret = m.exec_()
                self.lineEdit.setText("")
                self.refresh_all()
                self.debug_print("File contains no readable text: " + file_name)
示例#52
0
from translate import Translator

translator = Translator(to_lang="Corsican")

translation = translator.translate(" hello world rvce")

print(translation)
#from translate import Translator
#translator= Translator(from_lang="german",to_lang="spanish")
#translation = translator.translate("Guten Morgen")
#print (translation)
#Afrikaans Albanian  Amharic   Armenian
#Basque  Belarusian  Bengali Bosnian Bulgarian Burmese
#Catalan  Cebuano  Chichewa    Corsican  Croatian  Czech  Danish
示例#53
0
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import pandas as pd
from translate import Translator
translator = Translator(to_lang="zh")

l1 = pd.read_csv('cateCount.txt', skiprows=0)['cate']
l2 = []
for i in range(100):
    print("Correct ? %s to %s %d" % (str(
        l1[i]), translator.translate(str(l1[i]).replace('_', ' ')), i + 1))
    content = raw_input()
    if (content == 'q'):
        break
    elif (content == 'y' or content == 'Y'):
        l2.append(l1[i])
    i += 1
    print('\t')
l2 = pd.Series(l2).to_csv('cates.txt')
示例#54
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from translate import Translator
translator = Translator(to_lang="ru")
print translator.translate("exciting")
print translator.translate("retrieval")

toEng = Translator(from_lang="ru", to_lang="en")
print toEng.translate(u"захватывающий")
示例#55
0
translatorToEnglish = Translator(to_lang="en")


if __name__ == "__main__":
    token='xoxp-19745829781-38048263175-38056115377-d6ad0242f9'
    sc = SlackClient(token)

    if sc.rtm_connect():
        while True:
            json_messages = sc.rtm_read()
            for message in json_messages:
                print("DEBUG: json message is: " + str(message))
                print("DEBUG: type is: " + message['type'])
                if (message['type'] == "message" and message['channel'] == 'C0NP34ZCG' and "group3botRyan" not in json.dumps(message)):
                    print("DEBUG: Actual message is: " + message['text'])
                    frenchTranslation = translatorToFrench.translate(message['text'])
                    print("DEBUG: Translated message to french is: " + frenchTranslation)
                    
                    englishTranslation = translatorToEnglish.translate(frenchTranslation)
                    print("DEBUG: Translated message to english is: " + englishTranslation)
                    #sc.api_call("chat.postMessage", channel="#group3", text=frenchTranslation, username="******", icon_emoji=':robot_face:')
                    sc.api_call("chat.postMessage", channel="#group3", text=englishTranslation, username="******", icon_emoji=':robot_face:')

                print("")
                print("")
                print("")

            time.sleep(0.2)
    else:
        print "Connection Failed, invalid token?"
示例#56
0
 def _get_translation(message):
     translator = Translator(to_lang='Russian')
     text = message.split()
     new_text = ' '.join(map(str, text[1:]))
     return translator.translate(' '.join(map(str, text[1:])))
示例#57
0
else:
    print "Usage seed_translation.py lang"
    print "  where lang is your two letteer ISO-639-1 language code"
    exit()

po_files_dir = './translated_po/%s' % language_code

files = os.listdir(po_files_dir)
translate_all = True

translator= Translator(to_lang=language_code)

for po_file_name in files:
    print "TRANSLATE %s" % po_file_name
    po = polib.pofile(os.path.join(po_files_dir, po_file_name))
    for entry in po:
        if translate_all or entry.msgstr == '':
            print entry.msgid
            sentences = entry.msgid.split('.')
            translated_sentences = []
            for sentence in sentences:
                try:
                    translated_sentences.append(translator.translate(sentence))
                except:
                    print "ERROR TRANSLATING SENTENCE '%s'" % sentence
            translation = '. '.join(translated_sentences)
            print translation
            print "-" * 40
            entry.msgstr = translation.strip()
    po.save(os.path.join(po_files_dir, po_file_name))
示例#58
0
translated = {}

# _en_UK
path = os.path.dirname(os.path.abspath(__file__))
f = open(os.path.join(path, "en_UK.json"), "r")
language["en_UK"] = json.loads(f.read())
f.close()

# Translate into Afrikaans
translator = Translator(to_lang="af")
translated["af_AF"] = {}

for item in language["en_UK"]:
    # Translate strings
    if type(language["en_UK"][item]) == str:
        translation = translator.translate(language["en_UK"][item])
        print("{}: {}".format(item, translation))
        translated["af_AF"][item] = translation

    # Translate lists
    if type(language["en_UK"][item]) == list:
        new_list = []
        for sub in language["en_UK"][item]:
            if type(sub) == str:
                translation = translator.translate(sub)
                new_list.append(translation)

            # Do not translate sublist, just keep the contents
            if type(sub) == list:
                new_sub_list = []
                for i in range(len(sub)):
示例#59
0
from translate import Translator
trans = Translator(to_lang="zh-CN")
print trans.translate("hello")
示例#60
0
readme_file.readlines()
# close will simply close the current file
readme_file.close()

# standard way to read file w/out needing to close it
# default mode is read, with 'r+' we can read and write
# r -> read
# w -> write (also creates a new file if needed)
# a -> append
# even tho r+ seems to append in python 3.7.3 ­Ъци
# with open('./files.txt', mode='r+') as file:
# text = file.write(' :D')
# print(file.readlines())

#######################################################
# Exercise: translate the content of a file

_translate = Translator(to_lang="it")

try:
    with open('./file.txt', mode='r+', encoding='utf8') as file:
        text_lines = file.readlines()
        translated_text = '\r'.join(
            [_translate.translate(line) for line in text_lines])
        print(translated_text)
        text = ''.join(text_lines)
        open('./file_translated.txt', mode='w', encoding='utf8').write(
            f'{text}\n\n#Translated text#\n\n{translated_text}')
except Exception as err:
    raise err