Esempio n. 1
0
 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"
     ]
Esempio n. 2
0
    def scrape(self):

        rawFile = fileManager(self.path, 'r').split('\n')
        success = set()
        failed = set()

        for line in rawFile:

            try:
                sleep(randrange(0, 2))
                song = Lyrics(line)
                song.scrape()
                lyrics = song.lyrics

                if lyrics:
                    fileManager(
                        RANGE1.format(file=song.name), 'w', song.lyrics
                    )
                    success.add(line)

                else:
                    failed.add(line)

            except KeyboardInterrupt:
                break

            except Exception as e:
                print e
                continue

        self.__saveProgress(set(rawFile), success, failed)
Esempio n. 3
0
  def __init__(self, song, config):
    if song.info["background"]: self.background = song.info["background"]
    else: self.background = os.path.join(image_path, "bg.png")

    for key in ["movie", "filename", "title", "artist", "startat", "endat",
                "banner"]:
      self.__dict__[key] = song.info[key]

    self.soffset = song.info["gap"] * 1000

    self.crapout = 0

    self.__dict__.update(config)

    try:
        # if user used some internationalization in the configuration file,
	# so in mainconfig["lyriccolor"], maybe there is invalid colors
	# TODO: not save translated colors in the config file, only English
        clrs = [colors.color[_(c)] for c in mainconfig["lyriccolor"].split("/")]
    except:
        clrs = ["cyan","aqua"]

    clrs.reverse()
    self.lyricdisplay = Lyrics(clrs)

    atsec = 0
    for lyr in song.lyrics:
      self.lyricdisplay.addlyric(*lyr)
Esempio n. 4
0
 def __init__(self, *args, **kwargs):
     # set addon object
     self.m_addon = kwargs["addon"]
     # our we prefetching
     self.prefetch = kwargs.get("prefetch", False)
     # clear song info
     self._clear_song_attributes()
     # initialize our super classes
     Lyrics.__init__(self)
Esempio n. 5
0
class SongData(object):
    def __init__(self, song, config):
        if song.info["background"]: self.background = song.info["background"]
        else: self.background = os.path.join(image_path, "bg.png")

        for key in [
                "movie", "filename", "title", "artist", "startat", "endat",
                "banner"
        ]:
            self.__dict__[key] = song.info[key]

        self.soffset = song.info["gap"] * 1000

        self.crapout = 0

        self.__dict__.update(config)

        try:
            # if user used some internationalization in the configuration file,
            # so in mainconfig["lyriccolor"], maybe there is invalid colors
            # TODO: not save translated colors in the config file, only English
            clrs = [
                colors.color[_(c)] for c in mainconfig["lyriccolor"].split("/")
            ]
        except:
            clrs = ["cyan", "aqua"]

        clrs.reverse()
        self.lyricdisplay = Lyrics(clrs)

        atsec = 0
        for lyr in song.lyrics:
            self.lyricdisplay.addlyric(*lyr)

    def init(self):
        try:
            music.load(self.filename)
        except:
            print _("Not a supported file type:"), self.filename
            self.crapout = 1

    def play(self):
        music.play(0, self.startat)

    def kill(self):
        music.stop()

    def is_over(self):
        if not music.get_busy(): return True
        elif self.endat and music.get_pos() > self.endat * 1000:
            music.stop()
            return True
        else:
            return False
Esempio n. 6
0
	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"]
Esempio n. 7
0
class SongData(object):
  def __init__(self, song, config):
    if song.info["background"]: self.background = song.info["background"]
    else: self.background = os.path.join(image_path, "bg.png")

    for key in ["movie", "filename", "title", "artist", "startat", "endat",
                "banner"]:
      self.__dict__[key] = song.info[key]

    self.soffset = song.info["gap"] * 1000

    self.crapout = 0

    self.__dict__.update(config)

    try:
        # if user used some internationalization in the configuration file,
	# so in mainconfig["lyriccolor"], maybe there is invalid colors
	# TODO: not save translated colors in the config file, only English
        clrs = [colors.color[_(c)] for c in mainconfig["lyriccolor"].split("/")]
    except:
        clrs = ["cyan","aqua"]

    clrs.reverse()
    self.lyricdisplay = Lyrics(clrs)

    atsec = 0
    for lyr in song.lyrics:
      self.lyricdisplay.addlyric(*lyr)

  def init(self):
    try: music.load(self.filename)
    except:
      print _("Not a supported file type:"), self.filename
      self.crapout = 1

  def play(self):
    music.play(0, self.startat)

  def kill(self):
    music.stop()

  def is_over(self):
    if not music.get_busy(): return True
    elif self.endat and music.get_pos() > self.endat * 1000:
      music.stop()
      return True
    else: return False
Esempio n. 8
0
    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"
        ]
Esempio n. 9
0
  def __init__(self, song, config):
    if song.info["background"]: self.background = song.info["background"]
    else: self.background = os.path.join(image_path, "bg.png")

    for key in ["movie", "filename", "title", "artist", "startat", "endat",
                "banner"]:
      self.__dict__[key] = song.info[key]

    self.soffset = song.info["gap"] * 1000

    self.crapout = 0

    self.__dict__.update(config)

    try:
        # if user used some internationalization in the configuration file,
	# so in mainconfig["lyriccolor"], maybe there is invalid colors
	# TODO: not save translated colors in the config file, only English
        clrs = [colors.color[_(c)] for c in mainconfig["lyriccolor"].split("/")]
    except:
        clrs = ["cyan","aqua"]

    clrs.reverse()
    self.lyricdisplay = Lyrics(clrs)

    atsec = 0
    for lyr in song.lyrics:
      self.lyricdisplay.addlyric(*lyr)
