Files
narratio/internal/audio/names.go

70 lines
2.1 KiB
Go

package audio
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"path/filepath"
"sort"
"strings"
)
// PreparedNames preserves existing basename disambiguation for local sources.
func PreparedNames(audioPaths []string) map[string]string {
byBase := make(map[string][]string, len(audioPaths))
occupied := make(map[string]bool, len(audioPaths))
for _, audioPath := range audioPaths {
base := filepath.Base(audioPath)
byBase[base] = append(byBase[base], audioPath)
occupied[base] = true
}
destinations := make(map[string]string, len(audioPaths))
ordered := append([]string(nil), audioPaths...)
sort.Strings(ordered)
nextSuffix := make(map[string]int)
for _, source := range ordered {
if _, assigned := destinations[source]; assigned {
continue
}
base := filepath.Base(source)
if len(byBase[base]) == 1 {
destinations[source] = base
continue
}
extension := filepath.Ext(base)
stem := strings.TrimSuffix(base, extension)
digest := sha256.Sum256([]byte(filepath.Clean(source)))
generatedStem := stem + "-" + hex.EncodeToString(digest[:8])
candidate := generatedStem + extension
for occupied[candidate] {
nextSuffix[generatedStem+extension]++
candidate = fmt.Sprintf("%s-%d%s", generatedStem, nextSuffix[generatedStem+extension], extension)
}
destinations[source] = candidate
occupied[candidate] = true
}
return destinations
}
// SpeakerID derives the speaker identity from a prepared filename.
func SpeakerID(name string) string {
return strings.TrimSuffix(filepath.Base(name), filepath.Ext(name))
}
// ValidateSpeakerIDs rejects ambiguous prepared names and reports their sources.
func ValidateSpeakerIDs(sources []Source) error {
seen := map[string]string{}
for _, source := range sources {
id := SpeakerID(source.PreparedName)
if id == "" {
return fmt.Errorf("could not derive speaker id from %q", source.Path)
}
if previous, ok := seen[id]; ok {
return fmt.Errorf("duplicate speaker id %q from %q and %q; choose one encoding or rename recordings", id, previous, source.Path)
}
seen[id] = source.Path
}
return nil
}