def get_book_data(html): soup = BeautifulSoup(html, 'lxml') title, author = soup.select_one('h1').text.split(sep='::') img_url = soup.select_one('.bookimage img')['src'] comments = [ texts_comments.select_one('.black').text for texts_comments in soup.select('.texts') ] genres = get_genres(soup) return title.strip(), author.strip(), comments, genres, img_url
def go_to_search_page(): """Sets up search page and redirect user there.""" try: genres = get_genres() keys = get_key_list() modes = get_modes() return render_template("search.html", genres=genres, keys=keys, modes=modes) # A KeyError occurs if genres, keys, or modes aren't populated lists; these cannot be retrieved from the Spotify API unless authenticated except KeyError: return redirect('/')
def remove_playlist(): """Removes selected playlist from user's Spotify account""" try: delete_playlist(session['playlist_id']) message = "Playlist deleted from Spotify" genres = get_genres() keys = get_key_list() modes = get_modes() return render_template("search.html", genres=genres, keys=keys, modes=modes, message=message) except KeyError: redirect('/')
def index(): genre = request.args.get('genre') if genre and genre.lower() != "any": movie = movies_in_genre(genre).order_by(fn.Random()).get() else: movie = Movie.select().order_by(fn.Random()).get() r = movie.get_details(plot="full") title = r['attachments'][0]['title'] link = r['attachments'][0]['title_link'] description = r['attachments'][0]['text'] image = r['attachments'][0]['image_url'] netflix = get_netflix_id( title.split(' (')[0], title.split('(')[-1].split(')')[-2]) saying = random.choice(config.SAYINGS) if not genres: get_genres() list_genres = ["Any"] list_genres.extend(sorted(genres)) year = datetime.datetime.now().year version = VERSION return render_template("index.html", **locals())
import utils import pickle import settings token = utils.get_token(settings.CLIENT_ID, settings.CLIENT_SECRET) genres = utils.get_genres(token) discovered_artists = {} print("Discovering artists...") for genre in genres: res = utils.get_recommendations(seed_tracks=[], seed_artists=[], seed_genres=[genre], token=token) for track in res["tracks"]: artists = track["artists"] for artist in artists: if artist["id"] not in discovered_artists.keys(): discovered_artists[artist["id"]] = {} print("genre: %s, total artists: %d" % (genre, len(discovered_artists))) print("Enough discovered. Now will get info about them.") artists = {} buffer = [] it = 0 for key in discovered_artists.keys(): it += 1 if len(buffer) < 49: buffer.append(key) else: buffer.append(key)
def command(): text = request.form.get('text') if not text: return '', 400 args = text.split() # Check if we know about this command if args[0] == 'add': success, m = add_movie(' '.join(args[1:])) if success: m = m.get_details() m['text'] = "Added movie:" return Response(json.dumps(m), mimetype='application/json') elif args[0] == 'choose': if len(args) == 1: rand = Movie.select().order_by(fn.Random()) else: genre = ' '.join(args[1:]) rand = movies_in_genre(genre).order_by(fn.Random()) try: m = rand.get().get_details() m['text'] = random.choice(config.SAYINGS) return Response(json.dumps(m), mimetype='application/json') except Movie.DoesNotExist: return "No movies yet!" elif args[0] == 'watched': name = ' '.join(args[1:]) try: movie = Movie.get(fn.Lower(Movie.name) == name.lower()) except Movie.DoesNotExist: return "Sorry, I couldn't find that movie. You need to be exact." movie.watched = True movie.save() return "Marked _{}_ as watched".format(movie.name) elif args[0] == 'unwatch': # Undocumented commands name = ' '.join(args[1:]) try: movie = Movie.get(fn.Lower(Movie.name) == name.lower()) except Movie.DoesNotExist: return "Sorry, I couldn't find that movie. You need to be exact." movie.watched = False movie.save() return "Marked _{}_ as un-watched".format(movie.name) elif args[0] == 'list': data = {'text': "Must specify `movies` or `genres`."} if len(args) > 1: if args[1] == 'movies': if len(args) > 2: data = format_movies(' '.join(args[2:])) else: data = format_movies() elif args[1] == 'genres': data = format_genres() return Response(json.dumps(data), mimetype='application/json') # Management commands elif args[0] == 'refresh_genres': get_genres() return 'Done' elif args[0] == 'update': update() return '', 204 elif args[0] == 'reload': reload() return '', 204 return Response(json.dumps(help_text()), mimetype='application/json')
def show_recommendations(): """Processes search data against Spotify's API and gets the user to this results page.""" try: headers = {'Authorization': 'Bearer ' + session['token']} payload = {} # gets a list of artists to be searched for, if any if request.form.get('artist'): artist_list = "" for artist in request.form.getlist('artist'): artist_list += f"{artist}," payload['seed_artists'] = artist_list # gets a list of tracks to be searched for, if any if request.form.get('track'): track_list = "" for track in request.form.getlist('track'): track_list += f"{track}," payload['seed_tracks'] = track_list # gets the genre to be searched for, if any if request.form.get('seed_genre'): payload['seed_genres'] = request.form.get('seed_genre') # this series of seed inputs all aim to maximize that attribute (1.0 is 100%) but are 'target' values rather than 'maximum' values which would reduce the amount of results we get if request.form.get('acousticness'): payload['target_acousticness'] = 1.0 if request.form.get('danceability'): payload['target_danceability'] = 1.0 if request.form.get('energy'): payload['target_energy'] = 1.0 if request.form.get('instrumentalness'): payload['target_instrumentalness'] = 1.0 if request.form.get('liveness'): payload['target_liveness'] = 1.0 if request.form.get('speechiness'): payload['target_speechiness'] = 1.0 if request.form.get('valence'): payload['target_valence'] = 1.0 # these seed inputs include either ranges or select fields if request.form.get('include_min_duration'): payload['min_duration_ms'] = int(request.form.get('min_duration')) if request.form.get('include_max_duration'): payload['max_duration_ms'] = int(request.form.get('max_duration')) if request.form.get('key'): payload['target_key'] = int(request.form.get('key')) if request.form.get('include_loudness'): payload['target_loudness'] = float(request.form.get('loudness')) if request.form.get('mode'): payload['target_mode'] = int(request.form.get('mode')) if request.form.get('include_popularity'): payload['target_popularity'] = int(request.form.get('popularity')) if request.form.get('include_tempo'): payload['target_tempo'] = float(request.form.get('tempo')) if request.form.get('include_time_sig'): payload['target_time_signature'] = int( request.form.get('time_sig')) resp = requests.get('https://api.spotify.com/v1/recommendations', params=payload, headers=headers).json() # used in the case of app level authentication track_id_list = [] for track in resp['tracks']: track_id_list.append(track['id']) # used in the case of user level authentication track_uris = "" for track_uri in resp['tracks']: track_uris += track_uri['uri'] + ',' # necessary in the case of app authentication as this data is necessary rendered in the returned template playlist_id = None if session.get('user_id'): session['playlist_id'] = create_playlist(session['user_id']) playlist_id = session['playlist_id'] add_songs_to_playlist(session['playlist_id'], track_uris) return render_template("results.html", resp=resp, track_id_list=track_id_list, playlist_id=playlist_id) # a KeyError occurs when no artist, track, or genre is included in the seed search except KeyError: message = "Please enter at least an artist, song, or genre" genres = get_genres() keys = get_key_list() modes = get_modes() return render_template("search.html", genres=genres, keys=keys, modes=modes, message=message)