-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusic_metadata_scanner_simple_broken.ps1
More file actions
724 lines (619 loc) · 28.7 KB
/
Copy pathmusic_metadata_scanner_simple_broken.ps1
File metadata and controls
724 lines (619 loc) · 28.7 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# =====================================
# SCRIPT CREDITS
# =====================================
# Author: Benjamin Ohene-Adu
# Name of Script: music_metadata_scanner_simple.ps1
# Creation Date: October 31, 2025
# Intent of script: Comprehensive music metadata scanning and processing tool with advanced artist variable processing capabilities. Scans music files, extracts and processes complex artist information, generates detailed reports, and optionally writes cleaned metadata back to files.
# =====================================
[CmdletBinding()]
param(
[Parameter(Mandatory=$false, Position=0, HelpMessage="Directory path containing music files to scan")]
[ValidateScript({
if (-not (Test-Path $_)) {
throw "Directory does not exist: $_"
}
if (-not (Test-Path $_ -PathType Container)) {
throw "Path is not a directory: $_"
}
$true
})]
[string]$SourceDirectory = "C:\OrganizedMusic\DUPLICATES\Reggae\L1",
[Parameter(Position=1, HelpMessage="Output directory for processed metadata")]
[string]$OutputDirectory = ".\metadata_output",
[Parameter(HelpMessage="File extensions to process")]
[string[]]$Extensions = @('.mp3', '.flac', '.m4a', '.wav', '.wma', '.ogg'),
[Parameter(HelpMessage="Maximum number of genres to extract per artist")]
[int]$MaxGenres = 10,
[Parameter(HelpMessage="Export format: JSON, CSV, TXT, or All")]
[ValidateSet("JSON", "CSV", "TXT", "All")]
[string]$ExportFormat = "TXT",
[Parameter(HelpMessage="Process files recursively")]
[switch]$Recursive,
[Parameter(HelpMessage="Enable detailed output")]
[switch]$DetailedOutput,
[Parameter(HelpMessage="Dry run - scan only, don't process")]
[switch]$DryRun,
[Parameter(HelpMessage="Demo mode - use sample data")]
[switch]$DemoMode,
[Parameter(HelpMessage="Write processed metadata back to files")]
[switch]$WriteMetadata,
[Parameter(HelpMessage="Create backup files before writing metadata")]
[switch]$CreateBackups,
[Parameter(HelpMessage="Metadata fields to write back to files")]
[ValidateSet("artist", "albumartist", "title", "album", "genre", "year", "track", "discnumber", "all")]
[string[]]$MetadataFields = @("artist", "albumartist")
)
# =====================================
# CONFIGURATION SECTION - EDIT THESE VALUES
# =====================================
# Override default values if you want to hardcode settings
$HARDCODED_CONFIG = @{
# Set to $true to use demo mode by default (uses sample data)
UseDemoMode = $false
# Set to $true to enable dry run by default (preview only)
UseDryRun = $false
# Default source directory (change this to your music folder)
DefaultSourceDirectory = "C:\OrganizedMusic\DUPLICATES\Reggae\L1"
# Default export format: "JSON", "CSV", "HTML", or "All"
DefaultExportFormat = "HTML"
# Process subdirectories recursively
ProcessRecursively = $true
# Show detailed output during processing
ShowDetailedOutput = $true
# File extensions to process
FileExtensions = @('.mp3', '.flac', '.m4a', '.wav', '.wma', '.ogg')
# Maximum genres to extract per artist
MaxGenresToExtract = 10
# Output directory for results
OutputDirectory = ".\metadata_output"
}
# QUICK SETTINGS - Change these for common scenarios:
# For demo mode: Set UseDemoMode = $true
# For your music folder: Change DefaultSourceDirectory to your path
# For different output: Change DefaultExportFormat to "JSON", "CSV", "HTML", or "All"
# For dry run testing: Set UseDryRun = $true
# EXAMPLE CONFIGURATIONS:
# Demo mode with all formats:
# UseDemoMode = $true, DefaultExportFormat = "All"
# Real files with JSON output:
# DefaultSourceDirectory = "C:\Music", DefaultExportFormat = "JSON"
# Dry run test:
# UseDryRun = $true, DefaultSourceDirectory = "C:\Music"
# Apply hardcoded configuration if parameters weren't explicitly provided
if (-not $PSBoundParameters.ContainsKey('SourceDirectory')) {
$SourceDirectory = $HARDCODED_CONFIG.DefaultSourceDirectory
}
if (-not $PSBoundParameters.ContainsKey('ExportFormat')) {
$ExportFormat = $HARDCODED_CONFIG.DefaultExportFormat
}
if (-not $PSBoundParameters.ContainsKey('Recursive')) {
$Recursive = $HARDCODED_CONFIG.ProcessRecursively
}
if (-not $PSBoundParameters.ContainsKey('DetailedOutput')) {
$DetailedOutput = $HARDCODED_CONFIG.ShowDetailedOutput
}
if (-not $PSBoundParameters.ContainsKey('DryRun')) {
$DryRun = $HARDCODED_CONFIG.UseDryRun
}
if (-not $PSBoundParameters.ContainsKey('DemoMode')) {
$DemoMode = $HARDCODED_CONFIG.UseDemoMode
}
if (-not $PSBoundParameters.ContainsKey('Extensions')) {
$Extensions = $HARDCODED_CONFIG.FileExtensions
}
if (-not $PSBoundParameters.ContainsKey('MaxGenres')) {
$MaxGenres = $HARDCODED_CONFIG.MaxGenresToExtract
}
if (-not $PSBoundParameters.ContainsKey('OutputDirectory')) {
$OutputDirectory = $HARDCODED_CONFIG.OutputDirectory
}
# Initialize variables
$startTime = Get-Date
$totalFiles = 0
$processedFiles = 0
$errorFiles = 0
$extractedMetadata = @{}
$artistStats = @{}
$genreStats = @{}
# Create output directory
if (-not $DryRun -and -not (Test-Path $OutputDirectory)) {
New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
Write-Host "`[+`] Created output directory: $OutputDirectory" -ForegroundColor Green
}
# Core artist processing functions (simplified versions)
function Set-MusicFileMetadata {
param(
[Parameter(Mandatory=$true)]
[string]$FilePath,
[hashtable]$MetadataToWrite,
[switch]$CreateBackup
)
try {
# Create backup if requested
if ($CreateBackup) {
$backupPath = "$FilePath.backup"
if (-not (Test-Path $backupPath)) {
Copy-Item -Path $FilePath -Destination $backupPath
Write-Verbose "Backup created: $backupPath"
}
}
# Load the file with TagLib
$file = [TagLib.File]::Create($FilePath)
# Write metadata fields
foreach ($field in $MetadataToWrite.Keys) {
$value = $MetadataToWrite[$field]
switch ($field) {
'artist' {
if ($value -is [array]) {
$file.Tag.Performers = $value
} else {
$file.Tag.Performers = @($value)
}
}
'albumartist' {
if ($value -is [array]) {
$file.Tag.AlbumArtists = $value
} else {
$file.Tag.AlbumArtists = @($value)
}
}
'title' { $file.Tag.Title = $value }
'album' { $file.Tag.Album = $value }
'genre' {
if ($value -is [array]) {
$file.Tag.Genres = $value
} else {
$file.Tag.Genres = @($value)
}
}
'year' { $file.Tag.Year = [uint32]$value }
'track' { $file.Tag.Track = [uint32]$value }
'discnumber' { $file.Tag.Disc = [uint32]$value }
}
}
# Save the changes
$file.Save()
$file.Dispose()
return @{
'success' = $true
'message' = "Successfully updated metadata for: $(Split-Path $FilePath -Leaf)"
}
} catch {
return @{
'success' = $false
'message' = "Failed to update metadata for: $(Split-Path $FilePath -Leaf) - $($_.Exception.Message)"
}
}
}
function Get-ArtistVariables {
param(
[string]$ArtistString,
[string]$SourceType = "track"
)
if (-not $ArtistString) {
return @{}
}
# Parse artists from string (handles "feat.", "ft.", "&", "with")
$artists = @($ArtistString -split '(?i)\s*(?:feat\.?|ft\.?|&|with|\+)\s*' |
ForEach-Object { $_.Trim() } |
Where-Object { $_ -and $_.Length -gt 0 })
$result = @{}
if ($artists.Count -gt 0) {
# Primary artist (first one)
$primaryArtist = $artists[0]
$result["~artists_${SourceType}_primary_std"] = $primaryArtist
$result["~artists_${SourceType}_primary_sort"] = $primaryArtist
$result["~artists_${SourceType}_all_count"] = $artists.Count
# Additional artists (rest)
if ($artists.Count -gt 1) {
$additional = $artists[1..($artists.Count-1)] -join "; "
$result["~artists_${SourceType}_additional_std"] = $additional
$result["~artists_${SourceType}_additional_std_multi"] = $artists[1..($artists.Count-1)]
}
# All artists combined
$result["~artists_${SourceType}_all_std"] = $ArtistString
$result["~artists_${SourceType}_all_std_multi"] = $artists
# Join phrases (simplified)
$joinPhrases = @()
for ($i = 0; $i -lt $artists.Count - 1; $i++) {
$joinPhrases += " feat. "
}
if ($joinPhrases.Count -eq 0) { $joinPhrases += "" }
$result["~artists_${SourceType}_all_join_phrases"] = $joinPhrases
}
return $result
}
# Function to extract metadata from music files using TagLib
function Get-MusicFileMetadata {
param(
[string]$FilePath
)
try {
# Load TagLib if available
# HARDCODED TagLib DLL Path (relative to script location)
$taglibPath = Join-Path $PSScriptRoot "Libraries\taglib\src\TaglibSharp\bin\Debug\net462\TagLibSharp.dll"
if (Test-Path $taglibPath) {
Add-Type -Path $taglibPath -ErrorAction SilentlyContinue
$file = [TagLib.File]::Create($FilePath)
# Extract basic metadata
$metadata = @{
'title' = $file.Tag.Title
'album' = $file.Tag.Album
'albumartist' = $file.Tag.AlbumArtists -join '; '
'artist' = $file.Tag.Performers -join '; '
'date' = $file.Tag.Year
'genre' = $file.Tag.Genres -join '; '
'track' = $file.Tag.Track
'discnumber' = $file.Tag.Disc
'duration' = $file.Properties.Duration.TotalSeconds
'bitrate' = $file.Properties.AudioBitrate
'filename' = [System.IO.Path]::GetFileName($FilePath)
'filepath' = $FilePath
'filesize' = (Get-Item $FilePath).Length
}
$file.Dispose()
return $metadata
} else {
Write-Warning "TagLib not found. Using basic file information only."
return @{
'filename' = [System.IO.Path]::GetFileName($FilePath)
'filepath' = $FilePath
'filesize' = (Get-Item $FilePath).Length
'artist' = [System.IO.Path]::GetFileNameWithoutExtension($FilePath) -replace '^\d+[\s\-\.]*', ''
'title' = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
}
}
}
catch {
Write-Warning "Failed to extract metadata from: $FilePath - $($_.Exception.Message)"
return $null
}
}
# Function to create sample metadata for demo
function Get-DemoMetadata {
$demoFiles = @(
@{ filename = "01 - The Beatles - Hey Jude.mp3"; artist = "The Beatles"; title = "Hey Jude"; album = "The Beatles 1967-1970"; genre = "Rock"; year = 1968 }
@{ filename = "02 - Queen feat. David Bowie - Under Pressure.mp3"; artist = "Queen feat. David Bowie"; title = "Under Pressure"; album = "Hot Space"; genre = "Rock"; year = 1981 }
@{ filename = "03 - Johnny Cash & June Carter - It Ain't Me Babe.mp3"; artist = "Johnny Cash & June Carter"; title = "It Ain't Me Babe"; album = "Johnny Cash & June Carter"; genre = "Country"; year = 1967 }
@{ filename = "04 - Eminem ft. Dr. Dre - Forgot About Dre.mp3"; artist = "Eminem ft. Dr. Dre"; title = "Forgot About Dre"; album = "2001"; genre = "Hip-Hop"; year = 1999 }
@{ filename = "05 - Simon & Garfunkel - The Sound of Silence.mp3"; artist = "Simon & Garfunkel"; title = "The Sound of Silence"; album = "Sounds of Silence"; genre = "Folk Rock"; year = 1965 }
)
return $demoFiles
}
# Function to process a single music file
function Invoke-MusicFileProcessing {
param(
[hashtable]$FileMetadata
)
Write-Host "`[*`] Processing: $($FileMetadata.filename)" -ForegroundColor Yellow
try {
# Process album artist variables
$albumVariables = @{}
if ($FileMetadata.albumartist -or $FileMetadata.artist) {
$albumArtist = if ($FileMetadata.albumartist) { $FileMetadata.albumartist } else { $FileMetadata.artist }
$albumVariables = Get-ArtistVariables -ArtistString $albumArtist -SourceType "album"
}
# Process track artist variables
$trackVariables = @{}
if ($FileMetadata.artist) {
$trackVariables = Get-ArtistVariables -ArtistString $FileMetadata.artist -SourceType "track"
}
# Combine all processed variables
$processedVariables = @{}
$albumVariables.GetEnumerator() | ForEach-Object { $processedVariables[$_.Key] = $_.Value }
$trackVariables.GetEnumerator() | ForEach-Object { $processedVariables[$_.Key] = $_.Value }
# Create final result
$result = @{
'file_info' = $FileMetadata
'processed_variables' = $processedVariables
'processed_at' = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
# Write metadata back to file if requested
if ($WriteMetadata -and -not $DryRun) {
$metadataToWrite = @{}
# Build metadata based on processed variables
if ($MetadataFields -contains "artist" -or $MetadataFields -contains "all") {
if ($processedVariables.ContainsKey('~artists_track_primary_std')) {
$primaryArtist = $processedVariables['~artists_track_primary_std']
$additionalArtists = @()
if ($processedVariables.ContainsKey('~artists_track_additional_std')) {
$additionalArtists = $processedVariables['~artists_track_additional_std'] -split '; '
}
$allArtists = @($primaryArtist) + $additionalArtists
$metadataToWrite['artist'] = $allArtists
}
}
if ($MetadataFields -contains "albumartist" -or $MetadataFields -contains "all") {
if ($processedVariables.ContainsKey('~artists_album_primary_std')) {
$metadataToWrite['albumartist'] = $processedVariables['~artists_album_primary_std']
}
}
# Write metadata if we have any to write
if ($metadataToWrite.Count -gt 0) {
$writeResult = Set-MusicFileMetadata -FilePath $FileMetadata.filepath -MetadataToWrite $metadataToWrite -CreateBackup:$CreateBackups
$result['metadata_write_result'] = $writeResult
if ($writeResult.success) {
Write-Host " [✓] Metadata updated successfully" -ForegroundColor Green
} else {
Write-Host " [✗] Failed to update metadata: $($writeResult.message)" -ForegroundColor Red
}
}
}
# Update statistics
if ($processedVariables.ContainsKey('~artists_album_primary_std')) {
$primaryArtist = $processedVariables['~artists_album_primary_std']
if ($artistStats.ContainsKey($primaryArtist)) {
$artistStats[$primaryArtist]++
} else {
$artistStats[$primaryArtist] = 1
}
}
if ($FileMetadata.genre) {
$genres = $FileMetadata.genre -split ';|,' | ForEach-Object { $_.Trim() }
foreach ($genre in $genres) {
if ($genre -and $genreStats.ContainsKey($genre)) {
$genreStats[$genre]++
} elseif ($genre) {
$genreStats[$genre] = 1
}
}
}
return $result
}
catch {
Write-Error "Error processing file $($FileMetadata.filename): $($_.Exception.Message)"
return $null
}
}
# Function to export results in different formats
function Export-Results {
param(
[hashtable]$AllMetadata,
[string]$Format,
[string]$OutputPath
)
switch ($Format) {
"JSON" {
$AllMetadata | ConvertTo-Json -Depth 10 | Out-File -FilePath "$OutputPath\processed_metadata.json" -Encoding UTF8
Write-Host "`[+`] JSON export saved to: $OutputPath\processed_metadata.json" -ForegroundColor Green
}
"CSV" {
$csvData = @()
foreach ($fileKey in $AllMetadata.Keys) {
$data = $AllMetadata[$fileKey]
$csvRow = [PSCustomObject]@{
'Filename' = $data.file_info.filename
'FilePath' = $data.file_info.filepath
'Title' = $data.file_info.title
'Album' = $data.file_info.album
'Artist' = $data.file_info.artist
'PrimaryArtist' = $data.processed_variables['~artists_album_primary_std']
'AdditionalArtists' = $data.processed_variables['~artists_album_additional_std']
'ArtistCount' = $data.processed_variables['~artists_track_all_count']
'Genre' = $data.file_info.genre
'Year' = $data.file_info.date
'Duration' = $data.file_info.duration
'FileSize' = $data.file_info.filesize
'ProcessedAt' = $data.processed_at
}
$csvData += $csvRow
}
$csvData | Export-Csv -Path "$OutputPath\processed_metadata.csv" -NoTypeInformation -Encoding UTF8
Write-Host "`[+`] CSV export saved to: $OutputPath\processed_metadata.csv" -ForegroundColor Green
}
"TXT" {
$txtReport = @()
$txtReport += "MUSIC METADATA ANALYSIS REPORT"
$txtReport += "Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$txtReport += "=" * 70
$txtReport += ""
$txtReport += "SUMMARY:"
$txtReport += "Total Files Processed: $($AllMetadata.Keys.Count)"
$txtReport += ""
$txtReport += "FILE DETAILS:"
$txtReport += "-" * 70
foreach ($fileKey in $AllMetadata.Keys) {
$data = $AllMetadata[$fileKey]
$txtReport += "File: $($data.file_info.filename)"
$txtReport += " Original Artist: $($data.file_info.artist)"
$txtReport += " Primary Artist: $($data.processed_variables['~artists_track_primary_std'])"
$txtReport += " Additional Artists: $($data.processed_variables['~artists_track_additional_std'])"
$txtReport += " Artist Count: $($data.processed_variables['~artists_track_all_count'])"
$txtReport += " Album: $($data.file_info.album)"
$txtReport += " Genre: $($data.file_info.genre)"
$txtReport += ""
}
$txtReport -join "`n" | Out-File -FilePath "$OutputPath\metadata_report.txt" -Encoding UTF8
Write-Host "`[+`] Text report saved to: $OutputPath\metadata_report.txt" -ForegroundColor Green
}
default {
# Simple console output
Write-Host ""
Write-Host "PROCESSED METADATA SUMMARY:" -ForegroundColor Yellow
Write-Host "Total files: $($AllMetadata.Keys.Count)" -ForegroundColor White
foreach ($fileKey in $AllMetadata.Keys) {
$data = $AllMetadata[$fileKey]
Write-Host " $($data.file_info.filename)" -ForegroundColor Cyan
Write-Host " Artist: $($data.file_info.artist) -> $($data.processed_variables['~artists_track_primary_std'])" -ForegroundColor Gray
}
}
}
}
# Main processing logic
Write-Host "Music Metadata Scanner v1.0" -ForegroundColor Cyan
Write-Host "Using Artist Variables Processing" -ForegroundColor Gray
Write-Host ""
# Display current configuration
Write-Host "CURRENT CONFIGURATION:" -ForegroundColor Yellow
Write-Host " Source Directory: $SourceDirectory" -ForegroundColor White
Write-Host " Output Directory: $OutputDirectory" -ForegroundColor White
Write-Host " Export Format: $ExportFormat" -ForegroundColor White
Write-Host " Extensions: $($Extensions -join ', ')" -ForegroundColor White
Write-Host " Recursive: $Recursive" -ForegroundColor White
Write-Host " Detailed Output: $DetailedOutput" -ForegroundColor White
Write-Host " Dry Run: $DryRun" -ForegroundColor White
Write-Host " Demo Mode: $DemoMode" -ForegroundColor White
Write-Host ""
Write-Host "TIP: Edit the HARDCODED_CONFIG section at the top of this script to change defaults!" -ForegroundColor Green
Write-Host ""
if ($DryRun) {
Write-Host "[DRY RUN MODE] - Scanning only, no processing" -ForegroundColor Magenta
}
if ($DemoMode) {
Write-Host "[DEMO MODE] - Using sample data to demonstrate functionality" -ForegroundColor Magenta
}
Write-Host "`[*`] Source directory: $SourceDirectory" -ForegroundColor Yellow
Write-Host "`[*`] Extensions: $($Extensions -join ', ')" -ForegroundColor Cyan
Write-Host "`[*`] Output directory: $OutputDirectory" -ForegroundColor Cyan
Write-Host "`[*`] Export format: $ExportFormat" -ForegroundColor Cyan
if ($WriteMetadata) {
Write-Host "`[*`] Write metadata: ENABLED" -ForegroundColor Green
Write-Host "`[*`] Metadata fields: $($MetadataFields -join ', ')" -ForegroundColor Cyan
Write-Host "`[*`] Create backups: $CreateBackups" -ForegroundColor Cyan
} else {
Write-Host "`[*`] Write metadata: DISABLED (read-only mode)" -ForegroundColor Gray
}
Write-Host ""
if ($DemoMode) {
# Use demo data
$demoFiles = Get-DemoMetadata
$totalFiles = $demoFiles.Count
Write-Host "`[*`] Using $totalFiles demo music files" -ForegroundColor Green
Write-Host ""
if ($DryRun) {
Write-Host "Demo files that would be processed:" -ForegroundColor Yellow
$demoFiles | ForEach-Object {
Write-Host " $($_.filename) - $($_.artist)" -ForegroundColor White
}
Write-Host ""
Write-Host "`[+`] Demo dry run completed!" -ForegroundColor Green
return
}
# Process demo files
$currentFile = 0
foreach ($demoFile in $demoFiles) {
$currentFile++
$percentComplete = [math]::Round(($currentFile / $totalFiles) * 100, 1)
Write-Progress -Activity "Processing Demo Music Files" -Status "Processing: $($demoFile.filename)" -PercentComplete $percentComplete
$result = Invoke-MusicFileProcessing -FileMetadata $demoFile
if ($result) {
$extractedMetadata[$demoFile.filename] = $result
$processedFiles++
Write-Host "`[+`] Processed: $($demoFile.filename)" -ForegroundColor Green
} else {
$errorFiles++
Write-Host "`[-`] Failed: $($demoFile.filename)" -ForegroundColor Red
}
if ($DetailedOutput -and $result) {
Write-Host " Primary Artist: $($result.processed_variables['~artists_track_primary_std'])" -ForegroundColor Gray
Write-Host " Additional Artists: $($result.processed_variables['~artists_track_additional_std'])" -ForegroundColor Gray
Write-Host " Artist Count: $($result.processed_variables['~artists_track_all_count'])" -ForegroundColor Gray
}
}
} else {
# Get all music files from directory
# Convert extensions to file patterns (e.g., .mp3 -> *.mp3)
$filePatterns = $Extensions | ForEach-Object { "*$_" }
$searchParams = @{
Path = $SourceDirectory
Include = $filePatterns
File = $true
}
if ($Recursive) {
$searchParams.Recurse = $true
}
$musicFiles = Get-ChildItem @searchParams
$totalFiles = $musicFiles.Count
Write-Host "`[*`] Found $totalFiles music files" -ForegroundColor Green
Write-Host ""
if ($DryRun) {
Write-Host "Files that would be processed:" -ForegroundColor Yellow
$musicFiles | ForEach-Object {
Write-Host " $($_.FullName)" -ForegroundColor White
}
Write-Host ""
Write-Host "`[+`] Dry run completed!" -ForegroundColor Green
return
}
# Process each file
$currentFile = 0
foreach ($file in $musicFiles) {
$currentFile++
$percentComplete = [math]::Round(($currentFile / $totalFiles) * 100, 1)
Write-Progress -Activity "Processing Music Files" -Status "Processing: $($file.Name)" -PercentComplete $percentComplete
$metadata = Get-MusicFileMetadata -FilePath $file.FullName
if (-not $metadata) {
$errorFiles++
continue
}
$result = Invoke-MusicFileProcessing -FileMetadata $metadata
if ($result) {
$extractedMetadata[$file.FullName] = $result
$processedFiles++
Write-Host "`[+`] Processed: $($file.Name)" -ForegroundColor Green
} else {
$errorFiles++
Write-Host "`[-`] Failed: $($file.Name)" -ForegroundColor Red
}
if ($DetailedOutput -and $result) {
Write-Host " Primary Artist: $($result.processed_variables['~artists_track_primary_std'])" -ForegroundColor Gray
Write-Host " Additional Artists: $($result.processed_variables['~artists_track_additional_std'])" -ForegroundColor Gray
}
}
}
Write-Progress -Activity "Processing Music Files" -Completed
# Export results
if ($processedFiles -gt 0) {
Write-Host ""
Write-Host "`[*`] Exporting results..." -ForegroundColor Yellow
if ($ExportFormat -eq "All") {
Export-Results -AllMetadata $extractedMetadata -Format "JSON" -OutputPath $OutputDirectory
Export-Results -AllMetadata $extractedMetadata -Format "CSV" -OutputPath $OutputDirectory
Export-Results -AllMetadata $extractedMetadata -Format "TXT" -OutputPath $OutputDirectory
} else {
Export-Results -AllMetadata $extractedMetadata -Format $ExportFormat -OutputPath $OutputDirectory
}
}
# Generate summary report
$endTime = Get-Date
$duration = $endTime - $startTime
Write-Host ""
Write-Host "=" * 70 -ForegroundColor Cyan
Write-Host "MUSIC METADATA SCANNING SUMMARY" -ForegroundColor Yellow
Write-Host "=" * 70 -ForegroundColor Cyan
Write-Host "Start Time: $($startTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White
Write-Host "End Time: $($endTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor White
Write-Host "Duration: $($duration.ToString('hh\:mm\:ss'))" -ForegroundColor White
Write-Host "Source Directory: $SourceDirectory" -ForegroundColor White
Write-Host "Output Directory: $OutputDirectory" -ForegroundColor White
Write-Host ""
Write-Host "RESULTS:" -ForegroundColor Yellow
Write-Host " Total files found: $totalFiles" -ForegroundColor White
Write-Host " Files processed: $processedFiles" -ForegroundColor Green
Write-Host " Files with errors: $errorFiles" -ForegroundColor Red
Write-Host " Unique artists found: $($artistStats.Keys.Count)" -ForegroundColor Cyan
Write-Host " Unique genres found: $($genreStats.Keys.Count)" -ForegroundColor Cyan
if ($duration.TotalSeconds -gt 0 -and $processedFiles -gt 0) {
$filesPerSecond = [math]::Round($processedFiles / $duration.TotalSeconds, 2)
Write-Host " Processing rate: $filesPerSecond files/sec" -ForegroundColor Cyan
}
# Show top artists if any were found
if ($artistStats.Keys.Count -gt 0) {
Write-Host ""
Write-Host "TOP ARTISTS:" -ForegroundColor Yellow
$artistStats.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 5 | ForEach-Object {
Write-Host " $($_.Key): $($_.Value) tracks" -ForegroundColor Cyan
}
}
Write-Host ""
Write-Host "`[+`] Music metadata scanning completed successfully!" -ForegroundColor Green
Write-Host "=" * 70 -ForegroundColor Cyan
# Show usage examples
if ($DemoMode) {
Write-Host ""
Write-Host "USAGE EXAMPLES:" -ForegroundColor Yellow
Write-Host " Real music files: .\music_metadata_scanner_simple.ps1 -SourceDirectory 'C:\Music' -Recursive" -ForegroundColor Gray
Write-Host " Export all formats: .\music_metadata_scanner_simple.ps1 -SourceDirectory 'C:\Music' -ExportFormat All" -ForegroundColor Gray
Write-Host " Detailed output: .\music_metadata_scanner_simple.ps1 -SourceDirectory 'C:\Music' -DetailedOutput" -ForegroundColor Gray
}