import pandas as pd
from google.colab import files
import io
# Step 1: Upload the files
uploaded_files = files.upload()
all_data = []
# Step 2, 3, and 4: Read each uploaded CSV, add genre column, and concatenate
for filename in uploaded_files.keys():
# Read the file content into a pandas DataFrame
df = pd.read_csv(io.StringIO(uploaded_files[filename].decode('utf-8')))
# Assume that the filename before '.csv' is the genre name
genre_name = filename.split('.csv')[0]
df['genre'] = genre_name
all_data.append(df)
# Concatenate all dataframes
final_df = pd.concat(all_data, ignore_index=True)
# Step 5: Save the combined DataFrame into a new CSV file
final_df.to_csv('combined_movies.csv', index=False)
# Download the combined CSV
files.download('combined_movies.csv')
Run to view results
!pip install spotipy
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# After clicking the URL and authorizing, you'll be redirected to your specified redirect_uri.
# Extract the code parameter from that URL.
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists over the past 30 days
top_artists = sp.current_user_top_artists(time_range='short_term')
# Count the frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
genre_capitalized = genre.capitalize() # Capitalize first letter of each genre
if genre_capitalized in genre_count:
genre_count[genre_capitalized] += 1
else:
genre_count[genre_capitalized] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
print("Your Top 5 Genres from Spotify over the past 30 days:")
for genre in top_5_genres:
print(genre)
Run to view results
# Genre mapping
genre_mapping = {
# Main genres
'pop': ['action', 'adventure', 'romance'],
'art pop': ['animation', 'fantasy', 'romance'],
'reggaeton': ['action', 'adventure'],
'urbano latino': ['action', 'adventure'],
'trap latino': ['crime', 'thriller'],
'rock': ['action', 'adventure', 'war'],
'indie rock': ['drama', 'romance', 'adventure'],
'classical': ['biography', 'history', 'romance'],
'hip hop': ['action', 'crime', 'drama'],
'jazz': ['film-noir', 'romance', 'biography'],
'country': ['family', 'romance', 'history'],
'electronic': ['sci-fi', 'mystery', 'thriller'],
'metal': ['action', 'horror', 'war'],
'folk': ['family', 'history', 'biography'],
'blues': ['drama', 'biography', 'film-noir'],
'r&b': ['drama', 'romance', 'crime'],
'soul': ['drama', 'family', 'romance'],
'punk': ['action', 'thriller', 'mystery'],
'disco': ['comedy', 'romance', 'family'],
'house': ['sci-fi', 'thriller', 'mystery'],
'techno': ['sci-fi', 'action'],
'edm': ['action', 'adventure', 'sci-fi'],
'latin': ['romance', 'family', 'adventure'],
'reggae': ['comedy', 'adventure', 'family'],
'funk': ['comedy', 'romance', 'action'],
'k-pop': ['romance', 'comedy', 'action'],
'psychedelic': ['animation', 'fantasy', 'mystery'],
'world': ['history', 'family', 'biography'],
'ambient': ['mystery', 'sci-fi', 'animation'],
# Subgenres
'lo-fi beats': ['drama', 'romance', 'animation'],
'vaporwave': ['sci-fi', 'mystery', 'animation'],
'emo': ['drama', 'romance', 'mystery'],
'hardcore': ['action', 'thriller', 'war'],
'dubstep': ['sci-fi', 'action', 'thriller'],
'ska': ['comedy', 'family', 'adventure'],
'swing': ['history', 'romance', 'family'],
'trance': ['sci-fi', 'fantasy', 'thriller'],
'grime': ['action', 'crime', 'drama'],
'bluegrass': ['family', 'history', 'drama'],
'new wave': ['drama', 'sci-fi', 'mystery'],
'post-punk': ['drama', 'mystery', 'thriller'],
'trip hop': ['mystery', 'drama', 'sci-fi'],
'neosoul': ['drama', 'romance', 'family'],
'afrobeat': ['history', 'drama', 'family'],
'chillhop': ['drama', 'animation', 'romance'],
'synthwave': ['sci-fi', 'action', 'drama']
}
# Convert genre_mapping to DataFrame
df = pd.DataFrame.from_dict(genre_mapping, orient='index').reset_index()
df.columns = ['Music Genre', 'Movie Genre 1', 'Movie Genre 2', 'Movie Genre 3']
# Capitalize the first letter of each entry in the specified columns
df['Music Genre'] = df['Music Genre'].str.capitalize()
df['Movie Genre 1'] = df['Movie Genre 1'].str.capitalize()
df['Movie Genre 2'] = df['Movie Genre 2'].str.capitalize()
df['Movie Genre 3'] = df['Movie Genre 3'].str.capitalize()
# Display DataFrame
df
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# Extract the code from the redirected URL
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists
top_artists = sp.current_user_top_artists()
# Count frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
# Genre mapping
genre_mapping = {
# Main genres
'pop': ['action', 'adventure', 'romance'],
'art pop': ['animation', 'fantasy', 'romance'],
'reggaeton': ['action', 'adventure'],
'urbano latino': ['action', 'adventure'],
'trap latino': ['crime', 'thriller'],
'rock': ['action', 'adventure', 'war'],
'indie rock': ['drama', 'romance', 'adventure'],
'classical': ['biography', 'history', 'romance'],
'hip hop': ['action', 'crime', 'drama'],
'jazz': ['film-noir', 'romance', 'biography'],
'country': ['family', 'romance', 'history'],
'electronic': ['sci-fi', 'mystery', 'thriller'],
'metal': ['action', 'horror', 'war'],
'folk': ['family', 'history', 'biography'],
'blues': ['drama', 'biography', 'film-noir'],
'r&b': ['drama', 'romance', 'crime'],
'soul': ['drama', 'family', 'romance'],
'punk': ['action', 'thriller', 'mystery'],
'disco': ['comedy', 'romance', 'family'],
'house': ['sci-fi', 'thriller', 'mystery'],
'techno': ['sci-fi', 'action'],
'edm': ['action', 'adventure', 'sci-fi'],
'latin': ['romance', 'family', 'adventure'],
'reggae': ['comedy', 'adventure', 'family'],
'funk': ['comedy', 'romance', 'action'],
'k-pop': ['romance', 'comedy', 'action'],
'psychedelic': ['animation', 'fantasy', 'mystery'],
'world': ['history', 'family', 'biography'],
'ambient': ['mystery', 'sci-fi', 'animation'],
# Subgenres
'lo-fi beats': ['drama', 'romance', 'animation'],
'vaporwave': ['sci-fi', 'mystery', 'animation'],
'emo': ['drama', 'romance', 'mystery'],
'hardcore': ['action', 'thriller', 'war'],
'dubstep': ['sci-fi', 'action', 'thriller'],
'ska': ['comedy', 'family', 'adventure'],
'swing': ['history', 'romance', 'family'],
'trance': ['sci-fi', 'fantasy', 'thriller'],
'grime': ['action', 'crime', 'drama'],
'bluegrass': ['family', 'history', 'drama'],
'new wave': ['drama', 'sci-fi', 'mystery'],
'post-punk': ['drama', 'mystery', 'thriller'],
'trip hop': ['mystery', 'drama', 'sci-fi'],
'neosoul': ['drama', 'romance', 'family'],
'afrobeat': ['history', 'drama', 'family'],
'chillhop': ['drama', 'animation', 'romance'],
'synthwave': ['sci-fi', 'action', 'drama']
}
# Using the genre mapping to find corresponding movie genres
matching_genres = set()
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for movie_genre in genre_mapping[spotify_genre]:
matching_genres.add(movie_genre.title()) # capitalize each word
print("Matching Genres between Spotify and Movies:", list(matching_genres))
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
import random
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# Extract the code from the redirected URL
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists
top_artists = sp.current_user_top_artists()
# Count frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
# Genre mapping
genre_mapping = {
# Main genres
'pop': ['action', 'adventure', 'romance'],
'art pop': ['animation', 'fantasy', 'romance'],
'reggaeton': ['action', 'adventure'],
'urbano latino': ['action', 'adventure'],
'trap latino': ['crime', 'thriller'],
'rock': ['action', 'adventure', 'war'],
'indie rock': ['drama', 'romance', 'adventure'],
'classical': ['biography', 'history', 'romance'],
'hip hop': ['action', 'crime', 'drama'],
'jazz': ['film-noir', 'romance', 'biography'],
'country': ['family', 'romance', 'history'],
'electronic': ['sci-fi', 'mystery', 'thriller'],
'metal': ['action', 'horror', 'war'],
'folk': ['family', 'history', 'biography'],
'blues': ['drama', 'biography', 'film-noir'],
'r&b': ['drama', 'romance', 'crime'],
'soul': ['drama', 'family', 'romance'],
'punk': ['action', 'thriller', 'mystery'],
'disco': ['comedy', 'romance', 'family'],
'house': ['sci-fi', 'thriller', 'mystery'],
'techno': ['sci-fi', 'action'],
'edm': ['action', 'adventure', 'sci-fi'],
'latin': ['romance', 'family', 'adventure'],
'reggae': ['comedy', 'adventure', 'family'],
'funk': ['comedy', 'romance', 'action'],
'k-pop': ['romance', 'comedy', 'action'],
'psychedelic': ['animation', 'fantasy', 'mystery'],
'world': ['history', 'family', 'biography'],
'ambient': ['mystery', 'sci-fi', 'animation'],
# Subgenres
'lo-fi beats': ['drama', 'romance', 'animation'],
'vaporwave': ['sci-fi', 'mystery', 'animation'],
'emo': ['drama', 'romance', 'mystery'],
'hardcore': ['action', 'thriller', 'war'],
'dubstep': ['sci-fi', 'action', 'thriller'],
'ska': ['comedy', 'family', 'adventure'],
'swing': ['history', 'romance', 'family'],
'trance': ['sci-fi', 'fantasy', 'thriller'],
'grime': ['action', 'crime', 'drama'],
'bluegrass': ['family', 'history', 'drama'],
'new wave': ['drama', 'sci-fi', 'mystery'],
'post-punk': ['drama', 'mystery', 'thriller'],
'trip hop': ['mystery', 'drama', 'sci-fi'],
'neosoul': ['drama', 'romance', 'family'],
'afrobeat': ['history', 'drama', 'family'],
'chillhop': ['drama', 'animation', 'romance'],
'synthwave': ['sci-fi', 'action', 'drama']
}
# Using the genre mapping to find corresponding movie genres
matching_genres_weighted = []
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for movie_genre in genre_mapping[spotify_genre]:
# Add the movie genre according to its frequency
matching_genres_weighted.extend([movie_genre] * genre_count[spotify_genre])
# Read the CSV
df = pd.read_csv('/content/combined_movies.csv')
# Filter movies with rating 8 and above
df = df[df['rating'] >= 8]
# Filter movies with votes greater than or equal to 20,000
df = df[df['votes'] >= 20000]
# Filter movies based on matching genres
filtered_movies = df[df['genre'].isin(matching_genres_weighted)]
# If there are no movies matching the criteria, print a message
if filtered_movies.empty:
print("No movies found matching the criteria.")
else:
# Recommend a movie from the filtered movies based on the weighted genres
recommended_genre = random.choice(matching_genres_weighted)
recommended_movie = filtered_movies[filtered_movies['genre'] == recommended_genre].sample().iloc[0]
print(f"Recommended Movie: {recommended_movie['movie_name']} (Genre: {recommended_movie['genre'].capitalize()}, Rating: {recommended_movie['rating']}, Release Year: {recommended_movie['year']})")
Run to view results
!pip install spotipy
Run to view results
import pandas as pd
# Read the CSV file into a DataFrame
df = pd.read_csv('/content/tvshowdata.csv')
# Filter rows where the 'certificate' column contains "TV"
df = df[df['certificate'].str.contains("TV", na=False)]
# Drop rows where the 'genre' column is NaN
df = df.dropna(subset=['genre'])
# Split the genres on commas and flatten the list
all_genres = [genre.strip() for sublist in df['genre'].str.split(',') for genre in sublist]
# Get unique genres using a set
unique_genres = set(all_genres)
# Convert unique genres into a DataFrame
df_genres = pd.DataFrame(sorted(unique_genres), columns=['Genres'])
df_genres
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# After clicking the URL and authorizing, you'll be redirected to your specified redirect_uri.
# Extract the code parameter from that URL.
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists over the past 30 days
top_artists = sp.current_user_top_artists(time_range='short_term')
# Count the frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
genre_capitalized = genre.capitalize() # Capitalize first letter of each genre
if genre_capitalized in genre_count:
genre_count[genre_capitalized] += 1
else:
genre_count[genre_capitalized] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
print("Your Top 5 Genres from Spotify over the past 30 days:")
for genre in top_5_genres:
print(genre)
Run to view results
# Genre mapping
genre_mapping = {
# Main genres
'pop': ['Action', 'Adventure', 'Romance'],
'art pop': ['Animation', 'Fantasy', 'Romance'],
'reggaeton': ['Action', 'Adventure'],
'urbano latino': ['Action', 'Adventure'],
'trap latino': ['Crime', 'Thriller'],
'rock': ['Action', 'Adventure', 'War'],
'indie rock': ['Drama', 'Romance', 'Adventure'],
'classical': ['Biography', 'History', 'Romance'],
'hip hop': ['Action', 'Crime', 'Drama'],
'jazz': ['Musical', 'Romance', 'Biography'],
'country': ['Family', 'Romance', 'History'],
'electronic': ['Sci-Fi', 'Mystery', 'Thriller'],
'metal': ['Action', 'Horror', 'War'],
'folk': ['Family', 'History', 'Biography'],
'blues': ['Drama', 'Biography', 'Music'],
'r&b': ['Drama', 'Romance', 'Crime'],
'soul': ['Drama', 'Family', 'Romance'],
'punk': ['Action', 'Thriller', 'Mystery'],
'disco': ['Comedy', 'Romance', 'Family'],
'house': ['Sci-Fi', 'Thriller', 'Mystery'],
'techno': ['Sci-Fi', 'Action'],
'edm': ['Action', 'Adventure', 'Sci-Fi'],
'latin': ['Romance', 'Family', 'Adventure'],
'reggae': ['Comedy', 'Adventure', 'Family'],
'funk': ['Comedy', 'Romance', 'Action'],
'k-pop': ['Romance', 'Comedy', 'Action'],
'psychedelic': ['Animation', 'Fantasy', 'Mystery'],
'world': ['History', 'Family', 'Biography'],
'ambient': ['Mystery', 'Sci-Fi', 'Animation'],
# Subgenres
'lo-fi beats': ['Drama', 'Romance', 'Animation'],
'vaporwave': ['Sci-Fi', 'Mystery', 'Animation'],
'emo': ['Drama', 'Romance', 'Mystery'],
'hardcore': ['Action', 'Thriller', 'War'],
'dubstep': ['Sci-Fi', 'Action', 'Thriller'],
'ska': ['Comedy', 'Family', 'Adventure'],
'swing': ['History', 'Romance', 'Family'],
'trance': ['Sci-Fi', 'Fantasy', 'Thriller'],
'grime': ['Action', 'Crime', 'Drama'],
'bluegrass': ['Family', 'History', 'Drama'],
'new wave': ['Drama', 'Sci-Fi', 'Mystery'],
'post-punk': ['Drama', 'Mystery', 'Thriller'],
'trip hop': ['Mystery', 'Drama', 'Sci-Fi'],
'neosoul': ['Drama', 'Romance', 'Family'],
'afrobeat': ['History', 'Drama', 'Family'],
'chillhop': ['Drama', 'Animation', 'Romance'],
'synthwave': ['Sci-Fi', 'Action', 'Drama']
}
# Convert genre_mapping to DataFrame
df = pd.DataFrame.from_records([(key,) + tuple(val) + (None,) * (3 - len(val)) for key, val in genre_mapping.items()])
df.columns = ['Music Genre', 'TV Genre 1', 'TV Genre 2', 'TV Genre 3']
# Capitalize the first letter of every music genre in the 'Music Genre' column
df['Music Genre'] = df['Music Genre'].str.capitalize()
# Display DataFrame
df
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# Extract the code from the redirected URL
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists
top_artists = sp.current_user_top_artists()
# Count frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
# Genre mapping for TV Shows
genre_mapping = {
# Main genres
'pop': ['Action', 'Adventure', 'Romance'],
'art pop': ['Animation', 'Fantasy', 'Romance'],
'reggaeton': ['Action', 'Adventure'],
'urbano latino': ['Action', 'Adventure'],
'trap latino': ['Crime', 'Thriller'],
'rock': ['Action', 'Adventure', 'War'],
'indie rock': ['Drama', 'Romance', 'Adventure'],
'classical': ['Biography', 'History', 'Romance'],
'hip hop': ['Action', 'Crime', 'Drama'],
'jazz': ['Musical', 'Romance', 'Biography'],
'country': ['Family', 'Romance', 'History'],
'electronic': ['Sci-Fi', 'Mystery', 'Thriller'],
'metal': ['Action', 'Horror', 'War'],
'folk': ['Family', 'History', 'Biography'],
'blues': ['Drama', 'Biography', 'Music'],
'r&b': ['Drama', 'Romance', 'Crime'],
'soul': ['Drama', 'Family', 'Romance'],
'punk': ['Action', 'Thriller', 'Mystery'],
'disco': ['Comedy', 'Romance', 'Family'],
'house': ['Sci-Fi', 'Thriller', 'Mystery'],
'techno': ['Sci-Fi', 'Action'],
'edm': ['Action', 'Adventure', 'Sci-Fi'],
'latin': ['Romance', 'Family', 'Adventure'],
'reggae': ['Comedy', 'Adventure', 'Family'],
'funk': ['Comedy', 'Romance', 'Action'],
'k-pop': ['Romance', 'Comedy', 'Action'],
'psychedelic': ['Animation', 'Fantasy', 'Mystery'],
'world': ['History', 'Family', 'Biography'],
'ambient': ['Mystery', 'Sci-Fi', 'Animation'],
# Subgenres
'lo-fi beats': ['Drama', 'Romance', 'Animation'],
'vaporwave': ['Sci-Fi', 'Mystery', 'Animation'],
'emo': ['Drama', 'Romance', 'Mystery'],
'hardcore': ['Action', 'Thriller', 'War'],
'dubstep': ['Sci-Fi', 'Action', 'Thriller'],
'ska': ['Comedy', 'Family', 'Adventure'],
'swing': ['History', 'Romance', 'Family'],
'trance': ['Sci-Fi', 'Fantasy', 'Thriller'],
'grime': ['Action', 'Crime', 'Drama'],
'bluegrass': ['Family', 'History', 'Drama'],
'new wave': ['Drama', 'Sci-Fi', 'Mystery'],
'post-punk': ['Drama', 'Mystery', 'Thriller'],
'trip hop': ['Mystery', 'Drama', 'Sci-Fi'],
'neosoul': ['Drama', 'Romance', 'Family'],
'afrobeat': ['History', 'Drama', 'Family'],
'chillhop': ['Drama', 'Animation', 'Romance'],
'synthwave': ['Sci-Fi', 'Action', 'Drama']
}
# Using the genre mapping to find corresponding TV show genres
matching_genres = set()
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for tvshow_genre in genre_mapping[spotify_genre]:
matching_genres.add(tvshow_genre)
print("Matching Genres between Spotify and TV Shows:", list(matching_genres))
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
import random
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# Extract the code from the redirected URL
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists
top_artists = sp.current_user_top_artists()
# Count frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
# Update the genre mapping with TV Show genres
genre_mapping = {
# Main genres
'pop': ['Action', 'Adventure', 'Romance'],
'art pop': ['Animation', 'Fantasy', 'Romance'],
'reggaeton': ['Action', 'Adventure'],
'urbano latino': ['Action', 'Adventure'],
'trap latino': ['Crime', 'Thriller'],
'rock': ['Action', 'Adventure', 'War'],
'indie rock': ['Drama', 'Romance', 'Adventure'],
'classical': ['Biography', 'History', 'Romance'],
'hip hop': ['Action', 'Crime', 'Drama'],
'jazz': ['Musical', 'Romance', 'Biography'],
'country': ['Family', 'Romance', 'History'],
'electronic': ['Sci-Fi', 'Mystery', 'Thriller'],
'metal': ['Action', 'Horror', 'War'],
'folk': ['Family', 'History', 'Biography'],
'blues': ['Drama', 'Biography', 'Music'],
'r&b': ['Drama', 'Romance', 'Crime'],
'soul': ['Drama', 'Family', 'Romance'],
'punk': ['Action', 'Thriller', 'Mystery'],
'disco': ['Comedy', 'Romance', 'Family'],
'house': ['Sci-Fi', 'Thriller', 'Mystery'],
'techno': ['Sci-Fi', 'Action'],
'edm': ['Action', 'Adventure', 'Sci-Fi'],
'latin': ['Romance', 'Family', 'Adventure'],
'reggae': ['Comedy', 'Adventure', 'Family'],
'funk': ['Comedy', 'Romance', 'Action'],
'k-pop': ['Romance', 'Comedy', 'Action'],
'psychedelic': ['Animation', 'Fantasy', 'Mystery'],
'world': ['History', 'Family', 'Biography'],
'ambient': ['Mystery', 'Sci-Fi', 'Animation'],
# Subgenres
'lo-fi beats': ['Drama', 'Romance', 'Animation'],
'vaporwave': ['Sci-Fi', 'Mystery', 'Animation'],
'emo': ['Drama', 'Romance', 'Mystery'],
'hardcore': ['Action', 'Thriller', 'War'],
'dubstep': ['Sci-Fi', 'Action', 'Thriller'],
'ska': ['Comedy', 'Family', 'Adventure'],
'swing': ['History', 'Romance', 'Family'],
'trance': ['Sci-Fi', 'Fantasy', 'Thriller'],
'grime': ['Action', 'Crime', 'Drama'],
'bluegrass': ['Family', 'History', 'Drama'],
'new wave': ['Drama', 'Sci-Fi', 'Mystery'],
'post-punk': ['Drama', 'Mystery', 'Thriller'],
'trip hop': ['Mystery', 'Drama', 'Sci-Fi'],
'neosoul': ['Drama', 'Romance', 'Family'],
'afrobeat': ['History', 'Drama', 'Family'],
'chillhop': ['Drama', 'Animation', 'Romance'],
'synthwave': ['Sci-Fi', 'Action', 'Drama']
}
# Using the genre mapping to find corresponding TV show genres
matching_genres_weighted = []
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for tvshow_genre in genre_mapping[spotify_genre]:
# Add the TV show genre according to its frequency
matching_genres_weighted.extend([tvshow_genre] * genre_count[spotify_genre])
# Read the CSV for TV Shows
df = pd.read_csv('/content/tvshowdata.csv')
# Make a copy of the original dataframe to avoid SettingWithCopyWarning
df_copy = df.copy()
# Convert "votes" to strings
df_copy['votes'] = df_copy['votes'].astype(str)
# Remove commas and convert to float
df_copy['votes'] = df_copy['votes'].str.replace(',', '').astype(float)
# Now, convert to integers, but only for non-NaN values
df_copy.loc[df_copy['votes'].notna(), 'votes'] = df_copy['votes'].dropna().astype(int)
# Convert 'genre' column to string type
df_copy['genre'] = df_copy['genre'].astype(str)
# Now proceed with the genre filtering
filtered_tvshows = df_copy[df_copy['genre'].str.split(', ').apply(lambda x: bool(set(x) & set(matching_genres_weighted)) if x != 'nan' else False)]
# Continue with the rating and votes filters
filtered_tvshows = filtered_tvshows[filtered_tvshows['rating'] >= 8]
filtered_tvshows = filtered_tvshows[filtered_tvshows['votes'] >= 20000]
# Recommend a TV show from the filtered shows based on the weighted genres
if filtered_tvshows.empty:
print("No TV shows found matching the criteria.")
else:
recommended_genre = random.choice(matching_genres_weighted)
recommended_show = filtered_tvshows[filtered_tvshows['genre'].str.contains(recommended_genre)].sample().iloc[0]
# Extract the earliest year from the 'year' column
# Extract the earliest year from the 'year' column and remove any preceding '-'
earliest_year = str(recommended_show['year']).split('–')[0].strip().replace('-', '')
print(f"Recommended TV Show: {recommended_show['title']} (Genre: {recommended_genre}, Rating: {recommended_show['rating']}, Release Year: {earliest_year.strip('()')})")
Run to view results
! pip install pandas
Run to view results
! pip install spotipy
Run to view results
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
import random
import ipywidgets as widgets
from IPython.display import display
# Spotify API Credentials
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost/'
# Create OAuth2 object
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
# Get the authorization URL
auth_url = sp_oauth.get_authorize_url()
print("Please go to the following URL to authorize:")
print(auth_url)
# Extract the code from the redirected URL
code = input("Enter the code from the URL (localhost/code='...'): ")
token = sp_oauth.get_access_token(code, as_dict=False)
sp = spotipy.Spotify(auth=token)
# Fetch user's top artists
top_artists = sp.current_user_top_artists()
# Count frequency of each genre
genre_count = {}
for artist in top_artists['items']:
for genre in artist['genres']:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
# Sort genres by frequency and get top 5
top_5_genres = sorted(genre_count, key=genre_count.get, reverse=True)[:5]
# Movie genre mapping
movie_genre_mapping = {
# Main genres
'pop': ['action', 'adventure', 'romance'],
'art pop': ['animation', 'fantasy', 'romance'],
'reggaeton': ['action', 'adventure'],
'urbano latino': ['action', 'adventure'],
'trap latino': ['crime', 'thriller'],
'rock': ['action', 'adventure', 'war'],
'indie rock': ['drama', 'romance', 'adventure'],
'classical': ['biography', 'history', 'romance'],
'hip hop': ['action', 'crime', 'drama'],
'jazz': ['film-noir', 'romance', 'biography'],
'country': ['family', 'romance', 'history'],
'electronic': ['sci-fi', 'mystery', 'thriller'],
'metal': ['action', 'horror', 'war'],
'folk': ['family', 'history', 'biography'],
'blues': ['drama', 'biography', 'film-noir'],
'r&b': ['drama', 'romance', 'crime'],
'soul': ['drama', 'family', 'romance'],
'punk': ['action', 'thriller', 'mystery'],
'disco': ['comedy', 'romance', 'family'],
'house': ['sci-fi', 'thriller', 'mystery'],
'techno': ['sci-fi', 'action'],
'edm': ['action', 'adventure', 'sci-fi'],
'latin': ['romance', 'family', 'adventure'],
'reggae': ['comedy', 'adventure', 'family'],
'funk': ['comedy', 'romance', 'action'],
'k-pop': ['romance', 'comedy', 'action'],
'psychedelic': ['animation', 'fantasy', 'mystery'],
'world': ['history', 'family', 'biography'],
'ambient': ['mystery', 'sci-fi', 'animation'],
# Subgenres
'lo-fi beats': ['drama', 'romance', 'animation'],
'vaporwave': ['sci-fi', 'mystery', 'animation'],
'emo': ['drama', 'romance', 'mystery'],
'hardcore': ['action', 'thriller', 'war'],
'dubstep': ['sci-fi', 'action', 'thriller'],
'ska': ['comedy', 'family', 'adventure'],
'swing': ['history', 'romance', 'family'],
'trance': ['sci-fi', 'fantasy', 'thriller'],
'grime': ['action', 'crime', 'drama'],
'bluegrass': ['family', 'history', 'drama'],
'new wave': ['drama', 'sci-fi', 'mystery'],
'post-punk': ['drama', 'mystery', 'thriller'],
'trip hop': ['mystery', 'drama', 'sci-fi'],
'neosoul': ['drama', 'romance', 'family'],
'afrobeat': ['history', 'drama', 'family'],
'chillhop': ['drama', 'animation', 'romance'],
'synthwave': ['sci-fi', 'action', 'drama']
}
# TV genre mapping
tv_genre_mapping = {
# Main genres
'pop': ['Action', 'Adventure', 'Romance'],
'art pop': ['Animation', 'Fantasy', 'Romance'],
'reggaeton': ['Action', 'Adventure'],
'urbano latino': ['Action', 'Adventure'],
'trap latino': ['Crime', 'Thriller'],
'rock': ['Action', 'Adventure', 'War'],
'indie rock': ['Drama', 'Romance', 'Adventure'],
'classical': ['Biography', 'History', 'Romance'],
'hip hop': ['Action', 'Crime', 'Drama'],
'jazz': ['Musical', 'Romance', 'Biography'],
'country': ['Family', 'Romance', 'History'],
'electronic': ['Sci-Fi', 'Mystery', 'Thriller'],
'metal': ['Action', 'Horror', 'War'],
'folk': ['Family', 'History', 'Biography'],
'blues': ['Drama', 'Biography', 'Music'],
'r&b': ['Drama', 'Romance', 'Crime'],
'soul': ['Drama', 'Family', 'Romance'],
'punk': ['Action', 'Thriller', 'Mystery'],
'disco': ['Comedy', 'Romance', 'Family'],
'house': ['Sci-Fi', 'Thriller', 'Mystery'],
'techno': ['Sci-Fi', 'Action'],
'edm': ['Action', 'Adventure', 'Sci-Fi'],
'latin': ['Romance', 'Family', 'Adventure'],
'reggae': ['Comedy', 'Adventure', 'Family'],
'funk': ['Comedy', 'Romance', 'Action'],
'k-pop': ['Romance', 'Comedy', 'Action'],
'psychedelic': ['Animation', 'Fantasy', 'Mystery'],
'world': ['History', 'Family', 'Biography'],
'ambient': ['Mystery', 'Sci-Fi', 'Animation'],
# Subgenres
'lo-fi beats': ['Drama', 'Romance', 'Animation'],
'vaporwave': ['Sci-Fi', 'Mystery', 'Animation'],
'emo': ['Drama', 'Romance', 'Mystery'],
'hardcore': ['Action', 'Thriller', 'War'],
'dubstep': ['Sci-Fi', 'Action', 'Thriller'],
'ska': ['Comedy', 'Family', 'Adventure'],
'swing': ['History', 'Romance', 'Family'],
'trance': ['Sci-Fi', 'Fantasy', 'Thriller'],
'grime': ['Action', 'Crime', 'Drama'],
'bluegrass': ['Family', 'History', 'Drama'],
'new wave': ['Drama', 'Sci-Fi', 'Mystery'],
'post-punk': ['Drama', 'Mystery', 'Thriller'],
'trip hop': ['Mystery', 'Drama', 'Sci-Fi'],
'neosoul': ['Drama', 'Romance', 'Family'],
'afrobeat': ['History', 'Drama', 'Family'],
'chillhop': ['Drama', 'Animation', 'Romance'],
'synthwave': ['Sci-Fi', 'Action', 'Drama']
}
def recommend(choice):
matching_genres_weighted = []
if choice == "movie":
genre_mapping = movie_genre_mapping
elif choice == "tvshow":
genre_mapping = tv_genre_mapping
else:
print("Invalid choice!")
return
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for corresponding_genre in genre_mapping[spotify_genre]:
matching_genres_weighted.extend([corresponding_genre] * genre_count[spotify_genre])
# Movie Filtering
if choice == "movie":
df = pd.read_csv('/content/combined_movies.csv', on_bad_lines='warn')
# Filtering criteria
df = df[df['rating'] >= 8]
df = df[df['votes'] >= 20000]
filtered_movies = df[df['genre'].isin(matching_genres_weighted)]
if filtered_movies.empty:
print("No movies found matching the criteria.")
else:
recommended_genre = random.choice(matching_genres_weighted)
recommended_movie = filtered_movies[filtered_movies['genre'] == recommended_genre].sample().iloc[0]
print(f"Recommended Movie: {recommended_movie['movie_name']} (Genre: {recommended_movie['genre'].capitalize()}, Rating: {recommended_movie['rating']}, Release Year: {recommended_movie['year']})")
# TV Show Filtering
elif choice == "tvshow":
df = pd.read_csv('/content/tvshowdata.csv', on_bad_lines='warn')
df_copy = df.copy()
df_copy['votes'] = df_copy['votes'].astype(str)
df_copy['votes'] = df_copy['votes'].str.replace(',', '').astype(float)
df_copy.loc[df_copy['votes'].notna(), 'votes'] = df_copy['votes'].dropna().astype(int)
df_copy['genre'] = df_copy['genre'].astype(str)
filtered_tvshows = df_copy[df_copy['genre'].str.split(', ').apply(lambda x: bool(set(x) & set(matching_genres_weighted)) if x != 'nan' else False)]
filtered_tvshows = filtered_tvshows[filtered_tvshows['rating'] >= 8]
filtered_tvshows = filtered_tvshows[filtered_tvshows['votes'] >= 20000]
if filtered_tvshows.empty:
print("No TV shows found matching the criteria.")
else:
recommended_genre = random.choice(matching_genres_weighted)
recommended_show = filtered_tvshows[filtered_tvshows['genre'].str.contains(recommended_genre)].sample().iloc[0]
earliest_year = str(recommended_show['year']).split('–')[0].strip().replace('-', '')
print(f"Recommended TV Show: {recommended_show['title']} (Genre: {recommended_genre}, Rating: {recommended_show['rating']}, Release Year: {earliest_year.strip('()')})")
def on_button_click(button):
choice = button.description.lower().replace(' ', '')
recommend(choice)
movie_button = widgets.Button(description="Movie")
tv_button = widgets.Button(description="TV Show")
movie_button.on_click(on_button_click)
tv_button.on_click(on_button_click)
# Display the buttons
display(movie_button, tv_button)
Run to view results
/movierecs
/templates
- index.html
- loginpage.html
- displayrecommendation.html
- displayhistory.html
- __pycache__
- .DS_Store
- .cache
- .env
- .gitignore
- LICENSE.md
- README.md
- Watchify.py
Run to view results
from flask import Flask, render_template, request, redirect, url_for, flash, session
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import pandas as pd
import random
app = Flask(__name__)
app.secret_key = 'SECRET_KEY'
SPOTIPY_CLIENT_ID = 'ecec60c9a316409a84a45c923f7473ee'
SPOTIPY_CLIENT_SECRET = '3129b9225476463d86ddc4074cfc8500'
SPOTIPY_REDIRECT_URI = 'http://localhost:5000/callback'
# Spotify session
sp = None
# Define functions provided in the earlier response
def get_user_top_genres(token, limit=50):
global sp
sp = spotipy.Spotify(auth=token)
results = sp.current_user_top_artists(limit=limit)
genres = []
for artist in results['items']:
genres.extend(artist['genres'])
return genres
def get_top_genres_and_counts(token, top_n=5):
genres = get_user_top_genres(token)
genre_counts = pd.Series(genres).value_counts()
top_5_genres = genre_counts.head(top_n).index.tolist()
return top_5_genres, genre_counts
def get_recommendation(genres_weighted):
return random.choice(genres_weighted)
# Movie genre mapping
movie_genre_mapping = {
# Main genres
'pop': ['action', 'adventure', 'romance'],
'art pop': ['animation', 'fantasy', 'romance'],
'reggaeton': ['action', 'adventure'],
'urbano latino': ['action', 'adventure'],
'trap latino': ['crime', 'thriller'],
'rock': ['action', 'adventure', 'war'],
'indie rock': ['drama', 'romance', 'adventure'],
'classical': ['biography', 'history', 'romance'],
'hip hop': ['action', 'crime', 'drama'],
'jazz': ['film-noir', 'romance', 'biography'],
'country': ['family', 'romance', 'history'],
'electronic': ['sci-fi', 'mystery', 'thriller'],
'metal': ['action', 'horror', 'war'],
'folk': ['family', 'history', 'biography'],
'blues': ['drama', 'biography', 'film-noir'],
'r&b': ['drama', 'romance', 'crime'],
'soul': ['drama', 'family', 'romance'],
'punk': ['action', 'thriller', 'mystery'],
'disco': ['comedy', 'romance', 'family'],
'house': ['sci-fi', 'thriller', 'mystery'],
'techno': ['sci-fi', 'action'],
'edm': ['action', 'adventure', 'sci-fi'],
'latin': ['romance', 'family', 'adventure'],
'reggae': ['comedy', 'adventure', 'family'],
'funk': ['comedy', 'romance', 'action'],
'k-pop': ['romance', 'comedy', 'action'],
'psychedelic': ['animation', 'fantasy', 'mystery'],
'world': ['history', 'family', 'biography'],
'ambient': ['mystery', 'sci-fi', 'animation'],
# Subgenres
'lo-fi beats': ['drama', 'romance', 'animation'],
'vaporwave': ['sci-fi', 'mystery', 'animation'],
'emo': ['drama', 'romance', 'mystery'],
'hardcore': ['action', 'thriller', 'war'],
'dubstep': ['sci-fi', 'action', 'thriller'],
'ska': ['comedy', 'family', 'adventure'],
'swing': ['history', 'romance', 'family'],
'trance': ['sci-fi', 'fantasy', 'thriller'],
'grime': ['action', 'crime', 'drama'],
'bluegrass': ['family', 'history', 'drama'],
'new wave': ['drama', 'sci-fi', 'mystery'],
'post-punk': ['drama', 'mystery', 'thriller'],
'trip hop': ['mystery', 'drama', 'sci-fi'],
'neosoul': ['drama', 'romance', 'family'],
'afrobeat': ['history', 'drama', 'family'],
'chillhop': ['drama', 'animation', 'romance'],
'synthwave': ['sci-fi', 'action', 'drama']
}
# TV genre mapping
tv_genre_mapping = {
# Main genres
'pop': ['Action', 'Adventure', 'Romance'],
'art pop': ['Animation', 'Fantasy', 'Romance'],
'reggaeton': ['Action', 'Adventure'],
'urbano latino': ['Action', 'Adventure'],
'trap latino': ['Crime', 'Thriller'],
'rock': ['Action', 'Adventure', 'War'],
'indie rock': ['Drama', 'Romance', 'Adventure'],
'classical': ['Biography', 'History', 'Romance'],
'hip hop': ['Action', 'Crime', 'Drama'],
'jazz': ['Musical', 'Romance', 'Biography'],
'country': ['Family', 'Romance', 'History'],
'electronic': ['Sci-Fi', 'Mystery', 'Thriller'],
'metal': ['Action', 'Horror', 'War'],
'folk': ['Family', 'History', 'Biography'],
'blues': ['Drama', 'Biography', 'Music'],
'r&b': ['Drama', 'Romance', 'Crime'],
'soul': ['Drama', 'Family', 'Romance'],
'punk': ['Action', 'Thriller', 'Mystery'],
'disco': ['Comedy', 'Romance', 'Family'],
'house': ['Sci-Fi', 'Thriller', 'Mystery'],
'techno': ['Sci-Fi', 'Action'],
'edm': ['Action', 'Adventure', 'Sci-Fi'],
'latin': ['Romance', 'Family', 'Adventure'],
'reggae': ['Comedy', 'Adventure', 'Family'],
'funk': ['Comedy', 'Romance', 'Action'],
'k-pop': ['Romance', 'Comedy', 'Action'],
'psychedelic': ['Animation', 'Fantasy', 'Mystery'],
'world': ['History', 'Family', 'Biography'],
'ambient': ['Mystery', 'Sci-Fi', 'Animation'],
# Subgenres
'lo-fi beats': ['Drama', 'Romance', 'Animation'],
'vaporwave': ['Sci-Fi', 'Mystery', 'Animation'],
'emo': ['Drama', 'Romance', 'Mystery'],
'hardcore': ['Action', 'Thriller', 'War'],
'dubstep': ['Sci-Fi', 'Action', 'Thriller'],
'ska': ['Comedy', 'Family', 'Adventure'],
'swing': ['History', 'Romance', 'Family'],
'trance': ['Sci-Fi', 'Fantasy', 'Thriller'],
'grime': ['Action', 'Crime', 'Drama'],
'bluegrass': ['Family', 'History', 'Drama'],
'new wave': ['Drama', 'Sci-Fi', 'Mystery'],
'post-punk': ['Drama', 'Mystery', 'Thriller'],
'trip hop': ['Mystery', 'Drama', 'Sci-Fi'],
'neosoul': ['Drama', 'Romance', 'Family'],
'afrobeat': ['History', 'Drama', 'Family'],
'chillhop': ['Drama', 'Animation', 'Romance'],
'synthwave': ['Sci-Fi', 'Action', 'Drama']
}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login')
def login():
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
auth_url = sp_oauth.get_authorize_url()
return render_template('loginpage.html', auth_url=auth_url)
@app.route('/callback')
def callback():
sp_oauth = SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
client_secret=SPOTIPY_CLIENT_SECRET,
redirect_uri=SPOTIPY_REDIRECT_URI,
scope=["user-top-read"])
token_info = sp_oauth.get_access_token(request.args['code'])
session['token'] = token_info['access_token']
return redirect(url_for('recommend'))
@app.route('/recommend', methods=['POST'])
def recommend():
choice = request.form.get('choice', None)
if not choice:
flash('Choice is missing!', 'danger')
return redirect(url_for('index'))
# Assuming top_5_genres and genre_count are computed based on the session['token']
top_5_genres, genre_count = get_top_genres_and_counts(session['token'])
matching_genres_weighted = []
if choice == "movie":
genre_mapping = movie_genre_mapping
elif choice == "tvshow":
genre_mapping = tv_genre_mapping
else:
flash('Invalid choice!', 'danger')
return redirect(url_for('index'))
for spotify_genre in top_5_genres:
if spotify_genre in genre_mapping:
for corresponding_genre in genre_mapping[spotify_genre]:
matching_genres_weighted.extend([corresponding_genre] * genre_count[spotify_genre])
# Create a result variable based on matching_genres_weighted
result = get_recommendation(matching_genres_weighted)
return render_template('displayrecommendation.html', recommendation=result)
if __name__ == '__main__':
app.run(debug=True)
Run to view results