-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusic_metadata_scanner_simple.ps1
More file actions
412 lines (363 loc) · 16.8 KB
/
Copy pathmusic_metadata_scanner_simple.ps1
File metadata and controls
412 lines (363 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# =====================================
# SCRIPT CREDITS
# =====================================
# Author: Benjamin Ohene-Adu
# Name of Script: music_metadata_scanner_simple.ps1
# Creation Date: October 31, 2025
# Intent of script: Simplified and clean version of the music metadata scanner with metadata writing capabilities. Focuses on core functionality without HTML generation complexities.
# =====================================
[CmdletBinding()]
param(
[string]$SourceDirectory = "E:\MUSIC\Reggae",
[string]$OutputDirectory = ".\metadata_output",
[switch]$WriteMetadata,
[switch]$CreateBackups,
[switch]$DryRun,
[switch]$NormalizeTitles,
[switch]$StandardizeArtists,
[switch]$ReportOnly,
[switch]$StoreAdditionalArtists,
[switch]$FilenameTitleFirst,
[switch]$AutoDetectTitleFirst
)
# Load TagLib
try {
$tagLibPath = ".\Libraries\taglib\src\TaglibSharp\bin\Debug\net462\TagLibSharp.dll"
[System.Reflection.Assembly]::LoadFrom((Resolve-Path $tagLibPath).Path) | Out-Null
Write-Host "TagLib loaded successfully" -ForegroundColor Green
} catch {
Write-Error "Failed to load TagLib: $($_.Exception.Message)"
exit 1
}
function Get-ArtistVariables {
param([string]$ArtistString)
if (-not $ArtistString) { return @{} }
$artists = @($ArtistString -split '(?i)\s*(?:feat\.?|ft\.?|&|with|\+)\s*' |
ForEach-Object { $_.Trim() } |
Where-Object { $_ -and $_.Length -gt 0 })
$result = @{}
if ($artists.Count -gt 0) {
$result["primary"] = $artists[0]
$result["count"] = $artists.Count
if ($artists.Count -gt 1) {
$result["additional"] = $artists[1..($artists.Count-1)] -join "; "
}
}
return $result
}
function Get-FilenameMetadata {
param(
[string]$FileName,
[switch]$TitleFirst,
[switch]$AutoDetect,
[string]$HintArtist
)
# Derive artist/title from common filename patterns. Handles variants like:
# "01 - Artist - Title", "Artist - Title", "Artist – Title", "Artist: Title"
# Leading track/disc tokens like (01), [01], Disc 1 -, Track 03 -, 01. etc.
$base = [System.IO.Path]::GetFileNameWithoutExtension($FileName)
# Normalize unicode dashes to hyphen and underscores to spaces
$work = $base -replace "[\u2013\u2014]", "-"
$work = $work -replace "_", " "
$work = $work.Trim()
# Remove common leading tokens: Disc/CD/Track numbers, bracketed or punctuated indices
$work = ($work -replace '(?i)^(?:disc|cd|track)\s*\d+\s*[-._\)\]]\s*', '')
$work = ($work -replace '^\s*(?:\(|\[)?\d{1,3}[A-Za-z]?(?:\)|\])?\s*[-._\)\]]\s*', '')
$work = ($work -replace '^\s*\d{1,2}\s*of\s*\d{1,2}\s*[-._\)\]]\s*', '')
# Split on the first strong delimiter among: - : ~ / |
$parts = $work -split '\s*(?:-|:|~|/|\|)\s*', 2
$derived = @{}
if ($parts.Count -ge 2) {
$useTitleFirst = $false
if ($TitleFirst) {
$useTitleFirst = $true
} elseif ($AutoDetect) {
# Heuristic: prefer the token that best matches the hint artist as the Artist
$token0 = $parts[0].Trim()
$token1 = $parts[1].Trim()
$score0 = 0; $score1 = 0
if ($HintArtist) {
$norm = { param($s) ($s -replace "[^\p{L}\p{Nd}\s]"," ").ToLower() }
$toWords = { param($s) (($s | & $norm) -split '\s+' | Where-Object { $_.Length -ge 2 } | Select-Object -Unique) }
$ha = & $toWords $HintArtist
$w0 = & $toWords $token0
$w1 = & $toWords $token1
if ($ha -and $w0) { $score0 = (@(foreach($w in $w0){ if ($ha -contains $w) { $w } }) ).Count }
if ($ha -and $w1) { $score1 = (@(foreach($w in $w1){ if ($ha -contains $w) { $w } }) ).Count }
}
if ($score1 -gt $score0) {
# Right token matches artist better -> Title is first
$useTitleFirst = $true
} elseif ($score0 -eq $score1) {
# Fallback keyword heuristic: typical title keywords
$kw = '(?i)\b(remix|remaster|live|version|dub|mix|edit|single|lyrics|official|audio|radio|extended|feat\.?|ft\.?)\b'
$tok0IsTitley = ($token0 -match $kw)
$tok1IsTitley = ($token1 -match $kw)
if ($tok0IsTitley -and -not $tok1IsTitley) { $useTitleFirst = $true }
}
}
if ($useTitleFirst) {
$derived['title'] = $parts[0].Trim()
$derived['artist'] = $parts[1].Trim()
} else {
$derived['artist'] = $parts[0].Trim()
$derived['title'] = $parts[1].Trim()
}
} else {
# If no delimiter, treat entire name as title
$derived['title'] = $work.Trim()
}
return $derived
}
function ConvertTo-NormalizedTitle {
param([string]$Text)
if ([string]::IsNullOrWhiteSpace($Text)) { return $Text }
$t = $Text
# Replace underscores with spaces
$t = $t -replace "_", " "
# Normalize slashes and separators
$t = $t -replace "\s*/\s*", " / "
$t = $t -replace "\s*-\s*", " - "
# Collapse multiple spaces
$t = ($t -replace "\s{2,}", " ").Trim()
return $t
}
function Set-MusicFileMetadata {
param(
[string]$FilePath,
[hashtable]$MetadataToWrite,
[switch]$CreateBackup
)
try {
if ($CreateBackup) {
$backupPath = "$FilePath.backup"
if (-not (Test-Path $backupPath)) {
Copy-Item -Path $FilePath -Destination $backupPath
}
}
$file = [TagLib.File]::Create($FilePath)
if ($MetadataToWrite.ContainsKey('artist')) {
$file.Tag.Performers = @($MetadataToWrite['artist'])
}
if ($MetadataToWrite.ContainsKey('albumartist')) {
$file.Tag.AlbumArtists = @($MetadataToWrite['albumartist'])
}
if ($MetadataToWrite.ContainsKey('title')) {
$file.Tag.Title = $MetadataToWrite['title']
}
if ($MetadataToWrite.ContainsKey('comment')) {
$file.Tag.Comment = $MetadataToWrite['comment']
}
$file.Save()
$file.Dispose()
return @{ success = $true; message = "Updated successfully" }
} catch {
return @{ success = $false; message = $_.Exception.Message }
}
}
# Main execution
Write-Host "Music Metadata Scanner with Write Capability" -ForegroundColor Cyan
Write-Host "Source: $SourceDirectory" -ForegroundColor Yellow
Write-Host "Write Metadata: $WriteMetadata" -ForegroundColor $(if($WriteMetadata){'Green'}else{'Gray'})
Write-Host "Create Backups: $CreateBackups" -ForegroundColor $(if($CreateBackups){'Green'}else{'Gray'})
Write-Host "Dry Run: $DryRun" -ForegroundColor $(if($DryRun){'Magenta'}else{'Gray'})
Write-Host "Normalize Titles: $NormalizeTitles" -ForegroundColor $(if($NormalizeTitles){'Green'}else{'Gray'})
Write-Host "Standardize Artists: $StandardizeArtists" -ForegroundColor $(if($StandardizeArtists){'Green'}else{'Gray'})
Write-Host "Report Only: $ReportOnly" -ForegroundColor $(if($ReportOnly){'Yellow'}else{'Gray'})
Write-Host "Store Additional Artists in Comment: $StoreAdditionalArtists" -ForegroundColor $(if($StoreAdditionalArtists){'Green'}else{'Gray'})
Write-Host "Filename Title First: $FilenameTitleFirst" -ForegroundColor $(if($FilenameTitleFirst){'Green'}else{'Gray'})
Write-Host "Auto-detect Title First: $AutoDetectTitleFirst" -ForegroundColor $(if($AutoDetectTitleFirst){'Green'}else{'Gray'})
Write-Host ""
if (-not (Test-Path $OutputDirectory)) {
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
}
$startTime = Get-Date
$files = Get-ChildItem -Path $SourceDirectory -Recurse -Include "*.mp3","*.flac","*.m4a","*.wav"
$totalFiles = $files.Count
$processedFiles = 0
$results = @()
$issues = @()
Write-Host "Found $totalFiles files" -ForegroundColor Green
Write-Host ""
foreach ($file in $files) {
try {
$tagFile = [TagLib.File]::Create($file.FullName)
$originalArtist = $tagFile.Tag.Performers -join '; '
$currentTitle = $tagFile.Tag.Title
# Derive missing values from filename when needed
$derived = @{}
if ([string]::IsNullOrWhiteSpace($originalArtist) -or [string]::IsNullOrWhiteSpace($currentTitle)) {
$derived = Get-FilenameMetadata -FileName $file.Name -TitleFirst:$FilenameTitleFirst -AutoDetect:$AutoDetectTitleFirst -HintArtist $originalArtist
if ([string]::IsNullOrWhiteSpace($originalArtist) -and $derived.ContainsKey('artist')) {
$originalArtist = $derived['artist']
}
if ([string]::IsNullOrWhiteSpace($currentTitle) -and $derived.ContainsKey('title')) {
$currentTitle = $derived['title']
}
}
# Optionally normalize title even if present
$normalizedTitle = $currentTitle
if ($NormalizeTitles -and $currentTitle) {
$normalizedTitle = ConvertTo-NormalizedTitle -Text $currentTitle
if ($normalizedTitle -ne $currentTitle) {
Write-Host " Normalized Title: $normalizedTitle" -ForegroundColor DarkCyan
}
}
# Process artist variables
$artistVars = Get-ArtistVariables -ArtistString $originalArtist
Write-Host "Processing: $($file.Name)" -ForegroundColor Yellow
Write-Host " Original Artist: $originalArtist" -ForegroundColor White
if ($currentTitle) { Write-Host " Title: $currentTitle" -ForegroundColor White }
Write-Host " Primary Artist: $($artistVars.primary)" -ForegroundColor Cyan
if ($artistVars.additional) {
Write-Host " Additional Artists: $($artistVars.additional)" -ForegroundColor Cyan
}
# Collect issues for optional report-only mode
$missingArtist = [string]::IsNullOrWhiteSpace(($tagFile.Tag.Performers -join '; '))
$missingTitle = [string]::IsNullOrWhiteSpace($tagFile.Tag.Title)
$normalizedChanged = $NormalizeTitles -and $currentTitle -and ($normalizedTitle -ne $currentTitle)
if ($ReportOnly -and ($missingArtist -or $missingTitle -or $normalizedChanged)) {
$issues += [PSCustomObject]@{
File = $file.Name
MissingArtist = $missingArtist
MissingTitle = $missingTitle
OriginalTitle = $currentTitle
NormalizedTitleSuggestion = $(if ($normalizedChanged) { $normalizedTitle } else { $null })
ExtractedPrimary = $artistVars.primary
Additional = $artistVars.additional
}
}
# Write metadata back if requested
$plannedChanges = @()
if ($WriteMetadata) {
$metadataToWrite = @{}
# Artist/AlbumArtist writing rules
if ($StandardizeArtists) {
if ($artistVars.primary) {
$metadataToWrite['artist'] = $artistVars.primary
$metadataToWrite['albumartist'] = $artistVars.primary
$plannedChanges += 'Artist,AlbumArtist'
}
} else {
if ((-not $tagFile.Tag.Performers) -and $artistVars.primary) {
$metadataToWrite['artist'] = $artistVars.primary
$plannedChanges += 'Artist'
}
if ((-not $tagFile.Tag.AlbumArtists) -and $artistVars.primary) {
$metadataToWrite['albumartist'] = $artistVars.primary
$plannedChanges += 'AlbumArtist'
}
}
# Title writing rules: fill missing from derived; or normalize existing if requested
if ([string]::IsNullOrWhiteSpace($tagFile.Tag.Title) -and $currentTitle) {
$metadataToWrite['title'] = $currentTitle
$plannedChanges += 'Title(Filled)'
} elseif ($NormalizeTitles -and $normalizedTitle -and $normalizedTitle -ne $currentTitle) {
$metadataToWrite['title'] = $normalizedTitle
$plannedChanges += 'Title(Normalized)'
}
# Store additional artists in Comment if requested
if ($StoreAdditionalArtists -and $artistVars.additional) {
$existingComment = $tagFile.Tag.Comment
$addLine = "Additional Artists: $($artistVars.additional)"
$newComment = $null
if ($existingComment) {
if ($existingComment -match '(?im)^Additional Artists:') {
$newComment = ($existingComment -replace '(?im)^Additional Artists:.*$', $addLine)
} else {
$newComment = "$existingComment`n$addLine"
}
} else {
$newComment = $addLine
}
if ($newComment -and $newComment -ne $existingComment) {
$metadataToWrite['comment'] = $newComment
$plannedChanges += 'Comment(Additional Artists)'
}
}
if ($DryRun -or $ReportOnly) {
if ($metadataToWrite.Count -gt 0) {
Write-Host " [DRY-RUN] Would update: $($plannedChanges -join ', ')" -ForegroundColor DarkYellow
}
} elseif ($metadataToWrite.Count -gt 0) {
$writeResult = Set-MusicFileMetadata -FilePath $file.FullName -MetadataToWrite $metadataToWrite -CreateBackup:$CreateBackups
if ($writeResult.success) {
Write-Host " Metadata Write: SUCCESS" -ForegroundColor Green
} else {
Write-Host " Metadata Write: FAILED - $($writeResult.message)" -ForegroundColor Red
}
}
}
$results += [PSCustomObject]@{
File = $file.Name
OriginalArtist = $originalArtist
Title = $(if ($NormalizeTitles -and $normalizedTitle) { $normalizedTitle } else { $currentTitle })
PrimaryArtist = $artistVars.primary
AdditionalArtists = $artistVars.additional
ArtistCount = $artistVars.count
MetadataWritten = ($WriteMetadata -and -not $DryRun)
}
$tagFile.Dispose()
$processedFiles++
} catch {
Write-Warning "Error processing $($file.Name): $($_.Exception.Message)"
}
Write-Host ""
}
if (-not $ReportOnly) {
# Generate simple text report
$reportPath = "$OutputDirectory\metadata_report.txt"
$report = @()
$report += "MUSIC METADATA ANALYSIS REPORT"
$report += "Generated: $(Get-Date)"
$report += "Files Processed: $processedFiles of $totalFiles"
$report += ""
foreach ($result in $results) {
$report += "File: $($result.File)"
$report += " Original Artist: $($result.OriginalArtist)"
if ($result.Title) { $report += " Title: $($result.Title)" }
$report += " Primary Artist: $($result.PrimaryArtist)"
if ($result.AdditionalArtists) {
$report += " Additional Artists: $($result.AdditionalArtists)"
}
$report += " Artist Count: $($result.ArtistCount)"
$report += " Metadata Written: $($result.MetadataWritten)"
$report += ""
}
$report | Out-File -FilePath $reportPath -Encoding UTF8
} else {
# Generate issues-only report
$issuesPath = "$OutputDirectory\issues_report.txt"
$lines = @()
$lines += "MUSIC METADATA ISSUES REPORT"
$lines += "Generated: $(Get-Date)"
$lines += "Files Scanned: $processedFiles of $totalFiles"
$lines += "Issues Found: $($issues.Count)"
$lines += ""
foreach ($i in $issues) {
$lines += "File: $($i.File)"
if ($i.MissingArtist) { $lines += " Missing Artist" }
if ($i.MissingTitle) { $lines += " Missing Title" }
if ($i.NormalizedTitleSuggestion) { $lines += " Suggested Title: $($i.NormalizedTitleSuggestion)" }
if ($i.ExtractedPrimary) { $lines += " Extracted Primary: $($i.ExtractedPrimary)" }
if ($i.Additional) { $lines += " Extracted Additional: $($i.Additional)" }
$lines += ""
}
$lines | Out-File -FilePath $issuesPath -Encoding UTF8
}
$endTime = Get-Date
$duration = $endTime - $startTime
Write-Host "SUMMARY:" -ForegroundColor Yellow
Write-Host " Files processed: $processedFiles of $totalFiles" -ForegroundColor White
Write-Host " Duration: $($duration.ToString('mm\:ss'))" -ForegroundColor White
if (-not $ReportOnly) {
Write-Host " Report saved: $reportPath" -ForegroundColor Green
} else {
Write-Host " Issues report saved: $issuesPath" -ForegroundColor Yellow
}
if ($WriteMetadata -and -not $DryRun) {
$successCount = ($results | Where-Object { $_.MetadataWritten }).Count
Write-Host " Files with metadata updated: $successCount" -ForegroundColor Green
}
Write-Host ""
Write-Host "Processing completed!" -ForegroundColor Green