Esempio n. 10
0
    def __init__(self, app):
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна

        # config loading
        self.config = config.Config(self)
        library.init(self.config.getLibraryDirs())
        self.lyrics = Lyrics(self.config)

        # make post ui setup after library is initialized
        self.postSetupUi()

        # Load config goes after postSetupUi() to be able to restore columns width
        self.config.load(app)
        self.connectEvents(app)

        self.tableModel.refreshPlaylist()
Esempio n. 11
0
    def updateDisplay(self, eventDetails=None):
        SonosControllerWindow.updateDisplay(self, eventDetails)

        # Now we have updated the track currently playing read the details out and
        # set the windows properties for ArtistSlideshow
        # Only update if the track has changed
        if self.currentTrack not in [None, '']:
            # Check if we want to show lyrics for the track, although not part of the
            # artist slideshow feature (it is part of script.cu.lrclyrics) we treat
            # this in a similar manner, first set the values
            lyrics = None
            if Settings.isLyricsInfoLayout():
                lyrics = Lyrics(self.currentTrack,
                                self.getControl(SonosArtistSlideshow.LYRICS),
                                self.lyricListLinesCount)
                lyrics.setLyricRequest()

            # Artist Slideshow will set these properties for us
            xbmcgui.Window(self.windowId).setProperty(
                'CURRENTARTIST', self.currentTrack['artist'])
            xbmcgui.Window(self.windowId).setProperty(
                'CURRENTTITLE', self.currentTrack['title'])
            xbmcgui.Window(self.windowId).setProperty(
                'CURRENTALBUM', self.currentTrack['album'])

            # Check if lyrics are enabled, and set the test if they are
            if lyrics is not None:
                self.currentTrack = lyrics.populateLyrics()
                lyrics.refresh()
                del lyrics
Esempio n. 12
0
    def updateDisplay(self, eventDetails=None):
        SonosControllerWindow.updateDisplay(self, eventDetails)

        # Now we have updated the track currently playing read the details out and
        # set the windows properties for ArtistSlideshow
        # Only update if the track has changed
        if self.currentTrack not in [None, '']:
            # Check if we want to show lyrics for the track, although not part of the
            # artist slideshow feature (it is part of script.cu.lrclyrics) we treat
            # this in a similar manner, first set the values
            lyrics = None
            if Settings.isLyricsInfoLayout():
                lyrics = Lyrics(self.currentTrack, self.getControl(SonosArtistSlideshow.LYRICS), self.lyricListLinesCount)
                lyrics.setLyricRequest()

            # Artist Slideshow will set these properties for us
            xbmcgui.Window(self.windowId).setProperty('CURRENTARTIST', self.currentTrack['artist'])
            xbmcgui.Window(self.windowId).setProperty('CURRENTTITLE', self.currentTrack['title'])
            xbmcgui.Window(self.windowId).setProperty('CURRENTALBUM', self.currentTrack['album'])

            # Check if lyrics are enabled, and set the test if they are
            if lyrics is not None:
                self.currentTrack = lyrics.populateLyrics()
                lyrics.refresh()
                del lyrics
Esempio n. 13
0
    def parse_sanoitus(self, line):
        try:
            if line.strip() != "":
                parts = line.split(",")
                measure = int(parts[0].strip())  # measure
                start = parts[1].split("/")
                start = float(int(start[0].strip()) /
                              int(start[1].strip()))  # start
                string = parts[2].strip()

                lyric = Lyrics(measure, start, string)
                Composition.add_lyric(self.comp, lyric)
                return True
        except:
            print("Huono sanoitustavu.")
Esempio n. 14
0
def read_lyrics(lyrics_dir='lyrics', 
				print_stats=False, language='en-us', lookback=30):
	'''
	Read lyrics and compute Rhyme factor (riimikerroin) for each
	artist.

	Input:
		lyrics_dir  Path to the directory containing the lyrics.
		artist      Name of the artist directory under lyrics_dir (if this is
					not provided, all artists are analyzed).
		album       Name of the album directory under lyrics_dir/artist/
		print_stats Whether we print summary statistics for each individual
					song.
		language    Use either Finnish (fi), American English (en-us), 
					or English (en).
		lookback    How many previous words are checked for rhymes. For
					Finnish I've used 10 and for English 15.
	'''

	# Set up CSV file to add the stats of each song to
	with open('raplyzer_out.csv', 'wb') as csvfile:
		csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n',
								quotechar='|', quoting=csv.QUOTE_MINIMAL)
		csvwriter.writerow(["Artist", "Song", "Longest Rhyme Length", "Average Rhyme"])

	for a in os.listdir(lyrics_dir):
		print "Analyzing artist: %s" % a

		songs = os.listdir(lyrics_dir + '/' + a)
		songs = [s for s in songs if len(s) > 4 and s[-4:]=='.txt']
		for song in songs:
			file_name = lyrics_dir + '/' + a + '/' + song
			try:
				l = Lyrics(file_name, print_stats=print_stats, language='en-us', lookback=lookback)
				long_r = l.get_longest_rhyme()
				avg_r = l.get_avg_rhyme_length()
				print "\n%s -- %s" % (a, song)

			# Exception reading the file, scrap it and move on
			except:
				print 'Exception reading file ', file_name
				print '\tException: %s' % sys.exc_info()[0]
				long_r = (-1, "")
				avg_r = -1

			# Song file succesfully read
			# Calculate all the statistics we want
			else:
				# Calculate word statistics
				# text = l.text_orig.lower()
				# rx = re.compile(u'[^\wåäö]+')
				# text = rx.sub(' ', text)
				# all_words = text.split()
				# n_uwords = len(set(all_words))
				# n_words = len(all_words)
				# per_uwords = n_uwords / float(n_words)

				# Add the statistics to the csv file
				with open('raplyzer_out.csv', 'ab') as csvfile:
					csvwriter = csv.writer(csvfile, delimiter=',',
											quotechar='|', quoting=csv.QUOTE_MINIMAL)
					csvwriter.writerow([a, song, long_r[0], avg_r])
