예제 #1
0
파일: blog.py 프로젝트: woodenbrick/wedding
 def post(self):
   artist = cgi.escape(self.request.get('artist'))
   title = cgi.escape(self.request.get('title'))
   requested_by = cgi.escape(self.request.get('requested_by'))
   ip = self.request.remote_addr
   old_user = memcache.get(ip)
   if old_user is None:
     new_user = model.SongRequester(ip=ip, username=requested_by)
     new_user.put()
     memcache.set(ip, new_user)
   elif old_user != requested_by:
     previous_user = model.SongRequester.all().filter('ip = ', ip).get()
     previous_user.username = requested_by
     previous_user.put()
     memcache.set(ip, previous_user)
    
   if title == '' and artist == '':
     self.redirect('/musicrequest?error=1')
   else:
     #lets check last.fm for this song
     search_lastfm = True
     if title == '':
       title = 'Any song'
       search_lastfm = False
     elif artist == '':
       artist = 'Unknown artist'
     if requested_by == '':
       requested_by = 'Anonymous'
       search_lastfm = False
     #if search_lastfm:
     #  song_url = self.get_song_url(title, artist)
     song = Song(artist=artist, title=title, requested_by = requested_by)#, url=song_url)
     song.put()
     memcache.delete("songs")
     self.redirect('/musicrequest')
예제 #2
0
def not_error(item):
  try:
    Song.byPath(str(item.attrib['ref']))
    return 1
  except:
    turbogears.flash("Missing one or more songs, last missing song: " + item.attrib['ref'].replace('songs/','') + ' . . - song(s) not loaded')
    return 0
예제 #3
0
def insert_song(type: str, meta: dict):
    if (type=='song'):
        temp = Song(meta)
    elif (type=='podcast'):
        temp = Podcast(meta)
    elif (type=='audiobook'):
        temp = AudioBook(meta)

    id = db.insert_file("song", temp.convert_dict())
    return {"id": id}
예제 #4
0
    def play_all(self):
        songs = []

        for song in self.songs:
            songs.append(song)

        for band in self.bands:
            for song in band.songs:
                songs.append(song)

        from model import Song
        Song.play_song_list(songs)
예제 #5
0
def playlist_add_confirmed():
    is_uploaded = yt_re.search(request.form['uri']) is None

    # we'll clean up duplicates manually
    song = Song(uri=request.form['uri'], title=request.form['title'], artist=request.form['artist'])
    song.submitter = request.form['submitter']
    song.is_uploaded = is_uploaded
    song.created = datetime.datetime.now()

    db.session.add(song)
    db.session.commit()
    return render_template('playlist/add_confirmed.html', song=song)
예제 #6
0
  def songbook_view(self, path=c.ALL_SONGS_PATH):
    # we check to see if the user is trying to hack us with a bad path
    pathcheck(path)

    if path == c.ALL_SONGS_PATH:
      #create songbook all songs from scratch and save in location.  Then pass it to be viewed

      title = "All Songs"
      songbook_content = '''<songbook format-version="0.1">\n<title>''' + title.strip() + "</title>"

      #get all paths and sort them
      songs = [songs for songs in Song.select(orderBy=Song.q.title)]
      songs.sort(key=lambda x: x.title.lower() or 'No Title')
      
      for song in songs:
        songbook_content = songbook_content + '\n<songref ref="' + song.path +'" status="n"/>'
      
      songbook_content = songbook_content + '\n</songbook>'
      
      write = open(path, "w")
      write.write(songbook_content)
      write.close()
      
      try:
        all_songs_songbook = Songbook.byPath(str(path))
      except SQLObjectNotFound:
        all_songs_songbook = Songbook(title=title, path=str(path))

    try:
      if path != c.ALL_SONGS_PATH:
        #look up title from database
        songbook = Songbook.byPath(str(path))
        title = songbook.title
    except SQLObjectNotFound:
      raise cherrypy.HTTPRedirect(URL("/notfound?path=%s" % path))
    

    sb_xml = parse(path)

    #same as in songbook_edit below 
    item_els = sb_xml.getroot().getchildren()
    songbook_items=[]
    for item in item_els:
      if item.tag == 'songref':
        songbook_items.append((Song.byPath(str(item.attrib['ref'])).title, item.attrib['ref'], item.get('status','n')))
      if item.tag == 'section':
        songbook_items.append((item.attrib['title'],'','section'))

    return dict(title=title, path=path, songbook_items=songbook_items, songbooks=db.songbooks())
