def __init__(self, **kwargs):
        """ Initial class. Here i used **kwargs because I want to handle named arguments """
        super(SongsToLearnApp, self).__init__(**kwargs)

        self.song_collection = SongCollection()

        self.show_song = []
Exemple #2
0
    def build(self):
        SongCollection()  # initialise an empty list on program start
        Window.size = (900, 600)
        self.title = 'Songs to Learn 2.0'
        self.root = Builder.load_file('app.kv')
        songs_list = self.load_songs()
        self.create_entry_grids(songs_list)
        self.root.ids.message_box.text = 'Welcome to Songs to Learn 2.0'

        return self.root
Exemple #3
0
	def __init__(self, directories, *args, **kwargs):
		print(args, kwargs)
		tk.Tk.__init__(self, *args, **kwargs)
		
		# Stream for audio playback
		self.pa = pyaudio.PyAudio()
		self.stream = self.pa.open(format = pyaudio.paFloat32,
							channels=1,
							rate=44100,
							output=True)
		self.protocol("WM_DELETE_WINDOW", self.close_window)
		
		sc = SongCollection()
		print(directories)
		for dir_ in directories:
			sc.load_directory(dir_)
		self.songs = sc.get_marked()
		self.song = None
		
		self.varSongSelector = tk.Variable(self)
		self.songSelector = tk.OptionMenu(self, self.varSongSelector, '', *tuple([s.title for s in self.songs]), command = self.select_song)
		self.songSelector.grid(row=0,columnspan=3)
		
		tk.Label(self, text="Beats: ").grid(row=1)
		self.b_beats_play = tk.Button(self, text="[ > ]", command=self.play_beats)
		self.b_beats_play.grid(row=1,column=1)
		self.b_beats_fix = tk.Button(self, text="[+1]", command=self.shift_beats)
		self.b_beats_fix.grid(row=1,column=2)
		
		tk.Label(self, text="Downbeats: ").grid(row=2)
		self.b_downbeats_play = tk.Button(self, text="[ > ]", command=self.play_downbeats)
		self.b_downbeats_play.grid(row=2,column=1)
		self.b_downbeats_fix = tk.Button(self, text="[+1]", command=self.shift_downbeats)
		self.b_downbeats_fix.grid(row=2,column=2)
		
		tk.Label(self, text="Segments: ").grid(row=3)
		self.b_segments_shift_min8 = tk.Button(self, text="[-8]", command=lambda : self.shift_segments(-8))
		self.b_segments_shift_min8.grid(row=3,column=1)
		self.b_segments_shift_min1 = tk.Button(self, text="[-1]", command=lambda : self.shift_segments(-1))
		self.b_segments_shift_min1.grid(row=3,column=2)
		self.b_segments_shift_plus1 = tk.Button(self, text="[+1]", command=lambda : self.shift_segments(1))
		self.b_segments_shift_plus1.grid(row=3,column=3)
		self.b_segments_shift_plus8 = tk.Button(self, text="[+8]", command=lambda : self.shift_segments(8))
		self.b_segments_shift_plus8.grid(row=3,column=4)
		
		self.segment_buttons = []
		
		# TODO How to insert segments?
		
		self.b_save = tk.Button(self, text="[ SAVE CHANGES ]", command=self.save)
		self.b_save.grid(row=0,column=4)
Exemple #4
0
def run_tests():
    """Test SongCollection class."""

    # Test empty SongCollection (defaults)
    print("Test empty SongCollection:")
    song_collection = SongCollection()
    print(song_collection)
    assert not song_collection.song_list  # an empty list is considered False

    # Test loading songs
    print("Test loading songs:")
    song_collection.load_songs('songs.csv')
    print(song_collection)
    assert song_collection.song_list  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Song with values
    print("Test adding new song:")
    song_collection.add_song(Song("My Happiness", "Powderfinger", 1996, True))
    print(song_collection)

    # Test sorting songs
    print("Test sorting - year:")
    sorted_list = song_collection.sort_song("year", descending=True)
    print(song_collection.format_data(sorted_list))
    # Test sorting artists
    print("Test sorting - artist:")
    sorted_list_2 = song_collection.sort_song("artist", descending=True)
    print(song_collection.format_data(sorted_list_2))
    # test sorting titles
    print("Test sorting - title:")
    sorted_list_3 = song_collection.sort_song("title", descending=False)
    print(song_collection.format_data(sorted_list_3))

    #  Test saving songs (check CSV file manually to see results)
    print("Test saving songs:")
    song_collection.save_changes("songs.csv")
    print("Open songs.csv to check whether new song appears or not")

    # Add more tests, as appropriate, for each method
    # Test count learned songs
    print("Test count learned songs:")
    print(song_collection.count_learned())
    # Test count unlearned songs
    print("Test count unlearned songs:")
    print(song_collection.count_unlearned())
