コード例 #1
0
 def _build_playlist(self):
     """Search all the file reader paths for movie files with the provided
     extensions.
     """
     # Get list of paths to search from the file reader.
     paths = self._reader.search_paths()
     # Enumerate all movie files inside those paths.
     movies = []
     for ex in self._extensions:
         for path in paths:
             # Skip paths that don't exist or are files.
             if not os.path.exists(path) or not os.path.isdir(path):
                 continue
             # Ignore hidden files (useful when file loaded on usb
             # key from an OSX computer
             movies.extend(['{0}/{1}'.format(path.rstrip('/'), x) \
                            for x in os.listdir(path) \
                            if re.search('\.{0}$'.format(ex), x,
                                         flags=re.IGNORECASE) and \
                            x[0] is not '.'])
             # Get the video volume from the file in the usb key
             sound_vol_file_path = '{0}/{1}'.format(path.rstrip('/'),
                                                    self._sound_vol_file)
             if os.path.exists(sound_vol_file_path):
                 with open(sound_vol_file_path, 'r') as sound_file:
                     sound_vol_string = sound_file.readline()
                     if self._is_number(sound_vol_string):
                         self._sound_vol = int(float(sound_vol_string))
     # Create a playlist with the sorted list of movies.
     return Playlist(sorted(movies), self._is_random)
コード例 #2
0
ファイル: playlists.py プロジェクト: ubdreams/youtify
    def post(self):
        """Create new playlist"""
        youtify_user_model = get_current_youtify_user_model()
        if youtify_user_model == None:
            self.error(403)
            return

        json_playlist = simplejson.loads(self.request.get('json'))

        if json_playlist is None:
            self.error(500)

        playlist_model = Playlist(owner=youtify_user_model, json=None)
        playlist_model.private = json_playlist.get('isPrivate', False)
        playlist_model.tracks_json = simplejson.dumps(json_playlist['videos'])
        playlist_model.title = json_playlist['title']
        playlist_model.put()

        youtify_user_model.playlists.append(playlist_model.key())
        youtify_user_model.save()

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(
            simplejson.dumps(
                get_playlist_struct_from_playlist_model(playlist_model)))
コード例 #3
0
ファイル: playlist.py プロジェクト: sresis/Playlist-Together
def create_playlist(playlist_name):
    """Creates a playlist and adds to DB."""

    playlist = Playlist(playlist_name=playlist_name)
    db.session.add(playlist)
    db.session.commit()

    return playlist
コード例 #4
0
def create_playlist(playlist_name, user_id):
    """Create and return a new playlist"""

    playlist = Playlist(playlist_name=playlist_name, user_id=user_id)

    db.session.add(playlist)
    db.session.commit()

    return playlist
コード例 #5
0
ファイル: music_player.py プロジェクト: xb2342996/chatbot
def show_playlist():
    username = spotify_username()
    playlists = spotify.user_playlists(username)
    playlists_list = []

    for playlist in playlists['items']:
        # print(playlist)
        if playlist['images'] == []:
            play_list = Playlist(name=playlist['name'],
                                 uri=playlist['uri'],
                                 total=playlist['tracks']['total'])
        else:
            play_list = Playlist(name=playlist['name'],
                                 uri=playlist['uri'],
                                 total=playlist['tracks']['total'],
                                 image=playlist['images'][2]['url'])
        playlists_list.append(play_list.to_dict())
    return {'playlists': playlists_list}
コード例 #6
0
ファイル: music_player.py プロジェクト: xb2342996/chatbot
def show_top_tracks(artist_name):  # default: top10
    tracks_list = []
    artist = get_artist(artist_name)
    results = spotify.artist_top_tracks(artist['uri'])

    for track in results['tracks']:
        playlist = Playlist(name=track['name'],
                            uri=track['uri'],
                            image=track['album']['images'][1]['url'])
        tracks_list.append(playlist.to_dict())
    return {'playlists': tracks_list}
コード例 #7
0
    def get_playlist_from_context(self, context):
        """Return an Playlist from a Context.

        Args:
            context (dict): The Context to convert from.

        Returns:
            Playlist: The Playlist.
        """
        if context["uri"] == common.SAVED_TRACKS_CONTEXT_URI:
            # TODO: Consider creating a common/factory function for
            # obtaining the Saved PLaylist.
            return Playlist({
                "uri":common.SAVED_TRACKS_CONTEXT_URI,
                "name": "Saved"
                })

        playlist_id = id_from_uri(context["uri"])
        result = self.get_api_v1("playlists/{}".format(playlist_id))
        return Playlist(result or {})
