I have a challenging project that I would like to complete.
Assume that we take any song (of around 2100 total) from the label NoCopyrightSounds, and look at the lyrics. If the starting song has lyrics, and they contain the name of any another song, we will move on to check the lyrics of the referenced song. We then search the lyrics of the referenced song to see if any other song name is referenced. The goal is to continue for as long as possible, in order to find the longest non-looping chain of song names referenced in the lyrics of other songs. When the chain ends, either because of a loop, because a song with no lyrics was found, or because a song where the lyrics don't contain the name of another song is found, a number of how many songs are in the chain will be assigned. It should be noted that some songs will reference multiple in their lyrics, and for this, there will be two results: The longest chain where we only look at the first song referenced in each of the lyrics, and the longest chain where we're allowed to check any song referenced in the lyrics.
For this project to start, we need to gather the lyrics of all of NCS songs. This can be done through the NCS wiki, which has a page for every song, and if applicable, the lyrics as well.
These pages contain links to every song, although duplicates may exist and have to be sorted through. Make sure to account for Fandom's pagination:
https://nocopyrightsounds.fandom.com/wiki/Category:NoCopyrightSounds_songshttps://nocopyrightsounds.fandom.com/wiki/Category:NCS_Arcade_songshttps://nocopyrightsounds.fandom.com/wiki/Category:Removed_songshttps://nocopyrightsounds.fandom.com/wiki/List_of_NCS_SoundCloud_promotions_by_date
The SoundCloud promotions isn't a category page and contains a table with these in the columns: The artist's name, the song's name, the release date, the proof of the promotion's existence.
The column with the artist's name (first column) contains an emoji which further categorises the type of promotion - we're looking to search the songs (second column) where the artist's name has a 🟡 (yellow circle) emoji next to it, which means "Deleted SoundCloud Exclusive release".
Anyway, the lyrics in every song page are in a template titled "Lyrics". They work with JavaScript as opposed to HTML (as I've heard) and may need a more advanced method to be scraped.
In order for the final program to work, some technicalities will have to be accounted for:
Some song titles replace "and" with "&" (On & On, Win & Lose), and so, any occurrence of "and" in any of the lyrics would have to checked both as "and" and "&" to ensure that no song names are missed.
This also applies for numbers (1 - one, 2 - two...), UK/American spelling of words, currency names and symbols, math names and symbols, punctuation names and symbols, etc.
All lyrics and song titles will have to be normalised to one common standard.
Provide a completed program that can fulfill these goals.
Assistant
Certainly! Let's build a Python program that fulfills your requirements. We'll approach this step by step:
Gather all NCS song titles and lyrics from the NCS Wiki, including handling pagination and special categories.
Extract and normalize the lyrics and song titles, accounting for variations such as "&" vs. "and", numbers in words and digits, UK/US spelling differences, symbols, etc.
Construct a graph where each song is a node, and edges exist to songs referenced in the lyrics.
Implement algorithms to find the longest non-looping chains based on your two criteria:
Considering only the first referenced song in the lyrics.
Considering any referenced song in the lyrics.
Handle loops and termination conditions (no lyrics, no song references, etc.).
Below is the complete Python program with comments explaining each part.
python
import requests
import re
import sys
from collections import deque, defaultdict
from urllib.parse import unquote
# Install 'mwparserfromhell' for parsing the wiki text
# You can install it via pip: pip install mwparserfromhell
import mwparserfromhell
# Step 1: Gather all song titles from the specified categories
def get_song_titles():
categories = [
"Category:NoCopyrightSounds_songs",
"Category:NCS_Arcade_songs",
"Category:Removed_songs"
]
base_url = "https://nocopyrightsounds.fandom.com"
song_titles = set()
# Helper function to fetch pages from a category
def fetch_category_members(category):
url = f"{base_url}/api.php"
params = {
"action": "query",
"list": "categorymembers",
"cmtitle": category,
"cmlimit": "500",
"format": "json",
"continue": ""
}
while True:
response = requests.get(url, params=params).json()
members = response.get('query', {}).get('categorymembers', [])
for member in members:
song_titles.add(member['title'])
if 'continue' in response:
params.update(response['continue'])
else:
break
# Fetch songs from categories
for category in categories:
fetch_category_members(category)
# Handle SoundCloud promotions
# Fetch the page content of "List of NCS SoundCloud promotions by date"
promotions_url = f"{base_url}/api.php"
params = {
"action": "parse",
"page": "List of NCS SoundCloud promotions by date",
"prop": "wikitext",
"format": "json"
}
response = requests.get(promotions_url, params=params).json()
wikitext = response['parse']['wikitext']['*']
wikicode = mwparserfromhell.parse(wikitext)
# Now parse the table and extract songs with 🟡 emoji
yellow_circle = "🟡"
for table in wikicode.filter_tags(matches=lambda node: node.tag == 'table'):
for tr in table.contents.filter_tags(matches=lambda node: node.tag == 'tr'):
td_list = tr.contents.filter_tags(matches=lambda node: node.tag == 'td')
if len(td_list) >= 2:
artist_td = str(td_list[0])
song_td = str(td_list[1])
if yellow_circle in artist_td:
# Extract song title
song_title = mwparserfromhell.parse(song_td).strip_code().strip()
if song_title:
song_titles.add(song_title)
return list(song_titles)
# Step 2: For each song, get the lyrics
def get_song_lyrics(song_titles):
base_url = "https://nocopyrightsounds.fandom.com"
song_lyrics = {}
no_lyrics_songs = set()
for title in song_titles:
# Fetch the page wikitext
page_url = f"{base_url}/api.php"
params = {
"action": "parse",
"page": title,
"prop": "wikitext",
"format": "json"
}
response = requests.get(page_url, params=params).json()
if 'error' in response:
continue # Page doesn't exist
wikitext = response['parse']['wikitext']['*']
wikicode = mwparserfromhell.parse(wikitext)
# Extract lyrics from the 'Lyrics' template
lyrics = None
for template in wikicode.filter_templates():
if template.name.strip().lower() == 'lyrics':
lyrics = template.get(1).value.strip_code().strip()
break
if lyrics:
song_lyrics[title] = lyrics
else:
no_lyrics_songs.add(title)
return song_lyrics, no_lyrics_songs
# Step 3: Normalize song titles and lyrics
def normalize_text(text):
# Convert to lowercase
text = text.lower()
# Replace '&' with 'and' and vice versa
text = text.replace('&', 'and')
# Replace numbers with words and vice versa
numbers = {
'0': 'zero',
'1': 'one',
'2': 'two',
'3': 'three',
'4': 'four',
'5': 'five',
'6': 'six',
'7': 'seven',
'8': 'eight',
'9': 'nine'
}
for num, word in numbers.items():
text = text.replace(num, word)
# Remove punctuation
text = re.sub(r'[^\w\s]', '', text)
# Handle UK/US spelling differences (simplified example)
uk_us_spelling = {
'colour': 'color',
'flavour': 'flavor',
'honour': 'honor',
'centre': 'center',
'theatre': 'theater',
'defence': 'defense',
'licence': 'license',
'offence': 'offense',
'pretence': 'pretense',
'analyse': 'analyze',
'brexit': 'brexit' # Add more as needed
}
for uk, us in uk_us_spelling.items():
text = text.replace(uk, us)
# Normalize whitespace
text = ' '.join(text.split())
return text
def normalize_songs_and_lyrics(song_lyrics):
normalized_song_titles = {}
for title in song_lyrics.keys():
normalized_title = normalize_text(title)
normalized_song_titles[normalized_title] = title
normalized_lyrics = {}
for title, lyrics in song_lyrics.items():
normalized_lyrics[title] = normalize_text(lyrics)
return normalized_song_titles, normalized_lyrics
# Step 4: Build a mapping from song titles to referenced songs
def build_song_graph(normalized_song_titles, normalized_lyrics):
song_graph = defaultdict(list)
song_titles_set = set(normalized_song_titles.keys())
for title, lyrics in normalized_lyrics.items():
normalized_title = normalize_text(title)
# Search for song titles in the lyrics
for song_title in song_titles_set:
if song_title != normalized_title and song_title in lyrics:
original_song_title = normalized_song_titles[song_title]
song_graph[title].append(original_song_title)
return song_graph
# Step 5: Implement the chain-finding algorithms
def find_longest_chain_first_reference(song_graph, song_lyrics):
longest_chain = []
visited_global = set()
for start_song in song_lyrics.keys():
chain = []
visited = set()
current_song = start_song
while True:
if current_song in visited or current_song not in song_graph:
break
visited.add(current_song)
chain.append(current_song)
visited_global.add(current_song)
references = song_graph[current_song]
if not references:
break
# Consider only the first referenced song
next_song = references[0]
current_song = next_song
if len(chain) > len(longest_chain):
longest_chain = chain
return longest_chain
def find_longest_chain_any_reference(song_graph, song_lyrics):
longest_chain = []
visited_global = set()
for start_song in song_lyrics.keys():
stack = [(start_song, [start_song], set([start_song]))]
while stack:
current_song, path, visited = stack.pop()
references = song_graph.get(current_song, [])
extended = False
for next_song in references:
if next_song not in visited:
extended = True
stack.append((next_song, path + [next_song], visited | set([next_song])))
if not extended:
if len(path) > len(longest_chain):
longest_chain = path
return longest_chain
# Step 6: Main execution
def main():
print("Fetching song titles...")
song_titles = get_song_titles()
print(f"Found {len(song_titles)} songs.")
print("Fetching song lyrics...")
song_lyrics, no_lyrics_songs = get_song_lyrics(song_titles)
print(f"Retrieved lyrics for {len(song_lyrics)} songs.")
print(f"{len(no_lyrics_songs)} songs have no lyrics.")
print("Normalizing song titles and lyrics...")
normalized_song_titles, normalized_lyrics = normalize_songs_and_lyrics(song_lyrics)
print("Building song graph...")
song_graph = build_song_graph(normalized_song_titles, normalized_lyrics)
print("Song graph constructed.")
print("Finding the longest chain (first reference)...")
longest_chain_first = find_longest_chain_first_reference(song_graph, song_lyrics)
print("Longest chain considering only the first referenced song:")
print(" -> ".join(longest_chain_first))
print(f"Length of chain: {len(longest_chain_first)}")
print("\nFinding the longest chain (any reference)...")
longest_chain_any = find_longest_chain_any_reference(song_graph, song_lyrics)
print("Longest chain considering any referenced song:")
print(" -> ".join(longest_chain_any))
print(f"Length of chain: {len(longest_chain_any)}")
if __name__ == "__main__":
main()
Explanation:
Step 1: Fetching Song Titles
Uses the MediaWiki API to fetch all pages in the specified categories.
Handles pagination (cmlimit and continue parameters).
Parses the "List of NCS SoundCloud promotions by date" page to extract songs with the 🟡 emoji.
Step 2: Fetching Song Lyrics
For each song title, fetches the wikitext of the page.
Parses the wikitext using mwparserfromhell to extract the lyrics from the {{Lyrics}} template.
Keeps track of songs without lyrics.
Step 3: Normalizing Text
Defines a normalize_text function to standardize song titles and lyrics.
Accounts for "&" vs. "and", numbers as words and digits, UK/US spelling variations, and removes punctuation.
Converts text to lowercase and normalizes whitespace.
Step 4: Building the Song Graph
Constructs a mapping where each song points to songs that are referenced in its lyrics.
Uses the normalized lyrics and song titles for matching.
Avoids self-references.
Step 5: Finding the Longest Chains
find_longest_chain_first_reference considers only the first referenced song in the lyrics.
find_longest_chain_any_reference allows following any referenced song, exploring all possible paths using DFS.
Both functions avoid loops by keeping track of visited songs.
Step 6: Main Execution
Orchestrates the workflow, calling each function in order.
Prints out the longest chains found, along with their lengths.
Requirements:
Python 3 is required to run this program.
Install the required Python libraries:
requests for making HTTP requests.
mwparserfromhell for parsing MediaWiki wikitext.
Install via pip install mwparserfromhell
Running the Program:
Install the required libraries:
bash
pip install requests mwparserfromhell
Run the script:
bash
python ncs_chain_finder.py
Notes:
Performance:
Fetching data from the API may take some time due to the number of songs and network latency.
Parsing and normalizing large amounts of text can be resource-intensive.
Extensibility:
The normalization function can be extended to handle more cases (e.g., additional spelling variations, more symbols).
Error handling can be improved to handle network issues or changes in the wiki's structure.
Limitations:
The program assumes that song titles and lyrics are in English.
The matching is based on simple substring checks; more sophisticated methods (like regex or fuzzy matching) could be implemented for better accuracy.
Conclusion:
This program should fulfill your requirements by automating the process of finding the longest chain of referenced songs in the NCS catalog, considering the complexities of data extraction and normalization. Remember to comply with any terms of use or scraping policies of the NCS Wiki when running this script.