def run_tests():
    """Test SongCollection class."""

    # Test empty SongCollection (defaults)
    print("Test empty SongCollection:")
    song_collection = SongCollection()
    print(song_collection)
    assert not song_collection.songs  # an empty list is considered False

    # Test loading songs
    print("Test loading songs:")
    song_collection.load_songs('songs.csv')
    print(song_collection)
    assert song_collection.songs  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Song with values
    print("Test adding new song:")
    song_collection.add_song(Song("My Happiness", "Powderfinger", 1996, True))
    print(song_collection)

    # Test sorting songs
    print("Test sorting - year:")
    song_collection.sort("year")
    print(song_collection)
hop_size = 44100 * HOP_S

pool = Pool()

for idx in range(start_sample, stop_sample - length_samples, hop_size):
	print 'Analysed until {:.2f}'.format((idx/44100.0)/60)
	start_idx = idx
	end_idx = idx + length_samples
	fragment = audio[start_idx : end_idx]
	theme_descr = calculateThemeDescriptor(fragment)
	print theme_descr
	pool.add('theme_descriptors', theme_descr.tolist()[0])
	
# --------------------- Load all audio files ---------------------------
from songcollection import SongCollection
sc = SongCollection()
sc.load_directory('../music')
sc.load_directory('../moremusic')
sc.load_directory('../evenmoremusic')
sc.load_directory('../music/test')

songs = []

for song in sc.get_annotated():
	song.open()
	pool.add('song.themes', song.song_theme_descriptor.tolist()[0])
	songs.append(song.title)
	song.close()