Esempio n. 15
0
                        action='store_true')
    args = parser.parse_args()

    print(args.__dict__)
    cm = CmusPlayer()
    if not cm.is_cmus_playing():
        sys.exit()

    # TODO
    # arguments like:
    # - credential file
    # - retry if NOT FOUND

    try:
        s = Settings()
        s.get_settings()
        lyrics = Lyrics(s.settings)

    except Exception as e:
        sys.exit(e)

    main = Main(cm)

    if (main.cms.is_cmus_playing()):
        main.set_file(args.lyricspath)

        if not main.file_save_exists() or args.overwrite:
            main.get_lyrics(lyrics)

    main.print_lyrics()
Esempio n. 16
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
Esempio n. 17
0
def read_lyrics(lyrics_dir='lyrics_en', artist=None, album=None, 
                print_stats=False, language='en-us', lookback=15):
    '''
    Read lyrics and compute Rhyme factor (riimikerroin) for each
    artist.

    Input:
        lyrics_dir  Path to the directory containing the lyrics.
        artist      Name of the artist directory under lyrics_dir (if this is
                    not provided, all artists are analyzed).
        album       Name of the album directory under lyrics_dir/artist/
        print_stats Whether we print summary statistics for each individual
                    song.
        language    Use either Finnish (fi), American English (en-us), 
                    or English (en).
        lookback    How many previous words are checked for rhymes. For
                    Finnish I've used 10 and for English 15.
    '''
    if artist is not None:
        artists = [artist]
    else:
        artists = os.listdir(lyrics_dir)
    artist_scores = []
    song_scores = []
    song_names = []
    uniq_words = []
    longest_rhymes = []
    max_rhymes = 5
    for a in artists:
        print "Analyzing artist: %s" % a
        rls = []
        all_words = []
        if album is not None:
            albums = [album]
        else:
            albums = os.listdir(os.path.join(lyrics_dir, a))
            albums = sort_albums_by_year(albums)
        for al in albums:
            album_rls = []
            songs = os.listdir(os.path.join(lyrics_dir, a, al))
            # Only the .txt files
            songs = [s for s in songs if len(s)>=4 and s[-4:]=='.txt']
            for song in songs:
                file_name = os.path.join(lyrics_dir, a, al, song)
                l = Lyrics(file_name, print_stats=print_stats, 
                           language=language, lookback=lookback)
                rl = l.get_avg_rhyme_length()
                rls.append(rl)
                song_scores.append(rl)
                song_names.append(file_name)
                album_rls.append(rl)
                if len(longest_rhymes) < max_rhymes:
                    heapq.heappush(longest_rhymes, l.get_longest_rhyme())
                else:
                    heapq.heappushpop(longest_rhymes, l.get_longest_rhyme())

                if language == 'fi':
                    all_words += l.text.split()
                else:
                    text = l.text_orig.lower()
                    rx = re.compile(u'[^\wåäö]+')
                    text = rx.sub(' ', text)
                    all_words += text.split()
            # Print stats for the album
            #print "%s - %s: %.3f" % (a, al, np.mean(np.array(album_rls)))
            #print "%.5f" % (np.mean(np.array(album_rls)))

        # Compute the number of unique words the artist has used
        n_words = len(all_words)
        min_w = 20000
        if n_words >= min_w:
            n_uniq_words = len(set(all_words[:min_w]))
            uniq_words.append(n_uniq_words)
        else:
            uniq_words.append(-n_words)
        mean_rl = np.mean(np.array(rls))
        artist_scores.append(mean_rl)

    # Sort the artists based on their avg rhyme lengths
    artist_scores = np.array(artist_scores)
    artists = np.array(artists)
    uniq_words = np.array(uniq_words)
    order = np.argsort(artist_scores)[::-1]
    artists = artists[order]
    uniq_words = uniq_words[order]
    artist_scores = artist_scores[order]

    print "\nBest rhymes"
    while len(longest_rhymes) > 0:
        l, rhyme = heapq.heappop(longest_rhymes)
        print rhyme

    print "\nBest songs:"
    song_scores = np.array(song_scores)
    song_names = np.array(song_names)
    song_names = song_names[np.argsort(song_scores)[::-1]]
    song_scores = sorted(song_scores)[::-1]
    for i in range(min(10,len(song_scores))):
        print '%.3f\t%s' % (song_scores[i], song_names[i])

    print "\nBest artists:"
    for i in range(len(artist_scores)):
        rx = re.compile(u'_')
        name = rx.sub(' ', artists[i])
        print '%d.\t%.3f\t%s' % (i+1, artist_scores[i], name)
