示例#1
0
def resolve_txt_playlist_bea(ls):
	assert isinstance(ls, list), "list expected but got type %r" % type(ls)
	all_songs = []
	for txt in ls:
		txt = txt.strip()
		if not txt: continue
		title, rem = txt.split("\t", 1)
		rem = rem.split()
		songs = resolve_txt_song(title, single=False)
		assert songs, "no song found for title %r" % title
		duration_s = rem[0].replace(".", ":").strip()  # sometimes written like "m.s"
		if ":" in duration_s:
			m, s = duration_s.split(":")
			if len(s) < 2: s += "0"  # sometimes remaining 0 is missing
			assert len(s) == 2
			m, s = int(m), int(s)
		else:
			m, s = int(duration_s), 0
		duration = 60 * m + s
		# Select the song which most closely matches the duration.
		best_song = songs[0]
		for s in songs:
			if s.get("duration", 0) <= 0:
				ss = Song(s["url"])
				ss.get("duration", timeout=None)  # load if not available yet
				assert ss.duration > 0, "cannot get duration for song %r" % s
				s["duration"] = ss.duration
			if abs(s["duration"] - duration) < abs(best_song["duration"] - duration):
				best_song = s
		assert abs(best_song["duration"] - duration) < 2, "title %r, song %r does not really match duration %r" % (title, best_song, duration)
		all_songs += [best_song]
	return all_songs
示例#2
0
 def add_song(self, title):
     # This is the HEAD, use a first song to link to other songs
     # Create a "new_song" using the node from "Song.py".
     new_song = Song(title)
     # Use the "new_song" to call "set_next_song()" linked to "__first_song". This creates the LL's Head.
     new_song.set_next_song(self.__first_song)
     self.__first_song = new_song
示例#3
0
 def add_song(self, title):
   #creates a new node  
   new_song = Song(title)
   #setting the new song to be the head of the list
   new_song.next = self.__first_song
   self.__first_song = new_song
   print('new song added')
