Compare commits

...
Author SHA1 Message Date
Andrew Beveridge ☄️ e4223634d1 Merge pull request #81 from nomadkaraoke/fix/remove-instrumental-selector-export
Fix stale exports in job/index.ts and add frontend build CI check
2025-12-27 23:52:42 -05:00
Andrew BeveridgeandClaude Opus 4.5 b7c1850a3b Fix stale exports in job/index.ts and add frontend build CI check
The previous PR removed InstrumentalSelector.tsx but didn't update the
barrel export file, breaking the production build.

Changes:
- Remove stale InstrumentalSelector and StatusBadge exports from index.ts
- Add frontend-build job to CI workflow to catch build failures on PRs
- Add frontend-build to ci-gate and deploy-frontend dependencies

This ensures future PRs will fail CI if they break the frontend build.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:51:42 -05:00
Andrew Beveridge ☄️ 7736a4a8f7 Merge pull request #79 from nomadkaraoke/feature/instrumental-review-ui
Replace primitive instrumental selector with full-featured review UI
2025-12-27 23:36:45 -05:00
Andrew BeveridgeandClaude Opus 4.5 156b83ace1 Replace primitive instrumental selector with full-featured review UI
The web frontend now opens the same rich instrumental review UI that the
CLI uses. This provides waveform visualization, audio playback for
different stems, mute region selection, and custom instrumental creation.

Changes:
- Add instrumental review static HTML to frontend/public/instrumental/
- Update JobCard to open /instrumental/ page instead of showing dialog
- Remove InstrumentalSelector.tsx primitive dialog component
- Remove orphaned instrumental-review components (never used)
- Update tests to reflect link-based navigation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:34:20 -05:00
Andrew Beveridge ☄️ 8978eb6d96 Merge pull request #77 from nomadkaraoke/fix/flacfetch-youtube-url
Update flacfetch to 0.15.1 (fixes YouTube URL download)
2025-12-27 23:10:12 -05:00
Andrew Beveridge ☄️ c4143947ca Merge pull request #78 from nomadkaraoke/feature/mandatory-worktrees
Make git worktrees mandatory for all changes
2025-12-27 23:09:07 -05:00
Andrew BeveridgeandClaude Opus 4.5 8a28c95786 Simplify flacfetch workflow: no PR required
flacfetch changes can be committed directly to main once tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:07:36 -05:00
Andrew BeveridgeandClaude Opus 4.5 48acb6c4e1 Add flacfetch as a related project with workflow docs
Documents that flacfetch is a dependency we own, located at
/Users/andrew/Projects/flacfetch, and provides the workflow for
making changes to it and updating karaoke-gen's dependency.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:07:05 -05:00
Andrew BeveridgeandClaude Opus 4.5 da60495144 Clarify version bump rule applies only to code changes
Documentation-only changes (CLAUDE.md, README.md, etc.) don't require
version bumps since they don't affect deployed code.

Also reverts the unnecessary version bump from the previous commit.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:04:39 -05:00
Andrew BeveridgeandClaude Opus 4.5 e282f40758 Make git worktrees mandatory for all changes
Since all changes must go through a PR, worktrees are now required for
all changes (not just non-trivial ones). This keeps the main directory
clean on main and enables parallel work.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 23:03:54 -05:00
Andrew BeveridgeandClaude Opus 4.5 aaeda8679a Update flacfetch to 0.15.1 (fixes YouTube URL download)
Fixes the "Release.__init__() missing 1 required positional argument: 'quality'"
error that occurred when downloading from YouTube URLs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 22:59:31 -05:00
Andrew Beveridge ☄️ 6da6656c15 Merge pull request #76 from nomadkaraoke/fix/remove-deployment-tracking
Remove deployment tracking to fix PR banner
2025-12-27 22:50:44 -05:00
Andrew BeveridgeandClaude Opus 4.5 d81591ca99 Remove deployment tracking to fix PR banner
Remove the `environment` block from the deploy-frontend job to prevent
GitHub from creating deployment entries. This fixes the "This branch
has not been deployed" banner that appears on all PRs.

The deployment to GitHub Pages still works via actions/deploy-pages@v4,
but without tracked environment deployments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 22:49:44 -05:00
Andrew Beveridge ☄️ 0e66ac84ec Merge pull request #74 from nomadkaraoke/fix/youtube-url-support
Fix YouTube URL support in karaoke-gen CLI
2025-12-27 22:48:12 -05:00
Andrew BeveridgeandClaude Opus 4.5 d8e3542850 Address CodeRabbit lint feedback
- Remove f-string prefix from strings without placeholders (F541)
- Add 'from e' to ImportError handler to preserve stack trace (B904)
- Use raw string for regex pattern in pytest match (RUF043)
- Remove unused result variables (F841)
- Remove redundant KaraokePrep import in fixture (F811)
- Rename unused mock parameters with underscore prefix (ARG002)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 22:36:22 -05:00
Andrew Beveridge ☄️ 8b66e97459 Merge pull request #75 from nomadkaraoke/fix/progress-display-during-parallel-processing
Fix progress display to show step 4 when workers are active during download
2025-12-27 22:34:53 -05:00
Andrew Beveridge 8dc0a96734 Added CI gate check 2025-12-27 22:24:52 -05:00
17 changed files with 1672 additions and 970 deletions

No files matched your search