예제 #7
0
파일: blog.py 프로젝트: woodenbrick/wedding
 def get(self):
   #the only purpose of this is to clear all music
   #should be disabled except when debugging
   songs = Song.all()
   for song in songs:
     song.delete()
   self.redirect('/musicrequest')
예제 #8
0
def populateSongs(session, album_db_obj, album):
    """Populates the song database table with data from the Spotify API.

    Keyword arguments:
    session -- the database session.
    album_db_obj -- the album database object.
    album -- the album object containing Spotify data.
    """
    song_objects = []

    # Populate album information based on the album search.
    for track in album['tracks']['items']:
        track_info = sp.track(track['uri'])
        track_features = sp.audio_features(track['id'])[0]

        song = Song(uri=track_info['uri'],
                    track_number=track_info['track_number'],
                    name=track_info['name'],
                    popularity=track_info['popularity'],
                    duration=track_info['duration_ms'],
                    explicit=track_info['explicit'],
                    danceability=track_features['danceability'],
                    tempo=track_features['tempo'],
                    energy=track_features['energy'],
                    instrumentalness=track_features['instrumentalness'],
                    time_signature=track_features['time_signature'],
                    valence=track_features['valence'],
                    album_id=album_db_obj.id,
                    album=album_db_obj)
        song_objects.append(song)

    session.add_all(song_objects)
    session.commit()
예제 #9
0
  def songbook_edit(self, path):

    # we check to see if the user is trying to hack us with a bad path
    pathcheck(path)

    songbook = Songbook.byPath(str(path))
    path = songbook.path
    songbook_content = open(songbook.path, "rU").read()
    title = c.grab_title(songbook_content)
    sb_xml = parse(songbook.path)

    #same as in songbook_view above
    item_els = sb_xml.getroot().getchildren()
    songbook_items=[]
    for item in item_els:
      if item.tag == 'songref':
        songbook_items.append((Song.byPath(str(item.attrib['ref'])).title, item.attrib['ref'], item.get('status','n')))
      if item.tag == 'section':
        songbook_items.append((item.attrib['title'],'','section'))

    password = ''
    if sb_xml.find('password') != None:
      password = sb_xml.find('password').text 

    return dict(title=title, path=path, new=False, songs_list=db.songs(), songbooks=db.songbooks(), songbook_items=songbook_items, password=password, def_title="New Songbook")
예제 #10
0
파일: seed.py 프로젝트: rbarner14/protag
def load_songs(song_filename):
    """Load songs from songs.txt into database."""

    print("Songs")

    for i, row in enumerate(open(song_filename)):
        row = row.rstrip()
        song_id, song_title, song_release_date_str, song_release_year_str, song_release_month_str, song_release_day_str, apple_music_player_url = row.split(
            "|")

        if not song_release_year_str or song_release_year_str in (
                'None', 'None"', '') or len(song_release_year_str) != 4:
            song_release_year_str = None

        if not song_release_month_str or song_release_month_str in ('None',
                                                                    'None"',
                                                                    ''):
            song_release_month_str = None
        else:
            if len(song_release_month_str) == 1:
                song_release_month_str = "0" + song_release_month_str

        if not song_release_day_str or song_release_day_str in ('None',
                                                                'None"', ''):
            song_release_day_str = None
        else:
            if len(song_release_day_str) == 1:
                song_release_day_str = "0" + song_release_day_str

        if song_release_year_str and song_release_month_str and song_release_day_str:
            song_release_date_str = " ".join([
                song_release_year_str, song_release_month_str,
                song_release_day_str
            ])
            song_release_date = datetime.datetime.strptime(
                song_release_date_str, "%Y %m %d")

        song = Song(song_id=song_id,
                    song_title=song_title,
                    song_release_year=song_release_year_str,
                    song_release_date=song_release_date,
                    apple_music_player_url=apple_music_player_url)

        db.session.add(song)

        if i % 1000 == 0:
            print(i)

            # An optimization: if commit after every add, the database
            # will do a lot of work committing each record. However,
            # waiting until the end may be quite the load on computers with
            # smaller amounts of memory; it might thrash around. Committing
            # every 1,000th add is a good balance.
            db.session.commit()

    db.session.commit()
예제 #11
0
def add_songs_to_db(artist, db_setlist_list):
    """Add songs from list of strings to db with primary_artist id."""
    if db_setlist_list:
        for song in db_setlist_list:
            try:
                artist.songs.append(Song(song_name=song))
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
                continue
