Exemplo n.º 1
0
 def _translate_in_all_languages(self, language_o, words):
     for language in Language.list_all_languages().split('\n'):
         try:
             t = Translate(Language(language_o.upper()), Language(language))
             t.translate(words.encode('utf-8')).addCallback(self._success, jid, prot, language) \
                                               .addErrback(self._error, jid, prot) 
         except Exception:
             pass
Exemplo n.º 2
0
 def generate_query(self):
     if 'workload' in self.scheme:
         rel_list = [(x.source, x.target, x.label)
                     for x in self.relation_ins]
         wl = Workload(list(self.node_labels), rel_list, self.workload)
         queries = wl.generate_workload()
         filename = 'query.cypher'
         tl = Translate(filename)
         tl.translate(queries)
Exemplo n.º 3
0
 def _numba_compile(func):
     global __tr_map__
     llvm = kws.pop("llvm", True)
     if func in __tr_map__:
         print ("Warning: Previously compiled version of %r may be " "garbage collected!" % (func,))
     t = Translate(func, *args, **kws)
     t.translate()
     __tr_map__[func] = t
     return t.get_ctypes_func(llvm)
Exemplo n.º 4
0
 def translate_word(self):
     ab = self.TargetLanguageList1.get(
         self.TargetLanguageList1.curselection())
     nput = self.imgTxtScrolled.get("1.0", END)
     obj2 = Translate(nput)
     obj2.translate(ab)
     translatedLang = obj2.translatedLang()
     self.TargetLanguageTextScrolled.delete('0', END)
     self.TargetLanguageTextScrolled.insert('0', translatedLang)
     print(ab)
Exemplo n.º 5
0
def vectorize(func):
    try:
	t = Translate(func)
	t.translate()
	print t.mod
	return t.make_ufunc()
    except:
	print "Warning: Could not create fast version..."
	import numpy
	return numpy.vectorize(func)
Exemplo n.º 6
0
 def _numba_compile(func):
     global __tr_map__
     llvm = kws.pop('llvm', True)
     if func in __tr_map__:
         print(
             "Warning: Previously compiled version of %r may be "
             "garbage collected!" % (func, ))
     t = Translate(func, *args, **kws)
     t.translate()
     __tr_map__[func] = t
     return t.get_ctypes_func(llvm)
Exemplo n.º 7
0
 def __call__(self, jid, prot, args):
     language_o, raw = args.split(' ', 1)
     words, languages = raw.split(' -> ')
     languages = [ lan.strip() for lan in languages.split(',') ]
     for language in languages:
         try:
             t = Translate(Language(language_o.upper()), Language(language.upper()))
             t.translate(words.encode('utf-8')).addCallback(self._success, jid, prot, language.lower()) \
                                               .addErrback(self._error, jid, prot)
         except Exception, e:
             self._error(e.message, jid, prot)
Exemplo n.º 8
0
    def my_validater(self):
        nput = self.InputText.get()

        self.OutputText.delete('0', END)
        ab = self.TargetLanguageList2.get(
            self.TargetLanguageList2.curselection())

        obj2 = Translate(nput)
        obj2.translate(ab)
        translatedLang = obj2.translatedLang()
        self.OutputText.insert('0', translatedLang)

        return True
Exemplo n.º 9
0
def vectorize(func):
    global __tr_map__
    try:
        if func not in __tr_map__:
            t = Translate(func)
            t.translate()
            __tr_map__[func] = t
        else:
            t = __tr_map__[func]
        return t.make_ufunc()
    except:
        print "Warning: Could not create fast version..."
        import numpy

        return numpy.vectorize(func)
Exemplo n.º 10
0
    def __call__(self, iq, cmd, form):
        lin = form.fields['in'].value
        louts = set(form.fields['out'].values)
        text = form.fields['text'].value.encode('utf-8')

        log.msg(u"From %s to %s:  %s" % (lin, louts, unicode(text)))

        deferreds = []
        responses = {}

        def _handleResponse(out, lang):
            responses[lang] = out

        for l in louts:
            try:
                t = Translate(Language(lin.upper()), Language(l.upper()))
                d = t.translate(text)
                deferreds.append(d)
                d.addCallback(_handleResponse, l)
            except:
                log.err()

        dl = defer.DeferredList(deferreds, consumeErrors=1)
        dl.addCallback(self._formatResponses, iq, cmd, responses)

        return dl
Exemplo n.º 11
0
def vectorize(func):
    global __tr_map__
    try:
        if func not in __tr_map__:
            t = Translate(func)
            t.translate()
            __tr_map__[func] = t
        else:
            t = __tr_map__[func]
        return t.make_ufunc()
    except Exception as msg:
        print "Warning: Could not create fast version...", msg
        import traceback
        traceback.print_exc()
        import numpy
        return numpy.vectorize(func)
Exemplo n.º 12
0
class ArticleScraper(Crawler):

    def __init__(self):
        # initialize crawler object for Article Scraper
        super(ArticleScraper, self).__init__()
        self.crawler = self.browser

        # initialize a translator object 
        self.translator = Translate()

        self.CSS_SELECTOR = "div.bilingual.cf > div.cf.articleContent"

    def extract(self, url):
        """
        For each article, separate the chinese and english text and return a list of list of
        english and chinese text of this article
        """

        URL = url + "dual/"

        self.crawler.get(URL)

        ch_text = [] # chinese sentence
        en_text = [] # english sentence
        tr_text = [] # sentence translated from chinese to english

        try:    
            elements = self.crawler.find_elements_by_css_selector(self.CSS_SELECTOR)

            for i in range(len(elements) - 1):
                en, ch = elements[i].text.split("\n")
                # print (en)
                # print (cn)
                en_text.append(en)
                ch_text.append(ch)

                # translate chinese to english
                # this function has been shifted to another file

                tmp_translated = self.translator.translate(ch)
                tr_text.append(tmp_translated)

        except:
            # raise ValueError("Unable to extract content from URL:", URL)
            print ("Unable to extract content from URL:", URL)

        return (en_text, ch_text, tr_text)