+56 -5
View File
@@ -95,6 +95,31 @@ jobs:
path: frontend/coverage/
retention-days: 7
frontend-build:
name: "Frontend - Build"
runs-on: ubuntu-latest
needs: changes
if: ${{ needs.changes.outputs.frontend == 'true' || github.ref == 'refs/heads/main' }}
steps:
- uses: actions/checkout@v4
- name: Setup Node.js with caching
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Build frontend
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
run: npm run build
# ============================================
# PACKAGE TESTS (karaoke-gen Python CLI)
# ============================================
@@ -418,6 +443,35 @@ jobs:
poetry run python -m py_compile backend/main.py backend/config.py
echo "✅ Basic syntax validation passed"
# ============================================
# CI GATE - Required status check for PRs
# ============================================
ci-gate:
name: "CI Gate"
runs-on: ubuntu-latest
needs: [frontend-unit-tests, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint]
if: always()
steps:
- name: Check results
run: |
results=(
"${{ needs.frontend-unit-tests.result }}"
"${{ needs.frontend-build.result }}"
"${{ needs.package-unit-tests.result }}"
"${{ needs.package-integration-tests.result }}"
"${{ needs.backend-unit-tests.result }}"
"${{ needs.backend-emulator-tests.result }}"
"${{ needs.backend-lint.result }}"
)
for result in "${results[@]}"; do
if [[ "$result" == "failure" || "$result" == "cancelled" ]]; then
echo "❌ CI failed"
exit 1
fi
done
echo "✅ CI passed"
# ============================================
# DEPLOYMENTS (main branch only)
# ============================================
@@ -512,11 +566,8 @@ jobs:
deploy-frontend:
name: "Deploy - Frontend (GitHub Pages)"
runs-on: ubuntu-latest
needs: [frontend-unit-tests]
if: ${{ always() && github.ref == 'refs/heads/main' && github.event_name == 'push' && (needs.frontend-unit-tests.result == 'success' || needs.frontend-unit-tests.result == 'skipped') }}
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
needs: [frontend-unit-tests, frontend-build]
if: ${{ always() && github.ref == 'refs/heads/main' && github.event_name == 'push' && (needs.frontend-unit-tests.result == 'success' || needs.frontend-unit-tests.result == 'skipped') && (needs.frontend-build.result == 'success' || needs.frontend-build.result == 'skipped') }}
steps:
- name: Checkout
uses: actions/checkout@v4
+32 -11
View File
@@ -18,18 +18,15 @@ Create descriptive branch names like `feature/add-discord-notifications`, `fix/a
### Using Git Worktrees
**For non-trivial changes** (new features, multi-file edits, refactors):
- Create a git worktree in the parent folder before making any file changes:
```bash
git worktree add ../karaoke-gen-feat-xyz feature/xyz
```
**All changes require a git worktree.** Since all changes must go through a PR, always create a worktree in the parent folder before making any file changes:
```bash
git worktree add -b feature/xyz ../karaoke-gen-feat-xyz main
```
- This keeps the main directory clean on `main` and enables parallel work on multiple features
- Name the worktree folder descriptively, e.g., `../karaoke-gen-fix-audio-sync`
**For trivial changes** (typos, single-line fixes):
- Creating a branch in the current directory is acceptable
- Use `git checkout -b fix/typo-xyz` before making changes
**Cleanup:** When done with a worktree, remove it with:
```bash
git worktree remove ../karaoke-gen-feat-xyz
@@ -75,11 +72,13 @@ Do not attempt to work around auth issues or make assumptions about credentials.
## Version Management
When committing and pushing changes, always bump the patch version in `pyproject.toml`.
When committing and pushing **code changes**, bump the patch version in `pyproject.toml`.
The version is located at `tool.poetry.version` in `pyproject.toml`. For example, if the current version is `0.70.3`, bump it to `0.70.4`.
This ensures every commit pushed to the repository has a unique version number for tracking and deployment purposes.
**Skip version bumps** for documentation-only changes (e.g., updating `CLAUDE.md`, `README.md`, or other markdown files) that don't affect deployed code.
This ensures every code release has a unique version number for tracking and deployment purposes.
## Testing Requirements
@@ -129,3 +128,25 @@ Individual test commands:
**Do not commit or push code that fails tests. Fix any test failures before proceeding.**
## Related Projects
### flacfetch
**Location:** `/Users/andrew/Projects/flacfetch`
The `flacfetch` package is a dependency of karaoke-gen that we also own. When working on features that interact with flacfetch, you can read and modify its code directly.
**Workflow for flacfetch changes:**
1. Navigate to `/Users/andrew/Projects/flacfetch`
2. Make changes directly on `main` (no PR required for this repo)
3. Run tests and ensure they pass
4. Bump the version in flacfetch's `pyproject.toml`
5. Commit and push to `main`
6. Wait for CI workflow to complete and auto-release the new version
7. Return to karaoke-gen and update the poetry dependency:
```bash
poetry update flacfetch
```
8. Commit the updated `poetry.lock` in karaoke-gen
+13 -8
View File
@@ -29,10 +29,6 @@ jest.mock('../job/OutputLinks', () => ({
OutputLinks: () => <div data-testid="output-links">Output Links</div>
}))
jest.mock('../job/InstrumentalSelector', () => ({
InstrumentalSelector: () => <div data-testid="instrumental-selector">Instrumental Selector</div>
}))
jest.mock('../audio-search/AudioSearchDialog', () => ({
AudioSearchDialog: () => <div data-testid="audio-search-dialog">Audio Search Dialog</div>
}))
@@ -135,11 +131,20 @@ describe('JobCard', () => {
expect(screen.getByRole('button', { name: 'Select Audio' })).toBeInTheDocument()
})
it('shows instrumental selection button for awaiting_instrumental_selection status', () => {
const instrumentalJob = { ...mockJob, status: 'awaiting_instrumental_selection' }
it('shows instrumental selection link for awaiting_instrumental_selection status', () => {
const instrumentalJob = {
...mockJob,
status: 'awaiting_instrumental_selection',
state_data: { instrumental_token: 'test-instrumental-token' }
}
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
expect(screen.getByRole('button', { name: 'Select Instrumental' })).toBeInTheDocument()
const instrumentalLink = screen.getByText('Select Instrumental')
expect(instrumentalLink).toBeInTheDocument()
const href = instrumentalLink.closest('a')?.getAttribute('href') || ''
expect(href).toContain('/instrumental/')
expect(href).toContain('baseApiUrl=')
expect(href).toContain('instrumentalToken=test-instrumental-token')
})
})
@@ -164,7 +169,7 @@ describe('JobCard', () => {
render(<JobCard job={instrumentalJob} onRefresh={mockOnRefresh} />)
expect(screen.getByText(/Will auto-select clean/)).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select Instrumental' })).not.toBeInTheDocument()
expect(screen.queryByText('Select Instrumental')).not.toBeInTheDocument()
})
it('shows auto-select message for awaiting_audio_selection status', () => {
@@ -1,263 +0,0 @@
"use client"
import { useRef, useState, useEffect, useCallback } from "react"
import { Button } from "@/components/ui/button"
import { Slider } from "@/components/ui/slider"
import { Play, Pause, SkipBack, SkipForward, Volume2, VolumeX } from "lucide-react"
interface AudioPlayerProps {
src: string
onTimeUpdate?: (currentTime: number) => void
onDurationChange?: (duration: number) => void
seekTo?: number
label?: string
className?: string
}
export function AudioPlayer({
src,
onTimeUpdate,
onDurationChange,
seekTo,
label,
className = "",
}: AudioPlayerProps) {
const audioRef = useRef<HTMLAudioElement>(null)
const [isPlaying, setIsPlaying] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [duration, setDuration] = useState(0)
const [volume, setVolume] = useState(1)
const [isMuted, setIsMuted] = useState(false)
const [isLoading, setIsLoading] = useState(true)
// Handle external seek requests
useEffect(() => {
if (seekTo !== undefined && audioRef.current && !isNaN(seekTo)) {
audioRef.current.currentTime = seekTo
}
}, [seekTo])
// Handle audio events
useEffect(() => {
const audio = audioRef.current
if (!audio) return
const handleTimeUpdate = () => {
setCurrentTime(audio.currentTime)
onTimeUpdate?.(audio.currentTime)
}
const handleDurationChange = () => {
setDuration(audio.duration)
onDurationChange?.(audio.duration)
}
const handleLoadedData = () => {
setIsLoading(false)
setDuration(audio.duration)
onDurationChange?.(audio.duration)
}
const handleEnded = () => {
setIsPlaying(false)
}
const handleLoadStart = () => {
setIsLoading(true)
}
const handleCanPlay = () => {
setIsLoading(false)
}
// Sync isPlaying state with actual audio element state
const handlePlay = () => {
setIsPlaying(true)
}
const handlePause = () => {
setIsPlaying(false)
}
audio.addEventListener("timeupdate", handleTimeUpdate)
audio.addEventListener("durationchange", handleDurationChange)
audio.addEventListener("loadeddata", handleLoadedData)
audio.addEventListener("ended", handleEnded)
audio.addEventListener("loadstart", handleLoadStart)
audio.addEventListener("canplay", handleCanPlay)
audio.addEventListener("play", handlePlay)
audio.addEventListener("pause", handlePause)
return () => {
audio.removeEventListener("timeupdate", handleTimeUpdate)
audio.removeEventListener("durationchange", handleDurationChange)
audio.removeEventListener("loadeddata", handleLoadedData)
audio.removeEventListener("ended", handleEnded)
audio.removeEventListener("loadstart", handleLoadStart)
audio.removeEventListener("canplay", handleCanPlay)
audio.removeEventListener("play", handlePlay)
audio.removeEventListener("pause", handlePause)
}
}, [onTimeUpdate, onDurationChange])
// Update volume
useEffect(() => {
if (audioRef.current) {
audioRef.current.volume = isMuted ? 0 : volume
}
}, [volume, isMuted])
const togglePlay = useCallback(async () => {
const audio = audioRef.current
if (!audio) return
try {
if (audio.paused) {
await audio.play()
} else {
audio.pause()
}
// State will be updated by the play/pause event listeners
} catch (error) {
// Play was prevented (e.g., user hasn't interacted with page yet)
console.warn("Audio playback was prevented:", error)
}
}, [])
const handleSeek = useCallback((value: number[]) => {
const audio = audioRef.current
if (!audio) return
const newTime = value[0]
audio.currentTime = newTime
setCurrentTime(newTime)
}, [])
const skipBackward = useCallback(() => {
const audio = audioRef.current
if (!audio) return
audio.currentTime = Math.max(0, audio.currentTime - 5)
}, [])
const skipForward = useCallback(() => {
const audio = audioRef.current
if (!audio) return
audio.currentTime = Math.min(duration, audio.currentTime + 5)
}, [duration])
const toggleMute = useCallback(() => {
setIsMuted(!isMuted)
}, [isMuted])
const handleVolumeChange = useCallback((value: number[]) => {
setVolume(value[0])
if (value[0] > 0 && isMuted) {
setIsMuted(false)
}
}, [isMuted])
const formatTime = (time: number) => {
if (isNaN(time)) return "0:00"
const minutes = Math.floor(time / 60)
const seconds = Math.floor(time % 60)
return `${minutes}:${seconds.toString().padStart(2, "0")}`
}
return (
<div className={`bg-card rounded-lg p-4 ${className}`}>
<audio ref={audioRef} src={src} preload="metadata" />
{label && (
<div className="text-sm font-medium text-muted-foreground mb-3">
{label}
</div>
)}
{/* Progress bar */}
<div className="mb-4">
<Slider
value={[currentTime]}
max={duration || 100}
step={0.1}
onValueChange={handleSeek}
disabled={isLoading}
className="w-full"
/>
<div className="flex justify-between text-xs text-muted-foreground mt-1">
<span>{formatTime(currentTime)}</span>
<span>{formatTime(duration)}</span>
</div>
</div>
{/* Controls */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={skipBackward}
disabled={isLoading}
className="h-8 w-8"
>
<SkipBack className="h-4 w-4" />
</Button>
<Button
variant="default"
size="icon"
onClick={togglePlay}
disabled={isLoading}
className="h-10 w-10"
>
{isPlaying ? (
<Pause className="h-5 w-5" />
) : (
<Play className="h-5 w-5 ml-0.5" />
)}
</Button>
<Button
variant="ghost"
size="icon"
onClick={skipForward}
disabled={isLoading}
className="h-8 w-8"
>
<SkipForward className="h-4 w-4" />
</Button>
</div>
{/* Volume control */}
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={toggleMute}
className="h-8 w-8"
>
{isMuted || volume === 0 ? (
<VolumeX className="h-4 w-4" />
) : (
<Volume2 className="h-4 w-4" />
)}
</Button>
<Slider
value={[isMuted ? 0 : volume]}
max={1}
step={0.1}
onValueChange={handleVolumeChange}
className="w-20"
/>
</div>
</div>
{isLoading && (
<div className="text-xs text-muted-foreground text-center mt-2">
Loading audio...
</div>
)}
</div>
)
}
@@ -1,3 +0,0 @@
export { WaveformDisplay } from "./waveform-display"
export { AudioPlayer } from "./audio-player"
export { RegionSelector } from "./region-selector"
@@ -1,222 +0,0 @@
"use client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Trash2, VolumeX, Plus } from "lucide-react"
interface MuteRegion {
start_seconds: number
end_seconds: number
}
interface AudibleSegment {
start_seconds: number
end_seconds: number
duration_seconds: number
avg_amplitude_db: number
}
interface RegionSelectorProps {
muteRegions: MuteRegion[]
audibleSegments?: AudibleSegment[]
onAddRegion: (region: MuteRegion) => void
onRemoveRegion: (index: number) => void
onClearAll: () => void
onSeekTo?: (time: number) => void
isSelectionMode: boolean
onToggleSelectionMode: () => void
className?: string
}
export function RegionSelector({
muteRegions,
audibleSegments = [],
onAddRegion,
onRemoveRegion,
onClearAll,
onSeekTo,
isSelectionMode,
onToggleSelectionMode,
className = "",
}: RegionSelectorProps) {
const formatTime = (seconds: number) => {
const mins = Math.floor(seconds / 60)
const secs = Math.floor(seconds % 60)
const ms = Math.floor((seconds % 1) * 100)
return `${mins}:${secs.toString().padStart(2, "0")}.${ms.toString().padStart(2, "0")}`
}
const formatDuration = (seconds: number) => {
if (seconds < 1) {
return `${Math.round(seconds * 1000)}ms`
}
return `${seconds.toFixed(1)}s`
}
const totalMutedDuration = muteRegions.reduce(
(sum, r) => sum + (r.end_seconds - r.start_seconds),
0
)
// Quick mute: add mute region for an audible segment
const handleQuickMute = (segment: AudibleSegment) => {
onAddRegion({
start_seconds: segment.start_seconds,
end_seconds: segment.end_seconds,
})
}
// Check if a segment is already muted
const isSegmentMuted = (segment: AudibleSegment) => {
return muteRegions.some(
(r) =>
r.start_seconds <= segment.start_seconds &&
r.end_seconds >= segment.end_seconds
)
}
return (
<div className={`space-y-4 ${className}`}>
{/* Selection Mode Toggle */}
<Card>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-lg">Mute Regions</CardTitle>
<Button
variant={isSelectionMode ? "default" : "outline"}
size="sm"
onClick={onToggleSelectionMode}
>
<Plus className="h-4 w-4 mr-2" />
{isSelectionMode ? "Click waveform to select" : "Add Region"}
</Button>
</div>
</CardHeader>
<CardContent>
{muteRegions.length === 0 ? (
<p className="text-sm text-muted-foreground">
No mute regions selected. Click "Add Region" and drag on the waveform to select areas to mute.
</p>
) : (
<div className="space-y-2">
{muteRegions.map((region, index) => (
<div
key={index}
className="flex items-center justify-between p-2 bg-muted/50 rounded-lg group"
>
<div className="flex items-center gap-3">
<VolumeX className="h-4 w-4 text-destructive" />
<button
onClick={() => onSeekTo?.(region.start_seconds)}
className="text-sm font-mono hover:text-primary transition-colors"
>
{formatTime(region.start_seconds)}
</button>
<span className="text-muted-foreground">→</span>
<button
onClick={() => onSeekTo?.(region.end_seconds)}
className="text-sm font-mono hover:text-primary transition-colors"
>
{formatTime(region.end_seconds)}
</button>
<Badge variant="secondary" className="ml-2">
{formatDuration(region.end_seconds - region.start_seconds)}
</Badge>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => onRemoveRegion(index)}
className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
))}
<div className="flex items-center justify-between pt-2 border-t mt-3">
<span className="text-sm text-muted-foreground">
Total muted: {formatDuration(totalMutedDuration)}
</span>
<Button
variant="ghost"
size="sm"
onClick={onClearAll}
className="text-destructive hover:text-destructive"
>
Clear All
</Button>
</div>
</div>
)}
</CardContent>
</Card>
{/* Detected Audible Segments */}
{audibleSegments.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-lg">Detected Backing Vocals</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-3">
Click a segment to jump to that time, or click the mute button to add it as a mute region.
</p>
<div className="space-y-2 max-h-64 overflow-y-auto">
{audibleSegments.map((segment, index) => {
const isMuted = isSegmentMuted(segment)
return (
<div
key={index}
className={`flex items-center justify-between p-2 rounded-lg transition-colors ${
isMuted ? "bg-destructive/10" : "bg-muted/50 hover:bg-muted"
}`}
>
<button
onClick={() => onSeekTo?.(segment.start_seconds)}
className="flex items-center gap-3 text-left"
>
<span className="text-sm font-mono">
{formatTime(segment.start_seconds)} - {formatTime(segment.end_seconds)}
</span>
<Badge variant="outline" className="text-xs">
{formatDuration(segment.duration_seconds)}
</Badge>
<Badge
variant="outline"
className={`text-xs ${
segment.avg_amplitude_db > -20
? "border-yellow-500 text-yellow-500"
: "border-muted-foreground"
}`}
>
{segment.avg_amplitude_db.toFixed(1)}dB
</Badge>
</button>
{!isMuted && (
<Button
variant="ghost"
size="sm"
onClick={() => handleQuickMute(segment)}
className="text-xs"
>
<VolumeX className="h-3 w-3 mr-1" />
Mute
</Button>
)}
{isMuted && (
<Badge variant="destructive" className="text-xs">
Muted
</Badge>
)}
</div>
)
})}
</div>
</CardContent>
</Card>
)}
</div>
)
}
@@ -1,259 +0,0 @@
"use client"
import { useRef, useEffect, useState, useCallback } from "react"
interface AudibleSegment {
start_seconds: number
end_seconds: number
duration_seconds: number
avg_amplitude_db: number
}
interface MuteRegion {
start_seconds: number
end_seconds: number
}
interface WaveformDisplayProps {
amplitudes: number[]
duration: number
currentTime?: number
segments?: AudibleSegment[]
muteRegions?: MuteRegion[]
onSeek?: (time: number) => void
onRegionSelect?: (region: MuteRegion) => void
isSelecting?: boolean
width?: number
height?: number
className?: string
}
export function WaveformDisplay({
amplitudes,
duration,
currentTime = 0,
segments = [],
muteRegions = [],
onSeek,
onRegionSelect,
isSelecting = false,
width = 800,
height = 150,
className = "",
}: WaveformDisplayProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const [isDragging, setIsDragging] = useState(false)
const [dragStart, setDragStart] = useState<number | null>(null)
const [dragEnd, setDragEnd] = useState<number | null>(null)
const [hoveredTime, setHoveredTime] = useState<number | null>(null)
// Convert time to x position
const timeToX = useCallback((time: number) => {
return (time / duration) * width
}, [duration, width])
// Convert x position to time
const xToTime = useCallback((x: number) => {
return (x / width) * duration
}, [duration, width])
// Draw the waveform
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext("2d")
if (!ctx) return
// Clear canvas
ctx.fillStyle = "#1a1a2e"
ctx.fillRect(0, 0, width, height)
const barWidth = width / amplitudes.length
const centerY = height / 2
// Draw mute regions background
ctx.fillStyle = "rgba(255, 107, 107, 0.2)"
for (const region of muteRegions) {
const startX = timeToX(region.start_seconds)
const endX = timeToX(region.end_seconds)
ctx.fillRect(startX, 0, endX - startX, height)
}
// Draw current drag selection
if (isDragging && dragStart !== null && dragEnd !== null) {
const startX = Math.min(timeToX(dragStart), timeToX(dragEnd))
const endX = Math.max(timeToX(dragStart), timeToX(dragEnd))
ctx.fillStyle = "rgba(255, 107, 107, 0.3)"
ctx.fillRect(startX, 0, endX - startX, height)
}
// Draw segment highlights
for (const segment of segments) {
const startX = timeToX(segment.start_seconds)
const endX = timeToX(segment.end_seconds)
const startIdx = Math.floor((segment.start_seconds / duration) * amplitudes.length)
const endIdx = Math.ceil((segment.end_seconds / duration) * amplitudes.length)
ctx.fillStyle = "rgba(233, 69, 96, 0.4)"
for (let i = startIdx; i < endIdx && i < amplitudes.length; i++) {
const amplitude = amplitudes[i]
const barHeight = amplitude * height * 0.8
const x = i * barWidth
ctx.fillRect(x, centerY - barHeight / 2, barWidth - 1, barHeight)
}
}
// Draw main waveform
ctx.fillStyle = "#4a90d9"
for (let i = 0; i < amplitudes.length; i++) {
const amplitude = amplitudes[i]
const barHeight = amplitude * height * 0.8
const x = i * barWidth
ctx.fillRect(x, centerY - barHeight / 2, barWidth - 1, barHeight)
}
// Draw silence threshold line
ctx.strokeStyle = "rgba(255, 255, 255, 0.2)"
ctx.setLineDash([5, 5])
ctx.beginPath()
const thresholdY = height * 0.5 // Visual representation
ctx.moveTo(0, thresholdY)
ctx.lineTo(width, thresholdY)
ctx.stroke()
ctx.setLineDash([])
// Draw playhead
if (currentTime > 0) {
const playheadX = timeToX(currentTime)
ctx.strokeStyle = "#ffffff"
ctx.lineWidth = 2
ctx.beginPath()
ctx.moveTo(playheadX, 0)
ctx.lineTo(playheadX, height)
ctx.stroke()
}
// Draw hover position
if (hoveredTime !== null && !isDragging) {
const hoverX = timeToX(hoveredTime)
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(hoverX, 0)
ctx.lineTo(hoverX, height)
ctx.stroke()
}
// Draw time axis
ctx.fillStyle = "#ffffff"
ctx.font = "10px sans-serif"
ctx.textAlign = "center"
const tickInterval = duration > 300 ? 60 : duration > 60 ? 30 : 10
for (let t = 0; t <= duration; t += tickInterval) {
const x = timeToX(t)
const minutes = Math.floor(t / 60)
const seconds = Math.floor(t % 60)
const label = `${minutes}:${seconds.toString().padStart(2, "0")}`
ctx.fillText(label, x, height - 5)
// Tick mark
ctx.strokeStyle = "rgba(255, 255, 255, 0.3)"
ctx.beginPath()
ctx.moveTo(x, height - 20)
ctx.lineTo(x, height - 15)
ctx.stroke()
}
}, [amplitudes, duration, currentTime, segments, muteRegions, width, height, isDragging, dragStart, dragEnd, hoveredTime, timeToX])
// Handle mouse events for seeking and region selection
const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current
if (!canvas) return
const rect = canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const time = xToTime(x)
if (isSelecting) {
setIsDragging(true)
setDragStart(time)
setDragEnd(time)
} else if (onSeek) {
onSeek(time)
}
}
const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current
if (!canvas) return
const rect = canvas.getBoundingClientRect()
const x = e.clientX - rect.left
const time = xToTime(x)
setHoveredTime(time)
if (isDragging && isSelecting) {
setDragEnd(time)
}
}
const handleMouseUp = () => {
if (isDragging && dragStart !== null && dragEnd !== null && onRegionSelect) {
const start = Math.min(dragStart, dragEnd)
const end = Math.max(dragStart, dragEnd)
// Only create region if it's at least 0.1 seconds
if (end - start >= 0.1) {
onRegionSelect({ start_seconds: start, end_seconds: end })
}
}
setIsDragging(false)
setDragStart(null)
setDragEnd(null)
}
const handleMouseLeave = () => {
setHoveredTime(null)
if (isDragging) {
handleMouseUp()
}
}
// Format time for tooltip
const formatTime = (time: number) => {
const minutes = Math.floor(time / 60)
const seconds = Math.floor(time % 60)
const ms = Math.floor((time % 1) * 100)
return `${minutes}:${seconds.toString().padStart(2, "0")}.${ms.toString().padStart(2, "0")}`
}
return (
<div className={`relative ${className}`}>
<canvas
ref={canvasRef}
width={width}
height={height}
className={`rounded-lg ${isSelecting ? "cursor-crosshair" : "cursor-pointer"}`}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseLeave}
/>
{/* Time tooltip */}
{hoveredTime !== null && (
<div
className="absolute top-0 transform -translate-x-1/2 bg-black/80 text-white text-xs px-2 py-1 rounded pointer-events-none"
style={{ left: timeToX(hoveredTime) }}
>
{formatTime(hoveredTime)}
</div>
)}
</div>
)
}
@@ -1,166 +0,0 @@
"use client"
import { useState, useEffect } from "react"
import { api, InstrumentalOption } from "@/lib/api"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Loader2, Music2, Play, Pause } from "lucide-react"
interface InstrumentalSelectorProps {
jobId: string
open: boolean
onClose: () => void
onSelect: () => void
}
export function InstrumentalSelector({ jobId, open, onClose, onSelect }: InstrumentalSelectorProps) {
const [options, setOptions] = useState<InstrumentalOption[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isSelecting, setIsSelecting] = useState(false)
const [error, setError] = useState("")
const [playingId, setPlayingId] = useState<string | null>(null)
const [audioElements, setAudioElements] = useState<Map<string, HTMLAudioElement>>(new Map())
useEffect(() => {
if (open) {
loadOptions()
}
return () => {
// Cleanup audio elements
audioElements.forEach(audio => {
audio.pause()
audio.src = ""
})
}
}, [open])
async function loadOptions() {
setIsLoading(true)
setError("")
try {
const data = await api.getInstrumentalOptions(jobId)
setOptions(data.options || [])
} catch (err: any) {
console.error("Failed to load instrumental options:", err)
setError(err.message || "Failed to load options")
} finally {
setIsLoading(false)
}
}
async function handleSelect(selection: 'clean' | 'with_backing') {
setIsSelecting(true)
try {
await api.selectInstrumental(jobId, selection)
onSelect()
onClose()
} catch (err: any) {
console.error("Failed to select instrumental:", err)
setError(err.message || "Failed to select instrumental")
} finally {
setIsSelecting(false)
}
}
function togglePlayback(optionId: string, audioUrl: string) {
if (playingId === optionId) {
// Pause current
const audio = audioElements.get(optionId)
if (audio) {
audio.pause()
}
setPlayingId(null)
} else {
// Stop any currently playing audio
audioElements.forEach(audio => audio.pause())
// Play new audio
let audio = audioElements.get(optionId)
if (!audio) {
audio = new Audio(audioUrl)
audio.addEventListener('ended', () => setPlayingId(null))
audioElements.set(optionId, audio)
setAudioElements(new Map(audioElements))
}
audio.play()
setPlayingId(optionId)
}
}
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700">
<DialogHeader>
<DialogTitle className="text-white">Select Instrumental Version</DialogTitle>
<DialogDescription className="text-slate-400">
Choose between a clean instrumental or one with backing vocals
</DialogDescription>
</DialogHeader>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-slate-400" />
<span className="ml-2 text-slate-400">Loading options...</span>
</div>
) : error ? (
<div className="text-center py-8 text-red-400">{error}</div>
) : options.length === 0 ? (
<div className="text-center py-8 text-slate-500">
<Music2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No instrumental options available</p>
</div>
) : (
<div className="space-y-3">
{options.map((option) => (
<div
key={option.id}
className="border border-slate-700 rounded-lg p-4 hover:bg-slate-800/50 transition-colors"
>
<div className="flex items-center justify-between gap-3">
<div className="flex-1">
<p className="font-medium text-white">{option.label}</p>
{option.duration_seconds && (
<p className="text-xs text-slate-400 mt-1">
Duration: {Math.floor(option.duration_seconds / 60)}:
{(option.duration_seconds % 60).toString().padStart(2, '0')}
</p>
)}
</div>
<div className="flex items-center gap-2">
{option.audio_url && (
<Button
size="sm"
variant="ghost"
onClick={() => togglePlayback(option.id, option.audio_url)}
className="text-slate-400 hover:text-white"
>
{playingId === option.id ? (
<Pause className="w-4 h-4" />
) : (
<Play className="w-4 h-4" />
)}
</Button>
)}
<Button
size="sm"
onClick={() => handleSelect(option.id as 'clean' | 'with_backing')}
disabled={isSelecting}
className="bg-pink-600 hover:bg-pink-500 text-white"
>
{isSelecting ? (
<Loader2 className="w-3 h-3 animate-spin" />
) : (
"Select"
)}
</Button>
</div>
</div>
</div>
))}
</div>
)}
</DialogContent>
</Dialog>
)
}
+19 -14
View File
@@ -8,7 +8,6 @@ import { Loader2, ExternalLink, Zap } from "lucide-react"
import { JobActions } from "./JobActions"
import { JobLogs } from "./JobLogs"
import { OutputLinks } from "./OutputLinks"
import { InstrumentalSelector } from "./InstrumentalSelector"
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
import { getJobStep, formatStepIndicator, getJobProgressPercent } from "@/lib/job-status"
@@ -78,7 +77,6 @@ interface JobCardProps {
export function JobCard({ job, onRefresh }: JobCardProps) {
const [showLogs, setShowLogs] = useState(false)
const [showAudioSearch, setShowAudioSearch] = useState(false)
const [showInstrumentalSelector, setShowInstrumentalSelector] = useState(false)
const { enabled: autoModeEnabled, isProcessing: isAutoProcessing } = useAutoMode()
const createdAt = new Date(job.created_at).toLocaleString()
@@ -113,6 +111,18 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
return url
}
// Build instrumental review URL for awaiting_instrumental_selection status
const getInstrumentalUrl = () => {
const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'
const baseApiUrl = `${backendUrl}/api/jobs/${job.job_id}`
const encodedApiUrl = encodeURIComponent(baseApiUrl)
let url = `/instrumental/?baseApiUrl=${encodedApiUrl}`
if (job.state_data?.instrumental_token) {
url += `&instrumentalToken=${encodeURIComponent(job.state_data.instrumental_token)}`
}
return url
}
// Render primary action button based on status
const renderPrimaryAction = () => {
if (autoModeEnabled && isInteractive) {
@@ -163,13 +173,15 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
if (job.status === "awaiting_instrumental_selection") {
return (
<Button
size="sm"
onClick={() => setShowInstrumentalSelector(true)}
className="text-xs h-7 px-3 bg-blue-600 hover:bg-blue-500"
<a
href={getInstrumentalUrl()}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-blue-600 hover:bg-blue-500 text-white"
>
<ExternalLink className="w-3 h-3" />
Select Instrumental
</Button>
</a>
)
}
@@ -235,13 +247,6 @@ export function JobCard({ job, onRefresh }: JobCardProps) {
onClose={() => setShowAudioSearch(false)}
onSelect={onRefresh}
/>
<InstrumentalSelector
jobId={job.job_id}
open={showInstrumentalSelector}
onClose={() => setShowInstrumentalSelector(false)}
onSelect={onRefresh}
/>
</div>
)
}
+1 -2
View File
@@ -1,6 +1,5 @@
export { JobCard, StatusBadge } from "./JobCard"
export { JobCard } from "./JobCard"
export { JobActions } from "./JobActions"
export { JobLogs } from "./JobLogs"
export { OutputLinks } from "./OutputLinks"
export { InstrumentalSelector } from "./InstrumentalSelector"
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1696,7 +1696,7 @@ class RemoteFlacFetchAudioFetcher(AudioFetcher):
import re
self.logger.info(f"[RemoteFlacFetcher] Downloading from URL: {url}")
self.logger.info(f"[RemoteFlacFetcher] Using local flacfetch for YouTube download (no remote API needed)")
self.logger.info("[RemoteFlacFetcher] Using local flacfetch for YouTube download (no remote API needed)")
try:
# Use local flacfetch for YouTube downloads - no need for remote API
@@ -1762,7 +1762,7 @@ class RemoteFlacFetchAudioFetcher(AudioFetcher):
except ImportError as e:
raise DownloadError(
f"flacfetch is required for URL downloads but import failed: {e}"
)
) from e
except Exception as e:
raise DownloadError(f"Failed to download from URL {url}: {e}") from e
+1 -1
View File
@@ -503,7 +503,7 @@ class KaraokePrep:
)
# Update extractor to reflect the source
self.extractor = f"youtube"
self.extractor = "youtube"
else:
# Use flacfetch to search and download audio
self.logger.info(f"Using flacfetch to search and download: {self.artist} - {self.title}")
Generated
+3 -3
View File
@@ -1873,14 +1873,14 @@ platformdirs = ">=4.3.6"
[[package]]
name = "flacfetch"
version = "0.15.0"
version = "0.15.1"
description = "Search and download high-quality audio from multiple sources"
optional = false
python-versions = ">=3.8"
groups = ["main"]
files = [
{file = "flacfetch-0.15.0-py3-none-any.whl", hash = "sha256:fa2eb155dd92113d37952fe0df5587ce472c85d5c924574342955c0968e802a1"},
{file = "flacfetch-0.15.0.tar.gz", hash = "sha256:ff7ce633d89fae69c7c221a8244afdf56598bfbe2b1ae71e6584df424b9ca995"},
{file = "flacfetch-0.15.1-py3-none-any.whl", hash = "sha256:d50beda83866a8d5567e50e6a2f714379a3c48fae23ccbe5f8153403a5979f09"},
{file = "flacfetch-0.15.1.tar.gz", hash = "sha256:d0953931e63d858d71f5e9ece61a82886b8104c2b30be0bdf7b53c97290e6610"},
]
[package.dependencies]
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.76.17"
version = "0.76.20"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+9 -4
View File
@@ -568,7 +568,7 @@ class TestAsync:
basic_karaoke_gen.title = None # Missing title
# Test that ValueError is raised
with pytest.raises(ValueError, match="Either a local file path.*or both artist and title must be provided"):
with pytest.raises(ValueError, match=r"Either a local file path.*or both artist and title must be provided"):
await basic_karaoke_gen.process()
@pytest.mark.asyncio
@@ -610,7 +610,10 @@ class TestAsync:
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
mock_prep_single_track.return_value = {"track": "result"}
result = await basic_karaoke_gen.process()
await basic_karaoke_gen.process()
# Verify prep_single_track was called
mock_prep_single_track.assert_called_once()
# Verify URL mode was enabled
assert basic_karaoke_gen._use_audio_fetcher is True
@@ -631,7 +634,10 @@ class TestAsync:
with patch.object(basic_karaoke_gen, 'prep_single_track', new_callable=AsyncMock) as mock_prep_single_track:
mock_prep_single_track.return_value = {"track": "result"}
result = await basic_karaoke_gen.process()
await basic_karaoke_gen.process()
# Verify prep_single_track was called
mock_prep_single_track.assert_called_once()
# Verify URL mode was enabled
assert basic_karaoke_gen._use_audio_fetcher is True
@@ -645,7 +651,6 @@ class TestKaraokePrepIsUrlHelper:
@pytest.fixture
def karaoke_prep(self, tmp_path):
"""Create a KaraokePrep instance for testing."""
from karaoke_gen.karaoke_gen import KaraokePrep
return KaraokePrep(
artist="Test",
title="Test",
+6 -6
View File
@@ -2452,7 +2452,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
mock_manager.download_by_id.return_value = downloaded_path
mock_get_manager.return_value = mock_manager
result = fetcher.download_from_url(
fetcher.download_from_url(
url="https://www.youtube.com/embed/dQw4w9WgXcQ",
output_dir=str(tmp_path),
)
@@ -2468,7 +2468,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
mock_manager.download_by_id.return_value = downloaded_path
mock_get_manager.return_value = mock_manager
result = fetcher.download_from_url(
fetcher.download_from_url(
url="https://www.youtube.com/watch?v=test123test",
output_dir=str(tmp_path),
artist="Test Artist",
@@ -2486,7 +2486,7 @@ class TestFlacFetchAudioFetcherDownloadFromUrl:
mock_manager.download_by_id.return_value = downloaded_path
mock_get_manager.return_value = mock_manager
result = fetcher.download_from_url(
fetcher.download_from_url(
url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
output_dir=str(tmp_path),
)
@@ -2563,7 +2563,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
@patch('flacfetch.providers.youtube.YoutubeProvider')
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
def test_download_from_url_uses_local_flacfetch(
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
self, mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
):
"""Test that download_from_url uses local flacfetch (not remote API)."""
mock_manager_instance = MagicMock()
@@ -2593,7 +2593,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
@patch('flacfetch.providers.youtube.YoutubeProvider')
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
def test_download_from_url_extracts_video_id(
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
self, _mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
):
"""Test that video ID is extracted from URL correctly."""
mock_manager_instance = MagicMock()
@@ -2612,7 +2612,7 @@ class TestRemoteFlacFetchAudioFetcherDownloadFromUrl:
@patch('flacfetch.providers.youtube.YoutubeProvider')
@patch('flacfetch.downloaders.youtube.YoutubeDownloader')
def test_download_from_url_raises_on_failure(
self, mock_yt_downloader, mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
self, _mock_yt_downloader, _mock_yt_provider, mock_fetch_manager, fetcher, tmp_path
):
"""Test that DownloadError is raised on failure."""
mock_manager_instance = MagicMock()