def test_add_song_published_album(self): album = Album("The Sound of Perseverance") song = Song("Scavenger of Human Sorrow", 6.56, False) album.publish() message = album.add_song(song) expected = "Cannot add songs. Album is published." self.assertEqual(message, expected)
def test_remove_song_working(self): album = Album("The Sound of Perseverance") song = Song("Scavenger of Human Sorrow", 6.56, False) album.add_song(song) message = album.remove_song("Scavenger of Human Sorrow") expected = "Removed song Scavenger of Human Sorrow from album The Sound of Perseverance." self.assertEqual(message, expected)
def test_add_song_already_added(self): album = Album("The Sound of Perseverance") song = Song("Scavenger of Human Sorrow", 6.56, False) album.add_song(song) message = album.add_song(song) expected = "Song is already in the album." self.assertEqual(message, expected)
def test_save_failure(description, data, save_name_album, save_name_web, exceptions, pre_func): """Saves an album and verifies that an expected exception was thrown. Arguments: description: A description of the test case, at most 55 characters. data: A dictionary containing album data. save_name_album: The name under which to save the album, relative to a temporary directory. save_name_web: The name under which the web JSON will be saved, relative to a temporary directory. exceptions: A tuple of exceptions that indicate save failure. pre_func: A function to execute before the album is saved. The name of the temporary directory will be passed in as an argument. """ print(" Testing %s... " % (description), end="") nonlocal testsTotal, testsFailed testsTotal += 1 try: with tempfile.TemporaryDirectory() as temp_dir: if None is not pre_func: pre_func(temp_dir) Album.save(os.path.join(temp_dir, save_name_album), data) except exceptions as ex: print("passed.") if 2 <= verbosity: print(ex) except (Exception) as ex: print("FAILED!") testsFailed += 1 if 1 <= verbosity: print(ex) else: print("FAILED!") testsFailed += 1
def add_track(self, loc, trackdb): track = trackdb.get_track_by_loc(loc) if not track: track = Track(loc) respone = trackdb.add_track_from_trackobj(track) if not respone: return False tr_album = track.get_tag_raw('album', True) tr_albumartist = track.get_tag_raw('albumartist', True) if tr_albumartist == u'': tr_albumartist = track.get_tag_raw('artist', True) album = self.get_album_from_info(tr_album, tr_albumartist) if not album: # create new album album = Album(tr_album, tr_albumartist) self.__albums[(tr_album, tr_albumartist)] = album album.unchecked_add_song(track) self.__total_duration += track.get_tag_raw('__length') # cover = coverdb.get_cover(tr_album, tr_albumartist) # if not cover: # tr_cover = track.get_tag_disk('cover') # if tr_cover: # coverdb.add_cover(tr_album, tr_albumartist, tr_cover) return track
def test_to_and_from_str_with_albums(self): artist = Artist('artist name', 'country') first_album = Album('first album title', 2020) first_album.add(Song('first song title')) first_album.add(Song('second song title')) second_album = Album('second album title', 2021) second_album.add(Song('third song title')) assert Artist.from_string(str(artist)) == artist
def main(): log.info('Start process the gallery...') horcrux = Album(conf.PHOTOS_PATH, 'Horcrux', 0) config = horcrux.format() log.info('Now writing the config file to ' + str(conf.HORCRUX_PATH)) conf.write_json(conf.HORCRUX_PATH, config) Nest().main() log.ok('Success! Enjoy~')
def load_album(cls, fl_album, name): """Загрузка альбома""" with open(fl_album, 'r') as file_in: data = file_in.readlines() new_album = Album(name) for song in data: singer, name, duration = song.split(' - ') new_album.add_song(Song(singer, name, duration))
def test_get_repeated_sticker(self): album = Album() stickers = [1, 3, 3, 4, 5, 6, 1, 10, 11, 11, 15, 3] album.insert_sticker(stickers) repeated_stickers = album.get_repeated_sticker() self.assertEqual(repeated_stickers, {1: 1, 3: 2, 11: 1})
def test_get_number_of_repeated_sticker(self): album = Album() stickers = [1, 1, 1, 1, 3, 3, 4, 5, 6, 10, 10, 11, 11, 15, 15, 15, 15] album.insert_sticker(stickers) repeated_stickers = album.get_repeated_sticker() self.assertEqual(repeated_stickers, {1: 3, 3: 1, 10: 1, 11: 1, 15: 3})
def test_remove_album_published(self): band = Band("Death") album = Album("The Sound of Perseverance") album.publish() band.add_album(album) message = band.remove_album("The Sound of Perseverance") expected = "Album has been published. It cannot be removed." self.assertEqual(message, expected)
def test_insert_sticker(self): album = Album() stickers = [1, 2, 4, 5, 6] album.insert_sticker(stickers) stickers_album = album.get_sticker() self.assertEqual(stickers_album, [1, 2, 4, 5, 6])
def test_get_missing_sticker(self): album = Album() stickers = [sticker for sticker in range(1, 651)] album.insert_sticker(stickers) missing_stickers = album.get_missing_sticker() self.assertEqual(missing_stickers, [sticker for sticker in range(651, 683)])
def test_artist_with_multiple_albums(self): artist = Artist('artist name', 'country') artist.add_album(Album('first album title', 2020)) artist.add_album(Album('second album title', 2020)) expected_albums = [ Album('first album title', 2020), Album('second album title', 2020) ] assert list(artist.get_albums()) == expected_albums
def test_sort_key(self): first_album = Album('album title', 2020) newer_album = Album('album title', 2021) higher_album = Album('higher title', 2020) newer_but_lower_album = Album('aaa', 2021) assert Album.sort_key(first_album) < Album.sort_key(newer_album) assert Album.sort_key(first_album) < Album.sort_key(higher_album) assert Album.sort_key(first_album) < Album.sort_key( newer_but_lower_album)
def update_img(self, user_list=None, force=False, token_list=token_list): if user_list is None: user_list = self._get_all_user() album = Album() photo = Photo() for user in user_list: album.update(token_list, user, force) photo.update(token_list, user, force) photo.update_data(user) return True
def get_album_track_data(self, album_url): page = requests.get(album_url) self.nb_http_request += 1 data = json.loads(page.text[1:-2]) album = Album(data['albumName'], data['albumDesc'], self.treat_composer_publisher(data['albumComposerHtml']), data['albumLibraryName'], data['albumLibraryLCCode'], data['albumCode']) album.tracks = self.get_tracks_json(data['tracksJson'], album.cat_no) return album
def test_sort_albums_by_most_recent(self): artist = Artist('artist name', 'country') artist.add_album(Album('first album title', 2020)) artist.add_album(Album('second album title', 2021)) expected_albums = [ Album('second album title', 2021), Album('first album title', 2020) ] artist.sort_albums_by_date() assert list(artist.get_albums()) == expected_albums
def update_voice(self, user_list=None, force=False, token_list=token_list): if user_list is None: user_list = self._get_all_user() album = Album() voice = Voice() for user in user_list: album.update(token_list, user, force) voice.update(token_list, user, force) voice.update_data(user) return True
def __init__(self, album_sheets=700, idx=0): """Class constructor Args: album_sheets (int, optional): Album total sheets. Defaults to 700. idx (int, optional): Agent Identifier. Defaults to 0. """ self.__friends = [] self.__album = Album(size=album_sheets) self.__state = AgentState.LOOKING_FOR_SHEETS self.idx = idx self.__purchased_sheets = 0
def get_zhubo_albums(self, save_path=None): self.get_album_list() if save_path is None: save_path = '%d' % self.zhubo_id if not os.path.exists(save_path): os.mkdir(save_path) for album in my_zhubo.album_list[:3]: # print(album) album_url = 'https://www.ximalaya.com%s' % album['albumUrl'] print(album_url) album_id = album['id'] my_album = Album(album_url=album_url, album_id=album_id) my_album.get_album(save_path='%s/%d' % (save_path, album_id))
def load_from(data): if data["schema"] != DB_SCHEMA: return for d in data["genres"]: Genre.unpickle(d) for d in data["artists"]: Artist.unpickle(d) for d in data["albums"]: Album.unpickle(d) for d in data["tracks"]: Track.unpickle(d) for l in data["libraries"]: Library.unpickle(l)
def test_artists_with_multiple_songs(self): artist = Artist('artist name', 'country') first_album = Album('first album title', 2020) first_album.add(Song('first song title')) first_album.add(Song('second song title')) second_album = Album('second album title', 2020) second_album.add(Song('third song title')) artist.add_album(first_album) artist.add_album(second_album) expected_songs = [ Song('first song title'), Song('second song title'), Song('third song title') ] assert list(artist.get_songs()) == expected_songs
def get_albums_for_artist(path_to_artist): """Return array of album objects""" albums = [] for root, dirs, files in os.walk(path_to_artist): for name in dirs: new_album = Album() new_album.title = name new_album.path = os.path.join(root, name) for root, dirs, files in os.walk(new_album.path): new_album.num_tracks += len(files) albums.append(new_album) return albums
def test_save_success(description, data, save_name_album, save_name_web, compare_name_album, compare_name_web, pre_func): """Saves an album, compares the results against expected data, and reports success or failure depending on whether they matched. Arguments: description: A description of the test case, at most 55 characters. data: A dictionary containing album data. save_name_album: The name under which to save the album, relative to a temporary directory. save_name_web: The name under which the web JSON will be saved, relative to a temporary directory. compare_name_album: The name of the canonical album file, relative to the test case directory. compare_name_web: The name of the canonical web JSON file, relative to the test case directory. pre_func: A function to execute before the album is saved. The name of the temporary directory will be passed in as an argument. """ print(" Testing %s... " % (description), end="") nonlocal testsTotal, testsFailed testsTotal += 1 try: with tempfile.TemporaryDirectory() as temp_dir: if None is not pre_func: pre_func(temp_dir) Album.save(os.path.join(temp_dir, save_name_album), data) if not filecmp.cmp(os.path.join(temp_dir, save_name_album), os.path.join(TEST_CASE_DIR, compare_name_album), shallow=False): print("FAILED!") testsFailed += 1 shutil.copy(os.path.join(temp_dir, save_name_album), "/tmp/album.dyphal") if 1 <= verbosity: with open(os.path.join(temp_dir, save_name_album), "r") as f: for line in f.readlines(): print(line) elif not filecmp.cmp(os.path.join(temp_dir, save_name_web), os.path.join(TEST_CASE_DIR, compare_name_web), shallow=False): print("FAILED!") testsFailed += 1 if 1 <= verbosity: with open(os.path.join(temp_dir, save_name_web), "r") as f: for line in f.readlines(): print(line) else: print("passed.") except (Exception) as ex: print("FAILED!") testsFailed += 1 if 1 <= verbosity: print(ex)
def console_runner(): # noqa parser = argparse.ArgumentParser() parser.add_argument('-g', '--gui', help='launches program in gui mode', action='store_true') parser.add_argument('-i', '--info', help='prints info on song with some specifics', type=str) parser.add_argument('-r', '--recognize', help='recognizes [File B] in ' 'data base given in [Root A]', nargs=2) args = parser.parse_args() if args.gui: app = wx.App(False) form = AudioAlbum(None, 'Audio') form.SetSize((1020, 700)) form.Show() app.SetTopWindow(form) app.MainLoop() if args.info: try: reader = FileReader(directory='') song = reader.review_music_file(path_file=args.info) print('----Some info on this Song') print(song) print('----------') except FileNotFoundError: print('Did not find a path') if args.recognize: try: data_base = args.recognize[0] path_to_song = args.recognize[1] album = Album(data_base) album.setup_album() counts, name = album.predict_song(path_to_song) print("Using this data_base I found " + name + " Entry") print("With " + str(counts) + " Matches") except (FileNotFoundError, KeyError) as e: print("You have given wrong directory or nonexisting file")
def run(self): args = argManager() album_name = "songs" proxies, headers = setProxy() # Manage for jio saavn users if args.user: if args.email and args.password: email = args.email password = args.password else: email = input('Enter your email for jiosaavn: ').strip() password = input("Enter your password for jiosaavn: ").strip() account = Account(proxies=proxies, headers=headers, email=email, password=password) if args.p: account.start_download_playlist() elif args.a: account.start_download_album() elif args.clone: account.get_details_n_clone(args.clone, args.create, args.copy) elif args.create: account.create_user(email, password) # Manage for all default downloads # Note: Passing the url parameter to the contructor of Playlist, Album and Artist is must else: if args.url is None and args.file is None: dl_urls = [input("Enter the URL : ").strip()] elif args.url is None and args.file: dl_urls = self.read_urls(args.file) else: dl_urls = [args.url] for dl_url in dl_urls: dl_type = scan_url(url=dl_url) if dl_type == 'playlist': playlist = Playlist(proxies, headers, dl_url) playlist.start_download() elif dl_type == 'album': album = Album(proxies, headers, dl_url) album.start_download() elif dl_type == 'artist': artist = Artist(proxies, headers, args, dl_url) artist.start_download() print('DONE\n')
def buildAlbumList(self, response, playlistGenre): for item in response['items']: snippet = item['snippet'] if 'ALBUM REVIEW' in snippet['title'].upper(): self.allReveiwedAlbums.append( Album(videoSnippet=snippet, playlistGenre=playlistGenre)) return
def register_album(): global album_count print_header("Register new Album") try: # title, genre, artist, release_year, price, album_art, related_artist, record_label title = input("Please provide Title: ") genre = input("Please provide Genre: ") artist = input("Please provide Artist Name: ") release_year = int(input("Please provide Release year: ")) price = float(input("Please provide price: ")) album_art = input("Please provide Album_Art URL: ") related_artist = input("Please provide Related Artist: ") record_label = input("Please provide Record Label: ") album_count += 1 album = Album(album_count, title, genre, artist, release_year, price, album_art, related_artist, record_label) # push the album into the list catalog.append(album) print("***Album Created!") except ValueError: print("***Error : invalid number, try again!!") except: print("**Unexpected Error. try Again!")
def test_add_album_already_added(self): band = Band("Death") album = Album("The Sound of Perseverance") band.add_album(album) message = band.add_album(album) expected = "Band Death already has The Sound of Perseverance in their library." self.assertEqual(message, expected)
def test_remove_album_working(self): band = Band("Death") album = Album("The Sound of Perseverance") band.add_album(album) message = band.remove_album("The Sound of Perseverance") expected = "Album The Sound of Perseverance has been removed." self.assertEqual(message, expected)
def add_album (self, info): album = Album (parent = self.key) album.name = info["name"] album.status = 0 album.images = [] album.progress = 0 album.put () return album
def test_load(description, file_name, on_success, exceptions, on_failure): """Attempts to load an album and reports success or failure. Arguments: description: A description of the test case, at most 55 characters. file_name: The name of the album file to attempt to load, relative to the test case directory. on_success: A function to execute if loading succeeds. The album will be passed in as an argument. A return value of True indicates test case success; a return of False indicates failure. exceptions: A tuple of exceptions that indicate loading failure. on_failure: A function to execute if one of the exceptions in "exceptions" is caught. The exception will be passed in as an argument. A return value of True indicates test case success; a return of False indicates failure. """ print(" Testing %s... " % (description), end="") nonlocal testsTotal, testsFailed testsTotal += 1 try: album = Album.load(os.path.join(TEST_CASE_DIR, file_name)) except exceptions as ex: if on_failure(ex): print("passed.") if 2 <= verbosity: print(ex) else: print("FAILED!") testsFailed += 1 if 1 <= verbosity: print(ex) except (Exception) as ex: print("FAILED!") testsFailed += 1 if 1 <= verbosity: print(ex) else: if on_success(album): print("passed.") else: print("FAILED!") testsFailed += 1
def saveDisc(disc_info): category = disc_info["category"] disc_id = disc_info["disc_id"] title = disc_info["title"] (artistName, albumName) = disc_info["title"].split("/") artistName = artistName.strip() albumName = albumName.strip() #Search for existing artist artists = Artist.selectBy(name=artistName) if artists.count() == 0: #Create artist artist = Artist(name=artistName,category=category) else: #Use existing artist artist = artists[0] #Search for existing album albums = Album.selectBy(name=albumName) if albums.count() == 0: #Create album album = Album(disc_id=disc_id,name=albumName,artist=artist) #Create tracks (track_status, track_info) = CDDB.read(category, disc_id) tracks = {} for (k,v) in track_info.items(): if k.find("TTITLE") != -1: num = int(k[len("TTITLE"):]) + 1 tracks[num] = v tracks.items().sort() for (k,v) in tracks.items(): track = Track(num=k,name=v,album=album) print "***Saved in catalogue***" else: print "***Already catalogued***" printDisc(disc_info)
def map(self): """ map the retrieved information to the tagger specific objects """ album = Album(self.release.id, self.release.title, self.album_artists(self.release.artists)) album.sort_artist = self.sort_artist(self.release.artists) album.url = self.url album.catnumbers = [catno for name, catno in self.labels_and_numbers] album.labels = [name for name, catno in self.labels_and_numbers] album.images = self.images album.year = self.year album.genres = self.release.data["genres"] try: album.styles = self.release.data["styles"] except KeyError: album.styles = [""] if "country" in self.release.data: album.country = self.release.data["country"] else: logging.warn("no country set for relid %s" % self.release.id) album.country = "" if "notes" in self.release.data: album.notes = self.release.data["notes"] album.disctotal = self.disctotal album.is_compilation = self.is_compilation album.master_id = self.master_id album.discs = self.discs_and_tracks(album) return album
def albums (self): albums = Album.query (ancestor = self.key).fetch () return albums
def get_album(self): album = Album() album.set_controller(self._controller) if not album.get_existence(): return None return album
dataset = sys.argv[1] testdataset = dataset.replace("-training", "-test") if segment_method == 'slic': segment_method = seg_slic elif segment_method == 'canny': segment_method = seg_canny_watershed elif segment_method == 'otsu': segment_method = seg_otsu_watershed else: segment_method = None album = Album(directory=dataset, feature_method=feature_method, clustering_method=clustering_method, segment_method=segment_method, vocabulary_size=vocabulary_size, noise_ratio=noise_ratio, ) if similarity_method == 'lsi' and corpus_mode == 'segments': corpora = CorporaOfSentences(album) indexer = LSI(corpora.get_corpus(), album.vocabulary.get_size()) elif similarity_method == 'lsi' and corpus_mode == 'images': corpora = CorporaOfImages(album) indexer = LSI(corpora.get_corpus(), album.vocabulary.get_size()) elif similarity_method == 'tfidf' and corpus_mode == 'segments': corpora = CorporaOfSentences(album) indexer = TFIDF(corpora.get_corpus(), album.vocabulary.get_size()) elif similarity_method == 'tfidf' and corpus_mode == 'images': corpora = CorporaOfImages(album)
def log_name_change(old_name, new_name): print("\"%s\" -> \"%s\"" % (old_name, new_name)) def strip_leading_numbers(song): numberless_song = song.strip_leading_numbers() song.rename(numberless_song) log_name_change(song.name, numberless_song) def construct_parser(): cmd_help = { "dir": "a directory containing music files", "strip_numbers": "removes leading numbers from song files in 'dir'. " "turns \"06 Times Like These.mp3\" into \"Times Like These.mp3\"" } parser = argparse.ArgumentParser() parser.add_argument("dir", help=cmd_help["dir"]) parser.add_argument("-s", "--strip-numbers", action="store_const", const=True, help=cmd_help["strip_numbers"]) return parser parser = construct_parser() args = parser.parse_args() album = Album(args.dir) if args.strip_numbers: for song in album.get_songs(): if song.has_leading_numbers(): strip_leading_numbers(song)
def main(argv): print colored('FreeBand.py v0.6.0 (c) [email protected]', 'yellow') print colored('Simple tool reporting which Bandcamp free albums are missing on What.CD', 'yellow') bandcamptag = '' whatcdusername = '' try: opts, args = getopt.getopt(argv,"hb:u:",["bandcamptag=","whatcduser="******"-b", "--bandcamptag"): bandcamptag = arg elif opt in ("-u", "--whatcduser"): whatcdusername = arg if bandcamptag == '' or whatcdusername == '': usage() page = 1 proceed = True free_stuff = [] print colored('Looking for free albums on BandCamp using tag %s...' % bandcamptag, 'green') while proceed: r = requests.get('https://bandcamp.com/tag/%s?page=%dsort_asc=0&sort_field=date' % (bandcamptag, page)) # build the DOM Tree tree = lxml.html.fromstring(r.text) # Apply selectors to the DOM tree. art_results = art_css(tree) alb_results = alb_css(tree) if len(art_results) != len(alb_results): print colored('Albums don\'t match artists', 'red') exit(1) # get the text out of all the results art_data = [result.text for result in art_results] alb_data = [result.text for result in alb_results] page_data = OrderedDict(zip(alb_data, art_data)) really_free_page_data = [] # For every album go to its page and # 1) check if this album actually free # 2) if it's free, calculate its total duration, size, release year etc for album, artist in page_data.iteritems(): # Sanitize the CSS selector v1 = album.replace("/(:|\.|\[|\]|,)/g", "\\$1").replace("\"", "\\\"") # Select a link to details page get_details_url = CSSSelector('a[title="%s"]' % v1) try: details_url = get_details_url(tree)[0].get('href') details = requests.get(details_url) details_tree = lxml.html.fromstring(details.text) buyMe = name_your_price(details_tree)[0].text if 'name your price' in buyMe: print colored("Album %s -> %s is FREE!" % (album, details_url), 'green') # TODO sanitise album names for better What.CD search accuracy (remove EP, LP, Free Download) and stuff like that year_element = get_year(details_tree) year = 1970 try: if year_element is not None: year_s = year_element[0].attrib['content'] year = time.strptime(year_s, '%Y%m%d').tm_year else: print colored(' no release year found', 'yellow') except KeyError: print colored(' error getting release year', 'red') # Trying to retrieve the album size size = get_size(details_url).replace('size: ', '', 1) # Trying to retrieve the album cover art url cover = cover_art(details_tree)[0].get('href') # Creating an Album class instance album = Album(artist, album, year, details_url, size, cover) # Collecting tracks duration play_time = tracks_play_time(details_tree) for t in play_time: album.add_track(t.text) really_free_page_data.append(album) except IndexError: print colored('Problem getting url for album %s' % album, 'red') free_stuff.extend(really_free_page_data) nextel = has_next(tree) if nextel: print colored('Discovered %d albums so far' % (len(free_stuff)), 'green') page += 1 else: proceed = False else: print colored('Found %d free albums' %len(free_stuff), 'green') # Apply sorting by album size, largest albums first free_stuff = sorted(free_stuff, key=lambda x: x.size_bytes(), reverse=True) len_before = len(free_stuff) # Filter out small albums free_stuff = filter(lambda alb: alb.big(), free_stuff) len_after = len(free_stuff) if len_after == 0: exit(0) else: print colored('Filtered out %d small albums' % (len_before - len_after), 'green') # pygazelle is a Python API on top of Gazelle REST API (Gazelle is the engine What.CD runs on) whatcdpwd = getpass.getpass('What.CD password:'******'announcements') # just to log in print colored('Logged in to What.CD: %s' % (api.logged_in()), 'yellow') whatcd_missing = 0.0 for a in free_stuff: time.sleep(2) try: search_result = api.search_torrents(groupname=a.album, artistname=a.artist) # search by album and artist if not search_result['results']: whatcd_missing += 1 print colored('Album %s is missing' % (a.to_str()), 'cyan') a.dump_json() except KeyError: print colored('Error searching for album %s. Please look up manually' % (a.to_str()), 'red') print str(whatcd_missing / len(free_stuff) * 100) + '% discovered albums is missing'