示例#4
0
class Test_Song(unittest.TestCase):

    def setUp(self):
        self.song = Song(
            title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44")

    def test_init(self):
        self.assertTrue(isinstance(self.song, Song))
        self.assertEqual(self.song.title, 'Odin')
        self.assertEqual(self.song.artist, 'Manowar')
        self.assertEqual(self.song.album, "The Sons of Odin")
        self.assertEqual(self.song.length, "3:44")

    def test_str(self):
        self.assertEqual(
            str(self.song), 'Manowar - Odin from The Sons of Odin - 3:44')

    def test_hash(self):
        self.assertTrue(isinstance(hash(self.song), int))

    def test_eq(self):
        song2 = Song(
            title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44")
        song3 = Song(
            title="Odin1", artist="Manowar", album="The Sons of Odin", length="3:44")
        self.assertTrue(song2 == self.song)
        self.assertFalse(song3 == self.song)

    def test_length(self):
        self.assertEqual(self.song.get_length(seconds=True), 224)
        self.assertEqual(self.song.get_length(minutes=True), 3)
        self.assertEqual(self.song.get_length(hours=True), 0)
示例#5
0
 def test_eq(self):
     song2 = Song(
         title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44")
     song3 = Song(
         title="Odin1", artist="Manowar", album="The Sons of Odin", length="3:44")
     self.assertTrue(song2 == self.song)
     self.assertFalse(song3 == self.song)
示例#6
0
    def add_song(self, title):
        pass

        new_song = Song(title)
        new_song.set_next_song(self.__first_song)
        self._first_song = new_song
        print('Added')
示例#7
0
def getSongById(songId):
	f = getSongFilenameById(songId)
	if not f: return None
	song = Song(url=f)
	song.id = songId
	assert song
	return song
示例#8
0
def getSongById(songId):
    f = getSongFilenameById(songId)
    if not f: return None
    song = Song(url=f)
    song.id = songId
    assert song
    return song
 def __init__(self, song: Song, parent, remove_callback=None):
     """Show a popup with a songs details
     :type song: Song
     :param song: The song whose details should be shown
     :type parent: QWidget
     :param parent: The parent widget
     :type remove_callback: (Song) -> None
     :param remove_callback: A function to call when the song should be removed"""
     super().__init__(parent)
     # Set parameters
     self._song = song
     self._parent = parent
     self._remove_callback = remove_callback
     # Set gui
     self.setWindowTitle(song.get_name())
     #self.setWindowModality(Qt.ApplicationModal)
     self.layout = QVBoxLayout(self)
     self.setLayout(self.layout)
     # Remove action
     if remove_callback is not None:
         remove_button = QPushButton("Remove", self)
         remove_button.clicked.connect(self._remove_button_clicked)
         self.layout.addWidget(remove_button)
     # Song text
     label = QLabel(song.get_text(), self)
     self.layout.addWidget(label)
示例#10
0
def predict():
    try:
        choice = request.args.get('choice')
        artist = request.args.get('artist')
        song = request.args.get('song')

        user_song = Song(artist=artist, song=song, choice=choice)

        # Get data in format for machine learning model
        data = user_song.data
        song_features = user_song.song_features
        (song_name, artist_name, song_url, popularity, preview_url,
         preview_img_urls) = user_song.extract_trackinfo()
        print(song_url)
        # print(data)
        # print(data[0])
        with graph.as_default():
            # perform the prediction
            pred = model.predict(data)
            pred = "{0:.3f}".format(pred[0][0] * 100)
            # Multipling pred by 100 to get %
            # pred = str(pred[0][0] * 100)
            # pred = pred * 100
            # print(pred)
            return render_template('predict_copy.html',
                                   song_name=song_name,
                                   artist_name=artist_name,
                                   song_url=song_url,
                                   preview_img_urls=preview_img_urls,
                                   popularity=popularity, preview_url=preview_url,
                                   pred=pred, song_features=song_features,
                                   title='Prediction')
    except Exception:
        return render_template('500.html')
 def setUp(self):
     self.playlist = Playlist("random")
     song1 = Song(
         "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512)
     song2 = Song(
         "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512)
     self.playlist.add_song(song1)
     self.playlist.add_song(song2)
 def add_song(self, title):
   new_song = Song(title)
   if self.__first_song is None: 
     self.__first_song = new_song
     return
   else:
     new_song.set_next_song(self.__first_song)
     self.__first_song = new_song
示例#13
0
def run():
    for line in open("songextraction/songs.txt"):
        line = line.strip()
        song = Song(artist="Grateful Dead", title=line)
        lyr = song.lyricwikia()
        if lyr is not None:
            with open("songs/" + line.replace("\n", "") + ".txt", "w") as f:
                f.write(lyr)
示例#14
0
    def add_song(self, title):
        #  Create a new song
        new_song = Song(title)

        # Set new song's next pointer to where the __first_song is pointing
        new_song.set_next_song(self.__first_song)

        # Set __first_song pointer to point at the new song
        self.__first_song = new_song
示例#15
0
    def add_song(self, title):
        #create a new node
        new_song = Song(title)

        #sets the next song to the head of the linked list
        new_song.set_next_song(self.__first_song)

        #set new node to next pointer to point at the new node
        self.__first_song = new_song
示例#16
0
    def updateAllClients(self):

        if SongsQueue.queue:
            current_song = Song(SongsQueue.queue[0])
            msg = "CURRENT_" + current_song.getTitle(
            ) + "_" + current_song.getArtist() + "\r\n"
            print("Sending message: " + msg)
            for client in self.clients:
                client.send(msg.encode('utf-8'))
示例#17
0
  def add_song(self, title):
    print("=" * 90)

    add_song = Song(title)
    add_song.next = self.__first_song
    self.__first_song = add_song

    print("new song added to playlist")

    print("=" * 90 )
示例#18
0
 def generate_playlist(self):
     code_songs = Playlist(name="Code", repeat=True, shuffle=False)
     for music_file in self.files_in_dir:
         audio = MP3(self.path + music_file, ID3=EasyID3)
         artist = audio['artist'][0]
         title = audio['title'][0]
         album = audio['album'][0]
         length = str(datetime.timedelta(seconds=int(audio.info.length)))
         new_song = Song(
             title=title, artist=artist, album=album, length=length)
         new_song.path = self.path + music_file
         code_songs.add_song(new_song)
     return code_songs
示例#19
0
    def update(self, trgtdatabase=False):
        self.songs = []

        #We walk through the directories and parse through each file
        for root, dirs, files in os.walk(self.homeDirectory):
            for file in files:
                temp = self.songFileRE.search(file)
                #if the file is of the proper type, we create a new song object and append it to the contents of the library
                if (temp != None):
                    if trgtdatabase:
                        self.dataBase.addSongToDatabase(Song(root, file))

                    self.songs.append(Song(root, file))
示例#20
0
    def test_total_length(self):
        song1 = Song(title="Odin1",
                     artist="Manowar",
                     album="The Sons of Odin",
                     length="3:44")
        song2 = Song(title="Odin2",
                     artist="Manowar",
                     album="The Sons of Odin",
                     length="3:44")
        songs = [song1, song2]
        self.code_songs.add_songs(songs)

        self.assertEqual(self.code_songs.total_length(), '00:11:12')
示例#21
0
class SongTest(unittest.TestCase):
    def setUp(self):
        self.song = Song("TestTitle", "TestArtist",
                         "TestAlbum", 2, 200, 128, "")

    def test_init(self):
        self.assertEqual(self.song.title, "TestTitle")
        self.assertEqual(self.song.artist, "TestArtist")
        self.assertEqual(self.song.album, "TestAlbum")
        self.assertEqual(self.song.rating, 2)
        self.assertEqual(self.song.length, 200)
        self.assertEqual(self.song.bitrate, 128)
        self.assertEqual(self.song.path_to_file, "")

    def test_rate(self):
        self.song.rate(4)
        self.assertEqual(self.song.rating, 4)

    def test_get_artist(self):
        self.assertEqual(self.song.get_artist(), "TestArtist")

    def test_get_title(self):
        self.assertEqual(self.song.get_title(), "TestTitle")

    def test_get_album(self):
        self.assertEqual(self.song.get_album(), "TestAlbum")

    def test_get_rating(self):
        self.assertEqual(self.song.get_rating(), 2)

    def test_get_length(self):
        self.assertEqual(self.song.get_length(), 200)

    def test_get_bitrate(self):
        self.assertEqual(self.song.get_bitrate(), 128)
示例#22
0
 def test_save(self):
     song1 = Song(title="Oleeeee",
                  artist="Uhuuuuuuuu",
                  album="The Sons of Odin",
                  length="3:10")
     song2 = Song(title="Odin2",
                  artist="Manowar",
                  album="The Sons of Odin",
                  length="3:24")
     songs = [song1, song2]
     self.code_songs.add_songs(songs)
     self.code_songs.save()
     with open('./playlist-data/Code.json', "r") as f:
         contents = f.read()
         print(contents)
示例#23
0
 def add_song(self, title):
     if self.__first_song == None:
         # Create a new song object with title passed in
         new_song = Song(str(title).title())
         # Assign the new song as the first of the playlist
         self.__first_song = new_song
     else:
         # Create a new song object with title passed in
         new_song = Song(title)
         # Iterate through the list of existing songs until the end is reached
         current_song = self.__first_song
         while current_song.get_next_song() != None:
             current_song = current_song.get_next_song()
         # Assign the new song to the end
         current_song.set_next_song(new_song)
示例#24
0
文件: mxm.py 项目: acrabb/mp-complete
def IDSong(echoID):
	# print '[*] >>> ID:', echoID

	try:
		track = TRACK.Track(echoID, echonest=True)
	except Exception as e:
		print "[*] >>> SONG NOT FOUND :("
		print '[*] >>> e:', e
		return None
	songInfo = getInfo(track)
	song = Song()
	for key in songInfo.keys():
		song.setWhatever(key, songInfo.get(key))
	# print '[*] AFTER SETTING', song
	return song	
示例#25
0
 def get_billboard_chart_as_list(self, chart_id, gmusic=None):
     song_list = []
     entries = self.get_billboard_chart(chart_id)
     for entry in entries:
         song = Song(artist=entry.artist,
                     title=entry.title,
                     billboard_rank=entry.rank,
                     billboard_date=dt.datetime.now(),
                     billboard_change=entry.lastPos - entry.rank)
         if gmusic:
             result = gmusic.search_song(song)
             song.google_music_store_id = gmusic.get_store_id(result)
             song.google_music_rating = gmusic.get_google_rating(result)
         song_list.append(song)
     return song_list
示例#26
0
def read(path):
    with open(path, "r", encoding="utf-8", newline="") as file:
        playlists = []
        row_count = 0
        for row in csv.reader(file):
            if row_count == 0:
                title_index = row.index("title")
                artist_index = row.index("artist")
                album_index = row.index("album")
                id_index = row.index("id")
                playlist_index = row.index("playlist")
            else:
                song = Song(row[title_index], row[artist_index],
                            row[album_index], row[id_index])
                playlist_name = row[playlist_index]

                for playlist in playlists:
                    if playlist.name == playlist_name:
                        matching_playlist = playlist
                        break
                else:
                    matching_playlist = Playlist(playlist_name)
                    playlists.append(matching_playlist)

                matching_playlist.songs.append(song)

            row_count += 1

    return playlists
示例#27
0
    def get_playlist_information(self, playlist_id, ordered_by, ascending):
        cursor = self.con.cursor()
        query = '''SELECT playlistName, playlistDescription FROM Playlist WHERE playlistID = ?'''
        cursor.execute(query, (playlist_id, ))
        self.con.commit()

        playlist_info = cursor.fetchall()
        playlist = Playlist(*playlist_info[0])

        query = '''SELECT PlaylistContainsSong.songURL, albumTitle, Song.bandName, featured_artist, songName, songRelease, songLyrics, songLength, songGenre
                    FROM PlaylistContainsSong
                    INNER JOIN Song ON Song.songURL = PlaylistContainsSong.songURL
                    INNER JOIN Album ON Album.albumID = Song.albumID
                    INNER JOIN SongGenres ON SongGenres.songURL = Song.songURL
                    WHERE playlistID = ?
                    ORDER BY ''' + ordered_by + ''' ''' + ascending

        cursor.execute(query, (playlist_id, ))
        old_songs_list = cursor.fetchall()

        for item in old_songs_list:
            song = Song(*item)
            playlist.add_song(song)

        return playlist
示例#28
0
	def cmdAddId(self, url, position=None):
		if url.startswith("file://"):
			url = url[len("file://"):]
		if url[:1] != "/":
			import appinfo
			basedir = appinfo.musicdirs[0] + "/"
			url = basedir + url
		import os
		assert os.path.exists(url), "%s not found" % url
		from Song import Song
		song = Song(url=url)
		assert song, "cannot load song"
		with state.queue.queue.lock:
			if position is None:
				position = len(state.queue.queue)
			else:
				position = int(position)
				position -= self.baseIdx + 1
				if position > len(state.queue.queue):
					position = len(state.queue.queue)
				elif position < 0:
					position = 0
			state.queue.queue.insert(position, song)
		self.f.write("Id: %i\n" % (self.baseIdx + position + 1))
		# songids are messed up now. force reload
		self._resetPlaylist()
示例#29
0
文件: mxm.py 项目: acrabb/mp-complete
def makeSong(artist, name):
	'''
	Call 'searchQuery
			getInfo
		and setWhatever
	'''
	name = rmParends(name)
	songs = searchQuery(artist, name)
	if len(songs) < 1:
		return None
	songInfo = getInfo(songs[FIRST])
	song = Song()
	for key in songInfo.keys():
		song.setWhatever(key, songInfo.get(key))
	# print '[*] AFTER SETTING', song
	return song
示例#30
0
def load():
    with open("data_1") as json_file:
        data = json.load(json_file)

        array = []
        for son in data["data"]["data"]["songs"]:
            aname = son["singers"]
            song_name = son["songName"]

            listenFiles = son["listenFiles"]
            maxSize = 0
            fm = ""
            for files in listenFiles:
                size = float(files["fileSize"]) / 1024 / 1024
                if maxSize < size:
                    maxSize = size
                    lfile = files["listenFile"]
                    fm = files["format"]

            print aname
            print song_name
            print lfile
            print maxSize

            newSong = Song(artist_name=aname,
                           song_name=song_name,
                           url=lfile,
                           size=maxSize,
                           format=fm)
            array.append(newSong)
        for ns in array:
            ns.startDown()
示例#31
0
def __get_count_songs_list(song: Song, content: dict):
    """
    add count attr to song elem
    :param song: Song class
    :param content: dictionary that contain the type and value of searching
    """
    song.count = get_count_songs(content)
示例#32
0
    def collectSongs(self):
        script = self.soup.find('span', class_='ab_widget').text
        parsed = script.split(',')
        title_list_fluff = []
        artist_list_fluff = []
        duration_list_fluff = []
        title_list = []
        artist_list = []
        duration_list = []
        for p in parsed:
            if 'trackTitle' in p:
                title_list_fluff.append(p)
            if 'artists' in p:
                artist_list_fluff.append(p)
            if 'duration' in p:
                duration_list_fluff.append(p)
        #Garbage value
        del artist_list_fluff[0]
        for n in range(len(title_list_fluff)):
            title = title_list_fluff[n].split(':')
            title_list.append(title[1].replace('"', ''))

            artist = artist_list_fluff[n].split(':')
            artist_list.append(artist[1].replace('"', ''))

            duration = duration_list_fluff[n].split(':', 1)
            duration_list.append(duration[1].replace('"', ''))
        # print(title_list)
        # print(artist_list)
        # print(duration_list)
        for n in range(len(title_list)):
            newSong = Song(title_list[n], artist_list[n], duration_list[n])
            self.songList.append(newSong)
示例#33
0
    def loadLibrary(self, inputFilename):
        tempfile = open(inputFilename)
        csv_tempfile = csv.reader(tempfile)

        for file in csv_tempfile:
            self.songArray.append(Song(file))
        self.size = len(self.songArray)
示例#34
0
def normalize(db_path, normalized_database):
    """
    This function normalizes a single database using SQLAlchemy
    :param db_path: input database
    :param normalized_database: the resulting database
    :return:
    """
    try:
        data = make_queries(db_path)

        engine = create_engine(f"sqlite:///{normalized_database}", echo=False)
        Base.metadata.create_all(engine)
        Session = sessionmaker(bind=engine)
        session = Session()

        for metadata in data:
            song_obj = (session.query(Song)
                        .filter(Song.title == metadata[0])
                        .filter(Song.artist == metadata[1]).first())
            if song_obj is None:
                song_obj = Song(metadata[0], metadata[1], metadata[2], metadata[3], metadata[4], metadata[5], metadata[6])
                session.add(song_obj)
            else:
                # Clementine have multiple redundant songs, so the following increments may hurt the counters accuracy
                continue
                # song_obj.playcount += metadata[3]
                # song_obj.skipcount += metadata[4]
        session.commit()
    except TypeError:
        print(f"{db_path} is not a Clementine database")
示例#35
0
 def setUp(self):
     self.code_songs = Playlist(name="Code", repeat=True, shuffle=True)
     self.song = Song(title="Odin",
                      artist="Manowar",
                      album="The Sons of Odin",
                      length="3:44")
     self.code_songs.add_song(self.song)
示例#36
0
 def __init__(self, mashup_filename, source_filenames, 
         crossmatch=True, recompute=False, verbose=False):
     
     self.mashup = Song(mashup_filename, recompute, verbose)
     self.sources = [Song(s, recompute, verbose) for s in source_filenames]
     if crossmatch:
         if verbose: print("Crossmatching sources...")
         self.crossmatch_sources(recompute, verbose)
     self.labeled = None
示例#37
0
  def testSaving(self):
    config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)
    e = GameEngine(config)
    
    # Make a temp copy
    tmp   = "songtest_tmp"
    files = ["song.ini", "guitar.ogg", "song.ogg", "notes.mid"]
    try:
      os.mkdir(tmp)
      for f in files:
        shutil.copy(e.resource.fileName("tutorials", "bangbang", f), tmp)
    
      infoFile   = os.path.join(tmp, "song.ini")
      guitarFile = os.path.join(tmp, "guitar.ogg")
      songFile   = os.path.join(tmp, "song.ogg")
      noteFile   = os.path.join(tmp, "notes.mid")
      song       = Song(e, infoFile, guitarFile, songFile, None, noteFile)
      
      events1 = song.track[0].getAllEvents()
      
      song.save()
      song       = Song(e, infoFile, guitarFile, songFile, None, noteFile)
      
      events2 = song.track[0].getAllEvents()

      notes1 = [(time, event) for time, event in events1 if isinstance(event, Note)]      
      notes2 = [(time, event) for time, event in events2 if isinstance(event, Note)]
      
      for i, event in enumerate(zip(notes1, notes2)):
        t1, n1 = event[0]
        t2, n2 = event[1]
        
        if "-v" in sys.argv:
          print "%8d. %.3f + %.3f\t%2d\t     %.3f + %.3f\t%2d" % (i, t1, n1.length, n1.number, t2, n2.length, n2.number)
        
        # Allow 2ms of rounding error
        assert abs(t1 - t2) < 2
        assert abs(n1.length - n2.length) < 2
        assert n1.number == n2.number
    finally:
      # Load another song to free the copy
      pygame.mixer.music.load(e.resource.fileName("tutorials", "bangbang", "guitar.ogg"))
      shutil.rmtree(tmp)
示例#38
0
    def addNewSong(self):
        if self.dir:
            dir = self.dir
        else:
            dir = "."
        
        fileName = QFileDialog.getOpenFileName(self, self.tr("Open audio file"),
                                                   dir,
                                                   self.tr("mp3 (*.mp3)"))
        if fileName == "":
            return
        id3r = id3reader.Reader(str(fileName))
        album = id3r.getValue('album')
        title = id3r.getValue('title')
        artist = id3r.getValue('performer')

        song = Song(title, artist, album)
        song.id = self.id
        self.playlist[self.id]=song
        self.id+=1
        self.addSongToTable(song)
        self.tableViewSong.resizeColumnsToContents()
示例#39
0
class Test_Song(unittest.TestCase):
    def setUp(self):
        self.song = Song("Title", "Artist", "Album", 1, 160, 120)

    def test_song_init(self):
        self.assertEqual(self.song.artist, "Artist")
        self.assertEqual(self.song.title, "Title")
        self.assertEqual(self.song.album, "Album")
        self.assertEqual(self.song.rate, 1)
        self.assertEqual(self.song.length, 160)
        self.assertEqual(self.song.bitrate, 120)

    def test_rate_if_given_integer_more_than_5_or_less_than_0(self):
        with self.assertRaises(ValueError):
            self.song.rate_song(6)

    def test_rate(self):
        self.song.rate_song(4)
        self.assertEqual(self.song.rate, 4)

    def test_str(self):
        song = "Artist Title - 0:02:40"
        self.assertEqual(str(self.song), song)
示例#40
0
	def update_current_song(self):
		page_source = None
		url = self.url % self.current_channel
		try:
			page_source = urllib.urlopen(url)
		except urllib2.HTTPError:
			print "Get current song information failed"
		page_data = page_source.read()
		json_data =json.loads(page_data)
		new_json_data = json.dumps(json_data['song'], ensure_ascii=False)
		song_data = json.loads(new_json_data)

		self.current_song = Song(song_data[0]) 
		self.player.update_current_song(self.current_song)
示例#41
0
class TrackReader(MidiOutStream):
	"prints all note_on and note_off events"
	
	def __init__(self):
		self.song = Song()
	
	def tempo(self, value):
		bpm = 60.0 * 10.0**6 / value
		self.song.set_bpm(bpm)
		#print "Tempo", value, "BPM", bpm
		print self.song.bpm
	
	def note_on(self, channel=0, note=0x40, velocity=0x40):
		difficulty, value = noteMap[note]
		note = Note(time=self.abs_time(), value=value, type=NOTE_ON, velocity=velocity, channel=channel)
		self.song.add_note(difficulty, note)
	
	def note_off(self, channel=0, note=0x40, velocity=0x40):
		difficulty, value = noteMap[note]
		note = Note(time=self.abs_time(), value=value, type=NOTE_OFF, velocity=velocity, channel=channel)
		self.song.add_note(difficulty, note)
示例#42
0
 def setUp(self):
     self.song = Song("Title", "Artist", "Album", 1, 160, 120)
示例#43
0
 def setUp(self):
     self.song = Song("TestTitle", "TestArtist",
                      "TestAlbum", 2, 200, 128, "")
示例#44
0
	def __init__(self):
		self.song = Song()
示例#45
0
 def test_rate(self):
     song = Song(
         "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512)
     song.rate(5)
     self.assertEqual(song.rating, 5)
示例#46
0
#!/usr/bin/env python

import sys
from Song import Song
from WordTrader import WordTrader, ManualWordTrader

filename = ''
if len(sys.argv) > 1:
    filename = sys.argv[1]
else:
    print "Please provide a .kar karaoke file."
    sys.exit(0)

s = Song(filename)
if not s.midi.karfile:
    print "This is not a karaoke file."
    sys.exit(0)

tweetTrader=WordTrader("txts/corpus.songs.txt", "txts/corpus.tweets.txt")
blogTrader=WordTrader("txts/corpus.songs.txt", "txts/corpus.blogs.txt")
manualTrader=ManualWordTrader("txts/manual.tweets.txt")

## plain
#s.prepWordVoice()

## with automatic dict
s.prepWordVoice(tweetTrader)

## with a manual dict
#s.prepWordVoice(manualTrader)
示例#47
0
class Mashup:

    '''
    Associates mashup with its source songs and reconstructs mashup using source segments.
        mashup = graph of input mashup
        sources = graphs of input source songs
        labeled = graph of labeled mashup
        crossmatch = crossmatch all combinations of source songs
        recompute = force recompute graphs for tracks
        verbose = print results on screen
    '''
    def __init__(self, mashup_filename, source_filenames, 
            crossmatch=True, recompute=False, verbose=False):
        
        self.mashup = Song(mashup_filename, recompute, verbose)
        self.sources = [Song(s, recompute, verbose) for s in source_filenames]
        if crossmatch:
            if verbose: print("Crossmatching sources...")
            self.crossmatch_sources(recompute, verbose)
        self.labeled = None

    '''
    Crossmatch pairs of sources and add them to sources list
    '''
    def crossmatch_sources(self, recompute=False, verbose=False):
        #[(start,duration),...] by timing rather than node index
        def to_tuples(graph):
            return [(d['source'],d['duration']) for s,t,d in graph.edges_iter(data=True)]

        #for all combinations of source songs
        for pair in combinations(self.sources, 2):
            #get crossmatch filename and beats lists
            s1_s2 = "-".join([pair[0].mp3_path,pair[1].mp3_name,"cross.mp3"])
            s2_s1 = "-".join([pair[1].mp3_path,pair[0].mp3_name,"cross.mp3"])
            s1_beats, s2_beats = to_tuples(pair[0].graph), to_tuples(pair[1].graph)
            #use length of min source
            if len(s1_beats) > len(s2_beats):
                s1_beats = s1_beats[:len(s2_beats)]
            elif len(s2_beats) > len(s1_beats):
                s2_beats = s2_beats[:len(s1_beats)]

            #check if crossmatch mp3 exists
            try:
                f = open(s1_s2)
                f.close()
                if verbose: print("Found precomputed crossmatch %s" % s1_s2)
                if recompute: raise Exception()
                self.sources.append(Song(s1_s2))
            except:
                try:
                    f = open(s2_s1)
                    f.close()
                    if verbose: print("Found precomputed crossmatch %s" % s2_s1)
                    if recompute: raise Exception()
                    self.sources.append(Song(s2_s1))
                #RENDER new crossmatch mp3
                except:
                    if verbose and not recompute: print("Found no precomputed crossmatches.")
                    if verbose and recompute: print("Recomputing crossmatches...")
                    #load tracks
                    if pair[0].track == None: pair[0].load_track()
                    if pair[1].track == None: pair[1].load_track()
                    #equalize tracks
                    #TODO beat match to mashup tempo
                    pair[0].track, pair[1].track = equalize_tracks([pair[0].track,pair[1].track])
                    if verbose: print("Rendering crossmatch %s..." % s1_s2)
                    render([Crossmatch( (pair[0].track,pair[1].track), (s1_beats,s2_beats) )], s1_s2) 
                    self.sources.append(Song(s1_s2))


    '''
    Label mashup with sources using...
        "SA" = sequence alignment
        "GA" = genetic algorithm
    '''
    def label(self, algorithm="GA", verbose=False, out=None,
            size=300, maxgens=100, crossover=0.9, mutation=0.1, optimum=0.0, 
            restrict=False, converge=True, smooth=False):
        if algorithm == "SA":
            if verbose: print("Labeling %s using sequence alignment..." % self.mashup.mp3_name)
            self.labeled = alignment_labeling(self, verbose)
            return self.labeled
        else:
            if verbose: print("Labeling %s using genetic algorithm..." % self.mashup.mp3_name)
            self.labeled = genetic_labeling(self, verbose, out, 
                    size, maxgens, crossover, mutation, optimum,
                    restrict, converge, smooth)
            return self.labeled
    
    '''
    Evaluate mashup versus labeled mashup
    '''
    def eval(self):
        print("== LABELED GRAPH ==")
        for n,d in self.labeled.nodes_iter(data=True):
            print(n,d)

    '''
    Render reconstruction of mashup using labeled segments of sources
    '''
    def reconstruct(self, out, algorithm, verbose=False):
        # Check that we have loaded track from Echo Nest
        # Create source dictionary
        source_dict = {}
        if self.mashup.track == None: self.mashup.load_track(verbose)
        for s in self.sources:
            if s.track == None:
                s.load_track(verbose)
            source_dict[s.mp3_name] = s.track

        if verbose: print("Calculatiing actions in reconstructed mashup...")
        actions = get_actions(self.labeled, source_dict, verbose)
       	if verbose: print("Found actions: %s" % actions)
 
        filename = out+"-"+algorithm+"-reconstructed.mp3"
        if verbose: print("Rendering reconstructed mashup...")
        render(actions, filename)
    
    '''
    Write reconstruction out to 2 files: OUT.graph and OUT.segs
    .graph contains normal graph of mashup
    .segs constains: segment# .graph_start_node .graph_stop_node
    '''
    def write_graph(self, out, verbose=False):
        graph_filename = out+".graph"
        segs_filename = out+".segs"

        if verbose: print("Writing out .graph and .segs files for reconstructed mashup...")
        gf = open(graph_filename, "w")
        sf = open(segs_filename, "w")
        gf.write(str(self.labeled.number_of_nodes())+" "+str(self.labeled.number_of_edges())+"\n")
	# write node data out to file
        curr_seg = 0
        start = 0
        prev = self.labeled.node[0]['label'][1]-1
	prev_song = self.labeled.node[0]['label'][0]
        for n,d in self.labeled.nodes_iter(data=True):
            gf.write(str(n)+"\n")
            gf.write(" ".join(str(i) for i in d['timbre']))
            gf.write("\n")
            gf.write(" ".join(str(j) for j in d['pitch']))
            gf.write("\n")
            if d['label'][1] != prev+1:
                sf.write(" ".join([str(curr_seg), prev_song, str(start), str(n-1)]))
                sf.write("\n")
                start = n
                curr_seg += 1
                prev_song = d['label'][0]
            prev = d['label'][1]

        # write edge data out to file
        for s,t,d in self.labeled.edges_iter(data=True):
            gf.write(" ".join([str(s),str(t),
                str(d['duration']),str(d['source']),str(d['target'])]))
            gf.write("\n")
        gf.close()
        sf.close()

    '''
    Print mashup, sources, and labeled mashup to screen
    '''
    def __repr__(self):
        print("GRAPH FOR MASHUP: %s" % self.mashup.mp3_name)
        for n,d in self.mashup.graph.nodes_iter(data=True):
            print(n,d)
        for s in self.sources:
            print(s)
            print("GRAPH FOR SOURCE: %s" % s.mp3_name)
            for n,d in s.graph.nodes_iter(data=True):
                print(n,d)
        return "" #TODO I dont think this is orthodox
示例#48
0
from Song import Song

happy_bday = Song(["Happy birthday to you",
					"I don't want to get sued",
					"So I'll stop right here"])

happy_bday.sing_me_a_song()
示例#49
0
class Client(object):
	"""The client class that responds for the user input and menu print, as well as the main logics"""
	def __init__(self):
		self.url = 'http://douban.fm/j/mine/playlist?type=n&channel=%d&from=mainsite'
		self.current_song = None
		self.player = Player()
		self.channel = Channel()
		self.current_channel = self.channel.current_channel
		self.view = View(self.channel)
		self.update_current_song()
		self.is_playing = False
		self.seconds = 0
		self.length = self.current_song.length

	def update_current_song(self):
		page_source = None
		url = self.url % self.current_channel
		try:
			page_source = urllib.urlopen(url)
		except urllib2.HTTPError:
			print "Get current song information failed"
		page_data = page_source.read()
		json_data =json.loads(page_data)
		new_json_data = json.dumps(json_data['song'], ensure_ascii=False)
		song_data = json.loads(new_json_data)

		self.current_song = Song(song_data[0]) 
		self.player.update_current_song(self.current_song)

	def print_helper(self):
		self.view.print_helper()

	def play(self):
		self.is_playing = True
		self.player.play_current_song()

	def stop(self):
		self.is_playing = False
		self.seconds = 0
		self.player.stop_playing_current_song()

	def next(self):
		self.view.print_loading_information()
		self.player.stop_playing_current_song()
		self.update_current_song()
		self.play()

	def pre_channel(self):
		self.channel.pre_channel()
		self.change_channel()

	def next_channel(self):
		self.channel.next_channel()
		self.change_channel()

	def change_channel(self):
		new_channel = self.channel.current_channel
		if new_channel != self.current_channel:
			self.current_channel = new_channel
			self.next()

	def exit(self):
		self.player.stop_playing_current_song()
		self.view.print_exit_informaton()
		sys.exit()

	def display(self):
		while True:
			if self.is_playing == True:
				self.seconds = self.seconds + 1
				self.view.print_song_information(self.seconds, self.current_song.get_basic_information())
			else:
				self.view.print_pause_information()
				break
			time.sleep(1.0)

	def start(self):
		self.play()
		while True:
			self.display()
			i = getch._Getch()
			choice = i()
			if choice == 'p' and self.is_playing == False:
				self.play()
			elif choice == 's' and self.is_playing == True:
				self.stop()
			elif choice == 'n':
				self.next()
			elif choice == 'i':
				self.pre_channel()
			elif choice == 'k':
				self.next_channel()
			elif choice == 'h':
				self.print_helper()
			elif choice == 'q':
				self.exit()
示例#50
0
 def test_rate_out_of_scope(self):
     with self.assertRaises(ValueError):
         song = Song(
             "We Are!", "Hiroshi Kitadani", "One Piece OST", 5, 240, 512)
         song.rate(7)