I need to make a series of YouTube playlists that categorises every NoCopyrightSounds release, including old and removed ones, by genre.
Luckily, this doesn't have to be manual. The fandom wiki for NoCopyrightSounds has a page for every confirmed song and categorises them by genre.
To accomplish my goal, I need the following steps.
Step 1. Compile Info
I need a program that can scrape these pages:
https://nocopyrightsounds.fandom.com/wiki/Category:NoCopyrightSounds_songshttps://nocopyrightsounds.fandom.com/wiki/Category:NCS_Arcade_songshttps://nocopyrightsounds.fandom.com/wiki/List_of_NCS_SoundCloud_promotions_by_date
The SoundCloud promotions page is messier because it is not a category page. It contains a table with the artists name first, the song name second, the release date third, and proof of the promotion last.
The artists name table contains an emoji that categorises the promotion further - we're looking to search the songs where the artist name has a 🟡 emoji next to it, which symbolises that the song is a "Deleted SoundCloud Exclusive release". Keep in mind that this emoji is used in the artists name box in the table, and so, to enter the song's page, you'd have to click the hyperlink on the second box, which would be the song name.
All of the pages in the first two links should be scraped for a YouTube link (or YouTube Music with the url replaced if there is no normal one) and sorted by release date, alongside the ones in the SoundCloud releases page. All of this will be put in a CSV file. If there is no YouTube link, the song will still be entered, but with no link. Only links from info boxes should be scraped.
Since the SoundCloud pages won't have YouTube links, they'll be in the text file with no link for me to find remakes of on YouTube.
Now, with the full CSV file with every artist name (in the info box), song name (the title of the page), release date (info box), YouTube link (info box or self added), the wiki page link itself, and the community genres and subgenres of the song (info box), the next step starts.
Step 2. Add to playlists
Another program should place all of these songs in their corresponding genre playlists by date, on YouTube, using Selenium and a Chrome driver. Some songs will be put in several playlists since they'll have several genres. There are some instances where the umbrella terms of some genres are genres of their own. For example, drumstep (genre) and melodic drumstep (subgenre) would normally be put in the same playlist automatically named "Drumstep" (umbrella term), but I need logic that puts drumstep (genre - not the umbrella term) in its own playlist as well ("Drumstep"), rather than always together with the melodic drumstep (the umbrella term playlist which should be called "All Drumstep"). This should apply for other similar genres where the umbrella term is also its own genre. The prefix for all the playlists should be "NCS - ".
Assistant
Step 3. Update and upkeep
Opinions change and new songs release over time, so there needs to be a script that handles updating. Rescraping all of the Fandom pages to note any genre changes and add in the new songs and their details (this excludes SoundCloud promotions which are now defunct, thankfully). The script should then automatically move the songs that need be moved, placing them in the appropriate, release date accurate spot, also adding in the new releases.
Here's an entire song page for reference. They all have the same structure. Some genre labels are separated with a "|" rather than having their own unique entry which needs to be accounted for.
{{Infobox song
|Image = Back On Dash.jpg
|Artist = [[DJVI]]
|Remix =
|Featuring =
|Uncredited =
|Album =
|Brand = NoCopyrightSounds
|Released = November 8, 2024
|Genre = {{Subgenre|House|Progressive House}}
|Community Genre = {{Genre|House|verified}}
|Subgenre(s) = {{Subgenre|House|Commercial House}}
|Mood(s) = *{{Mood|Energetic}}
*{{Mood|Exciting}}
*{{Mood|Positive}}
|Length = 3:06
|Catalog Number = N/A
|BPM = 138
|Key = G minor
|Background = Back on Dash BG
|Amazon Music = B0DKLDYDXS
|Anghami = 1182859030
|Apple Music = 1775735684?i=1775735686
|Beatport =
|Deezer = track/3057282571
|NCS = backondash
|Pandora = djvi/back-on-dash/ALZ2rtrPPpthbv6
|SoundCloud = nocopyrightsounds/djvi-back-on-dash-geometry-dash
|Spotify = track/66i7MyCc1Tq4iGZxxHOCej
|Tidal = 395013787
|YouTube = VDbVXpJWA-k
|YouTube Music = RYdNsUZ9LyI
}}'''Back on Dash''' is a song by [[DJVI]] released on November 8, 2024. It was uploaded by NCS on YouTube on November 9, 2024.
==Trivia==
*This track is the third part of DJVI's original track, [https://www.youtube.com/watch?v=N9vDTYZpqXM Back On Track].
*The circle visualizer switches over to a square visulizer between 0:14 and 1:15 of the YouTube upload.
**This is the first upload to feature a rounded square visualizer.
{{DJVI}}
{{2024}}
[[Category:Commercial House music]]
That sounds like an exciting project! I'll help you break down each step and provide guidance on how to achieve your goal. We'll go through each of the three steps you've outlined, discussing the best approaches, tools, and methodologies to accomplish them.
Step 1: Compile Info
Objective:
Scrape data from specific pages on the NoCopyrightSounds Fandom wiki, extract detailed song information, and compile it into a CSV file.
Approach:
Choose a Web Scraping Framework:
Python Libraries:requests, BeautifulSoup, and pandas are ideal for this task.
Advantages:
requests handles HTTP requests.
BeautifulSoup parses HTML content.
pandas manages data structures and CSV files.
Understand the Structure of the Wiki Pages:
Category Pages: Lists of songs linking to individual song pages.
Song Pages: Contain infoboxes with song details in a consistent template format.
SoundCloud Promotions Page: A table with additional annotations.
Identify rows where the artist's name cell contains the 🟡 emoji.
Extract the song name from the second cell.
Extract Song Data from Each Song Page:
Data to Extract:
Artist Name: From the infobox (Artist field).
Song Name: Title of the page.
Release Date: From the infobox (Released field).
YouTube Link: From the infobox (YouTube or YouTube Music fields).
If only YouTube Music is available, modify the URL to match standard YouTube links.
Wiki Page Link: The URL of the song's wiki page.
Genres and Subgenres:
From the infobox (Community Genre and Subgenre(s) fields).
Handle multiple genres separated by |.
Method:
Parse the infobox using regex or an HTML parser.
Handle inconsistencies, such as missing fields or different delimiters.
Handle Non-Standard Cases:
Songs Without YouTube Links:
Leave the YouTube link field empty.
Mark for manual review to find remakes or alternate sources.
Special Characters and Emojis:
Ensure the parser correctly interprets emojis, especially on the SoundCloud promotions page.
Compile Data into a CSV File:
Columns:
Artist Name, Song Name, Release Date, YouTube Link, Wiki Page Link, Genres, Subgenres.
Method:
Use pandas to create a DataFrame and export to CSV.
Ensure proper encoding (e.g., UTF-8) to handle special characters.
Sample Code Outline:
python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
# Initialize an empty list to store song data
songs_data = []
# Function to scrape category pages
def scrape_category(url):
# Implement pagination handling
while url:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Find all song links on the page
song_links = soup.find_all('a', href=re.compile('/wiki/[^:]*$'))
for link in song_links:
song_url = 'https://nocopyrightsounds.fandom.com' + link['href']
scrape_song_page(song_url)
# Check for next page
next_page = soup.find('a', text='next page')
url = 'https://nocopyrightsounds.fandom.com' + next_page['href'] if next_page else None
# Function to scrape the SoundCloud promotions page
def scrape_soundcloud_promotions(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')[1:] # Skip header
for row in rows:
cells = row.find_all('td')
artist_cell = cells[0]
if '🟡' in artist_cell.get_text():
song_link = cells[1].find('a')
if song_link:
song_url = 'https://nocopyrightsounds.fandom.com' + song_link['href']
scrape_song_page(song_url)
# Function to scrape individual song pages
def scrape_song_page(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Parse the infobox
infobox = soup.find('table', class_='infobox')
if not infobox:
return
data = {}
data['Wiki Page Link'] = url
data['Song Name'] = soup.find('h1').text.strip()
rows = infobox.find_all('tr')
for row in rows:
header = row.find('th')
value = row.find('td')
if header and value:
key = header.text.strip()
val = value.text.strip()
data[key] = val
# Process data as needed
# Append to songs_data
songs_data.append(data)
# Run the scraping functions
scrape_category('https://nocopyrightsounds.fandom.com/wiki/Category:NoCopyrightSounds_songs')
scrape_category('https://nocopyrightsounds.fandom.com/wiki/Category:NCS_Arcade_songs')
scrape_soundcloud_promotions('https://nocopyrightsounds.fandom.com/wiki/List_of_NCS_SoundCloud_promotions_by_date')
# Convert to DataFrame and export to CSV
df = pd.DataFrame(songs_data)
df.to_csv('ncs_songs.csv', index=False, encoding='utf-8')
Note: This is a simplified outline. The actual implementation will need to handle various edge cases and ensure robust error handling.
Step 2: Add to Playlists
Objective:
Automatically add songs to their corresponding genre-specific playlists on YouTube, handling songs with multiple genres and umbrella terms.
Approach:
YouTube Data API vs. Selenium:
YouTube Data API:
Preferred method for interacting with YouTube programmatically.
Requires obtaining API credentials and handling quotas.
Limitations on operations per day.
Selenium and ChromeDriver:
Automates browser actions.
More flexible but can be less reliable due to dynamic page content and potential for being detected as a bot.
Recommend Using YouTube Data API:
Advantages:
Official and less likely to violate YouTube's terms of service.
More efficient and faster than browser automation.
Setup:
Register your application in the Google Developers Console.
Obtain OAuth 2.0 credentials.
Follow the OAuth consent flow to authorize the application.
Processing the CSV File:
Read the CSV file into a pandas DataFrame.
Iterate over each song and its associated genres.
Playlist Management Logic:
Playlist Naming Convention:
Prefix: NCS -
Examples: NCS - Drumstep, NCS - All Drumstep
Handling Genres and Subgenres:
Create a mapping between genres, subgenres, and umbrella terms.
Identify when a genre is both an umbrella term and a specific genre.
Adding Songs to Playlists:
For each song, determine all applicable playlists.
Use the YouTube API to add the song to these playlists.
Ensure that the song is placed in the correct position based on the release date.
Example Genre Handling:
Genre: Drumstep
Subgenres: Melodic Drumstep, Heavy Drumstep
Playlists:
NCS - Drumstep (for songs specifically labeled as Drumstep)
NCS - Melodic Drumstep
(includes all subgenres and Drumstep itself)
Sample Code Outline Using YouTube Data API:
python
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
import pandas as pd
import datetime
# Set up YouTube API credentials
scopes = ["https://www.googleapis.com/auth/youtube"]
flow = InstalledAppFlow.from_client_secrets_file('client_secrets.json', scopes)
credentials = flow.run_console()
youtube = build('youtube', 'v3', credentials=credentials)
# Read the CSV file
df = pd.read_csv('ncs_songs.csv')
# Function to get or create a playlist
def get_or_create_playlist(playlist_name):
# Search for existing playlists
# If exists, return playlist ID
# If not, create a new playlist and return its ID
pass
# Function to add a song to a playlist
def add_song_to_playlist(playlist_id, video_id, position):
# Use the YouTube API to add the video to the playlist at the specified position
pass
# Process each song
for index, row in df.iterrows():
video_id = extract_video_id(row['YouTube Link'])
# Skip if no video ID
if not video_id:
continue
release_date = datetime.datetime.strptime(row['Release Date'], '%B %d, %Y')
genres = row['Genres'].split('|') # Assuming genres are pipe-separated
subgenres = row['Subgenres'].split('|') if pd.notna(row['Subgenres']) else []
# Determine playlists
playlists = determine_playlists(genres, subgenres)
for playlist_name in playlists:
full_playlist_name = f'NCS - {playlist_name}'
playlist_id = get_or_create_playlist(full_playlist_name)
# Determine position based on release date
position = determine_position_in_playlist(playlist_id, release_date)
add_song_to_playlist(playlist_id, video_id, position)
Note: The above code outline contains placeholders (pass) where you'd need to implement the actual logic.
Step 3: Update and Upkeep
Objective:
Maintain the accuracy of playlists by updating them when genres change or new songs are released.
Approach:
Periodic Rescraping:
Schedule the scraping script to run regularly (e.g., daily, weekly).
Compare the newly scraped data with the existing CSV to detect changes.
Detecting Genre Changes:
Method:
Load the existing CSV and the new data into DataFrames.
Merge them on a unique identifier (e.g., Song Name and Artist Name).
Identify rows where the genre fields have changed.
Action:
Update playlists by removing the song from old genres and adding it to new ones.
Adding New Songs:
Identify songs that are in the new data but not in the existing CSV.
Process them as in Step 2, adding them to the appropriate playlists.
Removing Defunct Songs:
Detect songs that no longer appear on the wiki.
Optionally, remove them from playlists or mark them for review.
Automating Playlist Updates:
For each detected change, use the YouTube API to update playlists accordingly.
Handle deletions, insertions, and reordering based on release dates.
Logging and Notifications:
Keep logs of changes made for auditing purposes.
Optionally, send notifications when significant changes occur.
Best Practices:
Backup Playlists:
Periodically export playlist data to prevent data loss.
Respect API Usage Limits:
Monitor API quotas and implement exponential backoff in case of rate limiting.
Error Handling:
Implement retries and exception handling for network issues.
Implementing the Update Script:
Comparing DataFrames:
python
old_df = pd.read_csv('ncs_songs.csv')
new_df = pd.read_csv('ncs_songs_new.csv')
# Merge dataframes to find changes
merged_df = old_df.merge(new_df, on=['Song Name', 'Artist Name'], how='outer', indicator=True)
# Songs only in new data (new songs)
new_songs = merged_df[merged_df['_merge'] == 'right_only']
# Songs only in old data (potentially removed songs)
removed_songs = merged_df[merged_df['_merge'] == 'left_only']
# Songs present in both, check for genre changes
common_songs = merged_df[merged_df['_merge'] == 'both']
genre_changes = common_songs[common_songs['Genres_x'] != common_songs['Genres_y']]
Updating Playlists:
For New Songs:
Process as per Step 2 to add to playlists.
For Removed Songs:
Optionally remove from playlists or review manually.
For Genre Changes:
Remove the song from old playlists.
Add to new playlists based on updated genres.
Automating the Script:
Use a task scheduler (e.g., cron on Unix systems) to run the script at set intervals.
Ensure credentials are securely stored and refreshed as needed.
Additional Considerations
Handling Edge Cases in Genres:
Parsing Genres:
When genres are separated by |, split them correctly.
Account for genres with nested subgenres.
Umbrella Terms:
Create a hierarchy or mapping of genres to umbrella terms.
Decide whether to create both specific and umbrella playlists.
Compliance with YouTube's Terms of Service:
Respect User Policies:
Ensure that the use of the YouTube API complies with YouTube's terms.
Avoid excessive automation that may be flagged as spam.
OAuth Consent:
Make sure to handle user authentication securely.
Store sensitive data, such as tokens, securely.
Optimizing Performance:
Caching Playlist IDs:
Store playlist IDs locally to reduce API calls.
Batch API Requests:
Where possible, use batch requests to increase efficiency.
Summary
By systematically approaching each step, utilizing appropriate tools, and carefully handling data, you can achieve your goal of creating and maintaining genre-specific YouTube playlists for NoCopyrightSounds releases.
Step 1: Use web scraping tools to compile song data into a CSV file.
Step 2: Use the YouTube Data API to automate adding songs to playlists based on genre logic.
Step 3: Implement an update script to handle changes over time, keeping playlists current.
If you need further assistance with specific parts of the implementation or have questions about handling particular scenarios, feel free to ask!
Not yet included in a published release.
NCS - All Drumstep
Implementing the Logic:
Create Playlists If Not Exist:
Check if the playlist exists using the YouTube API.
If not, create it.
Adding to Multiple Playlists:
For songs with multiple genres, add them to each relevant playlist.
Ordering Songs by Release Date:
Retrieve the playlist items.
Insert the new song at the correct position.
Potential Challenges:
Rate Limits:
YouTube API has quotas; plan to handle them appropriately.
Error Handling:
Implement robust error handling for API calls.
Authentication:
Refresh tokens as needed to maintain authorization.