コード例 #8
0
def add_playlist_to_db(user_id, sp_playlist_id, playlist_name):
    """Add a playlist to database"""

    playlist = Playlist(user_id=user_id,
                        sp_playlist_id=sp_playlist_id,
                        name=playlist_name)
    db.session.add(playlist)
    db.session.commit()

    print "Added to DB:", playlist

    return playlist
コード例 #9
0
ファイル: crud.py プロジェクト: annewoosam/youtube-playlists
def create_playlist(channel_name, playlist_name, number_of_videos,
                    last_updated):

    playlist = Playlist(channel_name=channel_name,
                        playlist_name=playlist_name,
                        number_of_videos=number_of_videos,
                        last_updated=last_updated)

    db.session.add(playlist)

    db.session.commit()

    return playlist
コード例 #10
0
def populatePlaylists():
    """Populates the playlist tables with dummy data.
    """
    Base.metadata.bind = engine
    DBSession = sessionmaker(bind=engine)
    session = DBSession()

    user1 = User(email="*****@*****.**", password="******")
    user2 = User(email="*****@*****.**", password="******")
    user3 = User(email="*****@*****.**", password="******")

    session.add(user1)
    session.add(user2)
    session.add(user3)

    p1 = Playlist(name="Kaan's list", user_id=user1.id, user=user1)
    p2 = Playlist(name="Ryan's list", user_id=user1.id, user=user2)
    p3 = Playlist(name="Paul's list", user_id=user1.id, user=user3)

    session.add(p1)
    session.add(p2)
    session.add(p3)
    session.commit()
コード例 #11
0
    def get_user_playlists(self, user, progress=None):
        """Get the Playlists from the current user.

        Args:
            user (User): The User.
            progress (Progress): Progress associated with this call.

        Return:
            tuple: The Playlists.
        """
        q = {"limit": 50}
        url = "users/{}/playlists".format(user['id'])
        page = self.get_api_v1(url, q)
        return tuple([Playlist(p) for p in self.extract_page(page, progress)])
コード例 #12
0
def load_playlists():

	print("Loading playlists")

	Playlist.query.delete()

	for row in open("seed_data/playlist_data.csv"):
		row = row.rstrip()
		playlist_id, user_id, title = row.split(",")

		playlist = Playlist(playlist_id=playlist_id, user_id=user_id,
							title=title)

		db.session.add(playlist)

	db.session.commit()
コード例 #13
0
def newPlaylist():
    if request.method == 'POST':
        user_id_form = session.query(User).filter_by(
            email=request.form['user_email']).one()
        newPlaylistName = Playlist(name=request.form['name'],
                                   user_id=user_id_form.id)
        session.add(newPlaylistName)
        session.commit()
        flash("New playlist was created!")
        return redirect(url_for('index'))
    else:
        playlists = session.query(Playlist).all()
        users = session.query(User).all()
        return render_template('createNewPlaylist.html',
                               title='Create a playlist',
                               playlists=playlists,
                               users=users)
コード例 #14
0
    def get(self):
        user = get_current_youtify_user_model()

        if ON_PRODUCTION:
            return

        for type, username in EXTERNAL_USERS:
            url = 'http://soundcloud.com/' + username
            response = urlfetch.fetch(
                'https://api.soundcloud.com/resolve.json?consumer_key=206f38d9623048d6de0ef3a89fea1c4d&url='
                + url)
            response = simplejson.loads(response.content)
            external_user_model = ExternalUser(
                type=type,
                external_user_id=str(response['id']),
                username=username,
                avatar_url=response['avatar_url'])
            external_user_model.save()
            user.external_user_subscriptions.append(external_user_model.key())
            user.save()
            external_user_model.subscribers.append(user.key())
            external_user_model.save()

        self.redirect('/')
        return

        for i in range(0, 50):
            tracks_json = []
            for j in range(0, 100):
                tracks_json.append({
                    "videoId": 27985183,
                    "title": "Oceanic Crust",
                    "duration": 106331,
                    "type": "soundcloud"
                })
            m = Playlist(owner=user,
                         title="Mosaik " + str(i),
                         tracks_json=simplejson.dumps(tracks_json),
                         json=None)
            m.put()

            user.playlists.append(m.key())
            user.save()

        self.redirect('/')