Esempio n. 18
0
def read_lyrics(lyrics_dir='lyrics_en', artist=None, album=None, 
                print_stats=False, language='en-us', lookback=15):
    '''
    Read lyrics and compute Rhyme factor (riimikerroin) for each
    artist.

    Input:
        lyrics_dir  Path to the directory containing the lyrics.
        artist      Name of the artist directory under lyrics_dir (if this is
                    not provided, all artists are analyzed).
        album       Name of the album directory under lyrics_dir/artist/
        print_stats Whether we print summary statistics for each individual
                    song.
        language    Use either Finnish (fi), American English (en-us), 
                    or English (en).
        lookback    How many previous words are checked for rhymes. For
                    Finnish I've used 10 and for English 15.
    '''
    if artist is not None:
        artists = [artist]
    else:
        artists = os.listdir(lyrics_dir)
    artist_scores = []
    song_scores = []
    song_names = []
    uniq_words = []
    longest_rhymes = []
    max_rhymes = 5
    for a in artists:
        print "Analyzing artist: %s" % a
        rls = []
        all_words = []
        if album is not None:
            albums = [album]
        else:
            albums = os.listdir(os.path.join(lyrics_dir, a))
            albums = sort_albums_by_year(albums)
        for al in albums:
            album_rls = []
            songs = os.listdir(os.path.join(lyrics_dir, a, al))
            # Only the .txt files
            songs = [s for s in songs if len(s)>=4 and s[-4:]=='.txt']
            for song in songs:
                file_name = os.path.join(lyrics_dir, a, al, song)
                l = Lyrics(file_name, print_stats=print_stats, 
                           language=language, lookback=lookback)
                rl = l.get_avg_rhyme_length()
                rls.append(rl)
                song_scores.append(rl)
                song_names.append(file_name)
                album_rls.append(rl)
                if len(longest_rhymes) < max_rhymes:
                    heapq.heappush(longest_rhymes, l.get_longest_rhyme())
                else:
                    heapq.heappushpop(longest_rhymes, l.get_longest_rhyme())

                if language == 'fi':
                    all_words += l.text.split()
                else:
                    text = l.text_orig.lower()
                    rx = re.compile(u'[^\wåäö]+')
                    text = rx.sub(' ', text)
                    all_words += text.split()
            # Print stats for the album
            #print "%s - %s: %.3f" % (a, al, np.mean(np.array(album_rls)))
            #print "%.5f" % (np.mean(np.array(album_rls)))

        # Compute the number of unique words the artist has used
        n_words = len(all_words)
        min_w = 20000
        if n_words >= min_w:
            n_uniq_words = len(set(all_words[:min_w]))
            uniq_words.append(n_uniq_words)
        else:
            uniq_words.append(-n_words)
        mean_rl = np.mean(np.array(rls))
        artist_scores.append(mean_rl)

    # Sort the artists based on their avg rhyme lengths
    artist_scores = np.array(artist_scores)
    artists = np.array(artists)
    uniq_words = np.array(uniq_words)
    order = np.argsort(artist_scores)[::-1]
    artists = artists[order]
    uniq_words = uniq_words[order]
    artist_scores = artist_scores[order]

    print "\nBest rhymes"
    while len(longest_rhymes) > 0:
        l, rhyme = heapq.heappop(longest_rhymes)
        print rhyme

    print "\nBest songs:"
    song_scores = np.array(song_scores)
    song_names = np.array(song_names)
    song_names = song_names[np.argsort(song_scores)[::-1]]
    song_scores = sorted(song_scores)[::-1]
    for i in range(min(10,len(song_scores))):
        print '%.3f\t%s' % (song_scores[i], song_names[i])

    print "\nBest artists:"
    for i in range(len(artist_scores)):
        rx = re.compile(u'_')
        name = rx.sub(' ', artists[i])
        print '%d.\t%.3f\t%s' % (i+1, artist_scores[i], name)
Esempio n. 19
0
    def mergeTrackInfoAndEvent(self, track, eventDetails, previousTrack=None):
        # Check if the new and previous tracks are the same, if they are then we can
        # check to see if there are lyrics that should be copied over to stop us getting
        # them again
        track = Lyrics.copyLyricsIfSameTrack(track, previousTrack)

        # If there is no event data, then just return the track unchanged
        if eventDetails is None:
            # Check to see if the track has changed, if it has not, then we can
            # safely use the previous event we stored
            if (previousTrack is not None) and (track['uri'] == previousTrack['uri']) and (previousTrack['lastEventDetails'] is not None):
                log("Sonos: Using previous Event details for merge")
                track['lastEventDetails'] = previousTrack['lastEventDetails']
                eventDetails = previousTrack['lastEventDetails']
            else:
                log("Sonos: Event details not set for merge")
                track['lastEventDetails'] = None
                return track
        else:
            log("Sonos: Event details set for merge")
            track['lastEventDetails'] = eventDetails

        # We do not want to throw an exception if we fail to process an event
        # It has been seen to happen in some strange cases, so we just catch and
        # log the error
        try:
            # Now process each part of the event message
            if eventDetails.enqueued_transport_uri_meta_data not in [None, '']:
                enqueued_transport = eventDetails.enqueued_transport_uri_meta_data
                log("enqueued_transport_uri_meta_data = %s" % enqueued_transport)

                # Check if this is radio stream, in which case use that as the title
                # Station Name
                if hasattr(enqueued_transport, 'title') and (enqueued_transport.title not in [None, '']):
                    if not enqueued_transport.title.startswith('ZPSTR_'):
                        # Only set the title if not already set, or it is an Audio Broadcast
                        if (track['title'] is None) or (track['title'] == "") or isinstance(enqueued_transport, DidlAudioBroadcast):
                            track['title'] = enqueued_transport.title

            # Process the current track info
            if eventDetails.current_track_meta_data not in [None, '']:
                current_track = eventDetails.current_track_meta_data
                log("current_track_meta_data = %s" % current_track)

                # Check if this is radio stream, in which case use that as the album title
                if hasattr(current_track, 'radio_show') and (current_track.radio_show not in [None, '']):
                    if not current_track.radio_show.startswith('ZPSTR_'):
                        if (track['album'] is None) or (track['album'] == ""):
                            track['album'] = current_track.radio_show
                            # This may be something like: Drivetime,p239255 so need to remove the last section
                            trimmed = track['album'].rpartition(',p')[0]
                            if (trimmed is not None) and (trimmed != ""):
                                track['album'] = trimmed
                # If not a radio stream then use the album tag
                elif hasattr(current_track, 'album') and (current_track.album not in [None, '']):
                    if (track['album'] is None) or (track['album'] == ""):
                        track['album'] = current_track.album

                # Name of track. Can be ZPSTR_CONNECTING/_BUFFERING during transition,
                # or None if not a radio station
                if hasattr(current_track, 'stream_content') and (current_track.stream_content not in [None, '']):
                    if not current_track.stream_content.startswith('ZPSTR_'):
                        if (track['artist'] is None) or (track['artist'] == ""):
                            track['artist'] = current_track.stream_content
                # otherwise we have the creator to use as the artist
                elif hasattr(current_track, 'creator') and (current_track.creator not in [None, '']):
                    if (track['artist'] is None) or (track['artist'] == ""):
                        track['artist'] = current_track.creator

                # If it was a radio stream, the title will already have been set using the enqueued_transport
                if hasattr(current_track, 'title') and (current_track.title not in [None, '']):
                    if not current_track.title.startswith('ZPSTR_'):
                        if (track['title'] is None) or (track['title'] == ""):
                            track['title'] = current_track.title

                # If the track has no album art, use the event one (if it exists)
                if (track['album_art'] is None) or (track['album_art'] == ""):
                    if hasattr(current_track, 'album_art_uri') and (current_track.album_art_uri not in [None, '']):
                        track['album_art'] = current_track.album_art_uri
                        # Make sure the Album art is fully qualified
                        if not track['album_art'].startswith(('http:', 'https:')):
                            track['album_art'] = 'http://' + self.ip_address + ':1400' + track['album_art']

            # Process Next Track Information
            if eventDetails.next_track_meta_data not in [None, '']:
                next_track = eventDetails.next_track_meta_data
                log("next_track_meta_data = %s" % next_track)
                if hasattr(next_track, 'creator') and (next_track.creator not in [None, '']):
                    if not hasattr(track, 'next_artist') or (track['next_artist'] is None) or (track['next_artist'] == ""):
                        track['next_artist'] = next_track.creator
                if hasattr(next_track, 'album') and (next_track.album not in [None, '']):
                    if not hasattr(track, 'next_album') or (track['next_album'] is None) or (track['next_album'] == ""):
                            track['next_album'] = next_track.album
                if hasattr(next_track, 'title') and (next_track.title not in [None, '']):
                    if not hasattr(track, 'next_title') or (track['next_title'] is None) or (track['next_title'] == ""):
                        track['next_title'] = next_track.title
                if hasattr(next_track, 'album_art_uri') and (next_track.album_art_uri not in [None, '']):
                    if not hasattr(track, 'next_art_uri') or (track['next_art_uri'] is None) or (track['next_art_uri'] == ""):
                        track['next_art_uri'] = next_track.album_art_uri
        except:
            log("Sonos: Failed to update using event details: %s" % traceback.format_exc(), xbmc.LOGERROR)
            # Should really display on the screen that some of the display information
            # might not be complete of upto date, only show the error once
            if Sonos.SHOWN_ERROR is not True:
                Sonos.SHOWN_ERROR = True
                xbmc.executebuiltin('Notification(%s, %s, 3000, %s)' % (ADDON.getLocalizedString(32001).encode('utf-8'), ADDON.getLocalizedString(32063).encode('utf-8'), ICON))

        return track
Esempio n. 20
0
from lyrics import Lyrics
from colored import fg, bg, attr
import random

file_name = 'lyrics_fr/Feu_Zoe_short.txt'

language = 'fr'
print_stats = True
lookback = 30
rhyme_cutoff = 2
l = Lyrics(file_name, language=language, lookback=lookback)


def generate_color(number_of_colors):
    color = [
        "#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])
        for i in range(number_of_colors)
    ]
    return color


def get_text_in_color(text, color):
    '''
    :param text: text that you're planning to print in color
    :param color: Hex color
    :return: str
    '''
    color = fg(color) + bg("#FFFFFF")  # white background is kept constant.
    res = attr('reset')
    return color + text + res
Esempio n. 21
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
Esempio n. 22
0
File: sonos.py Progetto: noba3/KoTos
    def mergeTrackInfoAndEvent(self, track, eventDetails, previousTrack=None):
        # Check if the new and previous tracks are the same, if they are then we can
        # check to see if there are lyrics that should be copied over to stop us getting
        # them again
        track = Lyrics.copyLyricsIfSameTrack(track, previousTrack)

        # If there is no event data, then just return the track unchanged
        if eventDetails is None:
            # Check to see if the track has changed, if it has not, then we can
            # safely use the previous event we stored
            if (previousTrack is not None) and (
                    track['uri'] == previousTrack['uri']) and (
                        previousTrack['lastEventDetails'] is not None):
                log("Sonos: Using previous Event details for merge")
                track['lastEventDetails'] = previousTrack['lastEventDetails']
                eventDetails = previousTrack['lastEventDetails']
            else:
                log("Sonos: Event details not set for merge")
                track['lastEventDetails'] = None
                return track
        else:
            log("Sonos: Event details set for merge")
            track['lastEventDetails'] = eventDetails

        # We do not want to throw an exception if we fail to process an event
        # It has been seen to happen in some strange cases, so we just catch and
        # log the error
        try:
            # Now process each part of the event message
            if eventDetails.enqueued_transport_uri_meta_data not in [None, '']:
                enqueued_transport = eventDetails.enqueued_transport_uri_meta_data
                log("enqueued_transport_uri_meta_data = %s" %
                    enqueued_transport)

                # Check if this is radio stream, in which case use that as the title
                # Station Name
                if hasattr(enqueued_transport,
                           'title') and (enqueued_transport.title
                                         not in [None, '']):
                    if not enqueued_transport.title.startswith('ZPSTR_'):
                        if (track['title'] is None) or (track['title'] == ""):
                            track['title'] = enqueued_transport.title

            # Process the current track info
            if eventDetails.current_track_meta_data not in [None, '']:
                current_track = eventDetails.current_track_meta_data
                log("current_track_meta_data = %s" % current_track)

                # Check if this is radio stream, in which case use that as the album title
                if hasattr(current_track,
                           'radio_show') and (current_track.radio_show
                                              not in [None, '']):
                    if not current_track.radio_show.startswith('ZPSTR_'):
                        if (track['album'] is None) or (track['album'] == ""):
                            track['album'] = current_track.radio_show
                            # This may be something like: Drivetime,p239255 so need to remove the last section
                            trimmed = track['album'].rpartition(',p')[0]
                            if (trimmed is not None) and (trimmed != ""):
                                track['album'] = trimmed
                # If not a radio stream then use the album tag
                elif hasattr(current_track, 'album') and (current_track.album
                                                          not in [None, '']):
                    if (track['album'] is None) or (track['album'] == ""):
                        track['album'] = current_track.album

                # Name of track. Can be ZPSTR_CONNECTING/_BUFFERING during transition,
                # or None if not a radio station
                if hasattr(current_track,
                           'stream_content') and (current_track.stream_content
                                                  not in [None, '']):
                    if not current_track.stream_content.startswith('ZPSTR_'):
                        if (track['artist'] is None) or (track['artist']
                                                         == ""):
                            track['artist'] = current_track.stream_content
                # otherwise we have the creator to use as the artist
                elif hasattr(current_track,
                             'creator') and (current_track.creator
                                             not in [None, '']):
                    if (track['artist'] is None) or (track['artist'] == ""):
                        track['artist'] = current_track.creator

                # If it was a radio stream, the title will already have been set using the enqueued_transport
                if hasattr(current_track, 'title') and (current_track.title
                                                        not in [None, '']):
                    if not current_track.title.startswith('ZPSTR_'):
                        if (track['title'] is None) or (track['title'] == ""):
                            track['title'] = current_track.title

                # If the track has no album art, use the event one (if it exists)
                if (track['album_art'] is None) or (track['album_art'] == ""):
                    if hasattr(current_track, 'album_art_uri') and (
                            current_track.album_art_uri not in [None, '']):
                        track['album_art'] = current_track.album_art_uri
                        # Make sure the Album art is fully qualified
                        if not track['album_art'].startswith(
                            ('http:', 'https:')):
                            track[
                                'album_art'] = 'http://' + self.ip_address + ':1400' + track[
                                    'album_art']

            # Process Next Track Information
            if eventDetails.next_track_meta_data not in [None, '']:
                next_track = eventDetails.next_track_meta_data
                log("next_track_meta_data = %s" % next_track)
                if hasattr(next_track, 'creator') and (next_track.creator
                                                       not in [None, '']):
                    if not hasattr(track, 'next_artist') or (
                            track['next_artist'] is
                            None) or (track['next_artist'] == ""):
                        track['next_artist'] = next_track.creator
                if hasattr(next_track, 'album') and (next_track.album
                                                     not in [None, '']):
                    if not hasattr(track, 'next_album') or (
                            track['next_album'] is
                            None) or (track['next_album'] == ""):
                        track['next_album'] = next_track.album
                if hasattr(next_track, 'title') and (next_track.title
                                                     not in [None, '']):
                    if not hasattr(track, 'next_title') or (
                            track['next_title'] is
                            None) or (track['next_title'] == ""):
                        track['next_title'] = next_track.title
                if hasattr(next_track,
                           'album_art_uri') and (next_track.album_art_uri
                                                 not in [None, '']):
                    if not hasattr(track, 'next_art_uri') or (
                            track['next_art_uri'] is
                            None) or (track['next_art_uri'] == ""):
                        track['next_art_uri'] = next_track.album_art_uri
        except:
            log(
                "Sonos: Failed to update using event details: %s" %
                traceback.format_exc(), xbmc.LOGERROR)
            # Should really display on the screen that some of the display information
            # might not be complete of upto date, only show the error once
            if Sonos.SHOWN_ERROR is not True:
                Sonos.SHOWN_ERROR = True
                xbmc.executebuiltin(
                    'Notification(%s, %s, 3000, %s)' %
                    (__addon__.getLocalizedString(32001).encode('utf-8'),
                     __addon__.getLocalizedString(32063).encode('utf-8'),
                     __icon__))

        return track