Exemplo n.º 13
0
    def handle_message(self, message: Dict[str, Any],
                       bot_handler: Any) -> None:
        string = message['content'].split()
        content = "something went wrong"
        check = string[0].lower()
        if check == "calculate":
            content = Calculator.calculate(string)
        elif check == "coding_contest":
            content = Coding().getList()
        elif check.lower() == 'define':
            dictword = string[1]
            content = Dictionary.words(dictword)
        elif check.lower() == 'telljoke':
            content = Joke.tellJoke()
        elif check == "cricknews":
            content = Cricket().news()
        elif check == "proxy":
            if len(string) > 1:
                if string[1].lower() == "working":
                    content = Proxy.getWorkingProxy()
                    content = "Working Proxies in Your Area \n\n" + content
                elif string[1].lower() == "help":
                    content = Proxy.getHelpList()
                else:
                    content = WitHandler.getInfo(message['content'])
            else:
                content = Proxy.getProxyStatus()
                content = "Proxies Status--->\n\n" + content
        elif check.lower() == "play":
            try:
                pid = check_output(["pidof"], "mpg321")
                os.kill(int(pid), signal.SIGKILL)
                os.remove("hello.mp3")
                content = Music.main(string[1:])
            except:
                content = Music.main(string[1:])
            bot_handler.send_reply(message, "playing song ")
        elif check == "stop":
            pid = check_output(["pidof", "mpg321"])
            #print(int(pid))
            os.kill(int(pid), signal.SIGKILL)
            content = "Bye........:)"
            bot_handler.send_reply(message, content)
        elif check == "college_notice":
            content = Dean.getNotice()
        elif check == "add" and string[1] == "meeting":
            content = "Enter <Date> as <dd/mm/yyyy> <Time> as <hrs:min> and am/pm and purpose(one word)"

        elif len(string[0].split('/')) == 3:
            res = Meeting.AddMeeting(string)
            if res.lower() == "ok":
                content = "New Meeting successfully Added "
            else:
                content = res
        elif check == "show" and string[1].lower() == "meetings":
            content = Meeting.ShowMeeting()
        elif check == "pnr" and string[1].lower() == "status":
            content = Pnr.getpnr(string[2])
        elif check == "message" or check == "find" or check == "where":
            content = Send_message.sendMessage(string)
        # elif check=="mood":
        #     Mood.capture();
        elif check == "symptom":
            string_1 = " "
            gender = string[1]
            dob = string[2]
            st = string[3:]
            string_1 = string_1.join(st)
            content = Sympton.getExactSympton(string_1)
            try:
                content = "Please Tell me clearly\n" + content
            except:
                p = int(content)
                content = Sympton.getIssueId(str(p), gender, dob)
        elif check == "search":
            st = " "
            strlist = string[1:]
            st = st.join(strlist)
            st = FriendLocation.plot(st)
            if "https" in st:
                webbrowser.open(st)
                content = "check out below link \n" + st
            else:
                content = "Please type exact name :)\n" + st
        elif check == "getjobs":
            content = JOBS.getjobs()
        elif check == "translate":
            stri = " "
            stri = stri.join(list(string[1:]))
            content = Translate.translate(stri)
        elif check == "help":
            Help.Message()
            content = "Message sent"
        elif check == "nearby":
            content = Nearby.Place(string[1])
        else:
            #print(message['content'])
            content = WitHandler.getInfo(message['content'])
        bot_handler.send_reply(message, content)
Exemplo n.º 14
0
class ZulipBot(object):
    def __init__(self):
        self.client = zulip.Client(site="https://saharsh.zulipchat.com/api/")
        self.subscribe_all()
        self.trans = Translate()
        self.tw = Twimega()
        self.pnr = Pnr()
        self.weather = Weather()
        self.geo = Geocode()
        self.searching = Places()
        self.help = Help()

        print("Initialization Done ...")
        self.subkeys = [
            "translate", "weather", "pnr", "post", "post_image", "twitter",
            "help", "search"
        ]

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']
        if sender_email == BOT_MAIL:
            return
        if content[0].lower() == "ninjas33" or content[0] == "@**ninjas33**":
            if content[1].lower() == "translate":
                ip = content[2:]
                ip = " ".join(ip)
                message = self.trans.translate(ip)

                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "pnr":
                message = self.pnr.get_pnr(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "twitter":
                if len(content) > 2 and content[2] == "post":
                    if self.tw.stream == msg["display_recipient"]:
                        status = self.tw.post(" ".join(content[3:]))
                        x = json.dumps(status._json)
                        x = json.loads(x)
                        message = "https://twitter.com/{}/status/{}".format(
                            x["user"]["screen_name"], x["id_str"])
                        message = "Tweet Posted\n" + message
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": message
                        })
                    else:
                        message = "Use the stream **{}** to post a tweet".format(
                            self.tw.stream)
                        self.client.send_message({
                            "type": "stream",
                            "to": sender_email,
                            "content": message
                        })

            if len(content) > 2 and content[2] == "post_image":
                if self.tw.stream == msg["display_recipient"]:
                    status = self.tw.post_image(content[3],
                                                " ".join(content[4:]))
                    if isinstance(status, str):
                        message = status
                    else:
                        x = json.dumps(status._json)
                        x = json.loads(x)
                        message = "https://twitter.com/{}/status/{}".format(
                            x["user"]["screen_name"], x["id_str"])
                        message = "Tweet Posted\n" + message
                    self.client.send_message({
                        "type": "stream",
                        "subject": msg["subject"],
                        "to": msg["display_recipient"],
                        "content": message
                    })
                else:
                    message = "Use the stream **{}** to post a tweet".format(
                        self.tw.stream)
                    self.client.send_message({
                        "type": "private",
                        "to": sender_email,
                        "content": message
                    })

            if content[1].lower() == "help" and len(content) == 2:
                message = self.help.get_help()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "weather":
                place = " ".join(content[2:])
                try:
                    result = self.weather.getWeather(self.geo.convert(place))
                    message = "**" + "Weather update of " + place + "**" + "\n" + "Summary : " + "**" + result[
                        "currently"][
                            "summary"] + "**" + "\n" + "Temparature : " + "**" + str(
                                result["currently"]["temperature"]
                            ) + "**" + '\n' + "Apparent Temparature : " + "**" + str(
                                result["currently"]["apparentTemperature"]
                            ) + "**" + "\n" + "Dew Point : " + "**" + str(
                                result["currently"]["dewPoint"]
                            ) + "**" + "\n" + "Humidity : " + "**" + str(
                                result["currently"]["humidity"]) + "**"
                except KeyError:
                    message = "Not Working Right Now"
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "search":
                place = " ".join(content[2:])
                try:
                    result = self.searching.getPlaces(place)
                    y = result['results']
                    message = "Result for search \n"
                    #print(result)
                    for i in range(len(y)):
                        message += str(
                            i + 1) + ". " + y[i]['name'] + " , Rating:" + str(
                                y[i]['rating']
                            ) + " \n Address : " + y[i]['formatted_address']
                        message += "\n"
                except KeyError:
                    message = "Not Working Right Now"
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

        elif "ninjas33" in content and content[0] != "ninjas33":
            self.client.send_message({
                "type": "stream",
                "subject": msg["subject"],
                "to": msg["display_recipient"],
                "content": "Hey there! :blush:"
            })
        else:
            return