コード例 #15
0
    def get_playlists(self,
                      include_tracks=False) -> Generator[Playlist, None, None]:
        continue_ = True
        current_offset = 0
        while continue_:
            r = self._spotipy.user_playlists(self._user_id,
                                             offset=current_offset)

            for item in r["items"]:
                playlist = Playlist(item["name"], item["id"])

                if include_tracks:
                    playlist.extend(self.get_playlist_tracks(playlist))

                yield playlist

            continue_ = (r["offset"] + r["limit"]) < r["total"]
            current_offset = r["offset"] + 1
コード例 #16
0
ファイル: server.py プロジェクト: marsmans13/HB-Project
def add_new_playlist():
    """ Add a new playlist. """

    title = request.form.get("playlist-name")
    username = session.get('username')

    user = User.query.filter_by(username=username).first()
    user_id = user.user_id

    playlist = Playlist(user_id=user_id, title=title)

    db.session.add(playlist)
    db.session.commit()

    playlists = Playlist.query.filter_by(user_id=user_id).all()
    flash("Playlist added.")

    return redirect("/user")
コード例 #17
0
def create_playlist_return_as_dict(user_id,
                                   search_id,
                                   created_at,
                                   last_updated_at,
                                   playlist_title,
                                   spotify_playlist_id=None):
    """Create a new playlist and return as dict"""

    playlist = Playlist(user_id=user_id,
                        search_id=search_id,
                        created_at=created_at,
                        last_updated_at=last_updated_at,
                        playlist_title=playlist_title,
                        spotify_playlist_id=spotify_playlist_id)

    db.session.add(playlist)
    db.session.commit()

    return playlist.as_dict()
コード例 #18
0
 def _build_playlist(self):
     """Search all the file reader paths for movie files with the provided
     extensions.
     """
     # Get list of paths to search from the file reader.
     paths = self._reader.search_paths()
     # Enumerate all movie files inside those paths.
     movies = []
     for ex in self._extensions:
         for path in paths:
             # Skip paths that don't exist or are files.
             if not os.path.exists(path) or not os.path.isdir(path):
                 continue
             movies.extend(['{0}/{1}'.format(path.rstrip('/'), x) \
                            for x in os.listdir(path) \
                            if re.search('\.{0}$'.format(ex), x,
                                         flags=re.IGNORECASE)])
     # Create a playlist with the sorted list of movies.
     return Playlist(sorted(movies))
コード例 #19
0
ファイル: setlist_api.py プロジェクト: vivsnguyen/playlistify
def create_playlist_in_db(playlist_title, user_id):
    """Creates playlist in db if not already in db."""
    user = User.query.get(user_id)

    #check if user logged in
    #check if no user, no playlists
    #check if user has no playlists

    if not Playlist.query.filter_by(playlist_title=playlist_title,
                                    user_id=user_id).first():
        playlist = Playlist(playlist_title=playlist_title)
        user.playlists.append(playlist)

        db.session.commit()

    else:
        playlist = Playlist.query.filter_by(
            playlist_title=playlist_title).first()

    return playlist
コード例 #20
0
ファイル: music_player.py プロジェクト: xb2342996/chatbot
def show_artist_albums(artist_name):
    albums_list = []
    albums = []
    artist = get_artist(artist_name)
    results = spotify.artist_albums(artist['id'], album_type='album')
    albums.extend(results['items'])
    while results['next']:
        results = spotify.next(results)
        albums.extend(results['items'])
    seen = set()  # to avoid dups
    albums.sort(key=lambda album: album['name'].lower())
    for album in albums:
        name = album['name']
        if name not in seen:
            playlist = Playlist(name=name,
                                uri=album['uri'],
                                image=album['images'][2]['url'],
                                total=album['total_tracks'])
            albums_list.append(playlist.to_dict())
            seen.add(name)
    return {'playlists': albums_list}
コード例 #21
0
ファイル: mood.py プロジェクト: vamsden/Moodify
def create_playlist(auth_header, user_id, playlist_tracks, mood,
                    playlist_name):
    """ Create playlist and add tracks to playlist. """

    name = f'{playlist_name}'

    payload = {'name': name, 'description': 'Mood generated playlist'}

    playlist_request = f'{SPOTIFY_API_URL}/users/{user_id}/playlists'
    playlist_data = requests.post(playlist_request,
                                  data=json.dumps(payload),
                                  headers=auth_header).json()
    playlist_id = playlist_data['id']
    session['playlist'] = playlist_id

    playlist_exist = db.session.query(Playlist).filter(
        Playlist.id == playlist_id).all()

    if not playlist_exist:
        new_playlist = Playlist(id=playlist_id, user_id=user_id, mood=mood)
        db.session.add(new_playlist)

    for track in playlist_tracks:
        playlist_track_exist = db.session.query(PlaylistTrack).filter(
            PlaylistTrack.playlist_id == playlist_id,
            PlaylistTrack.track_uri == track).all()
        if not playlist_track_exist:
            new_playlist_track = PlaylistTrack(playlist_id=playlist_id,
                                               track_uri=track)
            db.session.add(new_playlist_track)

    db.session.commit()

    track_uris = '%2C'.join(playlist_tracks)
    add_tracks = f'{SPOTIFY_API_URL}/playlists/{playlist_id}/tracks?uris={track_uris}'
    tracks_added = requests.post(add_tracks, headers=auth_header).json()
    # tracks_added = post_spotify_data(add_tracks, auth_header)

    return playlist_data['external_urls']['spotify']