Esempio n. 23
0
def main(search, verbose):
    print('*** Searching for lyrics. ***')
    ly = Lyrics()
    lyrics = ly.get_lyrics(search)

    YT_search = search
    if lyrics == []:
        print("INFO: Could not found lyrics for your search.")
        lyric = None
    else:
        lyric = lyrics[0]
        if verbose:
            # list lyrics for user to choose
            for i, lyric in enumerate(lyrics, start=1):
                print(f'{i}. {lyric["author"]} {lyric["songName"]}')
            print('0. For no lyrics.')

            num = int(input('Choose lyrics: '))
            if num == 0:
                lyric = None
                YT_search = search
            elif num > len(lyrics) or num < 0:
                sys.exit('ERROR: Wrong input.')
            else:
                lyric = lyrics[num - 1]
                YT_search = f'{lyric["author"]} {lyric["songName"]}'
        else:
            print(f'Found: {lyric["author"]} - {lyric["songName"]}')

    print('Done.\n')

    # search youtube
    print(f"*** Searching Youtube for '{YT_search}'. ***")
    youtube = Youtube()
    songs = youtube.search(YT_search, sortByViews=False)

    song = songs[0]
    if verbose:
        # list youtube songs for use to choose
        for i, song in enumerate(songs, start=1):
            print(
                f'{i}. {song["title"]}, {song["views"]} views, {song["link"]}')
        print('0. Exit.')

        num = int(input('Choose lyrics: '))
        if num == 0:
            print('INFO: Exiting.')
            sys.exit(0)
        elif num > len(lyrics) or num < 0:
            exit('ERROR: Wrong input.')
        else:
            song = songs[num - 1]
    else:
        print(
            f'Found {song["title"]}, {song["views"]} views, {song["link"]}\n')

    print('Done.\n')

    # download a song from youtube
    print('*** Downloading and converting to mp3. ***')
    filepath, folder = youtube.download_and_convert_to_mp3(
        song['link'], DOWNLOAD_FOLDER)
    print('Done.\n')

    print('*** Filtering vocals. This could take a minute. ***')
    filter = Filter()
    vocals, instrum = filter.extract_vocals(filepath, folder)
    filter.mix_vocals_with_instrum(folder, vocals, instrum)
    print(f'Done.\n')

    if lyric is not None:
        print('*** Saving lyrics to file ***')
        ly.save(folder, lyric)
        print('Done saving lyrics to file.\n')

    absPath = os.path.abspath(folder)
    print(f'Output folder: {absPath}')
Esempio n. 24
0
from lyrics import Lyrics


file_name = 'lyrics_fr/Feu_Zoe_short.txt'

language = 'fr'
print_stats = True
lookback = 30
l = Lyrics(file_name, print_stats=print_stats, 
                  language=language, lookback=lookback)

for rhyme in (sorted(l.rhyme_map.items(), key=lambda x: x[1])):
    print rhyme[0], rhyme[1]



Esempio n. 25
0
class FooQt(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self, app):
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна

        # config loading
        self.config = config.Config(self)
        library.init(self.config.getLibraryDirs())
        self.lyrics = Lyrics(self.config)

        # make post ui setup after library is initialized
        self.postSetupUi()

        # Load config goes after postSetupUi() to be able to restore columns width
        self.config.load(app)
        self.connectEvents(app)

        self.tableModel.refreshPlaylist()

    def connectEvents(self, app):
        self.themeCombo.activated.connect(
            lambda: app.setStyle(self.themeCombo.currentText()))
        self.lyricsCombo.activated.connect(
            lambda: self.lyrics.setProvider(self.lyricsCombo.currentText()))
        self.browseDirBtn.clicked.connect(self.browseDirClick)
        self.rescanLibBtn.clicked.connect(self.rescanLibrary)
        self.settingsBtn.clicked.connect(self.openSettingsDialog)
        self.playBtn.clicked.connect(self.playBtnClick)
        self.nextBtn.clicked.connect(self.next)
        self.prevBtn.clicked.connect(self.prev)
        self.nextRndBtn.clicked.connect(self.nextRnd)
        self.searchEdit.textChanged.connect(self.searchChanged)
        self.treeView.clicked.connect(self.treeViewClick)
        self.tableView.doubleClicked.connect(self.play)
        self.posSlider.sliderMoved.connect(self.setPos)
        self.posSlider.sliderPressed.connect(self.setPos)
        self.timer.timeout.connect(self.updatePos)
        self.tableModel.modelAboutToBeReset.connect(
            self.tableModelBeforeChanged)
        self.tableModel.modelReset.connect(self.tableModelChanged)
        self.statusbar.clicked.connect(self.selectCurrentTrack)
        self.expandBtn.clicked.connect(self.expandBtnClick)
        self.volumeSlider.valueChanged.connect(self.setVolume)

    def treeViewClick(self, index: QtCore.QModelIndex):
        library.selected_dir_row = index.row()
        library.selected_dir = library.TreeModel().getDirPath(index)
        self.config.updateSelectedDir(library.selected_dir,
                                      library.selected_dir_row)
        self.searchChanged()

    def searchChanged(self):
        self.tableModel.refreshPlaylist(self.searchEdit.text())

    def stop(self):
        player.stop()
        self.updatePlayStatus()

    def updatePlayStatus(self):
        icon = qta.icon('fa.play') if player.isNoMusic() else qta.icon(
            'fa.pause')
        self.playBtn.setIcon(icon)
        if player.isNoMusic():
            self.timer.stop()
        else:
            self.timer.start()
        self.statusbar.showMessage(player.getNowPlayingMsg())

    def selectCurrentTrack(self):
        currentIndex = self.tableModel.getNowPlayIndex()
        if currentIndex is not False:
            self.tableView.setCurrentIndex(currentIndex)

    def playBtnClick(self):
        if not player.now_playing:
            return self.play((self.tableView.selectedIndexes() or [None])[0])

        player.playPause()
        self.updatePlayStatus()

    def play(self, index: QtCore.QModelIndex = None):
        if not index:
            return print('No item selected')

        track = player.play(index.row(), self.tableModel.tracks[index.row()])
        if track:
            self.selectCurrentTrack()
            self.updatePlayStatus()
            self.lyricsTxt.setText(self.lyrics.find())

    def next(self):
        nextIndex = self.tableModel.getNextIndex()
        if nextIndex:
            self.play(nextIndex)
        else:
            self.stop()

    def prev(self):
        prevIndex = self.tableModel.getPrevIndex()
        if prevIndex:
            self.play(prevIndex)
        else:
            self.stop()

    def nextRnd(self):
        rndIndex = self.tableModel.getRndIndex()
        if rndIndex:
            self.play(rndIndex)
        else:
            self.stop()

    def rescanLibrary(self):
        start_time = time.time()
        library.rescan()
        self.treeModel.loadTreeData()
        print("--- Library scan is completed in %s seconds ---" %
              (time.time() - start_time))

    def browseDirClick(self):
        newDir = QtWidgets.QFileDialog.getExistingDirectory(self)
        if newDir:
            self.config.updateLibraryDir(newDir)
            library.updateDirs([newDir, '', -1])
            self.rescanLibrary()

    def expandBtnClick(self):
        print(self.expandBtn.isChecked())
        # self.treeModel.
        # self.treeView.rootIndex().child()

    def setPos(self):
        self.timer.stop()
        pos = self.posSlider.value()
        player.mediaplayer.set_position(pos / 1000.0)
        self.timer.start()

    def updatePos(self):
        media_pos = int(player.mediaplayer.get_position() * 1000)
        # print('mediapos', media_pos)
        self.posSlider.setValue(media_pos)
        # No need to call this function if nothing is played
        if not player.mediaplayer.is_playing():
            if self.stopAfterBtn.isChecked():
                self.stopAfterBtn.setChecked(False)
                self.stop()
            else:
                self.nextRnd() if self.rndOrderBtn.isChecked() else self.next()

    def postSetupUi(self):
        # add invisible elements
        self.timer = QtCore.QTimer(self)
        self.treeModel = library.TreeModel()
        self.tableModel = library.TableModel()
        self.statusbar = StatusBar()
        # update qtDesigner non available properties
        self.timer.setInterval(100)
        # design updates
        self.themeCombo.addItems(QtWidgets.QStyleFactory.keys())
        self.lyricsCombo.addItems(self.lyrics.PROVIDERS)
        self.playBtn.setIcon(qta.icon('fa.play'))
        self.nextBtn.setIcon(qta.icon('mdi.skip-next'))
        self.prevBtn.setIcon(qta.icon('mdi.skip-previous'))
        self.nextRndBtn.setIcon(qta.icon('fa.question'))
        self.stopAfterBtn.setIcon(qta.icon('fa.stop-circle'))
        self.rndOrderBtn.setIcon(qta.icon('fa.random'))
        self.browseDirBtn.setIcon(qta.icon('fa.folder-open'))
        self.rescanLibBtn.setIcon(qta.icon('mdi.refresh'))
        self.expandBtn.setIcon(qta.icon('mdi.arrow-expand-vertical'))
        self.settingsBtn.setIcon(qta.icon('fa.cog'))

        self.posSlider.setMaximum(1000)
        # load Directory tree
        self.treeView.setModel(self.treeModel)
        # load Tracks
        self.tableView.setModel(self.tableModel)
        self.tableView.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        # my custom statusbar
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        # statusbar widgets
        self.volumeSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        self.volumeSlider.setMaximum(100)
        self.volumeSlider.setValue(player.getVolume())
        self.volumeSlider.setToolTip("Volume")
        self.volumeSlider.setFixedWidth(100)
        self.statusbar.addPermanentWidget(self.volumeSlider)

    def openSettingsDialog(self):
        dialog = SettingsDialog(self)
        dialog.confirmed.connect(self.saveSettingsFromDialog)
        dialog.geniusToken.setText(self.config.getLyricsGeniusToken())
        dialog.exec()

    def saveSettingsFromDialog(self, token):
        print('token = ' + token)
        self.config.updateLyricsGeniusToken(token)
        self.lyrics.onChangeTokens()

    def setVolume(self, volume):
        player.setVolume(volume)

    def tableModelBeforeChanged(self):
        for row in self.tableModel.groupRows:
            self.tableView.setSpan(row, 0, 1, 1)

    def tableModelChanged(self):
        for row in self.tableModel.groupRows:
            self.tableView.setSpan(row, 0, 1, library.Track.colCount())

    def closeEvent(self, event):
        self.config.save()
        event.accept()
Esempio n. 26
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