Exemplo n.º 15
0
class ZulipBot(object):
    def __init__(self):
        self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/")
        self.subscribe_all()
        self.chatbot = ChatBot(
            "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer')
        self.chatbot.train("chatterbot.corpus.english")
        self.crypto = Crypto()
        self.trans = Translate()
        self.g = Giphy()
        self.w = WikiPedia()
        self.tw = Twimega()
        self.motivate = Motivate()
        self.shortenedurl = Urlshortener()
        self.hacknews = Hackernews()
        self.geo = Geocode()
        self.weather = Weather()
        self.dict_ = Dictionary()
        self.joke = Joke()
        self.pnr = Pnr()
        self.mustread = Mustread()
        self.ss = Ss()
        self.cricket = Cricket()
        self.poll = Poll()
        self.subkeys = [
            "crypto", "translate", "define", "joke", "weather", "giphy", "pnr",
            "mustread", "poll", "hackernews", "hn", "HN", "motivate",
            "twitter", "screenshot", "memo", "cricnews", "help", "shorturl"
        ]

    def urls(self, link):
        urls = re.findall(
            'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            link)
        return urls

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def help(self):
        message = "**Welcome to Omega Bot**\nOmega Bot has various subfields\nType `omega help <subfield>` to get help for specific subfield.\n"
        message += "\n**Subfields**\n"
        message += "`crypto` - Get Crypto Currency Prices\n"
        message += "`translate` - Translate Foreign Languages to English\n"
        message += "`define` - Get Word Meanings\n"
        message += "`joke` - Get Jokes\n"
        message += "`weather` - Get Weather Details\n"
        message += "`giphy` - Get GIFs from Giphy\n"
        message += "`pnr` - Get PNR Status\n"
        message += "`mustread` - Share Must Read Messages to Teammates\n"
        message += "`poll` - Create Amazing Polls in Zulip\n"
        message += "`hn` - Get Top Hacker News Results\n"
        message += "`motivate` - Get Motivational Quotes\n"
        message += "`twitter` - Tweet Directly from Zulip\n"
        message += "`screenshot` - Take Screenshot of Web Pages\n"
        message += "`memo` - Create Memos in Cloud\n"
        message += "`cricnews` - Get Cricket News\n"
        message += "`shorturl` - Create goo.gl short URLs\n"
        message += "\nIf you're bored Talk to Omega Bot, it will supercharge you"
        return message

    def help_sub(self, key):
        key = key.lower()
        message = "**Usage**\n"
        if key == "crypto":
            message += "`omega crypto <crypto-currency-code>` - To Get Price in USD\n"
            message += "`omage crypto <crypto-currency-code> in <currency>` - To Get Price in Specified Currency\n"
        elif key == "translate":
            message += "`omega translate <phrase to be translated>` - To Get Translate from Foreign Language to English\n"
        elif key == "define":
            message += "`omega define <word>` - To Get Definition of the word\n"
        elif key == "joke":
            message += "`omega joke` - Get a Joke\n"
        elif key == "weather":
            message += "`omega weather <location>` - Get the weather details of the given place\n"
        elif key == "giphy":
            message += "`omega giphy <search word>` - Get a random GIF from Giphy related to the given search word\n"
        elif key == "pnr":
            message += "`omega pnr <valid pnr number>` - Get PNR Details of the Given PNR number\n"
        elif key == "mustread":
            message += "`omega mustread @**<User Mention>** <message>` - Pass Important Messages to Team Members\n"
        elif key == "poll":
            message += "`omega poll create <number of choices> question <question> option <option1> <option2>...` - To Create a New Poll. It will return with a Poll ID Number\n"
            message += "`omega poll vote <POLL_ID> <Choice>` - To Vote for specified option\n"
            message += "`omega poll show all` - List all available polls\n"
            message += "`omega poll show <ID>` - List all details from specified Poll ID\n"
            message += "`omega poll delete all` - Delete All Polls\n"
            message += "`omega poll delete <ID>` - Delete Poll with specified ID\n"
        elif key == "hn" or key == "hackernews":
            message += "`omega hn` OR `omega hackernews` - Show Top 10 stories from Hacker News\n"
        elif key == "motivate":
            message += "`omega motivate` - Get a refreshing and motivating quote\n"
        elif key == "twitter":
            message += "`omega twitter post <tweet>` - Post a Tweet with given tweet\n"
            message += "`omega twitter post_image <image_url> <tweet>` - Post a Tweet with given tweet and image url\n"
        elif key == "screenshot":
            message += "`omega screenshot <website url>` - Take a screenshot of the given url\n"
        elif key == "memo":
            message += "`omega memo <filename>` - Creates a New Memo file and returns its link\n"
        elif key == "cricnews":
            message += "`omega cricnews` - Get top 10 Cricket News\n"
        elif key == "shorturl":
            message += "`omega shorturl <url>` - Get a Shorten URL from goo.gl\n"
        else:
            message = self.help()
            message += "\n{} is not a valid subfield\n".format(key)
        return message

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']

        print(content)

        if sender_email == BOT_MAIL:
            return

        print("yeah")

        if content[0].lower() == "omega" or content[0] == "@**omega**":
            if content[1].lower() == "crypto":
                if len(content) > 3 and content[3].lower() == "in":
                    message = self.crypto.get_price(content[2], content[4])
                else:
                    message = self.crypto.get_price(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "translate":
                ip = content[2:]
                ip = " ".join(ip)
                message = self.trans.translate(ip)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "define":
                word = content[2].lower()
                result = self.dict_.words(word)
                print(result)
                self.client.send_message({
                    "type":
                    "stream",
                    "subject":
                    msg["subject"],
                    "to":
                    msg["display_recipient"],
                    "content":
                    "**" + word + " means :" + "**" + '\n' + result
                })
            if content[1].lower() == "screenshot":
                result = self.ss.get_ss(content[2])
                print(result)
                self.client.send_message({
                    "type":
                    "stream",
                    "subject":
                    msg["subject"],
                    "to":
                    msg["display_recipient"],
                    "content":
                    "Screenshot taken :wink:\n[Screenshot Link](" + result +
                    ")"
                })
            if content[1].lower() == "joke":
                text = self.joke.tellJoke()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": text
                })
            if content[1].lower() == "weather":
                place = " ".join(content[2:])
                try:
                    result = self.weather.getWeather(self.geo.convert(place))
                    message = "**" + "Weather update of " + place + "**" + "\n" + "Summary : " + "**" + result[
                        "currently"][
                            "summary"] + "**" + "\n" + "Temparature : " + "**" + str(
                                result["currently"]["temperature"]
                            ) + "**" + '\n' + "Apparent Temparature : " + "**" + str(
                                result["currently"]["apparentTemperature"]
                            ) + "**" + "\n" + "Dew Point : " + "**" + str(
                                result["currently"]["dewPoint"]
                            ) + "**" + "\n" + "Humidity : " + "**" + str(
                                result["currently"]["humidity"]) + "**"
                except KeyError:
                    message = "Weather Info is Not Working Right Now"
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "giphy":
                text = content[2:]
                text = " ".join(text)
                im = str(self.g.search(text))
                message = im[:im.find("?")]
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == 'memo':
                credentials = gdrivesignin.get_credentials()
                http = credentials.authorize(httplib2.Http())
                service = discovery.build('drive', 'v3', http=http)
                file_metadata = {'name': content[2], 'mimeType': "text/plain"}
                file = service.files().create(body=file_metadata,
                                              fields='id').execute()
                web_link = service.files().get(
                    fileId=file['id'],
                    fields="webViewLink").execute()['webViewLink']
                self.client.send_message({
                    "type":
                    "stream",
                    "to":
                    stream_name,
                    "subject":
                    stream_topic,
                    "content":
                    'Memo created.\nView & edit it at: ' + web_link
                })
            if content[1].lower() == "pnr":
                message = self.pnr.get_pnr(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "mustread":
                email = self.mustread.get_email(self.client.get_members(),
                                                msg["content"])
                senderusername = self.mustread.get_username(
                    self.client.get_members(), msg["sender_email"])
                print(email)
                self.client.send_message({
                    "type":
                    "private",
                    "to":
                    email,
                    "content":
                    "**" + senderusername +
                    "** mentioned you in must read ! \nThe message says : " +
                    " ".join(content[2:])
                })
            if content[1].lower() == "poll":
                if content[2].lower() == "create":
                    print(",".join(content[4:]))
                    idno = self.poll.create_poll(content[3], content[4:])
                    self.client.send_message({
                        "type":
                        "stream",
                        "subject":
                        msg["subject"],
                        "to":
                        msg["display_recipient"],
                        "content":
                        "Poll Successfully Created and id is : **" +
                        str(idno) + "**"
                    })
                elif content[2].lower() == "show":
                    if content[3].lower() == "all":
                        polldetails = self.poll.show_allpoll()
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": polldetails
                        })
                    else:
                        polldetails = self.poll.show_poll(content[3])
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "Poll ID: **" + polldetails["id"] +
                            "**\n Question : **" + polldetails["pollname"] +
                            "**\nOption : **" + polldetails["options"] +
                            "**\n Votes : **" + polldetails["votes"] + "**"
                        })
                elif content[2].lower() == "vote":
                    vote = self.poll.vote_poll(content[3], content[4])
                    self.client.send_message({
                        "type":
                        "stream",
                        "subject":
                        msg["subject"],
                        "to":
                        msg["display_recipient"],
                        "content":
                        "Your Vote Has Been Recorded!"
                    })
                elif content[2].lower() == "delete":
                    if content[3].lower() == "all":
                        deleted = self.poll.delete_allpoll()
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "all polls has been removed from database"
                        })
                    else:
                        deleted = self.poll.delete_poll(content[3])
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "The given poll has been removed from database"
                        })
            if content[1].lower() == 'motivate':
                quote_data = self.motivate.get_quote()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": quote_data
                })
            if content[1].lower() == "shorturl":
                short_url = self.shortenedurl.get_shorturl(content)
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": short_url
                })
            if content[1].lower() == 'hackernews' or content[1].lower(
            ) == 'hn' or content[1].lower() == 'HN':
                news = self.hacknews.get_hackernews()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": news
                })
            if content[1].lower() == "cricnews":
                news = self.cricket.news()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": news
                })
            if content[1].lower() == "help" and len(content) == 2:
                message = self.help()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "help" and len(content) > 2:
                subkey = content[2]
                message = self.help_sub(subkey)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "twitter":
                #tweets = self.tw.get()
                #print(tweets)
                if len(content) > 2 and content[2] == "post":
                    if self.tw.stream == msg["display_recipient"]:
                        status = self.tw.post(" ".join(content[3:]))
                        x = json.dumps(status._json)
                        x = json.loads(x)
                        message = "https://twitter.com/{}/status/{}".format(
                            x["user"]["screen_name"], x["id_str"])
                        message = "Tweet Posted\n" + message
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": message
                        })
                    else:
                        message = "Use the stream **{}** to post a tweet".format(
                            self.tw.stream)
                        self.client.send_message({
                            "type": "private",
                            "to": sender_email,
                            "content": message
                        })
                if len(content) > 2 and content[2] == "post_image":
                    if self.tw.stream == msg["display_recipient"]:
                        status = self.tw.post_image(content[3],
                                                    " ".join(content[4:]))
                        if isinstance(status, str):
                            message = status
                        else:
                            x = json.dumps(status._json)
                            x = json.loads(x)
                            message = "https://twitter.com/{}/status/{}".format(
                                x["user"]["screen_name"], x["id_str"])
                            message = "Tweet Posted\n" + message
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": message
                        })
                    else:
                        message = "Use the stream **{}** to post a tweet".format(
                            self.tw.stream)
                        self.client.send_message({
                            "type": "private",
                            "to": sender_email,
                            "content": message
                        })
            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
        if self.urls(" ".join(content)):
            summary = self.w.wiki(" ".join(content))
            if summary:
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": summary
                })
        elif "omega" in content and content[0] != "omega":
            self.client.send_message({
                "type":
                "stream",
                "subject":
                msg["subject"],
                "to":
                msg["display_recipient"],
                "content":
                "Alas! Finally you called me :blush:"
            })
        else:
            return
Exemplo n.º 16
0
class ZulipBot(object):
	def __init__(self):
		self.client = zulip.Client(site="https://technh.zulipchat.com/api/", api_key="vkEQgQYDPUgAGmXaTXdMPsMwlkkgMfM5", email="*****@*****.**")
		self.subscribe_all()
		self.hacknews = Hackernews()
		self.trans = Translate()
		self.movie= Movie()
		self.lyrics = Lyrics()
		self.holiday = Holiday()
		self.currency = Currency()
		self.cricket = Cricket()
		self.github = GitHub()
		self.chatbot = ChatBot(name="technehru")

		print("done init")
		self.subkeys = ["use", "help", "translate", "hackernews", "hn", "hotel", "HN", "cricnews", "cricketnews", "movie", "currency", "holiday", "lyrics", "github"]

	def subscribe_all(self):
		json = self.client.get_streams()["streams"]
		streams = [{"name": stream["name"]} for stream in json]
		self.client.add_subscriptions(streams)

	def process(self, msg):
		content = msg["content"].split()
		sender_email = msg["sender_email"]
		ttype = msg["type"]
		stream_name = msg['display_recipient']
		stream_topic = msg['subject']

		print(content)

		if sender_email == BOT_MAIL:
			return 

		print("Sucessfully heard.")

		if content[0].lower() == "technehru" or content[0] == "@**Technehru**":
			if content[1].lower() == "help" or content[1].lower() == "use":
				message = open("help.txt", "r")
				self.client.send_message({
					"type": "stream",
					"to": stream_name,
					"subject": stream_topic,
					"content": message.read()
					})

			if content[1].lower() == "translate":
				ip = content[2:]
				ip = " ".join(ip)
				message = self.trans.translate(ip)
				self.client.send_message({
					"type": "stream",
					"subject": msg["subject"],
					"to": msg["display_recipient"],
					"content": message
					})
			if content[1].lower() == "movie":
				ip = content[2:]
				ip = " +".join(ip)
				message = self.movie.about(ip)
				self.client.send_message({
					"type": "stream",
					"subject": msg["subject"],
					"to": msg["display_recipient"],
					"content": message
					})

			if content[1].lower() == "lyrics":
				author = content[2]
				title = content[3:]
				title = " ".join(title)
				message = self.lyrics.about(author, title)
				self.client.send_message({
					"type": "stream",
					"subject": msg["subject"],
					"to": msg["display_recipient"],
					"content": message
					})

			if content[1].lower() == 'holiday':
				quote_data = self.holiday.holiday()
				self.client.send_message({
					"type": "stream",
					"to": stream_name,
					"subject": stream_topic,
					"content": quote_data
					})

			if content[1].lower() == 'currency':
				x = content[2]
				y = content[3]

				quote_data = self.currency.currency(x,y)
				self.client.send_message({
					"type": "stream",
					"to": stream_name,
					"subject": stream_topic,
					"content": quote_data
					})

			if content[1].lower() == "cricnews" or content[1].lower() == "cricketnews":
				news = self.cricket.news()
				self.client.send_message({
					"type": "stream",
					"subject": msg["subject"],
					"to": msg["display_recipient"],
					"content": news  
					})

			if content[1].lower() == 'hackernews' or content[1].lower() == 'hn':
				news = self.hacknews.get_hackernews()
				self.client.send_message({
					"type": "stream",
					"to": stream_name,
					"subject": stream_topic,
					"content": news
					})

			if content[1].lower() == 'github':
				if content[2].lower() == 'reopen' and content[3].lower() == 'issue':
					repo = content[4]
					num = int(content[5])
					result = self.github.reopen_issue(repo, num)
					self.client.send_message({
						"type": "stream",
						"to": stream_name,
						"subject": stream_topic,
						"content": result  
						})

				if content[2].lower() == 'comment' and content[3].lower() == 'issue':
					repo = content[4]
					num = int(content[5])
					comment = content[6:]
					comment = " ".join(comment)
					result = self.github.comment_issue(repo, num, comment)
					self.client.send_message({
						"type": "stream",
						"to": stream_name,
						"subject": stream_topic,
						"content": result  
						})

				if content[2].lower() == 'close' and content[3].lower() == 'issue':
					repo = content[4]
					num = int(content[5])
					result = self.github.close_issue(repo, num)
					self.client.send_message({
						"type": "stream",
						"to": stream_name,
						"subject": stream_topic,
						"content": result  
						})

				if content[2].lower() == 'assign' and content[3].lower() == 'issue':
					repo = content[4]
					num = int(content[5])
					assignee = content[6]
					result = self.github.assign_issue(repo, num, assignee)
					self.client.send_message({
						"type": "stream",
						"to": stream_name,
						"subject": stream_topic,
						"content": result  
						})


			if content[1] not in self.subkeys:
				ip = content[1:]
				ip = " ".join(ip)
				message = self.chatbot.get_response(ip).text
				self.client.send_message({
					"type": "stream",
					"subject": msg["subject"],
					"to": msg["display_recipient"],
					"content": message
					})

		
		elif "technehru" in content and content[0].lower() != "technehru":
			self.client.send_message({
				"type": "stream",
				"subject": msg["subject"],
				"to": msg["display_recipient"],
				"content": "Hey there! :blush:"
				})
		else:
			return
Exemplo n.º 17
0
class ZulipBot(object):
    def __init__(self):
        self.client = zulip.Client(site="https://myra.zulipchat.com/api/")
        self.subscribe_all()
        self.hacknews = Hackernews()
        self.trans = Translate()
        self.movie = Movie()
        self.lyrics = Lyrics()
        self.holiday = Holiday()
        self.currency = Currency()
        self.cricket = Cricket()

        print("done init")
        self.subkeys = [
            "translate", "hackernews", "hn", "hotel", "HN", "askme",
            "cricnews", "movie", "currency", "holiday", "lyrics"
        ]

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']

        print(content)

        if sender_email == BOT_MAIL:
            return

        print("Sucessfully heard.")

        if content[0].lower() == "myra" or content[0] == "@**myra**":
            if content[1].lower() == "translate":
                ip = content[2:]
                ip = " ".join(ip)
                message = self.trans.translate(ip)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "movie":
                ip = content[2:]
                ip = " +".join(ip)
                message = self.movie.about(ip)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "lyrics":
                author = content[2]
                title = content[3:]
                title = " ".join(title)
                message = self.lyrics.about(author, title)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == 'holiday':
                quote_data = self.holiday.holiday()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": quote_data
                })

            if content[1].lower() == 'currency':
                x = content[2]
                y = content[3]

                quote_data = self.currency.currency(x, y)
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": quote_data
                })

            if content[1].lower() == "cricnews":
                news = self.cricket.news()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": news
                })

            if content[1].lower() == 'hackernews' or content[1].lower(
            ) == 'hn' or content[1].lower() == 'HN':
                news = self.hacknews.get_hackernews()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": news
                })

            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

        elif "myra" in content and content[0] != "myra":
            self.client.send_message({
                "type": "stream",
                "subject": msg["subject"],
                "to": msg["display_recipient"],
                "content": "Hey there! :blush:"
            })
        else:
            return
