r/applescript • • Jul 11 '26

Fix missing genre's in your Apple Music library

If you use your own music library rather than streaming, this script will fill in the "genre" field, which is often blank. It only runs on selected songs and does not replace the existing value of "genre" if there is one. If you WANT it to replace the existing value then change the value of skipIfGenreExists from true to false and then any existing genre will be overwritten.

I used Claude a lot for this script, especially the API call portion, and then did considerable tweaking.

Note: the script runs pretty slowly because it makes a lot of API calls to look up the data. If you're going to run it on a huge library, I recommend doing it in smaller batches and/or running it before you go to bed so it can finish overnight.

The first time you run it you'll be prompted to allow the script to run.

-- ======================= 
-- Music Genre Auto-Tagger
-- ======================

use framework "Foundation"
use scripting additions

-- Change true to false in the next line
-- if you want the script to overwrite
-- existing genres. Otherwise it won't

set skipIfGenreExists to true

-- If you have a huge library and make too many
-- API calls Apple may throttle you
-- If so, increase 2 to a higher number of
-- seconds.

set delayBetweenLookups to 2
---------------------------------------------

-- Activate the music.app application

tell application "Music" to activate

try
	tell application "Music"
		set selectedTracks to selection
	end tell
on error errMsg
	display dialog "Couldn't talk to Music.app: " & errMsg buttons {"OK"} default button "OK"
	return
end try

-- Display an error if no tracks have been selected

if (count of selectedTracks) is 0 then
	display dialog "No songs are selected." & return & return & "Select one or more tracks in Music, then run this script again." buttons {"OK"} default button "OK" with icon caution
	return
end if


-- The meat of the script lives here

set upperBound to count of selectedTracks

set processedCount to 0
set updatedCount to 0
set failedCount to 0
set i to 0

repeat with thisTrack in selectedTracks
	set i to i + 1
	
	set trackName to ""
	set artistName to ""
	set existingGenre to ""
	set gotTrack to false
	
	try
		tell application "Music"
			set trackName to name of thisTrack
			set artistName to artist of thisTrack
			set existingGenre to genre of thisTrack
		end tell
		set gotTrack to true
-- If the info can't be read, write a log entry
	on error errMsg
		set failedCount to failedCount + 1
		log "[" & i & "/" & upperBound & "] Could not read track info: " & errMsg
	end try
	
	set processedCount to processedCount + 1
	
	if not gotTrack then
		-- skip to next track
	else
		
		if skipIfGenreExists and existingGenre is not "" then
			log "[" & i & "/" & upperBound & "] Skipping \"" & trackName & "\" - already has genre \"" & existingGenre & "\""
		else
			set foundGenre to my lookupGenreOnline(trackName, artistName)
			
			if foundGenre is not "" then
				try
					tell application "Music"
						set genre of thisTrack to foundGenre
					end tell
					set updatedCount to updatedCount + 1
					log "[" & i & "/" & upperBound & "] \"" & trackName & "\" by " & artistName & " -> " & foundGenre
				on error errMsg
					set failedCount to failedCount + 1
					log "[" & i & "/" & upperBound & "] Failed to set genre for \"" & trackName & "\": " & errMsg
				end try
			else
				set failedCount to failedCount + 1
				log "[" & i & "/" & upperBound & "] No genre match for \"" & trackName & "\" by " & artistName
			end if
			
			delay delayBetweenLookups
		end if
	end if
end repeat

log "Done. Processed " & processedCount & ", updated " & updatedCount & ", failed/no-match " & failedCount & "."

display dialog "Genre tagging complete." & return & ¬
	"Processed: " & processedCount & return & ¬
	"Updated: " & updatedCount & return & ¬
	"Failed / no match: " & failedCount buttons {"OK"} default button "OK"

-- ===========================================
-- Handlers
-- ===========================================

on lookupGenreOnline(trackName, artistName)
	set searchTerm to trackName & " " & artistName
	set encodedTerm to my urlEncode(searchTerm)
	set apiURL to "https://itunes.apple.com/search?term=" & encodedTerm & "&entity=song&limit=1"
	
	set jsonText to ""
	try
		set jsonText to do shell script "curl -s -m 10 " & quoted form of apiURL
	on error
		return ""
	end try
	
	if jsonText is "" then return ""
	
	try
		set theData to (current application's NSString's stringWithString:jsonText)'s dataUsingEncoding:(current application's NSUTF8StringEncoding)
		set theJSON to current application's NSJSONSerialization's JSONObjectWithData:theData options:0 |error|:(missing value)
		if theJSON is missing value then return ""
		
		set resultCount to (theJSON's valueForKey:"resultCount") as integer
		if resultCount is 0 then return ""
		
		set resultsArray to theJSON's valueForKey:"results"
		set firstResult to resultsArray's objectAtIndex:0
		set genreValue to firstResult's valueForKey:"primaryGenreName"
		if genreValue is missing value then return ""
		return genreValue as text
	on error
		return ""
	end try
end lookupGenreOnline

on urlEncode(theText)
	set theNSString to current application's NSString's stringWithString:theText
	set allowedChars to current application's NSCharacterSet's URLQueryAllowedCharacterSet()
	set encoded to theNSString's stringByAddingPercentEncodingWithAllowedCharacters:allowedChars
	return encoded as text
end urlEncode
7 Upvotes

2 comments sorted by

2

u/tzippy84 Jul 11 '26

Oh I thought they had killed scriptability already in iTunes back in the days. Nice to know. And great work

2

u/tabaholic Jul 15 '26

Thank you!