예제 #12
0
  def song_view_content(self, path):
    # we check to see if the user is trying to hack us with a bad path
    pathcheck(path)
    
    try:
      song = Song.byPath(str(path))
    except SQLObjectNotFound:
      raise cherrypy.HTTPRedirect(URL("/notfound?path=%s" % path))

    songXML = open(song.path).read()
    return songXML
예제 #13
0
  def export_form(self, path="songs/jesujesu.son", selected="simple.cfg"):
    # we check to see if the user is trying to hack us with a bad path
    pathcheck(path)
    
    try:
      if 'songbook'in path:
        exportS = Songbook.byPath(str(path))
      elif 'song' in path:
        exportS = Song.byPath(str(path))
      else:
        raise cherrypy.HTTPRedirect(URL("/notfound?path=%s" % path))


    except SQLObjectNotFound:
      raise cherrypy.HTTPRedirect(URL("/notfound?path=%s" % path))
    title = exportS.title

    cf_dir = "config_files/"
    # grab all the paths for the config files
    config_paths = glob.glob(cf_dir + "*")
    config_files = dict()

    # for loop reads stylesheets and packages them in a list of dictionaries
    for c_path in config_paths:
      tmp_dict = dict()
      # read path and dump contents in tmp

      for line in open(c_path, "rU"):
        line = line.replace('--','').replace('-','_').split()
        if len(line) == 2:
          tmp_dict[line[0]]=line[1].replace('_','-')

      #config_files[c_path.replace(cf_dir,'')]=tmp_dict
      config_files[os.path.basename(c_path)]=tmp_dict

    songbook_configs = dict()
    songbook_xml = parse(path)
    for format_config in songbook_xml.findall('//formatter'):
      key = format_config.get('name')
      config_val = dict()

      # parse the config_val dict from the xml element content
      raw_args = format_config.text.replace('--', '').replace('-', '_').split()
      for i in range(0, len(raw_args), 2):
        if i+1 < len(raw_args): # can't go out of bounds
          config_val[raw_args[i]] = raw_args[i+1].replace('_', '-')

      # lets store this key and config
      songbook_configs[key] = config_val
    # done parsing songbook_configs

    #DEBUG:  print config_files
    return dict(title=title, path=path, config_files=config_files, songbook_configs=songbook_configs, songbooks=db.songbooks(), selected=selected)
예제 #14
0
  def song_edit(self, path):

    # we check to see if the user is trying to hack us with a bad path
    pathcheck(path)

    song = Song.byPath(str(path))
    path = song.path
    song_xml = ET.parse(path)

    # get information from song_xml
    title = 'Untitled' 
    author = ''
    scripture_ref =''
    intro = ''
    key = ''
    copyrights = ''
    cclis = None 
    categories = '' 

    if song_xml.find('stitle') != None:
      title = song_xml.find('stitle').text 
    if song_xml.find('author') != None:
      author = song_xml.find('author').text
    if song_xml.find('scripture_ref') != None:
      scripture_ref = song_xml.find('scripture_ref').text
    if song_xml.find('introduction') != None:
      intro = song_xml.find('introduction').text
    if song_xml.find('key') != None:
      key = song_xml.find('key').text
    if song_xml.find('copyright') != None:
      copyrights = song_xml.find('copyright').text
    if song_xml.find('cclis') != None:
      cclis = song_xml.find('cclis').text
    if song_xml.find('categories') != None and song_xml.find('categories').text != None:
      categories = [cat.strip() for cat in song_xml.find('categories').text.split(',')]

    chunks = song_xml.findall('chunk')

    for chunk in chunks:
      chunk_text=[]
      lines = chunk.findall('line')
      for line in lines:
        if song2mono.is_chord_line(ET.tostring(line))==1:
          chunk_text.append(song2mono.expand_chord(ET.tostring(line)))
        else:
          chunk_text.append(line.text or "")

      chunk.text = '\n'.join(chunk_text)

    return dict(title=title, author=author, scripture_ref=scripture_ref, introduction=intro, key=key, copyrights=copyrights, chunks=chunks, path=path, new=False, songbooks=db.songbooks(), cclis=cclis, categories=categories, def_title="New Song")
예제 #15
0
파일: blog.py 프로젝트: woodenbrick/wedding
 def get(self):
   # IMPLEMENT MEMCACHE HERE
   songlist = memcache.get("songs")
   ip = self.request.remote_addr
   previous_user = memcache.get(ip)
   if previous_user is None:
     previous_user = model.SongRequester.all().filter('ip=', ip).get()
   if songlist is None:
     songs = Song.all().order('-date')
     songlist = songs.fetch(20)
     memcache.add("songs", songlist)
   template_values = {'songs' : songlist, 'heading' : 'Song Request', 'previous_user' : previous_user}
   if self.request.get('error') == '1':
     template_values['error'] = 'At the very least, I need the title of the song, or an artist.'
   self.generate('music.html', template_values)