Exemplo n.º 18
0
class ZulipBot(object):
    def __init__(self):
        self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/")
        self.subscribe_all()
        self.hacknews = Hackernews()
        self.trans = Translate()
        self.movie = Movie()
        self.lyrics = Lyrics()
        self.holiday = Holiday()
        self.currency = Currency()
        self.cricket = Cricket()
        # self.chatbot.train("chatterbot.corpus.english")
        self.crypto = Crypto()
        self.trans = Translate()
        self.g = Giphy()
        self.w = WikiPedia()
        # self.tw = Twimega()
        # self.motivate = Motivate()
        self.shortenedurl = Urlshortener()
        self.geo = Geocode()
        self.weather = Weather()
        self.dict_ = Dictionary()
        self.joke = Joke()
        self.pnr = Pnr()
        self.mustread = Mustread()
        self.ss = Ss()
        self.cricket = Cricket()
        self.poll = Poll()
        print("done init")
        self.subkeys = [
            "crypto", "translate", "define", "joke", "weather", "giphy", "pnr",
            "mustread", "poll", "hackernews", "hn", "HN", "motivate",
            "twitter", "screenshot", "memo", "cricnews", "help", "shorturl",
            "movie", "currency", "holiday", "lyrics"
        ]

    def subscribe_all(self):
        json = self.client.get_streams()["streams"]
        streams = [{"name": stream["name"]} for stream in json]
        self.client.add_subscriptions(streams)

    def process(self, msg):
        content = msg["content"].split()
        sender_email = msg["sender_email"]
        ttype = msg["type"]
        stream_name = msg['display_recipient']
        stream_topic = msg['subject']

        print(content)

        if sender_email == BOT_MAIL:
            return

        print("Sucessfully heard.")

        if content[0].lower() == "magnus" or content[0] == "@**magnus**":
            if content[1].lower() == "translate":
                ip = content[2:]
                ip = " ".join(ip)
                message = self.trans.translate(ip)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "movie":
                ip = content[2:]
                ip = " +".join(ip)
                message = self.movie.about(ip)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "lyrics":
                author = content[2]
                title = content[3:]
                title = " ".join(title)
                message = self.lyrics.about(author, title)
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == 'holiday':
                quote_data = self.holiday.holiday()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": quote_data
                })

            if content[1].lower() == 'currency':
                x = content[2]
                y = content[3]

                quote_data = self.currency.currency(x, y)
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": quote_data
                })

            if content[1].lower() == "cricnews":
                news = self.cricket.news()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": news
                })

            if content[1].lower() == 'hackernews' or content[1].lower(
            ) == 'hn' or content[1].lower() == 'HN':
                news = self.hacknews.get_hackernews()
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": news
                })

            if content[1].lower() == "crypto":
                if len(content) > 3 and content[3].lower() == "in":
                    message = self.crypto.get_price(content[2], content[4])
                else:
                    message = self.crypto.get_price(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

            if content[1].lower() == "joke":
                text = self.joke.tellJoke()
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": text
                })

            # if content[1].lower() == 'motivate':
            # 	quote_data = self.motivate.get_quote()
            # 	self.client.send_message({
            # 		"type": "stream",
            # 		"to": stream_name,
            # 		"subject": stream_topic,
            # 		"content": quote_data
            # 		})
            if content[1].lower() == "mustread":
                email = self.mustread.get_email(self.client.get_members(),
                                                msg["content"])
                senderusername = self.mustread.get_username(
                    self.client.get_members(), msg["sender_email"])
                print(email)
                self.client.send_message({
                    "type":
                    "private",
                    "to":
                    email,
                    "content":
                    "**" + senderusername +
                    "** mentioned you in must read ! \nThe message says : " +
                    " ".join(content[2:])
                })

            if content[1].lower() == "pnr":
                message = self.pnr.get_pnr(content[2])
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })
            if content[1].lower() == "screenshot":
                result = self.ss.get_ss(content[2])
                print(result)
                self.client.send_message({
                    "type":
                    "stream",
                    "subject":
                    msg["subject"],
                    "to":
                    msg["display_recipient"],
                    "content":
                    "Screenshot taken :wink:\n[Screenshot Link](" + result +
                    ")"
                })

            if content[1].lower() == "poll":
                if content[2].lower() == "create":
                    print(",".join(content[4:]))
                    idno = self.poll.create_poll(content[3], content[4:])
                    self.client.send_message({
                        "type":
                        "stream",
                        "subject":
                        msg["subject"],
                        "to":
                        msg["display_recipient"],
                        "content":
                        "Poll Successfully Created and id is : **" +
                        str(idno) + "**"
                    })
                elif content[2].lower() == "show":
                    if content[3].lower() == "all":
                        polldetails = self.poll.show_allpoll()
                        self.client.send_message({
                            "type": "stream",
                            "subject": msg["subject"],
                            "to": msg["display_recipient"],
                            "content": polldetails
                        })
                    else:
                        polldetails = self.poll.show_poll(content[3])
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "Poll ID: **" + polldetails["id"] +
                            "**\n Question : **" + polldetails["pollname"] +
                            "**\nOption : **" + polldetails["options"] +
                            "**\n Votes : **" + polldetails["votes"] + "**"
                        })
                elif content[2].lower() == "vote":
                    vote = self.poll.vote_poll(content[3], content[4])
                    self.client.send_message({
                        "type":
                        "stream",
                        "subject":
                        msg["subject"],
                        "to":
                        msg["display_recipient"],
                        "content":
                        "Your Vote Has Been Recorded!"
                    })
                elif content[2].lower() == "delete":
                    if content[3].lower() == "all":
                        deleted = self.poll.delete_allpoll()
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "all polls has been removed from database"
                        })
                    else:
                        deleted = self.poll.delete_poll(content[3])
                        self.client.send_message({
                            "type":
                            "stream",
                            "subject":
                            msg["subject"],
                            "to":
                            msg["display_recipient"],
                            "content":
                            "The given poll has been removed from database"
                        })

            if content[1].lower() == "shorturl":
                short_url = self.shortenedurl.get_shorturl(content)
                self.client.send_message({
                    "type": "stream",
                    "to": stream_name,
                    "subject": stream_topic,
                    "content": short_url
                })

            if content[1] not in self.subkeys:
                ip = content[1:]
                ip = " ".join(ip)
                message = self.Chatbot.get_response(ip).text
                self.client.send_message({
                    "type": "stream",
                    "subject": msg["subject"],
                    "to": msg["display_recipient"],
                    "content": message
                })

        elif "magnus" in content and content[0] != "magnus":
            self.client.send_message({
                "type": "stream",
                "subject": msg["subject"],
                "to": msg["display_recipient"],
                "content": "Hey there! :blush:"
            })
        else:
            return