コード例 #22
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--size",
                        type=int,
                        help="Size of the generated playlist")
    parser.add_argument("--name",
                        type=str,
                        help="Name of the generated playlist")
    parser.add_argument("--user",
                        type=str,
                        help="User for whom to create the playlist")
    parser.add_argument("--seed", type=str, help="ID of the seed track")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    client = SpotifyClient(args.user)
    seed_track = client.get_track(args.seed)
    factory = ArtistChainFactory(client,
                                 seed_track,
                                 DriftingWeight(seed_track),
                                 unique_artists=False)

    # If a playlist of this name exists, use it, otherwise create one.
    for playlist_ in client.get_playlists():
        if playlist_.name == args.name:
            playlist = playlist_
            break
    else:
        playlist = Playlist(name=args.name)

    for _, track in zip(range(args.size), factory):
        playlist.append(track)

    LOG.info("Finished generating playlist %s", str(playlist))

    client.store_playlist(playlist)
コード例 #23
0
from model import Filme, Serie, Playlist

vingadores = Filme('vingadores - guerra infinita', 2018, 160)
atlanta = Serie('atlanta - um teste', 2018, 2)
the_office = Serie('The Office', 2005, 9)
titanic = Filme('titanic', 1996, 210)
vingadores.dar_like()
atlanta.dar_like()
atlanta.dar_like()
titanic.dar_like()
the_office.dar_like()
the_office.dar_like()
the_office.dar_like()
the_office.dar_like()
the_office.dar_like()

filmes_e_series = [vingadores, atlanta, titanic, the_office]
playlist_fds = Playlist('fim de semana', filmes_e_series)

print(f'Tamnanho da Playlist: {len(playlist_fds)}')

for programa in playlist_fds:
      # detalhes = programa.duracao if hasattr(programa, 'duracao') else programa.temporadas
      # print(f'{programa.nome} - {detalhes} D - {programa.likes}')
      print(programa)
コード例 #24
0
def add_playlist(name, desc):
    playlist = Playlist(name=name, description=desc)
    session.add(playlist)
    session.commit()
コード例 #25
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)
コード例 #26
0
from model import Filme, Serie, Playlist

vingadores = Filme('vingadores', 2018, 160)
vingadores.dar_likes()
vingadores.dar_likes()
atlanta = Serie('atlanta', 2018, 2)
enola_holmes = Serie('Enola Holmes', 2020, 124)
enola_holmes.dar_likes()
enola_holmes.dar_likes()
enola_holmes.dar_likes()
enola_holmes.dar_likes()

lista_filmes_e_series = [vingadores, atlanta, enola_holmes]
playlist = Playlist('Minha Playlist', lista_filmes_e_series)
print(f'Tamanho da playlist: {len(playlist)}')

for programa in playlist:
    print(programa)
コード例 #27
0
                    }
                    self._print(order + " - " + name + " - " + screen_time +
                                " - " + str(play_restriction))
                    fullPath = self._content_path + '/' + name
                    if not os.path.exists(fullPath):
                        continue
                    playlistTh.append(fullPath)
                    playlistRestrictions.append(play_restriction)
        except Exception, err:
            self._print("error")
            if hasattr(err, 'message'):
                self._print(err.message)
            else:
                self._print(err)
            pass
        return Playlist(playlistTh, playlistRestrictions, self._is_random)

    def _blank_screen(self):
        """Render a blank screen filled with the background color."""
        self._screen.fill(self._bgcolor)
        pygame.display.update()

    def _blank_screen_no_update(self):
        """Render a blank screen filled with the background color."""
        self._screen.fill(self._bgcolor)

    def _set_background_image(self, playlist):
        """Render background image
           and load bg from disk if playlist index =0 
        """
        try: