Close

Creating a Python script

A project log for SpinLast

Automatically scrobble your favorite radio tracks from Spinitron.com to last.fm

mx-jack-nelsonMx. Jack Nelson 04/24/2023 at 22:430 Comments

This Python script is designed to automatically scrobble the tracks played on a Spinitron radio station to a user's Last.fm account. It uses the Flask web framework to create a simple web application that allows users to input the URL of a Spinitron radio station. The script then periodically checks the Spinitron page for the currently playing track and scrobbles it to Last.fm if it's a new track.

Here's how the script works:

  1. The script starts by importing the necessary libraries, including threading, time, schedule, pylast, requests, BeautifulSoup, and Flask.
  2. The user's Last.fm API credentials (API key, API secret, and session key) are defined, and a Last.fm API client (network) is set up using the pylast library.
  3. The Flask web application is created with the app variable.
  4. Two global variables, last_scrobbled_track and spinitron_url, are defined to keep track of the most recently scrobbled track and the URL of the Spinitron radio station, respectively.
  5. An event object (stop_event) is created to control the scheduler thread.
  6. The run_scheduler function is defined to run the scheduled tasks in a separate thread. It uses the stop_event to stop the scheduler thread when needed.
  7. The scrobble_new_track function is defined to check the Spinitron page for the currently playing track. It fetches the HTML content of the Spinitron page, extracts the track information (artist, song, and release), and compares it to the last scrobbled track. If the current track is different, it scrobbles the track to Last.fm using the network.scrobble method.
  8. The index route renders the HTML page with a form for users to input the Spinitron URL.
  9. The submit route is triggered when the user submits the form. It extracts the Spinitron URL from the form data, performs an initial scrobble, and returns a message indicating the result.
  10. The latest_scrobble route returns the most recently scrobbled track in JSON format.
  11. The scrobble_new_track function is scheduled to run every minute using the schedule library.
  12. The scheduler thread is started, and the Flask web application is launched.
  13. If the Flask application is terminated (e.g., by pressing Ctrl+C), the scheduler thread is signaled to stop, and the script gracefully shuts down.

Discussions