예제 #16
0
def load_songs(song_list):
    """Load songs from Guitar Party API into database."""
    print "Songs"

    for item in song_list:

        if Song.query.filter_by(song_id=item['id']).first() == None:

            song = Song(song_id=item['id'],
                        title=item['title'],
                        body=item['body'],
                        body_chords_html=item['body_chords_html'],
                        permalink=item['permalink'])

            db.session.add(song)

    db.session.commit()
예제 #17
0
def view_playlist_details(playlist_id):
	"""Returns the playlist details."""
	# get playlist name
	playlist_name = playlist.get_playlist_name(playlist_id)
	#get songs in playlist
	song_ids = playlist_song.get_playlist_songs(playlist_id)
	songs_list = []
	for item in song_ids:
		song = crud.get_song(item)
		songs_list.append(song)

	#store in the dict
	song_dict = []
	for song in songs_list:
		x = Song.as_dict(song)
		song_dict.append(x)

	return jsonify({'songs': song_dict,
					'playlist_name': playlist_name})
예제 #18
0
def add_song(path):
    getcontext().prec = 3
    tag = tiny.get(path)
    artist = session.query(Artist).filter_by(name=tag.artist).first()
    if artist == None:
        artist = Artist(name=tag.artist)
        session.add(artist)
    album = session.query(Album).filter_by(name=tag.album).first()
    if album == None:
        album = Album(name=tag.album, num_songs=0, artist=artist)
        session.add(album)

    album.num_songs += 1
    duration = Decimal(tag.duration) / Decimal(60)
    song = Song(name=tag.title,
                release_date=tag.year,
                genre=tag.genre,
                length=duration,
                album=album,
                path=path)
    session.add(song)
    song.artists.append(artist)
    session.commit()
예제 #19
0
def create_song(song_title, song_uri, tempo, valence, danceability, energy,
                loudness, acousticness, speechiness, song_artist):
    """Creates a Song and adds it to the database."""

    song = Song(song_title=song_title,
                song_uri=song_uri,
                tempo=tempo,
                valence=valence,
                danceability=danceability,
                energy=energy,
                loudness=loudness,
                acousticness=acousticness,
                speechiness=speechiness,
                song_artist=song_artist)

    # makes sure the song isn't already in the db
    if get_song_id(song_uri) == None:

        db.session.add(song)
        db.session.commit()

        return song
    else:
        return song
예제 #20
0
def generate_playlist():

    original_spotify_info = spotify.base_playlist(
        spotify.generate_token(), session["genre"].lower(),
        session["minimum_danceability"], session["maximum_danceability"])

    clean_array = []

    index = 0
    for track in original_spotify_info["tracks"]:

        if track["preview_url"] is not None:
            clean_array.append(track)
        index += 1

    spotify_info = {"tracks": clean_array}

    if len(spotify_info.get("tracks")) <= 0:
        flash(
            "Change the search parameters of danceability. No playlist was generated."
        )
        return redirect("/create")
    else:

        playlist = Playlist(
            user_id=session["user_id"],
            playlist_image=spotify_info["tracks"][0]["album"]["images"][1]
            ["url"],
            playlist_genre=session["genre"].lower(),
            playlist_mindanceability=session["minimum_danceability"],
            playlist_maxdanceability=session["maximum_danceability"])
        db.session.add(playlist)
        db.session.commit()

        #store songs into Song database and song-playlist data into SongPlaylist database
        for track in spotify_info["tracks"]:
            #if Song database is empty, add generated song as new song in the database
            if len(db.session.query(Song).all()) <= 0:
                song = Song(
                    track_id=track["id"],
                    track_title=track["name"],
                    artist=[artist["name"] for artist in track["artists"]])
                db.session.add(song)
                db.session.commit()
        #if a song(s) exists in the database, check to see if there is a match with generated song
        #and existing song(s) match. If there is no match, add generated song as new song in the database.
        #Both if statements check to make sure new songs that are added into database do not already
        #exist in the database.
            if len(
                    db.session.query(Song).filter(
                        Song.track_id == track["id"]).all()) <= 0:
                song = Song(
                    track_id=track["id"],
                    track_title=track["name"],
                    artist=[artist["name"] for artist in track["artists"]])
                db.session.add(song)
                db.session.commit()
            songplaylist = SongPlaylist(track_id=track["id"],
                                        playlist_id=playlist.playlist_id)
            db.session.add(songplaylist)
            db.session.commit()

    #reveal newly generated playlist on generate_playlist.html page based on stored session from user input above

    #create json format that in the form that Amplitude.js can read
    spotify_info_list = []
    for track in spotify_info["tracks"]:
        spotify_info_dict = {}
        millis = int(track["duration_ms"])
        minutes = millis / (1000 * 60)
        minutes = int(minutes)
        seconds = (millis % (1000 * 60)) / 1000
        seconds = int(seconds)
        if seconds == 0:
            seconds = "00"
        if seconds == 1:
            seconds = "01"
        if seconds == 2:
            seconds = "02"
        if seconds == 3:
            seconds = "03"
        if seconds == 4:
            seconds = "04"
        if seconds == 5:
            seconds = "05"
        if seconds == 6:
            seconds = "06"
        if seconds == 7:
            seconds = "07"
        if seconds == 8:
            seconds = "08"
        if seconds == 9:
            seconds = "09"

        track["duration_ms"] = f'{minutes}:{seconds}'

        spotify_info_dict["name"] = track["name"]
        spotify_info_dict["artist"] = [
            f' {artist["name"]}' for artist in track["artists"]
        ]
        spotify_info_dict["album"] = track["album"]["name"]
        spotify_info_dict["url"] = track["preview_url"]
        spotify_info_dict["cover_art_url"] = track["album"]["images"][0]["url"]

        spotify_info_list.append(spotify_info_dict)

    fin_spotify_dict = {}
    fin_spotify_dict["songs"] = spotify_info_list

    return render_template("amplitude_generate_playlist.html",
                           spotify_info=spotify_info,
                           fin_spotify_dict=fin_spotify_dict)