# --------------------- Make nice plots ---------------------------
Y = pool['song.themes']	# All songs in "/music" and "/moremusic" libraries
Exemple #7
0
class SongsToLearnApp(App):

    current_selection = StringProperty()
    spinner_menu = ListProperty()
    songs = SongCollection()
    song = Song()
    song_id_list = []

    def build(self):
        SongCollection()  # initialise an empty list on program start
        Window.size = (900, 600)
        self.title = 'Songs to Learn 2.0'
        self.root = Builder.load_file('app.kv')
        songs_list = self.load_songs()
        self.create_entry_grids(songs_list)
        self.root.ids.message_box.text = 'Welcome to Songs to Learn 2.0'

        return self.root

    def create_entry_grids(self, input_list):
        self.clear_widget()
        for song in input_list:
            if song.is_learned == True:
                learn_state = '(Learned)'
                btn_color = (0, 1, 0, 1)
            else:
                learn_state = ''
                btn_color = (1, 0, 0, 1)
            btn_id = '{}_{}'.format(song.title, song.year)
            temp_button = Button(id=btn_id,
                                 background_color=btn_color,
                                 text='"{}" by {} ({}) {}'.format(
                                     song.title, song.artist, song.year,
                                     learn_state))
            self.root.ids.song_count.add_widget(temp_button)
            self.song_id_list.append(temp_button)
            temp_button.bind(on_release=self.handle_mark)
        self.song_status()

    def handle_clear(self):
        # Clears the text input fields to empty
        self.root.ids.input_title.text = ''
        self.root.ids.input_artist.text = ''
        self.root.ids.input_year.text = ''

    def handle_add(self):
        """Validates input, and passes the inputs to the function to create a new song object"""
        song_title = self.root.ids.input_title.text
        song_artist = self.root.ids.input_artist.text
        song_year = self.root.ids.input_year.text
        err_check = self.error_check()

        if err_check == 'Blank':
            self.root.ids.message_box.color = (1, 0, 0, 1)
            self.root.ids.message_box.text = 'All fields must be completed'
            self.root.ids.btn_add.background_color = (1, 0, 0, 1)
        elif err_check == 'Invalid':
            self.root.ids.message_box.color = (1, 0, 0, 1)
            self.root.ids.message_box.text = 'Year Invalid. Please enter Valid year (1800 to 2018)'
            self.root.ids.btn_add.background_color = (1, 0, 0, 1)
        elif err_check == 'Type':
            self.root.ids.message_box.color = (1, 0, 0, 1)
            self.root.ids.message_box.text = 'Error in Field "Year". Please Check Input'
            self.root.ids.btn_add.background_color = (1, 0, 0, 1)
        elif err_check == 'Duplicate':
            self.root.ids.message_box.color = (1, 0, 0, 1)
            self.root.ids.message_box.text = '{} by {} already exists'.format(
                song_title, song_artist)
            self.root.ids.btn_add.background_color = (1, 0, 0, 1)
        else:
            send_input = Song(song_title, song_artist, song_year, False)
            # Registers the song attribute given by the user, with additional attribute 'learned' automatically set to False
            added_list = self.songs.add_songs(send_input)
            self.make_entries(added_list)
            self.root.ids.message_box.color = (1, 1, 1, 1)
            self.root.ids.message_box.text = 'You added {} by {}'.format(
                song_title, song_artist)
            self.root.ids.btn_add.background_color = (0, 0, 1, 1)

    def handle_sort_change(self, spinner_choice):
        self.clear_widget()
        sort_attr = spinner_choice
        if sort_attr == 'Title':
            sorted_list = self.songs.sort_songs(0)
        elif sort_attr == 'Artist':
            sorted_list = self.songs.sort_songs(1)
        elif sort_attr == 'Year':
            sorted_list = self.songs.sort_songs(2)
        self.make_entries(sorted_list)
        self.root.ids.message_box.text = 'Sorted by {}'.format(sort_attr)

    def load_songs(self):
        sort_list = self.songs.load_songs('songs.csv')
        return sort_list

    def song_status(self):
        learn = self.songs.calculate_song_learned()
        not_learn = self.songs.calculate_song_not_learned()
        total_songs = learn + not_learn
        status_text = 'To learn:{}.is_learned:{}'.format(learn, not_learn)
        self.root.ids.status_bar.text = status_text

    def make_entries(self, input_list):
        self.clear_widget()
        for song in input_list:
            if song.is_learned == True:
                learn_state = '(Learned)'
                btn_color = (0, 1, 0, 1)
            else:
                learn_state = ''
                btn_color = (1, 0, 0, 1)
            btn_id = '{}_{}'.format(song.title, song.year)
            temp_button = Button(id=btn_id,
                                 background_color=btn_color,
                                 text='"{}" by {} ({}) {}'.format(
                                     song.title, song.artist, song.year,
                                     learn_state))
            self.song_id_list.append(temp_button)
            self.root.ids.song_count.add_widget(temp_button)
            temp_button.bind(on_release=self.handle_mark)
        self.song_status()

    def handle_mark(self, instance):
        btn = instance.id
        for song in self.songs.songs:
            validate = '{}_{}'.format(song.title, song.year)
            if btn == validate:
                if song.is_learned == True:
                    self.root.ids.message_box.text = 'You have already learned {} ({})'.format(
                        song.title, song.year)
                else:
                    self.songs.mark_as_learned(btn)
                    self.root.ids.message_box.text = (
                        'You learned {} ({})'.format(song.title, song.year))
        give_list = self.songs.give_songs()
        self.make_entries(give_list)

    def exit_app(self):
        self.songs.save_songs()

    def clear_widget(self):
        for song_id in self.song_id_list:
            self.root.ids.song_count.remove_widget(song_id)

    def error_check(self):
        title_check = self.root.ids.input_title.text
        artist_check = self.root.ids.input_artist.text
        year_check = self.root.ids.input_year.text
        error_state = ''
        if title_check == '' or artist_check == '' or year_check == '':
            error_state = 'Blank'
        else:
            try:
                int(year_check)
            except ValueError:
                error_state = 'Type'
            else:
                if int(year_check) > 2020 or int(year_check) < 1800:
                    error_state = 'Invalid'
        for song in self.songs.songs:
            if title_check == song.title and artist_check == song.artist and year_check == song.year:
                error_state = 'Duplicate'
        return error_state

    def handle_stop(self):
        self.songs.save_songs()
        sys.exit(0)
