From 8a4b935792c50101cf65b36e44f376c90c2d08c1 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Wed, 21 Jan 2026 21:43:40 +0200 Subject: improve: better audio player UI and debugging for bg-bg cards - Add debug logging to navigation.go to diagnose audio file loading issues Prints paths being checked and whether files are found - Improve AudioPlayer UI for Bulgarian-Bulgarian cards: - Add labels showing 'Front' and 'Back' for bg-bg audio buttons - Labels only show when audio files are actually loaded - Better visual distinction between the two playable audios - Reorganized button layout with VBox for cleaner appearance - Track bg-bg state in AudioPlayer (isBgBg field) - Automatically set when back audio file is loaded - Used to determine when to show labels This makes it clearer that Bulgarian-Bulgarian cards have two independently playable audio outputs, and helps debug why audio isn't being loaded. --- internal/gui/app.go | 292 ++++++++++++++++++++++++++++++++----------- internal/gui/audio_player.go | 116 +++++++++++++++-- internal/gui/generator.go | 117 +++++++++++++++++ internal/gui/navigation.go | 14 +++ internal/gui/queue.go | 2 + 5 files changed, 464 insertions(+), 77 deletions(-) (limited to 'internal/gui') diff --git a/internal/gui/app.go b/internal/gui/app.go index 9374973..cb0a4fe 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -39,6 +39,7 @@ type Application struct { imageDisplay *ImageDisplay audioPlayer *AudioPlayer translationEntry *CustomEntry + cardTypeSelect *widget.Select statusLabel *widget.Label queueStatusLabel *widget.Label imagePromptEntry *CustomMultiLineEntry @@ -57,19 +58,21 @@ type Application struct { deleteButton *ttwidget.Button // State management - currentWord string - currentAudioFile string - currentImage string - currentTranslation string - currentPhonetic string // Full phonetic information - currentJobID int - savedCards []anki.Card - existingWords []string // Words already in anki_cards folder - currentWordIndex int - deleteConfirming bool // Track if we're in delete confirmation mode - quitConfirming bool // Track if we're in quit confirmation mode - wordChangeTimer *time.Timer // Timer for detecting word changes - fileCheckTicker *time.Ticker // Ticker for checking missing files + currentWord string + currentAudioFile string + currentAudioFileBack string // Back audio file for bg-bg cards + currentImage string + currentTranslation string + currentPhonetic string // Full phonetic information + currentCardType string // Card type: "en-bg" or "bg-bg" + currentJobID int + savedCards []anki.Card + existingWords []string // Words already in anki_cards folder + currentWordIndex int + deleteConfirming bool // Track if we're in delete confirmation mode + quitConfirming bool // Track if we're in quit confirmation mode + wordChangeTimer *time.Timer // Timer for detecting word changes + fileCheckTicker *time.Ticker // Ticker for checking missing files // Word processing queue queue *WordQueue @@ -257,6 +260,19 @@ func (a *Application) setupUI() { a.window.Canvas().Unfocus() }) + // Create card type selector + a.cardTypeSelect = widget.NewSelect([]string{"English → Bulgarian", "Bulgarian → Bulgarian"}, func(selected string) { + if selected == "Bulgarian → Bulgarian" { + a.currentCardType = "bg-bg" + a.translationEntry.SetPlaceHolder("Bulgarian definition...") + } else { + a.currentCardType = "en-bg" + a.translationEntry.SetPlaceHolder("English translation...") + } + }) + a.cardTypeSelect.SetSelected("English → Bulgarian") + a.currentCardType = "en-bg" + // Create navigation buttons (tooltips will be set after tooltip layer is created) a.submitButton = ttwidget.NewButton("", a.onSubmit) a.submitButton.Icon = theme.ConfirmIcon() @@ -267,10 +283,11 @@ func (a *Application) setupUI() { a.nextWordBtn = ttwidget.NewButton("", a.onNextWord) a.nextWordBtn.Icon = theme.NavigateNextIcon() - // Create a grid layout for inputs - inputGrid := container.New(layout.NewGridLayout(2), + // Create a grid layout for inputs with card type selector + inputGrid := container.New(layout.NewGridLayout(3), a.wordInput, a.translationEntry, + a.cardTypeSelect, ) inputSection := container.NewBorder( @@ -468,51 +485,55 @@ func (a *Application) Run() { // onSubmit handles word submission func (a *Application) onSubmit() { bulgarianText := strings.TrimSpace(a.wordInput.Text) - englishText := strings.TrimSpace(a.translationEntry.Text) + secondaryText := strings.TrimSpace(a.translationEntry.Text) + isBgBg := a.currentCardType == "bg-bg" // Determine which word to process and if translation is needed var wordToProcess string var needsTranslation bool var translationDirection string - if bulgarianText != "" && englishText != "" { + if isBgBg { + // Bulgarian-Bulgarian mode: both fields should be Bulgarian + if bulgarianText == "" { + return + } + wordToProcess = bulgarianText + needsTranslation = false + a.currentTranslation = secondaryText + } else if bulgarianText != "" && secondaryText != "" { // Both provided - use Bulgarian as primary, no translation needed wordToProcess = bulgarianText needsTranslation = false - a.currentTranslation = englishText - } else if bulgarianText != "" && englishText == "" { + a.currentTranslation = secondaryText + } else if bulgarianText != "" && secondaryText == "" { // Only Bulgarian provided - translate to English wordToProcess = bulgarianText needsTranslation = true translationDirection = "bg-to-en" - } else if bulgarianText == "" && englishText != "" { + } else if bulgarianText == "" && secondaryText != "" { // Only English provided - translate to Bulgarian needsTranslation = true translationDirection = "en-to-bg" - // We'll get the Bulgarian word after translation } else { - // Both empty return } // Handle English to Bulgarian translation first if needed if translationDirection == "en-to-bg" { - a.updateStatus(fmt.Sprintf("Translating '%s' to Bulgarian...", englishText)) - bulgarian, err := a.translateEnglishToBulgarian(englishText) + a.updateStatus(fmt.Sprintf("Translating '%s' to Bulgarian...", secondaryText)) + bulgarian, err := a.translateEnglishToBulgarian(secondaryText) if err != nil { dialog.ShowError(fmt.Errorf("Translation failed: %w", err), a.window) return } wordToProcess = bulgarian a.wordInput.SetText(bulgarian) - a.currentTranslation = englishText - // Update current word for saving + a.currentTranslation = secondaryText a.currentWord = bulgarian - // Save the translation immediately a.saveTranslation() - needsTranslation = false // We've already done the translation, don't translate back + needsTranslation = false } else if translationDirection == "bg-to-en" { - // Handle Bulgarian to English translation immediately a.updateStatus(fmt.Sprintf("Translating '%s' to English...", bulgarianText)) english, err := a.translateWord(bulgarianText) if err != nil { @@ -521,8 +542,7 @@ func (a *Application) onSubmit() { } a.currentTranslation = english a.translationEntry.SetText(english) - needsTranslation = false // We've already done the translation - // Save the translation immediately + needsTranslation = false a.saveTranslation() } @@ -532,6 +552,14 @@ func (a *Application) onSubmit() { return } + // For bg-bg cards, also validate the back text + if isBgBg && secondaryText != "" { + if err := audio.ValidateBulgarianText(secondaryText); err != nil { + dialog.ShowError(fmt.Errorf("invalid back text: %w", err), a.window) + return + } + } + // Get custom prompt from the UI customPrompt := a.imagePromptEntry.Text @@ -540,13 +568,11 @@ func (a *Application) onSubmit() { // Store whether translation is needed and the translation if already provided job.NeedsTranslation = needsTranslation + job.CardType = a.currentCardType if a.currentTranslation != "" { job.Translation = a.currentTranslation } - // Don't clear the input fields yet - they should stay populated - // until the user is ready to enter a new word - // Update status to show word was queued a.updateStatus(fmt.Sprintf("Added '%s' to queue (Job #%d)", wordToProcess, job.ID)) @@ -1004,36 +1030,128 @@ func (a *Application) onRegenerateRandomImage() { }() } -// onRegenerateAudio regenerates audio with a different voice +// onRegenerateAudio regenerates front audio (or single audio for en-bg cards) func (a *Application) onRegenerateAudio() { // Only disable the audio-related buttons a.regenerateAudioBtn.Disable() a.regenerateAllBtn.Disable() - a.showProgress("Regenerating audio...") + + isBgBg := a.currentCardType == "bg-bg" + if isBgBg { + a.showProgress("Regenerating front audio...") + } else { + a.showProgress("Regenerating audio...") + } a.incrementProcessing() // Audio processing starts a.wg.Add(1) go func() { defer a.wg.Done() - defer a.decrementProcessing() // Image processing ends + defer a.decrementProcessing() + + // Store the word we're generating for + wordForGeneration := a.currentWord + + a.startOperation(wordForGeneration) + defer a.endOperation(wordForGeneration) + + // Get or create context for this card + cardCtx, _ := a.getOrCreateCardContext(wordForGeneration) + + // Ensure card directory exists + cardDir, err := a.ensureCardDirectory(wordForGeneration) + if err != nil { + fyne.Do(func() { + a.showError(fmt.Errorf("Failed to create card directory: %w", err)) + }) + return + } + + if isBgBg { + // For bg-bg cards, regenerate only front audio + audioFile, err := a.generateAudioFront(cardCtx, wordForGeneration, cardDir) + if err != nil { + fyne.Do(func() { + a.showError(fmt.Errorf("Front audio regeneration failed: %w", err)) + }) + } else { + a.mu.Lock() + if a.currentWord == wordForGeneration { + a.currentAudioFile = audioFile + a.mu.Unlock() + fyne.Do(func() { + a.mu.Lock() + if a.currentWord == wordForGeneration { + a.audioPlayer.SetAudioFile(audioFile) + } + a.mu.Unlock() + }) + } else { + a.mu.Unlock() + } + } + } else { + // For en-bg cards, regenerate single audio file + audioFile, err := a.generateAudio(cardCtx, wordForGeneration, cardDir) + if err != nil { + fyne.Do(func() { + a.showError(fmt.Errorf("Audio regeneration failed: %w", err)) + }) + } else { + a.mu.Lock() + if a.currentWord == wordForGeneration { + a.currentAudioFile = audioFile + a.mu.Unlock() + fyne.Do(func() { + a.mu.Lock() + if a.currentWord == wordForGeneration { + a.audioPlayer.SetAudioFile(audioFile) + } + a.mu.Unlock() + }) + } else { + a.mu.Unlock() + } + } + } + + fyne.Do(func() { + a.hideProgress() + a.regenerateAudioBtn.Enable() + a.regenerateAllBtn.Enable() + }) + }() +} + +// onRegenerateBackAudio regenerates back audio for bg-bg cards +func (a *Application) onRegenerateBackAudio() { + if a.currentCardType != "bg-bg" { + return + } + + a.regenerateAudioBtn.Disable() + a.regenerateAllBtn.Disable() + a.showProgress("Regenerating back audio...") + + a.incrementProcessing() + + a.wg.Add(1) + go func() { + defer a.wg.Done() + defer a.decrementProcessing() - // Use the current translation to avoid re-translating translation := a.currentTranslation if translation == "" { - // Use the text from translationEntry if currentTranslation is not set translation = strings.TrimSpace(a.translationEntry.Text) } - // Store the word we're generating for wordForGeneration := a.currentWord - a.startOperation(wordForGeneration) // Track operation start - defer a.endOperation(wordForGeneration) // Track operation end + a.startOperation(wordForGeneration) + defer a.endOperation(wordForGeneration) - // Get or create context for this card cardCtx, _ := a.getOrCreateCardContext(wordForGeneration) - // Ensure card directory exists cardDir, err := a.ensureCardDirectory(wordForGeneration) if err != nil { fyne.Do(func() { @@ -1042,22 +1160,20 @@ func (a *Application) onRegenerateAudio() { return } - audioFile, err := a.generateAudio(cardCtx, wordForGeneration, cardDir) + audioFile, err := a.generateAudioBack(cardCtx, translation, cardDir) if err != nil { fyne.Do(func() { - a.showError(fmt.Errorf("Audio regeneration failed: %w", err)) + a.showError(fmt.Errorf("Back audio regeneration failed: %w", err)) }) } else { - // Only update if we're still on the same word a.mu.Lock() if a.currentWord == wordForGeneration { - a.currentAudioFile = audioFile + a.currentAudioFileBack = audioFile a.mu.Unlock() fyne.Do(func() { - // Double-check inside the UI update that we're still on the same word a.mu.Lock() if a.currentWord == wordForGeneration { - a.audioPlayer.SetAudioFile(audioFile) + a.audioPlayer.SetBackAudioFile(audioFile) } a.mu.Unlock() }) @@ -1068,7 +1184,6 @@ func (a *Application) onRegenerateAudio() { fyne.Do(func() { a.hideProgress() - // Re-enable audio-related buttons a.regenerateAudioBtn.Enable() a.regenerateAllBtn.Enable() }) @@ -1416,9 +1531,13 @@ func (a *Application) onShowHotkeys() { ## Regeneration **i/и** Regenerate image **m/м** Random image -**a/а** Regenerate audio +**a/а** Regenerate audio (front for bg-bg) +**A/А** Regenerate back audio (bg-bg only) **r/р** Regenerate all -**p/п** Play audio + +## Playback +**p/п** Play audio (front for bg-bg) +**P/П** Play back audio (bg-bg only) **u/у** Toggle auto-play ## Export & Archive @@ -1694,7 +1813,7 @@ func (a *Application) setupTooltips() { a.regenerateRandomImageBtn.SetToolTip("Random image (m)") } if a.regenerateAudioBtn != nil { - a.regenerateAudioBtn.SetToolTip("Regenerate audio (a)") + a.regenerateAudioBtn.SetToolTip("Regenerate audio (a/A for back)") } if a.regenerateAllBtn != nil { a.regenerateAllBtn.SetToolTip("Regenerate all (r)") @@ -1708,7 +1827,10 @@ func (a *Application) setupTooltips() { // Audio player tooltips if a.audioPlayer != nil && a.audioPlayer.playButton != nil { - a.audioPlayer.playButton.SetToolTip("Play audio (p)") + a.audioPlayer.playButton.SetToolTip("Play audio (p/P for back)") + } + if a.audioPlayer != nil && a.audioPlayer.playBackButton != nil { + a.audioPlayer.playBackButton.SetToolTip("Play back audio (P)") } if a.audioPlayer != nil && a.audioPlayer.stopButton != nil { a.audioPlayer.stopButton.SetToolTip("Stop audio") @@ -1860,12 +1982,22 @@ func (a *Application) processWordJob(job *WordJob) { return } + // Determine if this is a bg-bg card + isBgBg := job.CardType == "bg-bg" + + // Save card type + if isBgBg { + internal.SaveCardType(cardDir, internal.CardTypeBgBg) + } else { + internal.SaveCardType(cardDir, internal.CardTypeEnBg) + } + // Handle translation var translation string var err error - if job.NeedsTranslation { - // Translate word + if job.NeedsTranslation && !isBgBg { + // Translate word (only for en-bg cards) fyne.Do(func() { a.updateStatus(fmt.Sprintf("Translating '%s'...", job.Word)) }) @@ -1900,8 +2032,9 @@ func (a *Application) processWordJob(job *WordJob) { // Create channels for parallel operations type audioResult struct { - file string - err error + file string + fileBack string + err error } type imageResult struct { file string @@ -1925,17 +2058,25 @@ func (a *Application) processWordJob(job *WordJob) { // 1. Audio generation go func() { - a.startOperation(job.Word) // Track operation start - defer a.endOperation(job.Word) // Track operation end + a.startOperation(job.Word) + defer a.endOperation(job.Word) fyne.Do(func() { - a.incrementProcessing() // Audio processing starts + a.incrementProcessing() }) - audioFile, err := a.generateAudio(cardCtx, job.Word, cardDir) - a.decrementProcessing() // Audio processing ends + var audioFile, audioFileBack string + var err error - audioChan <- audioResult{file: audioFile, err: err} + if isBgBg && translation != "" { + // Generate audio for both sides + audioFile, audioFileBack, err = a.generateAudioBgBg(cardCtx, job.Word, translation, cardDir) + } else { + audioFile, err = a.generateAudio(cardCtx, job.Word, cardDir) + } + a.decrementProcessing() + + audioChan <- audioResult{file: audioFile, fileBack: audioFileBack, err: err} }() // 2. Image generation (includes scene description) @@ -2010,7 +2151,7 @@ func (a *Application) processWordJob(job *WordJob) { }() // Wait for all operations to complete - var audioFile, imageFile string + var audioFile, audioFileBack, imageFile string var phoneticInfo string var hasError bool @@ -2021,18 +2162,19 @@ func (a *Application) processWordJob(job *WordJob) { hasError = true } else { audioFile = audioRes.file + audioFileBack = audioRes.fileBack // Update UI with audio immediately if this is still the current job a.mu.Lock() isCurrentJob := a.currentJobID == job.ID if isCurrentJob { a.currentAudioFile = audioFile + a.currentAudioFileBack = audioFileBack } a.mu.Unlock() if isCurrentJob { fyne.Do(func() { - // Double-check that we're still on the same job before updating UI a.mu.Lock() if a.currentJobID != job.ID { a.mu.Unlock() @@ -2041,7 +2183,9 @@ func (a *Application) processWordJob(job *WordJob) { a.mu.Unlock() a.audioPlayer.SetAudioFile(audioFile) - // Enable audio-related actions + if isBgBg && audioFileBack != "" { + a.audioPlayer.SetBackAudioFile(audioFileBack) + } a.regenerateAudioBtn.Enable() }) } @@ -2282,10 +2426,14 @@ func (a *Application) setupKeyboardShortcuts() { if !a.regenerateRandomImageBtn.Disabled() { a.onRegenerateRandomImage() } - case 'а', 'А': // а = a + case 'a', 'а': // a = regenerate front audio if !a.regenerateAudioBtn.Disabled() { a.onRegenerateAudio() } + case 'A', 'А': // A = regenerate back audio (for bg-bg cards) + if a.currentCardType == "bg-bg" && !a.regenerateAudioBtn.Disabled() { + a.onRegenerateBackAudio() + } case 'р', 'Р': // р = r if !a.regenerateAllBtn.Disabled() { a.onRegenerateAll() @@ -2294,10 +2442,14 @@ func (a *Application) setupKeyboardShortcuts() { if !a.deleteButton.Disabled() { a.onDelete() } - case 'п', 'П': // п = p (play audio) + case 'p', 'п': // p = play front audio if a.currentAudioFile != "" { a.audioPlayer.Play() } + case 'P', 'П': // P = play back audio (for bg-bg cards) + if a.currentAudioFileBack != "" { + a.audioPlayer.PlayBack() + } case 'ж', 'Ж': // ж = x a.onExportToAnki() case 'в', 'В': // в = v diff --git a/internal/gui/audio_player.go b/internal/gui/audio_player.go index c0b3a0d..f9d0ad7 100644 --- a/internal/gui/audio_player.go +++ b/internal/gui/audio_player.go @@ -21,13 +21,18 @@ import ( type AudioPlayer struct { widget.BaseWidget - container *fyne.Container - playButton *ttwidget.Button - stopButton *ttwidget.Button - statusLabel *widget.Label - phoneticLabel *widget.Label + container *fyne.Container + playButton *ttwidget.Button + playButtonLabel *widget.Label // Label for front audio button + playBackButton *ttwidget.Button // Play back audio for bg-bg cards + playBackLabel *widget.Label // Label for back audio button + stopButton *ttwidget.Button + statusLabel *widget.Label + phoneticLabel *widget.Label audioFile string + audioFileBack string // Back audio file for bg-bg cards + isBgBg bool // Track if this is a bg-bg card isPlaying bool playCmd *exec.Cmd voiceInfo string // Stores voice and speed info @@ -41,6 +46,15 @@ func NewAudioPlayer() *AudioPlayer { // Create controls (tooltips will be set later after tooltip layer is created) p.playButton = ttwidget.NewButton("", p.onPlay) p.playButton.Icon = theme.MediaPlayIcon() + + p.playButtonLabel = widget.NewLabel("") + p.playButtonLabel.TextStyle = fyne.TextStyle{Bold: true} + + p.playBackButton = ttwidget.NewButton("", p.onPlayBack) + p.playBackButton.Icon = theme.MediaSkipNextIcon() + + p.playBackLabel = widget.NewLabel("") + p.playBackLabel.TextStyle = fyne.TextStyle{Bold: true} p.stopButton = ttwidget.NewButton("", p.onStop) p.stopButton.Icon = theme.MediaStopIcon() @@ -56,11 +70,17 @@ func NewAudioPlayer() *AudioPlayer { // Initially disable controls p.playButton.Disable() + p.playBackButton.Disable() + p.playBackButton.Hide() // Only show for bg-bg cards + p.playBackLabel.Hide() p.stopButton.Disable() // Create main container with phonetic display p.container = container.NewHBox( - p.playButton, + container.NewVBox( + container.NewHBox(p.playButton, p.playButtonLabel), + container.NewHBox(p.playBackButton, p.playBackLabel), + ), p.stopButton, p.phoneticLabel, layout.NewSpacer(), @@ -108,6 +128,13 @@ func (p *AudioPlayer) SetAudioFile(audioFile string) { p.voiceInfo = "" } + // Update button label based on whether this is bg-bg + if p.isBgBg { + p.playButtonLabel.SetText("Front") + } else { + p.playButtonLabel.SetText("") + } + // Format status text with voice and speed info statusText := fmt.Sprintf("Audio: %s%s", filepath.Base(audioFile), p.voiceInfo) p.statusLabel.SetText(statusText) @@ -128,16 +155,53 @@ func (p *AudioPlayer) SetAudioFile(audioFile string) { } } +// SetBackAudioFile sets the back audio file for bg-bg cards +func (p *AudioPlayer) SetBackAudioFile(audioFile string) { + p.audioFileBack = audioFile + if audioFile != "" { + p.isBgBg = true + p.playBackButton.Enable() + p.playBackButton.Show() + p.playBackLabel.SetText("Back") + p.playBackLabel.Show() + // Update front label now that we know it's bg-bg + p.playButtonLabel.SetText("Front") + } else { + p.isBgBg = false + p.playBackButton.Disable() + p.playBackButton.Hide() + p.playBackLabel.SetText("") + p.playBackLabel.Hide() + // Clear front label if not bg-bg + p.playButtonLabel.SetText("") + } + // Refresh container to update layout after show/hide + if p.container != nil { + p.container.Refresh() + } +} + // Clear clears the audio player func (p *AudioPlayer) Clear() { - p.onStop() // Stop any playing audio + p.onStop() p.audioFile = "" + p.audioFileBack = "" + p.isBgBg = false p.isPlaying = false p.voiceInfo = "" p.playButton.Disable() + p.playBackButton.Disable() + p.playBackButton.Hide() + p.playButtonLabel.SetText("") + p.playBackLabel.SetText("") + p.playBackLabel.Hide() p.stopButton.Disable() p.statusLabel.SetText("No audio loaded") p.phoneticLabel.SetText("") + // Refresh container to update layout after hiding back button + if p.container != nil { + p.container.Refresh() + } } // SetPhonetic sets the phonetic transcription text @@ -179,6 +243,35 @@ func (p *AudioPlayer) onPlay() { p.statusLabel.SetText(fmt.Sprintf("Playing: %s%s", filepath.Base(p.audioFile), p.voiceInfo)) } +// onPlayBack handles back audio button click (for bg-bg cards) +func (p *AudioPlayer) onPlayBack() { + if p.audioFileBack == "" { + return + } + + if p.isPlaying { + p.onStop() + } + + // Temporarily swap audio files to play the back audio + originalFile := p.audioFile + p.audioFile = p.audioFileBack + + if err := p.startPlayback(); err != nil { + p.statusLabel.SetText(fmt.Sprintf("Error: %v", err)) + p.audioFile = originalFile + return + } + + p.isPlaying = true + p.playButton.SetIcon(theme.MediaPauseIcon()) + p.stopButton.Enable() + p.statusLabel.SetText(fmt.Sprintf("Playing back audio: %s", filepath.Base(p.audioFileBack))) + + // Restore original file after playback starts + p.audioFile = originalFile +} + // onStop handles stop button click func (p *AudioPlayer) onStop() { if p.playCmd != nil && p.playCmd.Process != nil { @@ -201,6 +294,15 @@ func (p *AudioPlayer) Play() { } } +// PlayBack triggers back audio playback (for bg-bg cards) +func (p *AudioPlayer) PlayBack() { + if !p.playBackButton.Disabled() { + fyne.Do(func() { + p.onPlayBack() + }) + } +} + // startPlayback starts audio playback using platform-specific commands func (p *AudioPlayer) startPlayback() error { var cmd *exec.Cmd diff --git a/internal/gui/generator.go b/internal/gui/generator.go index cfb8ad3..a3a0a4d 100644 --- a/internal/gui/generator.go +++ b/internal/gui/generator.go @@ -152,6 +152,123 @@ func (a *Application) generateAudio(ctx context.Context, word string, cardDir st return outputFile, nil } +// generateAudioFront generates front audio for a bg-bg card +func (a *Application) generateAudioFront(ctx context.Context, word string, cardDir string) (string, error) { + if cardDir == "" { + return "", fmt.Errorf("card directory not provided") + } + + allVoices := []string{"alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"} + rand.Seed(time.Now().UnixNano()) + voice := allVoices[rand.Intn(len(allVoices))] + speed := 0.90 + rand.Float64()*0.10 + + audioConfig := *a.audioConfig + audioConfig.OpenAIVoice = voice + audioConfig.OpenAISpeed = speed + audioConfig.OutputDir = a.config.OutputDir + + provider, err := audio.NewProvider(&audioConfig) + if err != nil { + return "", err + } + + fmt.Printf("Generating front audio for '%s' with voice: %s, speed: %.2f\n", word, voice, speed) + frontFile := filepath.Join(cardDir, fmt.Sprintf("audio_front.%s", a.config.AudioFormat)) + if err := provider.GenerateAudio(ctx, word, frontFile); err != nil { + return "", fmt.Errorf("failed to generate front audio: %w", err) + } + + // Update metadata + metadataFile := filepath.Join(cardDir, "audio_metadata.txt") + metadata := fmt.Sprintf("voice=%s\nspeed=%.2f\ncardtype=bg-bg\n", voice, speed) + if err := os.WriteFile(metadataFile, []byte(metadata), 0644); err != nil { + fmt.Printf("Warning: Failed to save audio metadata: %v\n", err) + } + + return frontFile, nil +} + +// generateAudioBack generates back audio for a bg-bg card +func (a *Application) generateAudioBack(ctx context.Context, text string, cardDir string) (string, error) { + if cardDir == "" { + return "", fmt.Errorf("card directory not provided") + } + + allVoices := []string{"alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"} + rand.Seed(time.Now().UnixNano()) + voice := allVoices[rand.Intn(len(allVoices))] + speed := 0.90 + rand.Float64()*0.10 + + audioConfig := *a.audioConfig + audioConfig.OpenAIVoice = voice + audioConfig.OpenAISpeed = speed + audioConfig.OutputDir = a.config.OutputDir + + provider, err := audio.NewProvider(&audioConfig) + if err != nil { + return "", err + } + + fmt.Printf("Generating back audio for '%s' with voice: %s, speed: %.2f\n", text, voice, speed) + backFile := filepath.Join(cardDir, fmt.Sprintf("audio_back.%s", a.config.AudioFormat)) + if err := provider.GenerateAudio(ctx, text, backFile); err != nil { + return "", fmt.Errorf("failed to generate back audio: %w", err) + } + + return backFile, nil +} + +// generateAudioBgBg generates audio for both sides of a bg-bg card +func (a *Application) generateAudioBgBg(ctx context.Context, front, back, cardDir string) (string, string, error) { + if cardDir == "" { + return "", "", fmt.Errorf("card directory not provided") + } + + allVoices := []string{"alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"} + rand.Seed(time.Now().UnixNano()) + voice := allVoices[rand.Intn(len(allVoices))] + speed := 0.90 + rand.Float64()*0.10 + + audioConfig := *a.audioConfig + audioConfig.OpenAIVoice = voice + audioConfig.OpenAISpeed = speed + audioConfig.OutputDir = a.config.OutputDir + + provider, err := audio.NewProvider(&audioConfig) + if err != nil { + return "", "", err + } + + // Generate front audio + fmt.Printf("Generating front audio for '%s' with voice: %s, speed: %.2f\n", front, voice, speed) + frontFile := filepath.Join(cardDir, fmt.Sprintf("audio_front.%s", a.config.AudioFormat)) + if err := provider.GenerateAudio(ctx, front, frontFile); err != nil { + return "", "", fmt.Errorf("failed to generate front audio: %w", err) + } + + // Generate back audio + fmt.Printf("Generating back audio for '%s' with voice: %s, speed: %.2f\n", back, voice, speed) + backFile := filepath.Join(cardDir, fmt.Sprintf("audio_back.%s", a.config.AudioFormat)) + if err := provider.GenerateAudio(ctx, back, backFile); err != nil { + return frontFile, "", fmt.Errorf("failed to generate back audio: %w", err) + } + + // Save audio attribution + if err := a.saveAudioAttribution(front, frontFile, voice, speed); err != nil { + fmt.Printf("Warning: Failed to save audio attribution: %v\n", err) + } + + // Save voice metadata + metadataFile := filepath.Join(cardDir, "audio_metadata.txt") + metadata := fmt.Sprintf("voice=%s\nspeed=%.2f\ncardtype=bg-bg\n", voice, speed) + if err := os.WriteFile(metadataFile, []byte(metadata), 0644); err != nil { + fmt.Printf("Warning: Failed to save audio metadata: %v\n", err) + } + + return frontFile, backFile, nil +} + // generateImages downloads images for a word func (a *Application) generateImages(ctx context.Context, word string, cardDir string) (string, error) { return a.generateImagesWithPrompt(ctx, word, "", "", cardDir) diff --git a/internal/gui/navigation.go b/internal/gui/navigation.go index 4b1f8bf..82176d2 100644 --- a/internal/gui/navigation.go +++ b/internal/gui/navigation.go @@ -429,26 +429,40 @@ func (a *Application) loadExistingFiles(word string) { frontAudio := filepath.Join(wordDir, fmt.Sprintf("audio_front.%s", a.config.AudioFormat)) backAudio := filepath.Join(wordDir, fmt.Sprintf("audio_back.%s", a.config.AudioFormat)) + fmt.Printf("Looking for front audio at: %s\n", frontAudio) + fmt.Printf("Looking for back audio at: %s\n", backAudio) + if _, err := os.Stat(frontAudio); err == nil { + fmt.Printf("Found front audio file: %s\n", frontAudio) a.currentAudioFile = frontAudio fyne.Do(func() { a.audioPlayer.SetAudioFile(frontAudio) }) + } else { + fmt.Printf("Front audio file not found (error: %v)\n", err) } + if _, err := os.Stat(backAudio); err == nil { + fmt.Printf("Found back audio file: %s\n", backAudio) a.currentAudioFileBack = backAudio fyne.Do(func() { a.audioPlayer.SetBackAudioFile(backAudio) }) + } else { + fmt.Printf("Back audio file not found (error: %v)\n", err) } } else { // For en-bg cards, load standard audio file audioFile := filepath.Join(wordDir, fmt.Sprintf("audio.%s", a.config.AudioFormat)) + fmt.Printf("Looking for audio at: %s\n", audioFile) if _, err := os.Stat(audioFile); err == nil { + fmt.Printf("Found audio file: %s\n", audioFile) a.currentAudioFile = audioFile fyne.Do(func() { a.audioPlayer.SetAudioFile(audioFile) }) + } else { + fmt.Printf("Audio file not found (error: %v)\n", err) } // Hide back audio button for en-bg cards a.currentAudioFileBack = "" diff --git a/internal/gui/queue.go b/internal/gui/queue.go index 1c52c9f..86c6ffd 100644 --- a/internal/gui/queue.go +++ b/internal/gui/queue.go @@ -13,6 +13,7 @@ type WordJob struct { Word string Translation string AudioFile string + AudioFileBack string // Back audio file (only for bg-bg cards) ImageFile string // Changed from ImageFiles []string to single image Status JobStatus Error error @@ -20,6 +21,7 @@ type WordJob struct { CompletedAt time.Time CustomPrompt string // Custom prompt for image generation NeedsTranslation bool // Whether translation is needed + CardType string // Card type: "en-bg" or "bg-bg" } // JobStatus represents the current state of a job -- cgit v1.2.3