-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvert-InputData.ps1
More file actions
460 lines (357 loc) · 13.7 KB
/
Copy pathConvert-InputData.ps1
File metadata and controls
460 lines (357 loc) · 13.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
$ErrorActionPreference = "Continue"
# Slopsmith Phase Shift / Guitar Hero converter wrapper
# - Keeps original converter.py
# - Builds one mixed song.ogg for converter.py
# - Reopens .sloppak, adds separate audio stems, patches manifest
# - rhythm -> Bass, drums1/drums2/drums3 -> Drums
# - If drum_tab exists: exposes it as the main Drums arrangement
$Base = $PSScriptRoot
$Converter = Join-Path $Base "converter.py"
$InputDir = Join-Path $Base "Input Data"
$OutputDir = Join-Path $Base "Output Data"
$LocalWorkDir = Join-Path $env:TEMP "slopsmith-convert-work"
$Log = Join-Path $Base ("convert-input-log_{0}.txt" -f (Get-Date -Format "yyyyMMdd_HHmmss"))
$VorbisQuality = 3
$AudioExts = @(".ogg", ".wav", ".mp3", ".opus", ".flac", ".m4a", ".aac")
New-Item -ItemType Directory -Force -Path $LocalWorkDir | Out-Null
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Log {
param([string]$Text)
$line = "[{0}] {1}" -f (Get-Date -Format "HH:mm:ss"), $Text
Write-Host $line
Add-Content -LiteralPath $Log -Value $line
}
function Get-SafeFileName {
param([string]$Name)
$invalid = [IO.Path]::GetInvalidFileNameChars() -join ''
$regex = '[{0}]' -f [Regex]::Escape($invalid)
$safe = ($Name -replace $regex, '_').Trim()
if ([string]::IsNullOrWhiteSpace($safe)) { return "converted" }
return $safe
}
function Get-RelativePathSafe {
param([string]$BasePath, [string]$TargetPath)
$baseFull = [IO.Path]::GetFullPath($BasePath)
$targetFull = [IO.Path]::GetFullPath($TargetPath)
if (-not $baseFull.EndsWith([IO.Path]::DirectorySeparatorChar)) {
$baseFull += [IO.Path]::DirectorySeparatorChar
}
$baseUri = [Uri]$baseFull
$targetUri = [Uri]$targetFull
$relativeUri = $baseUri.MakeRelativeUri($targetUri)
$relative = [Uri]::UnescapeDataString($relativeUri.ToString())
return $relative.Replace('/', [IO.Path]::DirectorySeparatorChar)
}
function Get-ChartAudioFiles {
param([string]$ChartFolder)
return @(
Get-ChildItem -LiteralPath $ChartFolder -Recurse -File -ErrorAction SilentlyContinue |
Where-Object {
$ext = $_.Extension.ToLowerInvariant()
$name = $_.Name.ToLowerInvariant()
($AudioExts -contains $ext) -and
($name -notmatch "^preview\.") -and
($name -notmatch "preview")
} |
Sort-Object FullName
)
}
function Get-StemIdForAudioFile {
param([string]$FileName)
$n = [System.IO.Path]::GetFileNameWithoutExtension($FileName).ToLowerInvariant()
$n = $n -replace "[\s\-]+", "_"
if ($n -match "preview") { return $null }
if ($n -match "^(drums?|drums?_?[0-9]+|drum?_?[0-9]+|kick|snare|kit|cymbals?|toms?)$") {
return "drums"
}
if ($n -match "^(bass|bass_?[0-9]+|rhythm|rhythm_?[0-9]+)$") {
return "bass"
}
if ($n -match "^(guitar|guitar_?[0-9]+|lead|lead_guitar)$") {
return "guitar"
}
if ($n -match "^(vocals?|vocals?_?[0-9]+|voice|vox)$") {
return "vocals"
}
if ($n -match "^(piano|keys|keyboard|synth)$") {
return "piano"
}
return "other"
}
function Convert-ToOgg {
param([string[]]$Inputs, [string]$OutFile)
if ($Inputs.Count -lt 1) { throw "Convert-ToOgg called with no inputs" }
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $OutFile) | Out-Null
if ($Inputs.Count -eq 1) {
Log "Creating OGG:"
Log " FROM: $($Inputs[0])"
Log " TO: $OutFile"
& ffmpeg -y -i $Inputs[0] -vn -map 0:a:0 -c:a libvorbis -q:a $VorbisQuality $OutFile 2>&1 |
ForEach-Object { Log $_.ToString() }
}
else {
Log "Mixing audio files into OGG:"
Log " INPUTS: $($Inputs.Count)"
Log " TO: $OutFile"
$ffArgs = @("-y")
foreach ($i in $Inputs) { $ffArgs += @("-i", $i) }
$filter = "amix=inputs=$($Inputs.Count):duration=longest:normalize=0,alimiter=limit=0.95"
$ffArgs += @(
"-filter_complex", $filter,
"-vn",
"-c:a", "libvorbis",
"-q:a", "$VorbisQuality",
$OutFile
)
& ffmpeg @ffArgs 2>&1 |
ForEach-Object { Log $_.ToString() }
}
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $OutFile -PathType Leaf)) {
throw "FFmpeg failed while creating: $OutFile"
}
}
function Prepare-ChartForConverter {
param([string]$ChartFolder)
$audioFiles = @(Get-ChartAudioFiles -ChartFolder $ChartFolder)
if ($audioFiles.Count -eq 0) {
Log "No audio files found in: $ChartFolder"
return $ChartFolder
}
if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
throw "FFmpeg not found. Install it with: winget install -e --id Gyan.FFmpeg"
}
$TempChart = Join-Path $LocalWorkDir ("chart_" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path $TempChart | Out-Null
Get-ChildItem -LiteralPath $ChartFolder -Force |
Copy-Item -Destination $TempChart -Recurse -Force
Get-ChildItem -LiteralPath $TempChart -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $AudioExts -contains $_.Extension.ToLowerInvariant() } |
Remove-Item -Force -ErrorAction SilentlyContinue
$mixedOgg = Join-Path $TempChart "song.ogg"
Log "Preparing full mixed audio for original converter."
Log "Source audio files: $($audioFiles.Count)"
foreach ($file in $audioFiles) {
$sizeMb = [math]::Round($file.Length / 1MB, 3)
Log " AUDIO: $($file.FullName) [$sizeMb MB]"
}
Convert-ToOgg -Inputs ($audioFiles.FullName) -OutFile $mixedOgg
$mixedSizeMb = [math]::Round((Get-Item -LiteralPath $mixedOgg).Length / 1MB, 3)
Log "Prepared mixed audio:"
Log " FILE: $mixedOgg"
Log " SIZE: $mixedSizeMb MB"
return $TempChart
}
function Patch-SloppakToMultiStemDrumsOnly {
param(
[string]$SloppakPath,
[string]$FinalOutput,
[string]$OriginalChartFolder,
[string]$WorkingChartFolder
)
$audioFiles = @(Get-ChartAudioFiles -ChartFolder $OriginalChartFolder)
if ($audioFiles.Count -eq 0) { throw "No original audio files found for stem repack: $OriginalChartFolder" }
$UnpackDir = Join-Path $LocalWorkDir ("unpack_" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path $UnpackDir | Out-Null
Log "Unpacking sloppak for stem patch:"
Log " FROM: $SloppakPath"
Log " TEMP: $UnpackDir"
[System.IO.Compression.ZipFile]::ExtractToDirectory($SloppakPath, $UnpackDir)
$StemDir = Join-Path $UnpackDir "stems"
New-Item -ItemType Directory -Force -Path $StemDir | Out-Null
$mixedOgg = Join-Path $WorkingChartFolder "song.ogg"
if (Test-Path -LiteralPath $mixedOgg -PathType Leaf) {
Copy-Item -LiteralPath $mixedOgg -Destination (Join-Path $StemDir "full.ogg") -Force
Log "Added fallback full mix: stems/full.ogg"
}
$Groups = @{}
foreach ($af in $audioFiles) {
$sid = Get-StemIdForAudioFile $af.Name
Log "MAP: $($af.Name) -> $sid"
if ($null -eq $sid) { continue }
if (-not $Groups.ContainsKey($sid)) {
$Groups[$sid] = New-Object System.Collections.Generic.List[string]
}
$Groups[$sid].Add($af.FullName)
}
$StemOrder = @("guitar", "bass", "drums", "vocals", "piano", "other")
$WrittenStemIds = @()
foreach ($sid in $StemOrder) {
if (-not $Groups.ContainsKey($sid)) { continue }
$outStem = Join-Path $StemDir ($sid + ".ogg")
Convert-ToOgg -Inputs ($Groups[$sid].ToArray()) -OutFile $outStem
$WrittenStemIds += $sid
Log "Stem written: $sid from $($Groups[$sid].Count) source file(s)"
}
if ($WrittenStemIds.Count -eq 0) { throw "No separate stems were written." }
$PatchScript = Join-Path $UnpackDir "_patch_manifest.py"
Set-Content -LiteralPath $PatchScript -Encoding UTF8 -Value @'
import pathlib
import sys
try:
import yaml
except ImportError:
raise SystemExit("PyYAML missing. Run: py -3 -m pip install pyyaml")
root = pathlib.Path(sys.argv[1])
stem_ids = sys.argv[2:]
manifest = None
for name in ("manifest.yaml", "manifest.yml"):
p = root / name
if p.exists():
manifest = p
break
if manifest is None:
raise SystemExit("No manifest.yaml or manifest.yml found in sloppak.")
data = yaml.safe_load(manifest.read_text(encoding="utf-8")) or {}
names = {
"guitar": "Guitar",
"bass": "Bass",
"drums": "Drums",
"vocals": "Vocals",
"piano": "Piano",
"other": "Other",
}
data["stems"] = [
{
"id": sid,
"name": names.get(sid, sid.title()),
"file": f"stems/{sid}.ogg",
}
for sid in stem_ids
]
# Corrected drum mode:
# Slopsmith needs at least one arrangement entry.
# We expose drum_tab.json as a Drums arrangement instead of leaving arrangements empty.
if data.get("drum_tab"):
drum_file = data.get("drum_tab")
# Remove guitar/bass tuning metadata for drum-only songs.
# This prevents our package from explicitly declaring "E Standard" or any guitar tuning.
for key in (
"tuning",
"tuning_name",
"tuningName",
"tuning_label",
"tuningLabel",
"capo",
"string_count",
"stringCount",
):
data.pop(key, None)
# Some Slopsmith UI paths fall back to "E Standard" when tuning metadata is absent.
# These fields do NOT add E Standard; they try to override the visible tuning badge.
data["tuning"] = []
data["tuning_name"] = "No tuning"
data["tuningName"] = "No tuning"
data["tuning_label"] = "No tuning"
data["tuningLabel"] = "No tuning"
data["arrangements"] = [
{
"id": "drums",
"name": "Drums",
"file": drum_file,
"instrument": "drums",
"type": "drums",
"tuning": [],
"tuning_name": "No tuning",
"tuningName": "No tuning",
"tuning_label": "No tuning",
"tuningLabel": "No tuning",
}
]
data["instrument"] = "drums"
data["instruments"] = ["drums"]
data["primary_instrument"] = "drums"
manifest.write_text(
yaml.safe_dump(data, sort_keys=False, allow_unicode=True),
encoding="utf-8"
)
'@
$pyArgs = @("-3", $PatchScript, $UnpackDir) + $WrittenStemIds
Log "Patching manifest:"
& py @pyArgs 2>&1 |
ForEach-Object { Log $_.ToString() }
if ($LASTEXITCODE -ne 0) { throw "Manifest patch failed." }
if (Test-Path -LiteralPath $FinalOutput) {
Remove-Item -LiteralPath $FinalOutput -Force
}
Log "Repacking final sloppak:"
Log " TO: $FinalOutput"
[System.IO.Compression.ZipFile]::CreateFromDirectory($UnpackDir, $FinalOutput)
Remove-Item -LiteralPath $UnpackDir -Recurse -Force -ErrorAction SilentlyContinue
}
if (-not (Test-Path -LiteralPath $Converter -PathType Leaf)) {
Log "ERROR: converter.py not found: $Converter"
exit 1
}
New-Item -ItemType Directory -Force -Path $InputDir | Out-Null
New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null
Log "Input folder: $InputDir"
Log "Output folder: $OutputDir"
Log "Local temp folder: $LocalWorkDir"
Log "Vorbis quality: $VorbisQuality"
$songIniFiles = @(Get-ChildItem -LiteralPath $InputDir -Filter "song.ini" -File -Recurse -ErrorAction SilentlyContinue)
if ($songIniFiles.Count -eq 0) {
Log "No song.ini found. Put Phase Shift song folders into Input Data."
exit 0
}
$chartFolders = @(
$songIniFiles |
ForEach-Object { $_.Directory.FullName } |
Sort-Object -Unique
)
Log "Found chart folders: $($chartFolders.Count)"
$success = 0
$failed = 0
foreach ($chartFolder in $chartFolders) {
$workingChart = $null
try {
$relativeChart = Get-RelativePathSafe -BasePath $InputDir -TargetPath $chartFolder
$relativeParent = Split-Path -Parent $relativeChart
$chartName = Split-Path -Leaf $chartFolder
$outName = Get-SafeFileName $chartName
if ([string]::IsNullOrWhiteSpace($relativeParent)) {
$outSubDir = $OutputDir
}
else {
$outSubDir = Join-Path $OutputDir $relativeParent
}
New-Item -ItemType Directory -Force -Path $outSubDir | Out-Null
$finalOutput = Join-Path $outSubDir ($outName + ".sloppak")
$tempOutput = Join-Path $LocalWorkDir ([Guid]::NewGuid().ToString("N") + ".sloppak")
$workingChart = Prepare-ChartForConverter -ChartFolder $chartFolder
Log "Convert:"
Log " FROM: $workingChart"
Log " TEMP: $tempOutput"
Log " TO: $finalOutput"
& py -3 $Converter $workingChart -o $tempOutput 2>&1 |
ForEach-Object { Log $_.ToString() }
if ($LASTEXITCODE -eq 0 -and (Test-Path -LiteralPath $tempOutput -PathType Leaf)) {
Patch-SloppakToMultiStemDrumsOnly `
-SloppakPath $tempOutput `
-FinalOutput $finalOutput `
-OriginalChartFolder $chartFolder `
-WorkingChartFolder $workingChart
Remove-Item -LiteralPath $tempOutput -Force -ErrorAction SilentlyContinue
$outSizeMb = [math]::Round((Get-Item -LiteralPath $finalOutput).Length / 1MB, 3)
Log "OK: $finalOutput [$outSizeMb MB]"
$success++
}
else {
Log "FAILED: $chartFolder"
$failed++
}
}
catch {
Log "FAILED: $chartFolder"
Log $_.Exception.Message
$failed++
}
finally {
if ($workingChart -and $workingChart.StartsWith($LocalWorkDir)) {
Remove-Item -LiteralPath $workingChart -Recurse -Force -ErrorAction SilentlyContinue
}
}
}
Log "Done."
Log "Successful: $success"
Log "Failed: $failed"
Log "Log file: $Log"