예제 #21
0
파일: blog.py 프로젝트: woodenbrick/wedding
 def get(self):
   full_list = memcache.get("songs_full_list")
   if full_list is None:
     full_list = Song.all().order('artist')
   template_values = {'songs' : full_list}
   self.generate('full_music_list.html', template_values)
예제 #22
0
def populateDataManually():
    """Populates the database tables with dummy data.
    """
    # Populate starter data in the database
    # Bind the engine to the metadata of the Base class (enables declaratives to be accessed through a DBSession
    # instance)
    Base.metadata.bind = engine

    DBSession = sessionmaker(bind=engine)

    # A DBSession() instance establishes all conversations with the database and represents a "staging zone"
    # for all the objects loaded into the database session object. Any change made against the objects in the
    # session won't be persisted into the database until you call session.commit(). If you're not happy about the
    # changes, you can revert all of them back to the last commit by calling session.rollback()
    session = DBSession()

    # Initial dummy data.
    user1 = User(email="*****@*****.**", password="******")
    user2 = User(email="*****@*****.**", password="******")
    user3 = User(email="*****@*****.**", password="******")
    session.add(user1)
    session.add(user2)
    session.add(user3)
    session.commit()

    artist1 = Artist(name="Purity Ring", uri="dummy", followers=1)
    session.add(artist1)
    session.commit()

    album1 = Album(name="Another Eternity",
                   uri="dummyuri",
                   release_date=date.today,
                   artist_id=artist1.id, artist=artist1)
    session.add(album1)
    session.commit()

    song_objects = [
        Song(uri="dummyuri", track_number=1, name="Heartsigh", popularity=100, duration=189000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=2, name="Bodyache", popularity=100, duration=179000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=3, name="Push Pull", popularity=100, duration=169000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=4, name="Repetition", popularity=100, duration=159000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=5, name="Stranger than Earth", popularity=100, duration=149000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=6, name="Begin Again", popularity=100, duration=139000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=7, name="Dust Hymn", popularity=100, duration=129000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=8, name="Flood on the Floor", popularity=100, duration=119000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=9, name="Sea Castle", popularity=100, duration=144000, danceability=1.0,
             explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100, valence=1.0,
             album_id=album1.id, album=album1),
        Song(uri="dummyuri", track_number=10, name="Stillness in Woe", popularity=100, duration=155000,
             danceability=1.0, explicit=False, tempo=1.0, energy=1.0, instrumentalness=1.0, time_signature=100,
             valence=1.0, album_id=album1.id, album=album1)
    ]
    session.add_all(song_objects)
    session.commit()
예제 #23
0
 def song_title(f):
   try:
     return Song.byPath(str(f)).title, 
   except SQLObjectNotFound:
     return '[SONG NOT IN DATABASE -- REPORT THIS]'