This is an ambitious and interesting project that combines web scraping, text processing, and graph traversal algorithms. Below, I'll outline a plan to help you achieve your goal, addressing each of the challenges you've mentioned.
1. Gathering the List of NCS Songs
Firstly, you need to compile a comprehensive list of all songs released by NoCopyrightSounds (NCS), including those that have been deleted or are only available on SoundCloud.
Sources to Scrape:
-
Category Pages:
Be aware that these category pages have pagination, so you'll need to iterate through all pages to gather the full list.
-
SoundCloud Promotions:
Focus on the entries where the artist's name is preceded by a 🟡 (yellow circle) emoji, which denotes "Deleted SoundCloud Exclusive release."
Approach:
-
Web Scraping Tools: Use a library like requests (for basic HTTP requests) and BeautifulSoup (for HTML parsing) in Python. Since some pages might require JavaScript to fully render content (more on this later), you might need more advanced tools.
-
Handling Pagination: Check the HTML structure to find the pagination links and iterate through them programmatically.
-
Data Extraction: For each song, extract:
- Song Title
- Artist Name
- Link to the song's page on the NCS wiki
2. Scraping the Lyrics
The NCS wiki includes lyrics in a template titled "Lyrics," which may rely on JavaScript for rendering. Since requests and BeautifulSoup cannot execute JavaScript, you'll need a tool that can render JavaScript content.
Options:
-
Selenium: Automates web browsers and can execute JavaScript. Good for complex interactions but can be slower.
-
Headless Browsers:
- Headless Chrome with Puppeteer (Node.js): Allows you to control Chrome programmatically.
- Playwright (Python/Node.js): Can automate Chromium, Firefox, and WebKit with a single API.
-
Requests-HTML: A Python library that combines requests with the ability to render JavaScript.
Recommended Approach:
Use Playwright with Python for efficient scraping:
from playwright.sync_api import sync_playwright
def scrape_lyrics(song_url):
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(song_url)
# Wait for the lyrics content to load
page.wait_for_selector('.lyricsbox')
# Extract lyrics text
lyrics = page.inner_text('.lyricsbox')
browser.close()
return lyrics
Note: The CSS selector .lyricsbox is hypothetical—you'll need to inspect the page to find the correct selector.
3. Normalizing Song Titles
Song titles can have variations due to symbols, numbers, spelling differences, etc. Before matching song titles within lyrics, normalize both song titles and lyrics.
Normalization Steps:
-
Convert to Lowercase: Makes matching case-insensitive.
-
Replace Symbols:
- Replace "&" with "and" and vice versa.
- Replace numbers with their word equivalents and vice versa (e.g., "4" ↔ "four").
- Use the
inflect library in Python to convert numbers to words.
-
Handle Spelling Variations:
- Use a library like
pyenchant or textblob to detect and convert between UK and US spellings.
- Create a mapping of common spelling variations.
-
Remove Punctuation: Strip out punctuation symbols unless they are significant in song titles.
-
Currency Symbols: Map symbols to words (e.g., "$" to "dollar").
Example Normalization Function:
import re
import inflect
def normalize_text(text):
p = inflect.engine()
# Convert to lowercase
text = text.lower()
# Replace "&" with "and" and vice versa
text = text.replace("&", " and ").replace(" and ", " & ")
# Replace numbers with words
text = re.sub(r'\b\d+\b', lambda x: p.number_to_words(x.group()), text)
# Handle spelling variations (you may need a custom mapping)
# Example: 'colour' to 'color'
spelling_variations = {'colour': 'color', 'organisation': 'organization'}
for uk_spelling, us_spelling in spelling_variations.items():
text = text.replace(uk_spelling, us_spelling)
# Remove punctuation
text = re.sub(r'[^\w\s]', '', text)
return text
4. Building a Searchable Song Title Database
After normalization, build a searchable database (e.g., a Python dictionary or a more advanced data structure like a trie) of all song titles.
Example:
song_titles = ['on and on', 'run away', 'one for all']
normalized_titles = {normalize_text(title): title for title in song_titles}
5. Parsing Lyrics to Find Song References
For each song's lyrics:
-
Normalize the lyrics text using the same function used for song titles.
-
Tokenization:
- Split the lyrics into words or n-grams (groups of words).
- Consider sliding windows of words to match multi-word song titles.
-
Matching:
- Check if any of the normalized phrases in the lyrics match normalized song titles in your database.
- Keep track of all matches found.
Example Matching Function:
def find_song_references(lyrics, normalized_titles):
words = lyrics.split()
references = set()
max_title_length = max(len(title.split()) for title in normalized_titles.keys())
for i in range(len(words)):
for j in range(1, max_title_length + 1):
phrase = ' '.join(words[i:i+j])
if phrase in normalized_titles:
references.add(normalized_titles[phrase])
return references
6. Building the Chains
Model the songs and their references as a directed graph where nodes are songs and edges represent a reference from one song to another in the lyrics.
Approach:
- Graph Representation: Use a dictionary to represent the adjacency list of the graph.
graph = {}
for song in all_songs:
lyrics = scrape_lyrics(song.url)
normalized_lyrics = normalize_text(lyrics)
references = find_song_references(normalized_lyrics, normalized_titles)
graph[song.title] = references
-
Chain Construction:
-
Loop Detection:
- Keep a visited set during traversal to avoid cycles.
-
Termination Conditions:
- No further song references.
- A song with no lyrics.
- A song already in the current chain (to prevent loops).
Example DFS for Mode 2:
def dfs(current_song, visited, path):
visited.add(current_song)
path.append(current_song)
max_chain = list(path)
for neighbor in graph.get(current_song, []):
if neighbor not in visited:
new_chain = dfs(neighbor, visited.copy(), path.copy())
if len(new_chain) > len(max_chain):
max_chain = new_chain
return max_chain
Finding the Longest Chain:
Iterate through each song and perform DFS to find the longest chain starting from that song.
longest_chain = []
for song in all_songs:
chain = dfs(song.title, set(), [])
if len(chain) > len(longest_chain):
longest_chain = chain
7. Handling Multiple References (Branching Paths)
In Mode 2, where multiple references are allowed, the problem resembles finding the longest path in a directed acyclic graph (DAG), which is an NP-hard problem. However, since the graph is likely not huge (around 2100 songs), a DFS approach is feasible.
Optimizations:
-
Memoization: Store the longest path from each node to avoid redundant calculations.
-
Pruning: If the current path length plus the maximum possible remaining length is less than the current longest chain, prune the search.
8. Dealing with Technicalities and Edge Cases
-
Duplicate Song Titles: Ensure that each song title maps to a unique song. If there are duplicate titles, include the artist name or a unique identifier.
-
Special Characters and Symbols in Lyrics: Ensure that the normalization process accounts for all possible variations.
-
Songs Without Lyrics: For songs without lyrics, store an empty string or skip them during the lyrics scraping phase.
9. Testing and Verification
-
Sample Data: Test your code with a small subset of songs to ensure that the normalization and matching are working correctly.
-
Manual Verification: Manually check some of the chains found to verify their correctness.
10. Ethical and Legal Considerations
-
Respect Copyright: While scraping lyrics for analysis may fall under fair use, ensure that you are compliant with the website's terms of service and relevant laws.
-
Data Use: Use the data responsibly and avoid distributing the scraped lyrics.
Conclusion
By following this plan, you should be able to collect all the necessary data, process it appropriately, and find the longest non-looping chains of song references within the NCS catalog. This project involves several complex steps, but breaking it down and tackling each challenge methodically will make it manageable.
Tools and Libraries Recommended:
-
Python Libraries:
requests or aiohttp for HTTP requests
BeautifulSoup for HTML parsing
Playwright for JavaScript rendering
re for regular expressions
inflect for number-to-word conversion
networkx for graph representation and traversal (optional)
-
Node.js Alternative:
- Use Puppeteer for web scraping if you prefer JavaScript over Python.
Next Steps:
-
Set up your development environment with the necessary libraries.
-
Start by implementing the song list extraction and lyrics scraping.
-
Proceed to normalize song titles and lyrics.
-
Build the matching and traversal algorithms.
-
Test your implementation thoroughly with subsets of data.
Remember to document your code and process, which will help in debugging and future enhancements. Good luck with your project!