Exemple #8
0
def index_dj(request):
    template = get_template("Index.html")
    LOG_LEVEL = logging.DEBUG
    LOGFORMAT = "%(log_color)s%(message)s%(reset)s"
    logging.root.setLevel(LOG_LEVEL)
    formatter = ColoredFormatter(LOGFORMAT)
    stream = logging.StreamHandler()
    stream.setLevel(LOG_LEVEL)
    stream.setFormatter(formatter)
    logger = logging.getLogger('colorlogger')
    logger.setLevel(LOG_LEVEL)
    logger.addHandler(stream)

    sc = SongCollection()
    tl = TrackLister(sc)
    dj = DjController(tl)

    essentia.log.infoActive = False
    essentia.log.warningActive = False

    if request.method == "POST":
        cmd = request.POST.get("cmd", None)
        cmd = str(cmd)
        # cmd_split = str(cmd).split
        # cmd = cmd_split[0]
        while (True):
            # try:
            #     cmd_split = str.split(input('> : '), ' ')
            # except KeyboardInterrupt:
            #     logger.info('Goodbye!')
            #     break
            # cmd = cmd_split[0]
            # if cmd == 'loaddir':
            #     if len(cmd_split) == 1:
            #         return HttpResponse('Please provide a directory name to load!')
            #         continue
            #     elif not os.path.isdir(cmd_split[1]):
            #         return HttpResponse(cmd_split[1] + ' is not a valid directory!')
            #         continue
            message = "abc"
            sc.load_directory("/home/ddman/音樂/upload")
            message = str(len(sc.songs)) + ' songs loaded [annotated: ' + str(
                len(sc.get_annotated())) + ']'
            if cmd == 'play':
                if len(sc.get_annotated()) == 0:
                    message = 'Use the loaddir command to load some songs before playing!'
                    continue

                # if len(cmd_split) > 1 and cmd_split[1] == 'save':
                #     message = 'Saving this new mix to disk!'
                #     save_mix = True
                # else:
                #     save_mix = False

                message = 'Starting playback!'
                try:
                    dj.play(save_mix=False)
                except Exception as e:
                    logger.error(e)
                return render(request, "Index.html", locals())
            elif cmd == 'pause':
                message = 'Pausing playback!'
                try:
                    dj.pause()
                except Exception as e:
                    logger.error(e)
                return render(request, "Index.html", locals())
            elif cmd == 'skip' or cmd == 's':
                message = 'Skipping to next segment...'
                try:
                    dj.skipToNextSegment()
                except Exception as e:
                    logger.error(e)
                return render(request, "Index.html", locals())
            elif cmd == 'stop':
                message = 'Stopping playback!'
                dj.stop()
                return render(request, "Index.html", locals())
            elif cmd == 'save':
                message = 'Saving the next new mix!'
                return render(request, "Index.html", locals())
            elif cmd == 'showannotated':
                message = 'Number of annotated songs ' + str(
                    len(sc.get_annotated()))
                message = 'Number of unannotated songs ' + str(
                    len(sc.get_unannotated()))
                return render(request, "Index.html", locals())
            elif cmd == 'annotate':
                message = 'Started annotating!'
                sc.annotate()
                message = 'Done annotating!'
                return render(request, "Index.html", locals())
            elif cmd == 'debug':
                LOG_LEVEL = logging.DEBUG
                logging.root.setLevel(LOG_LEVEL)
                stream.setLevel(LOG_LEVEL)
                logger.setLevel(LOG_LEVEL)
                message = 'Enabled debug info. Use this command before playing, or it will have no effect.'
                return render(request, "Index.html", locals())
            elif cmd == 'mark':
                dj.markCurrentMaster()
                return render(request, "Index.html", locals())
            elif cmd == "quit":
                break
                return render(request, "Index.html", locals())
            else:
                message = 'The command ' + str(cmd) + ' does not exist!'
                return render(request, "Index.html", locals())
    return render(request, "Index.html", locals())
Exemple #9
0
"""
Name: Nguyen Quoc Minh Quan
Date: 22/5/2020
Brief Project Description:  My CP1404 final assignment working with
    classes and Kivy, i have the chance to re-create my assignment 1 with classes and create GUI with Kivy
GitHub URL: https://github.com/JCUS-CP1404/assignment-02-songs-app-minhquan0902
"""
# TODO: Copy your first assignment to this file, commit, then update to use Song class

from song import Song
import csv
from songcollection import SongCollection

my_song = SongCollection()
my_song.load_songs('songs.csv')


def main():
    """Main function of the program"""
    print("Songs to Learn 1.0 - by Quan Nguyen")
    print("{} songs loaded".format(len(my_song.song_list)))
    print("\n")

    flag = False
    while not flag:
        print("Menu: ")
        print("L - List songs")
        print("A - Add new song")
        print("S - Search a song")
        print("C - Complete a song")
        print("Q - Quit")