def concurrent_translate(data): executor = concurrent.futures.ThreadPoolExecutor(max_workers=200) gs = goslate.Goslate(executor=executor) translated = gs.translate(data, 'en') return list(translated)
#querys = '["pray4paris"] since:2015-11-23 until:2015-11-28' querys = ['pray4paris',u'syria réfugiés','paris attacks','Eagles of Death Metal','pray4peace','Bataclan','Mohamed Abdeslam','Le Carillon','ISIL Paris','pray4syria',u'syria attaques','hezbollah','assad'] #querys = '"syrian refugees" since:2015-11-15 until:2015-11-28' # query = '"big bang theory" since:2015-09-01 until:2015-09-08' # RUSSIAN QUERIES #querys = ['pray4paris'] # ARABIC QUERIES #querys = ['pray4paris'] # Translate: gs = goslate.Goslate() langs=["fr"] count=10 pages=1 filename="frenchd02_.json" en_stop = get_stop_words('en') # Create p_stemmer of class PorterStemmer p_stemmer = PorterStemmer() gen_stop = ['-','rt','RT','get','ReTweet','Le',':','|','i','much','#'] cnt=0 #sin_id=670979025204094048 #maxi_id=670979025204994048 alchemyapi = AlchemyAPI()
def main(): print("Welcome to Hangman! A word will be chosen at random and", "you must try to guess the word correctly letter by letter", "before you run out of attempts. Good luck!", sep="\n") # setting up the play_again loop play_again = True while play_again: # set up the game loop # Unixwords is simply a newline-delimited list of dictionary words. # rstrip("\n") rstrip lets you pass in what characters you want to remove from the end of a string. chosen_word = random.choice( open("Unixwords").readlines()).lower().rstrip("\n") player_guess = None # will hold the players guess guessed_letters = [] # a list of letters guessed so far word_guessed = [] for letter in chosen_word: word_guessed.append( "-") # create an unguessed, blank version of the word randomNumber = random.randrange(len(chosen_word)) word_guessed[randomNumber] = chosen_word[ randomNumber] # give a hint character joined_word = None # joins the words in the list word_guessed HANGMAN = ( "--------\n| |\n|\n|\n|\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n|\n|\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n| -+-\n|\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n| /-+-\n|\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n|\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n|\n|\n|\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n| |\n|\n|\n|--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n| |\n| |\n|\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n| |\n| |\n| |\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n| |\n| | |\n| |\n|\n--------", "--------\n| |\n| 0\n| /-+-\ \n| |\n| |\n| | |\n| | |\n|\n--------" ) print(HANGMAN[0]) attempts = len(HANGMAN) - 1 while (attempts != 0 and "-" in word_guessed): print(("\nYou have {} attempts remaining").format(attempts)) joined_word = "".join(word_guessed) print(("The letter : {}").format(joined_word)) print(("You have guess letter : {}").format(guessed_letters)) try: player_guess = str( input("\nPlease select a letter between A-Z" + "\n> ")).lower() except KeyboardInterrupt: print("Ok ok, quitting") sys.exit(1) except EOFError: # Ctrl+D will cause EOFError exception sys.exit(0) except: # check valid input print("That is not valid input. Please try again.") continue else: if not player_guess.isalpha( ): # check the input is a letter. Also checks an input has been made. print("That is not a letter. Please try again.") continue elif len(player_guess ) > 1: # check the input is only one letter print("That is more than one letter. Please try again.") continue elif player_guess in guessed_letters: # check it letter hasn't been guessed already print( "You have already guessed that letter. Please try again." ) continue else: pass guessed_letters.append(player_guess) for idx, letter in enumerate(chosen_word): if player_guess == letter: word_guessed[ idx] = player_guess # replace all letters in the chosen word that match the players guess if player_guess not in chosen_word: attempts -= 1 print(HANGMAN[(len(HANGMAN) - 1) - attempts]) if "-" not in word_guessed: # no blanks remaining print(("\nCongratulations! {} was the word").format(chosen_word)) gs = goslate.Goslate() print(gs.translate(chosen_word, 'zh')) else: # loop must have ended because attempts reached 0 print(("\nUnlucky! The word was {}.").format(chosen_word)) gs = goslate.Goslate() print(gs.translate(chosen_word, 'zh')) print("\nWould you like to play again? [Y/N]\n") response = input("> ").lower() if response not in ("yes", "y"): play_again = False
def translate_into_lang(): _slate_ = goslate.Goslate() result = _slate_.translate(open('data/DATA', 'r').read(), entry.get()) label = Label(root, text=result) label.grid(row=2, column=0)
def main(): getting_tweets() gs = goslate.Goslate() for line in open("sentiments.txt").readlines(): print(gs.translate(line, 'en'))
"cfg/translator.config.yml", { "translationService": 0, "msTranslateID": '', "msTranslateSecret": '' } ) if plugin_config['translationService'] == 1 and plugin_config['msTranslateID'] != '' and plugin_config['msTranslateSecret'] != '': import microsofttranslator provider = "Bing" translator = microsofttranslator.Translator(plugin_config['msTranslateID'], plugin_config['msTranslateSecret']) lastKeyTime = time.time() else: import goslate provider = "Google" translator = goslate.Goslate() @p.on_initial_connect_hook def create_preferences(client): """ :type client: ShipProxy """ if client.playerId in data.clients.connectedClients: user_prefs = data.clients.connectedClients[client.playerId].preferences if not user_prefs.has_preference('translate_chat'): user_prefs.set_preference('translate_chat', False) user_prefs.set_preference('translate_out', False) @p.CommandHook("jpin", "Toggles proxy-end chat translation. (Powered by %s Translate, Incoming only.)" % provider)
def record_callback(reply): if reply.category != record.FromServer: return if reply.client_swapped: print "* received swapped protocol data, cowardly ignored" return if not len(reply.data) or ord(reply.data[0]) < 2: # not an event return data = reply.data while len(data): event, data = rq.EventField(None).parse_binary_value(data, record_dpy.display, None, None) # deal with the event type if event.type == X.ButtonRelease: # get text global Alive pipe = os.popen("xclip -o") text = pipe.readline().strip('\r\n\x00 ').lower() #如果首行以连字符'-'结尾,则去掉'-'和空格接次行,否则加空格接次行 if text.endswith('-'): text = text.strip(' -') + pipe.readline().strip('\r\n\x00 ').lower() else: text = text + ' ' + pipe.readline().strip('\r\n\x00 ').lower() text = text.strip() pipe.readlines() #清空管道剩余部分 pipe.close() print "您选取的是: ", text if(gl.pre_text != text and text!=""and gl.lock=="0" or text=="%lock%"): url = "" gl.pre_text = text if(False==os.path.exists(gl.cachedir)): os.system("mkdir \'" + gl.cachedir + "\'") for dir in (gl.origindir,gl.resultdir,gl.historydir,gl.keyworddir): if(False==os.path.exists(dir)): os.system("touch \'" + dir + "\'") #youdao if "%zh2enlj%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2enlj.html" gl.searchurl=gl.zh2enlj url = "" gl.func="lj" gl.Dict="youdao" gl.title="汉英例句" elif "%zh2japlj%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2japlj.html" gl.searchurl=gl.zh2japlj url = "" gl.func="lj" gl.Dict="youdao" gl.title="汉日例句" elif "%zh2kolj%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2kolj.html" gl.searchurl=gl.zh2kolj url = "" gl.func="lj" gl.Dict="youdao" gl.title="汉韩例句" elif "%zh2frlj%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2frlj.html" gl.searchurl=gl.zh2frlj url = "" gl.func="lj" gl.Dict="youdao" gl.title="汉法例句" elif "%zh2en%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2en.html" gl.searchurl=gl.zh2en url = "" gl.Dict="youdao" gl.title="汉英互译" elif "%zh2jap%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2jap.html" gl.searchurl=gl.zh2jap url = "" gl.Dict="youdao" gl.title="汉日互译" elif "%zh2ko%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2ko.html" gl.searchurl=gl.zh2ko url = "" gl.Dict="youdao" gl.title="汉韩互译" elif "%zh2fr%" in text: gl.homeurl="file:///usr/share/openyoudao/zh2fr.html" gl.searchurl=gl.zh2fr url = "" gl.Dict="youdao" gl.title="汉法互译" #config elif "%index%" in text: gl.homeurl="file:///usr/share/openyoudao/config.html" url = "" gl.title="有道首页" elif "%helps%" in text: gl.homeurl="file:///usr/share/openyoudao/help.html" url = "" gl.title="使用说明" elif "%goslate%" in text: gl.homeurl="file:///usr/share/openyoudao/goslate.html" url = "" gl.Dict="google" gl.title="谷歌翻译" elif "%donate%" in text: gl.homeurl="file:///usr/share/openyoudao/donate.html" url = "" gl.title="捐赠页面" elif "%expand%" in text: gl.homeurl="file:///usr/share/openyoudao/expand.html" url = "" gl.title="展开选项" elif "%history%" in text: gl.homeurl= "file://" + gl.historydir if Alive==1: his_tar=open(gl.historydir,'w') print >> his_tar,"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>History</title></head><body><p>%s %s</p>"%("%index%","%expand%") keyword=open(gl.keyworddir,'r') print >> his_tar,''.join(keyword.readlines()[::-1]) print >> his_tar,"</body></html>" his_tar.close() keyword.close() url = "" gl.title="取词历史" elif "%lock%" in text: if gl.lock=="0": gl.lock="1" gl.homeurl="file:///usr/share/openyoudao/lock.html" gl.title="锁定取词" else: gl.lock="0" gl.homeurl="file:///usr/share/openyoudao/unlock.html" gl.title="取词解锁" url = "" elif "%exits%" in text: Alive=0 else: url= gl.searchurl + text if url !="": if Alive==1: k_tar=open(gl.keyworddir,'a') print >> k_tar,"<p>%s</p>" % text k_tar.close() #fp = file(gl.keyworddir) #lines = [] #for line in fp: # 内置的迭代器, 效率很高 # lines.append(line) #fp.close() #lines.insert(0, "<p>%s</p>" % text) # 在第二行插入 #s = '\n'.join(lines) #fp = file(gl.keyworddir, 'w') #fp.write(s) #fp.close() #[google youdao] if gl.Dict=="google": gs = goslate.Goslate() gl.lang=gs.detect(text) g_tar=open(gl.googledir,'w+') if gl.lang=='zh-CN': basehtml="<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Google Translate</title></head><body><p>Source Language: %s</p><p>Target Language : %s</p><p>Selected Text : %s</p><p>Target Text : %s</p><p>%s %s</p></body></html>"%(gl.lang,'en',text,gs.translate(text, 'en'),"%index%","%expand%") else: basehtml="<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Google Translate</title></head><body><p>Source Language: %s</p><p>Target Language : %s</p><p>Selected Text : %s</p><p>Target Text : %s</p><p>%s %s</p></body></html>"%(gl.lang,'zh-CN',text,gs.translate(text, 'zh-CN'),"%index%","%expand%") print >> g_tar,basehtml g_tar.close() gl.homeurl= "file://" + gl.googledir if gl.Dict=="youdao": #os.system("curl -m 5 -A \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36\" -s -w %{http_code}:%{time_connect}:%{time_starttransfer}:%{time_total}:%{speed_download} -o \'" + gl.origindir +"\' \'" + url+ "\'") #获得网页(非代理) os.system("curl -m 5 -s -w %{http_code}:%{time_connect}:%{time_starttransfer}:%{time_total}:%{speed_download} -o \'" + gl.origindir +"\' \'" + url+ "\'") #获得网页(非代理) fusionyoudao.reconstruct(gl.func) gl.homeurl="file://" + gl.resultdir #合成最终缓冲访问地址 if Alive==1: window.settitle(gl.title) window.load(gl.homeurl) window.show()
def handle_message(event): text = event.message.text #simplify for receove message sender = event.source.user_id #get user_id gid = event.source.sender_id #get group_id #=====[ LEAVE GROUP OR ROOM ]==========[ ARSYBAI ]====================== if "/yt" in text: separate = text.split(" ") search = text.replace(separate[0] + " ", "") url = requests.get( "http://api.w3hills.com/youtube/search?keyword={}&api_key=86A7FCF3-6CAF-DEB9-E214-B74BDB835B5B" .format(search)) data = url.json() no = 0 result = "Search" for anu in data["videos"]: no += 1 result += "\n{}. {}\n{}".format(str(no), str(anu["title"]), str(anu["webpage"])) result += "\nall{}".format(str(len(data["videos"]))) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=result)) if "/news" in text: try: separate = text.split(" ") country = text.replace(separate[0] + " ", "") if (separate == None): country == "th" user_agent = {'User-agent': 'Mozilla/5.0'} url = requests.get( "https://newsapi.org/v2/top-headlines?country={}&apiKey=763b6fc67a594a4e9e0f9d29303f83dd" .format(country)) data = url.json() result = "New Releases" for anu in data["articles"]: if len(result) > 500: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=result)) else: result += "\n" + anu["title"] + "\n" + anu["url"] + "\n" line_bot_api.reply_message(event.reply_token, TextSendMessage(text=result)) except Exception as Error: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=Error)) if "/snews" in text: separate = text.split(" ") searchx = text.replace(separate[0] + " ", "") search = searchx gs = goslate.Goslate() search = gs.translate(searchx, 'en') r = requests.get("http://www.google.co.th/search?q=" + search + "&tbm=nws") content = r.text news_summaries = [] soup = BeautifulSoup(content, "html.parser") st_divs = soup.findAll("div", {"class": "st"}) g_divs = soup.findAll("div", {"class": "g"}) trs = "News about " + searchx news_d = [] for g_div in g_divs: news_d.append(g_div.text) for st_div in st_divs: news_summaries.append(st_div.text) for i in news_summaries: for x in news_d: try: if len(trs) > 600: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=trs)) else: gs = goslate.Goslate() x = gs.translate(x, 'en') trs += "\n\n" + x + "\nRead more at" except Exception as error: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=error)) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=trs)) if text == "/bye": if (event.source.user_id == "U2c7d1341178eed8c93c23e914cbcb6a0"): confirm_template_message = TemplateSendMessage( alt_text='God message', template=ConfirmTemplate( text='Will remove the bot? Are you sure?', actions=[ PostbackAction(label='sure', text='goodbye', data='action=buy&itemid=1'), MessageAction(label='Not', text='...') ])) line_bot_api.reply_message(event.reply_token, confirm_template_message) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="This user is not allowed.")) if "/ti/g/" in text: link_re = re.compile( '(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?') links = link_re.findall(text) n_links = [] for l in links: if l not in n_links: n_links.append(l) for ticket_id in n_links: group = line_bot_api.findGroupByTicket(ticket_id) line_bot_api.acceptGroupInvitationByTicket(group.id, ticket_id) if text == '/contact': buttons_template_message = TemplateSendMessage( alt_text='God message', template=ButtonsTemplate( thumbnail_image_url= 'https://gamingroom.co/wp-content/uploads/2017/11/CyCYOArUoAA2T6d.jpg', title='Contact', text='contact', actions=[ PostbackAction(label='Line', text='http://line.me/ti/p/~1535915621_', data='action=buy&itemid=1'), MessageAction(label="Facebook", text='https://www.facebook.com/DPunisher'), URIAction(label='Contact', uri='http://line.me/ti/p/~1535915621_') ])) line_bot_api.reply_message(event.reply_token, buttons_template_message) bubble = BubbleContainer( direction='ltr', hero=ImageComponent( url= 'http://images4.fanpop.com/image/photos/15800000/Animes-anime-cuties-15887436-1400-875.jpg', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://line.me/ti/p/~esci_', label='@')), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='PASUNx', weight='bold', size='xl'), # review # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='place', color='#aaaaaa', size='sm', flex=1), TextComponent(text='Bangkok, Thailand', wrap=True, color='#666666', size='sm', flex=5) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Time', color='#aaaaaa', size='sm', flex=1), TextComponent( text="00:00 - 23:59", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # separator SeparatorComponent(), # websiteAction ButtonComponent(style='link', height='sm', action=URIAction( label='contact', uri="https://line.me/ti/p/~esci_")) ]), ) #message = FlexSendMessage(alt_text="God message", contents=bubble) #line_bot_api.reply_message( # event.reply_token, # buttons_template_message #) if '/wiki ' in text: try: wiki = text.replace("/wiki ", "") wikipedia.set_lang("en") pesan = "Wikipedia About" pesan += wikipedia.page(wiki).title pesan += "\n\n" pesan += wikipedia.summary(wiki, sentences=1) pesan += "\n\nRead more\n" pesan += wikipedia.page(wiki).url titlex = wikipedia.page(wiki).title textx = wikipedia.summary(wiki, sentences=1) urlx = wikipedia.page(wiki).url line_bot_api.reply_message(event.reply_token, TextSendMessage(text=pesan)) except: try: pesan = "Over limit message! Please click the link below to read more.\n" pesan += wikipedia.page(wiki).url line_bot_api.reply_message(event.reply_token, TextSendMessage(text=pesan)) except Exception as e: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=str(e))) if text == "/kick": line_bot_api.kickoutFromGroup(0, event.source.group_id, "Udaa0a2f396dd41e4398b106d903d92fd") if text == "/2kick": line_bot_api.kickoutFromGroup(event.source.group_id, "u541bbaba15d68f3a652106a0de5a3e94") if text == "/3kick": line_bot_api.kickoutFromGroup(0, event.source.group_id, "u541bbaba15d68f3a652106a0de5a3e94") if text == "/4kick": line_bot_api.kickoutFromGroup(event.source.group_id, "Udaa0a2f396dd41e4398b106d903d92fd") if text == '/gid': profile = line_bot_api.get_profile(event.source.user_id) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.display_name)) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.source.group_id)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.picture_url)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.status_message)) if text == '/id': profile = line_bot_api.get_profile(event.source.user_id) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.display_name)) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.source.user_id)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.picture_url)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.status_message)) if text == '/bio': profile = line_bot_api.get_profile(event.source.user_id) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.display_name)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.source.user_id)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.picture_url)) line_bot_api.reply_message( event.reply_token, TextSendMessage(text=profile.status_message)) if text == '/pic': profile = line_bot_api.get_profile(event.source.user_id) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.display_name)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.source.user_id)) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=profile.picture_url)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.status_message)) if text == '/name': profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=profile.display_name)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.source.user_id)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.picture_url)) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=profile.status_message)) if text == 'goodbye': if (event.source.user_id == "U2c7d1341178eed8c93c23e914cbcb6a0"): if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Outgoing...')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Outgoing...')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="The bot can not leave chat. 1:1 have")) elif "/idline " in event.message.text: skss = event.message.text.replace('/idline ', '') sasa = "http://line.me/R/ti/p/~" + skss text_message = TextSendMessage(text=sasa) line_bot_api.reply_message(event.reply_token, text_message) elif '/check' in text: originURLx = text.split(" ") originURL = text.replace(originURLx[0] + " ", "") result = requests.get( "http://shorturlbyzefyrinusx.000webhostapp.com/api/check.php?id=" + originURL + "&type=api").text line_bot_api.reply_message(event.reply_token, TextSendMessage(text=result)) elif '/shorturl' in text: originURLx = text.split(" ") originURL = text.replace(originURLx[0] + " ", "") result = requests.get( "http://shorturlbyzefyrinusx.000webhostapp.com/api/urlshorten.php?url=" + originURL).text buttons_template_message = TemplateSendMessage( alt_text='God message', template=ButtonsTemplate( thumbnail_image_url= 'https://gamingroom.co/wp-content/uploads/2017/11/CyCYOArUoAA2T6d.jpg', title='RESULT', text=result, actions=[ PostbackAction(label='information URL', text='/check ' + result, data='action=buy&itemid=1'), MessageAction(label="URL", text=result), URIAction(label='turns on URL', uri=result) ])) line_bot_api.reply_message(event.reply_token, buttons_template_message) elif '/help' in text: line_bot_api.reply_message(event.reply_token, TextSendMessage(text=helpmessage)) elif '/test' in text: buttons_template_message = TemplateSendMessage( alt_text='Buttons template', template=ButtonsTemplate( thumbnail_image_url='https://example.com/image.jpg', title='Menu', text='God message', actions=[ PostbackAction(label='postback', text='postback text', data='action=buy&itemid=1'), MessageAction(label='message', text='message text'), URIAction(label='uri', uri='http://example.com/') ])) line_bot_api.reply_message(event.reply_token, image_carousel_template_message)
def translate_main(start=0, count=100, logger=None, db_spec='DB_SPEC'): if not logger: logger = get_logger() with RoseVisionDb(getattr(global_settings, 'DATABASE')[db_spec]) as db: gs = goslate.Goslate() proxy_name = get_proxy() proxy = urllib2.ProxyHandler({'http': proxy_name }) if proxy_name else None opener = urllib2.build_opener(proxy) backup_gs = goslate.Goslate(opener=opener, debug=True) sorted_region = get_sorted_region(db) fingerprint_start = start fingerprint_count = count logger.info(str.format("Translate process start")) while 1: fingerprints = get_fingerprints(db, fingerprint_start, fingerprint_count) if not fingerprints: logger.info(str.format("Translate process end")) break else: logger.info( str.format("Translate process offset : {0} count : {1}", fingerprint_start, len(fingerprints))) fingerprint_start += fingerprint_count for fingerprint in fingerprints: is_exist = db.query_match({'fingerprint'}, 'products_translate', { 'fingerprint': fingerprint }).num_rows() if is_exist: continue product_infos = get_product(db, fingerprint) # 按权重排序 product_infos = sorted(product_infos.items(), key=lambda e: sorted_region.index(e[0])) product_infos = {e[0]: e[1] for e in product_infos} final_description_cn = None final_details_cn = None final_description_en = None final_details_en = None description_cn = check_cns_region(product_infos, 'description') details_cn = check_cns_region(product_infos, 'details') if is_chs(description_cn): final_description_cn = description_cn elif is_cht(description_cn): final_description_cn = translate_text_to( gs, description_cn, 'zh-cn', source='zh-cn', backup_gs=backup_gs) if is_chs(details_cn): final_details_cn = details_cn elif is_cht(details_cn): final_details_cn = translate_text_to(gs, details_cn, 'zh-cn', source='zh-cn', backup_gs=backup_gs) description_en = check_ens_region(product_infos, 'description') details_en = check_ens_region(product_infos, 'details') if is_eng(description_en): final_description_en = description_en if is_eng(details_en): final_details_en = details_en try: if not final_description_cn: for region, info in product_infos.items(): if product_infos[region]['description']: final_description_cn = translate_text_to( gs, product_infos[region]['description'], 'zh-cn', backup_gs=backup_gs) break if not final_details_cn: for region, info in product_infos.items(): if product_infos[region]['details']: final_details_cn = translate_text_to( gs, product_infos[region]['details'], 'zh-cn', backup_gs=backup_gs) break if not final_description_en: for region, info in product_infos.items(): if region != 'cn': # 尽量不从中文翻译到其他外语 if product_infos[region]['description']: final_description_en = translate_text_to( gs, product_infos[region]['description'], 'en', backup_gs=backup_gs) break if not final_details_en: for region, info in product_infos.items(): if region != 'cn': # 尽量不从中文翻译到其他外语 if product_infos[region]['details']: final_details_en = translate_text_to( gs, product_infos[region]['details'], 'en', backup_gs=backup_gs) break if not final_description_en and final_description_cn: final_description_en = translate_text_to( gs, final_description_cn, 'en', 'zh-cn', backup_gs=backup_gs) if not final_details_en and final_details_cn: final_details_en = translate_text_to( gs, final_details_cn, 'en', 'zh-cn', backup_gs=backup_gs) except: pass insert_dict = {} if final_description_cn: insert_dict['description_cn'] = final_description_cn if final_details_cn: insert_dict['details_cn'] = final_details_cn if final_description_en: insert_dict['description_en'] = final_description_en if final_details_en: insert_dict['details_en'] = final_details_en if insert_dict: insert_dict['fingerprint'] = fingerprint result = db.query_match({'fingerprint'}, 'products_translate', {'fingerprint': fingerprint}) try: if result.num_rows() == 0: db.insert(insert_dict, 'products_translate') else: db.update( insert_dict, 'products_translate', str.format('fingerprint="{0}"', fingerprint)) except: logger.info( str.format( "Error: Insert or update sql error with {0}", insert_dict)) pass else: logger.info( str.format( "Error: No insert_dict for fingerprint : {0}", fingerprint))
def trns(word, lang="en"): gs = goslate.Goslate() a = gs.translate(word, lang) return a
def slate(tran, lang): #I think they changed the translation API? gs = goslate.Goslate() tr = gs.translate(tran, lang) return tr