Exemplo n.º 19
0
    def runTransformation(self):
        if self.inputImage is None:
            self.setStatus("Please load and input image.")
            return

        if self.transformationSelection.get() == 1:
            # rotation
            rotationObject = Rotation2(self.inputImage,
                                       self.retrieveRotationAngle())

            rotationType = None
            rotated_image = None
            if self.interpVar.get() == "Bilinear":
                rotated_image = rotationObject.rotateImage_Bilinear()
                rotationType = "Bilinear"
            elif self.interpVar.get() == "Bicubic":
                rotated_image = rotationObject.rotateImage_Bicubic()
                rotationType = "Bicubic"
            else:
                rotated_image = rotationObject.rotateImage_NearestNeighbor()
                rotationType = "Nearest Neighbor"

            self.setOutputImageShape(rotated_image.shape)

            self.displayImageOnLabel(self.outputImageLabel, rotated_image,
                                     self.IMAGE_SIZE)

            self.outputImage = rotated_image
            interpolationType = self.interpVar.get()
            if interpolationType == "Interpolation":
                interpolationType = "Nearest_Neighbor"
            self.currentOutFileName = self.outFileInitialName + "_rotation_" + interpolationType \
                                      + "_" + str(self.retrieveRotationAngle())

            self.setStatus("Rotated image " +
                           str(self.retrieveRotationAngle()) + "° using " +
                           rotationType + " interpolation.")

        elif self.transformationSelection.get() == 2:
            # scale
            scale_object = Scale()

            (N, M) = self.inputImage.shape

            try:
                scale_x = int(np.round(float(self.scaling_x_Entry.get())))
            except ValueError:
                scale_x = N

            try:
                scale_y = int(np.round(float(self.scaling_y_Entry.get())))
            except ValueError:
                scale_y = M

            scaled_image = scale_object.resize(self.inputImage, scale_x,
                                               scale_y, self.interpVar.get())

            self.displayImageOnLabel(self.outputImageLabel, scaled_image,
                                     self.IMAGE_SIZE)

            self.setOutputImageShape(scaled_image.shape)

            self.outputImage = scaled_image
            interpolationType = self.interpVar.get()
            if interpolationType == "Interpolation":
                interpolationType = "Nearest_Neighbor"
            self.currentOutFileName = self.outFileInitialName + "_scale_" + interpolationType \
                                      + "_height_" + str(self.scaling_x_Entry.get()) + "_width_" \
                                       + str(self.scaling_y_Entry.get())

            self.setStatus("Scaled image using " + interpolationType + " interpolation to: " + str(scale_x) \
                                   + " x " + str(scale_y) + " .")

        elif self.transformationSelection.get() == 3:
            # reflection
            print("Reflection Radio Button Selected")
            self.setStatus("Reflecting image.")

            reflectionObject = Reflection()

            axis = self.reflectionVar.get()

            if axis == "X-axis" or axis == "Reflection Type":
                reflected_image = reflectionObject.reflectOnAxisX(
                    self.inputImage)
            elif axis == "Y-axis":
                reflected_image = reflectionObject.reflectOnAxisY(
                    self.inputImage)
            else:
                reflected_image = self.inputImage

            self.displayImageOnLabel(self.outputImageLabel, reflected_image,
                                     self.IMAGE_SIZE)

            self.setOutputImageShape(reflected_image.shape)

            self.outputImage = reflected_image
            reflectionType = self.reflectionVar.get()
            if reflectionType == "Reflection Type":
                reflectionType = "X-axis"

            self.currentOutFileName = self.outFileInitialName + "_reflected_on_" + reflectionType

            self.setStatus("Reflected Image on " + reflectionType + ".")

        elif self.transformationSelection.get() == 4:
            # translation
            translate_object = Translate()

            try:
                translation_x = int(
                    np.round(float(self.translation_x_Entry.get())))
            except ValueError:
                translation_x = 0

            try:
                translation_y = int(
                    np.round(float(self.translation_y_Entry.get())))
            except ValueError:
                translation_y = 0

            translated_image = translate_object.translate(
                self.inputImage, translation_x, translation_y)
            translated_image_display = self.makeDisplayImage(
                translated_image, self.IMAGE_SIZE)
            self.setOutputImageShape(translated_image.shape)
            self.outputImageLabel.configure(image=translated_image_display)
            self.outputImageLabel.image = translated_image_display

            self.outputImage = translated_image
            self.currentOutFileName = self.outFileInitialName + "_translate_x_" \
                                      + str(translation_x) + "_y_" + str(translation_y)

            self.setStatus("Translating image: x: " + str(translation_x) +
                           " , y: " + str(translation_y))

        elif self.transformationSelection.get() == 5:
            # shear
            shear_object = Shear()

            try:
                m_entry = float(self.shear_m_Entry.get())
            except ValueError:
                m_entry = 0.0

            sheared_image = shear_object.shear(self.inputImage, m_entry,
                                               self.shear_var.get(),
                                               self.interpVar.get())

            self.displayImageOnLabel(self.outputImageLabel, sheared_image,
                                     self.IMAGE_SIZE)

            self.setOutputImageShape(sheared_image.shape)

            self.outputImage = sheared_image

            interpolationType = self.interpVar.get()
            if interpolationType == "Interpolation":
                interpolationType = "Nearest_Neighbor"

            shearType = self.shear_var.get()
            if shearType == "Shear Type":
                shearType = "Vertical"
            self.currentOutFileName = self.outFileInitialName + "_shear_" + interpolationType \
                                      + "_m_" + str(m_entry) + "_type_" \
                                      + str(shearType)

            self.setStatus("Sheared image type: " + shearType + " using " + interpolationType \
                           + " interpolation with m = " + str(m_entry))

        else:
            self.setStatus("No image geometric transformation is selected.")
