mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
feat: show all incomplete jobs first + hide-completed toggle (#393)
## Summary - **Priority sorting**: Blocking + processing jobs always appear first in Recent Jobs, regardless of creation date - **Hide completed toggle**: Eye/EyeOff button filters out completed and failed jobs, showing only incomplete ones - **Persistent preferences**: Both the display limit dropdown and hide-completed toggle persist in localStorage across page reloads - **Oversized lyrics truncation fix**: Corrected screen generation for songs with unusually long lyric lines ## Changes - `frontend/lib/job-status.ts`: Added `hideCompleted` parameter to `getDisplayJobs()` — filters by job priority before applying display limit - `frontend/app/app/page.tsx`: Added Eye/EyeOff toggle with tooltip, localStorage persistence for both `jobLimit` and `hideCompleted` - `frontend/__tests__/job-status.test.ts`: 5 new tests covering hideCompleted filtering behavior ## Test plan - [x] All 168 tests pass (`make test`) - [x] 85 job-status unit tests pass including 5 new hideCompleted tests - [ ] Visual verification: toggle button appears next to limit dropdown, state persists on reload <!-- @coderabbitai ignore --> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
fe51369d30
commit
4fe960481b
8 files changed
+321
-15
No files matched your search
@@ -2,7 +2,7 @@
|
||||
* Unit tests for job-status.ts utility functions
|
||||
*/
|
||||
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, JobStep } from '../lib/job-status';
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, getJobProgressPercent, getJobPriority, sortJobsByPriority, getDisplayJobs, JobStep } from '../lib/job-status';
|
||||
import type { Job } from '../lib/api';
|
||||
|
||||
// Helper to create a minimal Job object for testing
|
||||
@@ -595,3 +595,138 @@ describe('sortJobsByPriority', () => {
|
||||
expect(sorted[4].status).toBe('failed'); // failed
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDisplayJobs', () => {
|
||||
// Helper: pre-sorted jobs (blocking, processing, complete, failed)
|
||||
function createSortedJobs(counts: { blocking?: number; processing?: number; complete?: number; failed?: number }): Job[] {
|
||||
const jobs: Job[] = [];
|
||||
let t = 20; // descending timestamp within each priority group
|
||||
for (let i = 0; i < (counts.blocking ?? 0); i++) {
|
||||
jobs.push({ job_id: `blocking-${i}`, status: 'awaiting_review', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.processing ?? 0); i++) {
|
||||
jobs.push({ job_id: `processing-${i}`, status: 'rendering_video', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.complete ?? 0); i++) {
|
||||
jobs.push({ job_id: `complete-${i}`, status: 'complete', progress: 100, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
for (let i = 0; i < (counts.failed ?? 0); i++) {
|
||||
jobs.push({ job_id: `failed-${i}`, status: 'failed', progress: 0, created_at: `2024-01-01T${t--}:00:00Z`, updated_at: '2024-01-01T00:00:00Z' });
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
it('returns all jobs when fewer than display limit', () => {
|
||||
const jobs = createSortedJobs({ complete: 3 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(3);
|
||||
expect(totalFetched).toBe(3);
|
||||
});
|
||||
|
||||
it('returns empty array for empty input', () => {
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs([], 5);
|
||||
expect(displayedJobs).toHaveLength(0);
|
||||
expect(totalFetched).toBe(0);
|
||||
});
|
||||
|
||||
it('limits to displayLimit when no incomplete jobs', () => {
|
||||
const jobs = createSortedJobs({ complete: 10 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('expands beyond limit when more incomplete than limit', () => {
|
||||
const jobs = createSortedJobs({ blocking: 3, processing: 4, complete: 5 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// 7 incomplete > limit of 5, so show all 7
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
expect(displayedJobs.filter(j => j.status === 'awaiting_review')).toHaveLength(3);
|
||||
expect(displayedJobs.filter(j => j.status === 'rendering_video')).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('fills remaining slots with completed when fewer incomplete than limit', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 10 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// 2 incomplete < 5 limit, so show 5 total (2 incomplete + 3 completed)
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
expect(displayedJobs[0].status).toBe('awaiting_review');
|
||||
expect(displayedJobs[1].status).toBe('rendering_video');
|
||||
expect(displayedJobs[2].status).toBe('complete');
|
||||
});
|
||||
|
||||
it('returns all jobs when displayLimit is -1 (All mode)', () => {
|
||||
const jobs = createSortedJobs({ blocking: 2, complete: 20 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(22);
|
||||
expect(totalFetched).toBe(22);
|
||||
});
|
||||
|
||||
it('preserves sort order from input', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 1, complete: 3 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
expect(displayedJobs[0].status).toBe('awaiting_review');
|
||||
expect(displayedJobs[1].status).toBe('rendering_video');
|
||||
expect(displayedJobs[2].status).toBe('complete');
|
||||
expect(displayedJobs[3].status).toBe('complete');
|
||||
expect(displayedJobs[4].status).toBe('complete');
|
||||
});
|
||||
|
||||
describe('hideCompleted filter', () => {
|
||||
it('filters out complete and failed jobs when hideCompleted is true', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, processing: 2, complete: 5, failed: 3 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, -1, true);
|
||||
expect(totalFetched).toBe(11);
|
||||
expect(displayedJobs).toHaveLength(3);
|
||||
expect(displayedJobs.every(j => j.status === 'awaiting_review' || j.status === 'rendering_video')).toBe(true);
|
||||
});
|
||||
|
||||
it('respects display limit after filtering', () => {
|
||||
const jobs = createSortedJobs({ blocking: 2, processing: 5, complete: 10 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5, true);
|
||||
// 7 incomplete jobs, all visible since incomplete count (7) > limit (5)
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('returns empty when all jobs are complete and hideCompleted is true', () => {
|
||||
const jobs = createSortedJobs({ complete: 10 });
|
||||
const { displayedJobs, totalFetched } = getDisplayJobs(jobs, 5, true);
|
||||
expect(displayedJobs).toHaveLength(0);
|
||||
expect(totalFetched).toBe(10);
|
||||
});
|
||||
|
||||
it('does not filter when hideCompleted is false', () => {
|
||||
const jobs = createSortedJobs({ blocking: 1, complete: 5, failed: 2 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1, false);
|
||||
expect(displayedJobs).toHaveLength(8);
|
||||
});
|
||||
|
||||
it('defaults to showing all when hideCompleted is omitted', () => {
|
||||
const jobs = createSortedJobs({ complete: 5, failed: 2 });
|
||||
const { displayedJobs } = getDisplayJobs(jobs, -1);
|
||||
expect(displayedJobs).toHaveLength(7);
|
||||
});
|
||||
});
|
||||
|
||||
it('core bug: old incomplete job visible even when recent jobs are all completed', () => {
|
||||
// Simulate the bug scenario: 5 recent completed jobs + 1 older blocking job
|
||||
// With old behavior (LIMIT 5 at query), the blocking job would never be fetched.
|
||||
// With new behavior, all 6 are fetched and display limit of 5 expands to show blocking.
|
||||
const jobs = sortJobsByPriority([
|
||||
{ job_id: 'old-blocking', status: 'awaiting_review', progress: 0, created_at: '2024-01-01T01:00:00Z', updated_at: '2024-01-01T01:00:00Z' },
|
||||
{ job_id: 'new-1', status: 'complete', progress: 100, created_at: '2024-01-10T01:00:00Z', updated_at: '2024-01-10T01:00:00Z' },
|
||||
{ job_id: 'new-2', status: 'complete', progress: 100, created_at: '2024-01-09T01:00:00Z', updated_at: '2024-01-09T01:00:00Z' },
|
||||
{ job_id: 'new-3', status: 'complete', progress: 100, created_at: '2024-01-08T01:00:00Z', updated_at: '2024-01-08T01:00:00Z' },
|
||||
{ job_id: 'new-4', status: 'complete', progress: 100, created_at: '2024-01-07T01:00:00Z', updated_at: '2024-01-07T01:00:00Z' },
|
||||
{ job_id: 'new-5', status: 'complete', progress: 100, created_at: '2024-01-06T01:00:00Z', updated_at: '2024-01-06T01:00:00Z' },
|
||||
]);
|
||||
|
||||
const { displayedJobs } = getDisplayJobs(jobs, 5);
|
||||
// The blocking job must be visible
|
||||
const blockingJobs = displayedJobs.filter(j => j.status === 'awaiting_review');
|
||||
expect(blockingJobs).toHaveLength(1);
|
||||
expect(blockingJobs[0].job_id).toBe('old-blocking');
|
||||
// Should show 5 total (1 incomplete + 4 completed, since limit is 5 and max(5, 1) = 5)
|
||||
expect(displayedJobs).toHaveLength(5);
|
||||
});
|
||||
});
|
||||
+57
-13
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback, Suspense, useRef } from "react"
|
||||
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { api, Job, getAccessToken } from "@/lib/api"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun } from "lucide-react"
|
||||
import { sortJobsByPriority } from "@/lib/job-status"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Eye, EyeOff } from "lucide-react"
|
||||
import { sortJobsByPriority, getDisplayJobs } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { JobSubmission } from "@/components/job/JobSubmission"
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
function AppPageContent() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [jobs, setJobs] = useState<Job[]>([])
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
const [isLoadingJobs, setIsLoadingJobs] = useState(true)
|
||||
const [isInitialLoad, setIsInitialLoad] = useState(true)
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
@@ -44,11 +44,25 @@ function AppPageContent() {
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(5)
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 5
|
||||
const saved = localStorage.getItem("nomad-karaoke-job-limit")
|
||||
return saved ? Number(saved) : 5
|
||||
})
|
||||
const [hideCompleted, setHideCompleted] = useState<boolean>(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-karaoke-hide-completed") === "true"
|
||||
})
|
||||
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Derive displayed jobs from allJobs + display limit + filter (instant, no re-fetch)
|
||||
const { displayedJobs: jobs, totalFetched } = useMemo(
|
||||
() => getDisplayJobs(allJobs, jobLimit, hideCompleted),
|
||||
[allJobs, jobLimit, hideCompleted]
|
||||
)
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
const loadJobs = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
@@ -57,13 +71,13 @@ function AppPageContent() {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Only admins can filter test jobs, and by default we hide them
|
||||
// Always fetch 100 jobs; display limit is applied client-side
|
||||
const data = await api.listJobs({
|
||||
limit: jobLimit === -1 ? 100 : jobLimit,
|
||||
limit: 100,
|
||||
exclude_test: isAdmin ? !showTestData : undefined
|
||||
})
|
||||
// Sort: blocking jobs first, then processing, then completed
|
||||
setJobs(sortJobsByPriority(data))
|
||||
setAllJobs(sortJobsByPriority(data))
|
||||
} catch (err: any) {
|
||||
// Don't log auth errors - user just needs to authenticate
|
||||
if (err?.status !== 401) {
|
||||
@@ -73,10 +87,10 @@ function AppPageContent() {
|
||||
setIsLoadingJobs(false)
|
||||
setIsInitialLoad(false)
|
||||
}
|
||||
}, [isAdmin, showTestData, jobLimit])
|
||||
}, [isAdmin, showTestData])
|
||||
|
||||
// Enable notifications for job status changes (sound + title animation)
|
||||
useJobNotifications(jobs)
|
||||
useJobNotifications(allJobs)
|
||||
|
||||
// Refresh jobs immediately when tab becomes visible (after returning from review UIs)
|
||||
useVisibilityRefresh(loadJobs, isAuthenticated === true)
|
||||
@@ -158,7 +172,7 @@ function AppPageContent() {
|
||||
return (
|
||||
<div className="min-h-screen animated-gradient">
|
||||
{/* AutoProcessor - handles non-interactive mode for jobs with that flag */}
|
||||
<AutoProcessor jobs={jobs} onJobsChanged={loadJobs} />
|
||||
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
|
||||
|
||||
{/* Header */}
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
@@ -235,7 +249,33 @@ function AppPageContent() {
|
||||
<CardTitle style={{ color: 'var(--text)' }}>Recent Jobs</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
{isLoadingJobs && <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--text-muted)' }} />}
|
||||
<Select value={String(jobLimit)} onValueChange={(v) => setJobLimit(Number(v))}>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
onClick={() => {
|
||||
const next = !hideCompleted
|
||||
setHideCompleted(next)
|
||||
localStorage.setItem("nomad-karaoke-hide-completed", String(next))
|
||||
}}
|
||||
>
|
||||
{hideCompleted ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{hideCompleted ? "Show all jobs" : "Hide completed jobs"}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<Select value={String(jobLimit)} onValueChange={(v) => {
|
||||
const val = Number(v)
|
||||
setJobLimit(val)
|
||||
localStorage.setItem("nomad-karaoke-job-limit", String(val))
|
||||
}}>
|
||||
<SelectTrigger className="h-7 w-[80px] text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -249,7 +289,11 @@ function AppPageContent() {
|
||||
</div>
|
||||
</div>
|
||||
<CardDescription style={{ color: 'var(--text-muted)' }}>
|
||||
{jobs.length} job{jobs.length !== 1 ? 's' : ''} shown
|
||||
{hideCompleted
|
||||
? `${jobs.length} incomplete of ${totalFetched} total`
|
||||
: jobs.length < totalFetched
|
||||
? `Showing ${jobs.length} of ${totalFetched} jobs`
|
||||
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="px-3 sm:px-6">
|
||||
|
||||
@@ -292,3 +292,42 @@ export function sortJobsByPriority(jobs: Job[]): Job[] {
|
||||
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Select which jobs to display from a sorted list, ensuring all incomplete
|
||||
* jobs (blocking + processing) are always visible even if they exceed the
|
||||
* display limit. Completed/failed jobs fill remaining slots.
|
||||
*
|
||||
* @param sortedJobs - Jobs already sorted by sortJobsByPriority
|
||||
* @param displayLimit - Max jobs to show (-1 = show all)
|
||||
* @returns Object with displayedJobs array and totalFetched count
|
||||
*/
|
||||
export function getDisplayJobs(
|
||||
sortedJobs: Job[],
|
||||
displayLimit: number,
|
||||
hideCompleted: boolean = false
|
||||
): { displayedJobs: Job[]; totalFetched: number } {
|
||||
const totalFetched = sortedJobs.length;
|
||||
|
||||
// Filter out completed/failed jobs when toggle is on
|
||||
const filteredJobs = hideCompleted
|
||||
? sortedJobs.filter((job) => getJobPriority(job) <= 1)
|
||||
: sortedJobs;
|
||||
|
||||
// Show all: -1 or fewer jobs than limit
|
||||
if (displayLimit === -1 || filteredJobs.length <= displayLimit) {
|
||||
return { displayedJobs: filteredJobs, totalFetched };
|
||||
}
|
||||
|
||||
// Count incomplete jobs (priority 0 = blocking, 1 = processing)
|
||||
const incompleteCount = filteredJobs.filter(
|
||||
(job) => getJobPriority(job) <= 1
|
||||
).length;
|
||||
|
||||
// Show at least displayLimit jobs, but expand if there are more incomplete
|
||||
const showCount = Math.max(displayLimit, incompleteCount);
|
||||
return {
|
||||
displayedJobs: filteredJobs.slice(0, showCount),
|
||||
totalFetched,
|
||||
};
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 463 KiB After Width: | Height: | Size: 463 KiB |
@@ -27,6 +27,11 @@ class LyricsProviderConfig:
|
||||
class BaseLyricsProvider(ABC):
|
||||
"""Base class for lyrics providers."""
|
||||
|
||||
# Lyrics text beyond this length are almost certainly not real song lyrics
|
||||
# (e.g. screenplays, articles, or other non-lyrics content from web scraping).
|
||||
# Typical songs are 1000-4000 chars; 3000 is a safe truncation point.
|
||||
MAX_LYRICS_LENGTH = 3000
|
||||
|
||||
def __init__(self, config: LyricsProviderConfig, logger: Optional[logging.Logger] = None):
|
||||
self.logger = logger or logging.getLogger(__name__)
|
||||
self.cache_dir = Path(config.cache_dir) if config.cache_dir else None
|
||||
@@ -123,6 +128,20 @@ class BaseLyricsProvider(ABC):
|
||||
Returns:
|
||||
List of LyricsSegment objects with unique IDs and Word objects
|
||||
"""
|
||||
# Guard against abnormally long text (screenplays, articles, etc.)
|
||||
if len(text) > self.MAX_LYRICS_LENGTH:
|
||||
self.logger.warning(
|
||||
f"{self.get_name()}: Lyrics text is {len(text):,} chars, truncating to ~{self.MAX_LYRICS_LENGTH:,} "
|
||||
f"(likely non-lyrics content)"
|
||||
)
|
||||
# Truncate at the last complete line before the limit
|
||||
truncated = text[: self.MAX_LYRICS_LENGTH]
|
||||
last_newline = truncated.rfind("\n")
|
||||
if last_newline > 0:
|
||||
text = truncated[:last_newline]
|
||||
else:
|
||||
text = truncated
|
||||
|
||||
segments = []
|
||||
lines = text.strip().split("\n")
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.118.1"
|
||||
version = "0.118.3"
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Tests for BaseLyricsProvider, specifically the MAX_LYRICS_LENGTH truncation guard."""
|
||||
|
||||
import logging
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.lyrics.base_lyrics_provider import BaseLyricsProvider, LyricsProviderConfig
|
||||
from karaoke_gen.lyrics_transcriber.types import LyricsData
|
||||
|
||||
|
||||
class StubProvider(BaseLyricsProvider):
|
||||
"""Minimal concrete subclass for testing base class methods."""
|
||||
|
||||
def _fetch_data_from_source(self, artist: str, title: str) -> Optional[Dict[str, Any]]:
|
||||
return None
|
||||
|
||||
def _convert_result_format(self, raw_data: Dict[str, Any]) -> LyricsData:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class TestCreateSegmentsWithWords:
|
||||
def _make_provider(self) -> StubProvider:
|
||||
config = LyricsProviderConfig()
|
||||
return StubProvider(config, logger=logging.getLogger("test"))
|
||||
|
||||
def test_short_text_unchanged(self):
|
||||
provider = self._make_provider()
|
||||
text = "Hello world\nThis is a song\nLa la la"
|
||||
segments = provider._create_segments_with_words(text)
|
||||
assert len(segments) == 3
|
||||
assert segments[0].text == "Hello world"
|
||||
|
||||
def test_text_at_limit_unchanged(self):
|
||||
provider = self._make_provider()
|
||||
# Build text exactly at the limit
|
||||
line = "A" * 49 + "\n" # 50 chars per line including newline
|
||||
text = (line * (BaseLyricsProvider.MAX_LYRICS_LENGTH // 50)).rstrip()
|
||||
assert len(text) <= BaseLyricsProvider.MAX_LYRICS_LENGTH
|
||||
segments = provider._create_segments_with_words(text)
|
||||
# All lines should be present
|
||||
assert len(segments) == BaseLyricsProvider.MAX_LYRICS_LENGTH // 50
|
||||
|
||||
def test_long_text_truncated(self):
|
||||
provider = self._make_provider()
|
||||
# Create text well over the limit (simulating a screenplay)
|
||||
lines = [f"Line number {i} of the screenplay" for i in range(500)]
|
||||
text = "\n".join(lines)
|
||||
assert len(text) > BaseLyricsProvider.MAX_LYRICS_LENGTH
|
||||
|
||||
segments = provider._create_segments_with_words(text)
|
||||
# Should have far fewer segments than the original 500 lines
|
||||
total_text = "\n".join(s.text for s in segments)
|
||||
assert len(total_text) <= BaseLyricsProvider.MAX_LYRICS_LENGTH
|
||||
|
||||
def test_truncation_preserves_complete_lines(self):
|
||||
provider = self._make_provider()
|
||||
lines = [f"Line {i}: some lyrics text here" for i in range(200)]
|
||||
text = "\n".join(lines)
|
||||
|
||||
segments = provider._create_segments_with_words(text)
|
||||
# Each segment should be a complete line (not cut mid-word)
|
||||
for seg in segments:
|
||||
assert seg.text.startswith("Line ")
|
||||
|
||||
def test_truncation_logs_warning(self, caplog):
|
||||
provider = self._make_provider()
|
||||
text = "x\n" * 5000 # Way over limit
|
||||
with caplog.at_level(logging.WARNING):
|
||||
provider._create_segments_with_words(text)
|
||||
assert "truncating" in caplog.text.lower()
|
||||
Reference in new issue
Block a user