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)
Assistant
User
It works and I've noticed that:
Song titles include parentheses which aren't necessary, such as when they're remixed, or the artist's name when the song name is used by multiple other songs.
The lyrics file only contains the first line which implies that the entire lyrics aren't being searched through.
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',
'labour': 'labor',
'centre': 'center',
'theatre': 'theater',
'metre': 'meter',
'defence': 'defense',
'licence': 'license',
'offence': 'offense',
'pretence': 'pretense',
'analyse': 'analyze',
'realise': 'realize',
'recognise': 'recognize',
'paralyse': 'paralyze',
'dialogue': 'dialog',
'catalogue': 'catalog',
'programme': 'program',
'aeroplane': 'airplane',
'cheque': 'check',
'jewellery': 'jewelry',
'plough': 'plow',
'savoury': 'savory',
'tyre': 'tire',
'aluminium': 'aluminum',
'favour': 'favor',
'humour': 'humor',
'labourer': 'laborer',
'mould': 'mold',
'sceptical': 'skeptical',
'specialise': 'specialize',
'theorise': 'theorize',
'brexit': 'brexit'
}
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
code
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
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
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
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
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()
I have this program here. I need to add a function that saves all scraped information locally for future use, to save time and also to avoid frequently sending requests to the servers of the scraped site.
To efficiently store and retrieve scraped information locally, you can use a simple solution such as saving the data in JSON format. This will allow your program to avoid re-fetching data if it has already been retrieved and stored. Here's how you can implement this:
Save the scraped data to local JSON files.
Load the data from these files at the start of your program, if available.
Below, I'll walk you through the modifications needed to implement this feature in your existing program.
Step 1: Save Data Locally
Add functions to save the song titles and lyrics to JSON files:
python
import json
import os
def save_to_json(data, filename):
"""Saves data to a JSON file."""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
def load_from_json(filename):
"""Loads data from a JSON file."""
if os.path.exists(filename):
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
return None
Step 2: Modify get_song_titles and get_song_lyrics Functions
Update these functions to use the local JSON files, if they exist, instead of sending requests every time.
python
def get_song_titles():
# Check if we have cached data
cached_titles = load_from_json('song_titles.json')
if cached_titles is not None:
return cached_titles
# [Your existing code for fetching song titles]
# Save the song titles to a file
save_to_json(list(song_titles), 'song_titles.json')
return list(song_titles)
def get_song_lyrics(song_titles):
# Check if we have cached data
cached_lyrics = load_from_json('song_lyrics.json')
cached_no_lyrics = load_from_json('no_lyrics_songs.json')
if cached_lyrics is not None and cached_no_lyrics is not None:
return cached_lyrics, set(cached_no_lyrics)
# [Your existing code for fetching song lyrics]
# Save the song lyrics to files
save_to_json(song_lyrics, 'song_lyrics.json')
save_to_json(list(no_lyrics_songs), 'no_lyrics_songs.json')
return song_lyrics, no_lyrics_songs
Step 3: Integrate In Main
Ensure these checks and file operations are integrated into your main() function without any modifications, since the changes are already encapsulated within the modified functions. Here’s how you can start executing the updated functions:
python
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.")
# [Rest of your existing code in main function]
Summary
By saving the data to JSON files and checking for the existence of these files before making network requests, your program will become more efficient and considerate of server resources. This also allows for faster start-up times when local data is already available. If needed, you can extend this solution with data expiry logic to ensure freshness (e.g., by checking timestamps or versions), but even a basic implementation like this greatly improves efficiency.
To address the issues you've mentioned, we'll need to modify two parts of your implementation:
Remove Unnecessary Parentheses from Song Titles:
We should clean the song titles by removing any extra information enclosed in parentheses. This typically includes remix details or artist names that are not necessary for identifying the title itself.
Ensure Entire Lyrics are Extracted:
For the song lyrics, we'll need to make sure that we're correctly parsing the entire content of the Lyrics template. It's possible that your current parsing approach only retrieves the first line, so we'll adjust the parsing logic accordingly.
Step 1: Clean Song Titles
To remove unnecessary parts from song titles, we can utilize regular expressions to strip content within parentheses and restructure the normalize_text function accordingly.
python
def clean_song_title(title):
"""Remove parentheses and their content from song titles."""
# Use regex to remove text within parentheses
cleaned_title = re.sub(r'\(.*?\)', '', title)
# Trim any leading or trailing whitespace
return cleaned_title.strip()
# Modify normalize_text or wherever you're using titles to apply cleaning:
def normalize_text(text):
text = text.lower()
# Clean out parenthetical content, apply to titles specifically
text = clean_song_title(text)
...
return text
Step 2: Ensure Lyrics Template is Fully Parsed
Make sure we are extracting complete lyrics from the Lyrics template within the Wikipedia page content. You can adjust your existing logic to confirm you're capturing the full content.
python
def get_song_lyrics(song_titles):
base_url = "https://nocopyrightsounds.fandom.com"
song_lyrics = {}
no_lyrics_songs = set()
for title in song_titles:
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)
lyrics = None
for template in wikicode.filter_templates():
if template.name.strip().lower() == 'lyrics':
lyrics = template.get(0).value.strip() # Ensure extracting entire data
break
if lyrics:
song_lyrics[title] = lyrics
else:
no_lyrics_songs.add(title)
return song_lyrics, no_lyrics_songs
Apply Changes in Main Execution
With these changes, ensure when normalizing the text or when processing lyrics in your main application logic, these modifications are used.
The clean_song_title method is applied in sequence where you handle titles for normalization or when building your song graph, while parsing adjustments should ensure capturing the full song lyrics.
Summary
By cleaning up the song titles and ensuring the full lyrics are extracted, your program becomes more accurate in processing and subsequently analyzing the data. It's important to test these changes to make sure that they work with the data format as expected. If you find specific cases where parsing still isn't correct, additional adjustments in regular expressions or parsing logic might be necessary.