Exemplo n.º 20
0
class Card(jp.Div):
    def __init__(self, **kwargs):
        self.span_list = []
        kwargs[
            'class_'] = 'w-2/3 bg-white mt-20  rounded-lg shadow p-12 flex flex-wrap'
        kwargs['style'] = 'min-height: 20rem;'
        super().__init__(**kwargs)
        self.en_area = None
        self.tw_area = None
        self.sentence_list = []

        self.ts = Translate('zh-TW', 'en')

    async def make_sound(self, target):
        eval_text = f"""
            let utterance = new window.SpeechSynthesisUtterance("{target.replace('"', '')}");
            utterance.lang = 'en-US';
            window.speechSynthesis.speak(utterance)
            console.log("{target}")
            """
        await self.page.run_javascript(eval_text)

    async def change_area_text(self, english):
        self.en_area.value = english
        self.tw_area.text = self.ts.translate(english)
        await self.make_sound(english)

    async def click(self, _):
        await self.rebuild()

    async def build(self):
        self.delete_components()
        self.span_list = []
        sentence = self.sentence_list.pop(0)
        for word in sentence.split():
            el = Word(text=word)
            self.add_component(el)
            self.span_list.append(el)

        self.add_component(jp.Button(text='更新', click=self.click))
        self.add_component(jp.Div(class_='bg-gray-600 h-px my-6 w-full'))
        self.en_area = jp.Textarea(class_='w-full')
        self.add_component(jp.Button(text='更新', click=self.click_to_build))
        self.add_component(self.en_area)
        self.add_component(jp.Div(class_='bg-gray-600 h-px my-6 w-full'))
        self.tw_area = jp.Div()
        self.add_component(self.tw_area)

        await self.change_area_text(sentence)

    async def click_to_build(self, _):
        await self.build()

    async def rebuild(self):
        words = []
        for el in self.span_list:
            if el.is_green:
                words.append(el.text)
        await self.change_area_text(" ".join(words))

    def init_sentence(self):
        for sentence in re.split(r'[\.!?]', self.page.original_english):
            if sentence:
                self.sentence_list.append(sentence)
Exemplo n.º 21
0
    "gene": "name",
    "id": "identity",
    "alignment": "alignment_length",
    "gene_lenght": "ref_gene_lenght",
    "cov": "coverage"
}

translator = Translate("gene", test_trans_table)

test_gene2 = {
    "primary": "some_gene_key2",
    "gene": "gen_name2",
    "id": "97",
    "alignment": "800",
    "gene_lenght": "800",
    "cov": "99"
}

result.add_class(cl="genes",
                 result_type="gene",
                 **translator.translate(test_gene2))

try:
    result.check_results()
    soft_result.check_results()
except CGECoreOutInputError as e:
    print("Error dict:\n{}".format(e.errors))

print(json.dumps(result))
print(json.dumps(soft_result))