mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-06 08:04:37 +00:00
feat(webui): allow generating transcripts from video detail panel (#564)
This commit is contained in:
@@ -62,6 +62,12 @@ vi.mock('@/ui/api/client', () => ({
|
||||
json: async () => ({ languages: [] }),
|
||||
}),
|
||||
},
|
||||
'transcription-status': {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => null,
|
||||
}),
|
||||
},
|
||||
comments: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
@@ -70,6 +76,12 @@ vi.mock('@/ui/api/client', () => ({
|
||||
},
|
||||
},
|
||||
},
|
||||
'signup-info': {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ transcriptionEnabled: false }),
|
||||
}),
|
||||
},
|
||||
me: {
|
||||
$get: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
|
||||
@@ -102,7 +102,10 @@ export function MobileFileDetail({
|
||||
const { canEdit } = usePermissions(projectId)
|
||||
const { members } = useMemberStore()
|
||||
const mediaControllerRef = useRef<MediaController | null>(null)
|
||||
const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined)
|
||||
const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined, {
|
||||
canEdit: canEdit && !isPublic,
|
||||
projectId,
|
||||
})
|
||||
|
||||
const [sheetHeightPercent, setSheetHeightPercent] = useState(50)
|
||||
const [annotations, setAnnotations] = useState<Annotation[]>([])
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React, { createRef } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { TranscriptPanel } from './transcript-panel'
|
||||
|
||||
const mockLanguagesGet = vi.fn()
|
||||
const mockGeneratePost = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
transcription: {
|
||||
languages: {
|
||||
$get: () => mockLanguagesGet(),
|
||||
},
|
||||
},
|
||||
files: {
|
||||
':fileId': {
|
||||
transcripts: {
|
||||
$post: (...args: unknown[]) => mockGeneratePost(...args),
|
||||
':language': {
|
||||
$get: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
describe('TranscriptPanel empty and generating states', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
mockLanguagesGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
model: 'whisper-tiny',
|
||||
languages: [{ code: 'en', name: 'English' }],
|
||||
}),
|
||||
})
|
||||
mockGeneratePost.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ kind: 'queued', taskId: 'task-1' }),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
queryClient.clear()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows empty state with Generate Transcripts button and opens the dialog to submit', async () => {
|
||||
const onJobAccepted = vi.fn().mockResolvedValue(undefined)
|
||||
const mediaControllerRef = createRef<MediaController | null>()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TranscriptPanel
|
||||
id="transcript-panel"
|
||||
assetId="video-1"
|
||||
assetName="demo.mp4"
|
||||
languages={[]}
|
||||
canEdit
|
||||
canGenerate
|
||||
canStartGeneration
|
||||
isTranscribing={false}
|
||||
onJobAccepted={onJobAccepted}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('No transcript yet')).toBeDefined()
|
||||
expect(screen.queryByRole('combobox', { name: 'Language' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Search transcript' })).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Generate Transcripts' }))
|
||||
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Generate Transcripts' })
|
||||
expect(dialog).toBeDefined()
|
||||
const generateButton = screen.getByRole('button', { name: 'Generate' })
|
||||
await waitFor(() => expect((generateButton as HTMLButtonElement).disabled).toBe(false))
|
||||
|
||||
fireEvent.click(generateButton)
|
||||
|
||||
await waitFor(() => expect(onJobAccepted).toHaveBeenCalledWith('video-1'))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
})
|
||||
|
||||
it('disables the Generate Transcripts button when the video proxy is not ready', () => {
|
||||
const mediaControllerRef = createRef<MediaController | null>()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TranscriptPanel
|
||||
id="transcript-panel"
|
||||
assetId="video-1"
|
||||
assetName="demo.mp4"
|
||||
languages={[]}
|
||||
canEdit
|
||||
canGenerate
|
||||
canStartGeneration={false}
|
||||
isTranscribing={false}
|
||||
onJobAccepted={vi.fn()}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const button = screen.getByRole('button', { name: 'Generate Transcripts' }) as HTMLButtonElement
|
||||
expect(button.disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('shows a spinner and transcribing status while a job is running', () => {
|
||||
const mediaControllerRef = createRef<MediaController | null>()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TranscriptPanel
|
||||
id="transcript-panel"
|
||||
assetId="video-1"
|
||||
assetName="demo.mp4"
|
||||
languages={[]}
|
||||
canEdit
|
||||
canGenerate
|
||||
canStartGeneration
|
||||
isTranscribing
|
||||
onJobAccepted={vi.fn()}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
onClose={vi.fn()}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const status = screen.getByRole('status')
|
||||
expect(status.textContent).toContain('Transcribing…')
|
||||
expect(screen.queryByRole('button', { name: 'Generate Transcripts' })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,14 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { GenerateTranscriptsDialog } from '@/ui/components/file-browser/generate-transcripts-dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Empty,
|
||||
EmptyContent,
|
||||
EmptyDescription,
|
||||
EmptyHeader,
|
||||
EmptyMedia,
|
||||
EmptyTitle,
|
||||
} from '@/ui/components/ui/empty'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
@@ -10,8 +19,8 @@ import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { getLocale } from '@/ui/paraglide/runtime.js'
|
||||
import type { TranscriptSegment } from '@shumai/dtos'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
|
||||
import { skipToken, useQuery } from '@tanstack/react-query'
|
||||
import { Captions, ChevronDown, ChevronUp, Loader2, Search, X } from 'lucide-react'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
@@ -29,8 +38,13 @@ import { useTranscriptScroll } from './use-transcript-scroll'
|
||||
interface TranscriptPanelProps {
|
||||
id: string
|
||||
assetId: string
|
||||
assetName?: string
|
||||
languages: string[]
|
||||
canEdit: boolean
|
||||
canGenerate?: boolean
|
||||
canStartGeneration?: boolean
|
||||
isTranscribing?: boolean
|
||||
onJobAccepted?: (assetId: string) => Promise<void>
|
||||
mediaControllerRef: RefObject<MediaController | null>
|
||||
onClose: () => void
|
||||
className?: string
|
||||
@@ -60,8 +74,13 @@ function findMatches(segments: TranscriptSegment[], search: string) {
|
||||
export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
id,
|
||||
assetId,
|
||||
assetName = '',
|
||||
languages,
|
||||
canEdit,
|
||||
canGenerate = false,
|
||||
canStartGeneration = false,
|
||||
isTranscribing = false,
|
||||
onJobAccepted,
|
||||
mediaControllerRef,
|
||||
onClose,
|
||||
className,
|
||||
@@ -76,29 +95,33 @@ export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, locale))
|
||||
}, [languages, locale])
|
||||
const hasTranscript = options.length > 0
|
||||
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
|
||||
const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0].code
|
||||
const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0]?.code
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
const [matchIndex, setMatchIndex] = useState(0)
|
||||
const [following, setFollowing] = useState(true)
|
||||
const [activeId, setActiveId] = useState<string>()
|
||||
const [editingId, setEditingId] = useState<string>()
|
||||
const [generateDialogOpen, setGenerateDialogOpen] = useState(false)
|
||||
const toggleSearchRef = useRef<HTMLButtonElement>(null)
|
||||
const closeRef = useRef<HTMLButtonElement>(null)
|
||||
const { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel } =
|
||||
useTranscriptScroll(() => setFollowing(false))
|
||||
|
||||
const transcript = useQuery({
|
||||
queryKey: savedTranscriptKey(assetId, language),
|
||||
queryFn: async ({ signal }) => {
|
||||
const response = await client.api.files[':fileId'].transcripts[':language'].$get(
|
||||
{ param: { fileId: assetId, language } },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!response.ok) throw new Error(m.transcript_load_failed())
|
||||
return await response.json()
|
||||
},
|
||||
queryKey: savedTranscriptKey(assetId, language ?? ''),
|
||||
queryFn: language
|
||||
? async ({ signal }) => {
|
||||
const response = await client.api.files[':fileId'].transcripts[':language'].$get(
|
||||
{ param: { fileId: assetId, language } },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!response.ok) throw new Error(m.transcript_load_failed())
|
||||
return await response.json()
|
||||
}
|
||||
: skipToken,
|
||||
retry: false,
|
||||
})
|
||||
const segments = transcript.data?.segments ?? noSegments
|
||||
@@ -180,39 +203,45 @@ export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
>
|
||||
<div className="shrink-0 space-y-2 border-b border-border p-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="min-w-0 [&>[data-slot=native-select-wrapper]]:max-w-full">
|
||||
<NativeSelect
|
||||
size="sm"
|
||||
className="max-w-40 truncate"
|
||||
aria-label={m.language()}
|
||||
value={language}
|
||||
disabled={!!editingId}
|
||||
onChange={(event) => {
|
||||
cancelScroll()
|
||||
setPreferredLanguage(event.target.value)
|
||||
setMatchIndex(0)
|
||||
setFollowing(true)
|
||||
}}
|
||||
>
|
||||
{options.map(({ code, name }) => (
|
||||
<NativeSelectOption key={code} value={code}>
|
||||
{name}
|
||||
</NativeSelectOption>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
{hasTranscript && language ? (
|
||||
<div className="min-w-0 [&>[data-slot=native-select-wrapper]]:max-w-full">
|
||||
<NativeSelect
|
||||
size="sm"
|
||||
className="max-w-40 truncate"
|
||||
aria-label={m.language()}
|
||||
value={language}
|
||||
disabled={!!editingId}
|
||||
onChange={(event) => {
|
||||
cancelScroll()
|
||||
setPreferredLanguage(event.target.value)
|
||||
setMatchIndex(0)
|
||||
setFollowing(true)
|
||||
}}
|
||||
>
|
||||
{options.map(({ code, name }) => (
|
||||
<NativeSelectOption key={code} value={code}>
|
||||
{name}
|
||||
</NativeSelectOption>
|
||||
))}
|
||||
</NativeSelect>
|
||||
</div>
|
||||
) : (
|
||||
<h2 className="truncate px-1 text-sm font-medium">{m.transcript_title()}</h2>
|
||||
)}
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
ref={toggleSearchRef}
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-expanded={searchOpen}
|
||||
aria-label={m.transcript_search()}
|
||||
title={m.transcript_search()}
|
||||
onClick={toggleSearch}
|
||||
>
|
||||
<Search />
|
||||
</Button>
|
||||
{hasTranscript && (
|
||||
<Button
|
||||
ref={toggleSearchRef}
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
aria-expanded={searchOpen}
|
||||
aria-label={m.transcript_search()}
|
||||
title={m.transcript_search()}
|
||||
onClick={toggleSearch}
|
||||
>
|
||||
<Search />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
ref={closeRef}
|
||||
size="icon-sm"
|
||||
@@ -225,7 +254,7 @@ export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{searchOpen && (
|
||||
{hasTranscript && searchOpen && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Input
|
||||
autoFocus
|
||||
@@ -280,76 +309,120 @@ export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{transcript.isPending && (
|
||||
<p role="status" className="p-3 text-sm text-muted-foreground">
|
||||
{m.loading()}
|
||||
</p>
|
||||
)}
|
||||
{transcript.isError && (
|
||||
<div className="space-y-2 p-3">
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.transcript_load_failed()}
|
||||
</p>
|
||||
<Button size="sm" variant="outline" onClick={() => void transcript.refetch()}>
|
||||
{m.retry()}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{transcript.data && (
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<ScrollArea
|
||||
className="h-full [&>div>div]:block!"
|
||||
viewportProps={{
|
||||
ref: setViewport,
|
||||
tabIndex: 0,
|
||||
className: '[overflow-anchor:none]',
|
||||
onScroll,
|
||||
onWheel,
|
||||
}}
|
||||
{!hasTranscript ? (
|
||||
isTranscribing ? (
|
||||
<div
|
||||
role="status"
|
||||
className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6 text-center"
|
||||
>
|
||||
<ol className="space-y-0.5 px-2 pt-2 pb-14">
|
||||
{segments.map((segment) => {
|
||||
const segmentMatches = matches.bySegment.get(segment.id)
|
||||
return (
|
||||
<TranscriptSegmentRow
|
||||
key={segment.id}
|
||||
segment={segment}
|
||||
active={segment.id === activeId}
|
||||
matches={segmentMatches}
|
||||
selectedMatch={
|
||||
segmentMatches?.some(({ index }) => index === selectedMatch)
|
||||
? selectedMatch
|
||||
: undefined
|
||||
}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
canEdit={canEdit}
|
||||
onEdit={canEdit && !editingId ? startEditing : undefined}
|
||||
editTarget={
|
||||
segment.id === editingId
|
||||
? { assetId, language, onFinish: finishEditing }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</ScrollArea>
|
||||
{!following && !editingId && (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="pointer-events-auto rounded-full shadow-md dark:bg-background dark:hover:bg-accent"
|
||||
onClick={() => {
|
||||
viewportRef.current?.focus({ preventScroll: true })
|
||||
setFollowing(true)
|
||||
}}
|
||||
>
|
||||
{m.transcript_sync_to_playback()}
|
||||
<Loader2 className="size-6 animate-spin text-muted-foreground" aria-hidden="true" />
|
||||
<p className="text-sm text-muted-foreground">{m.transcript_generating()}</p>
|
||||
</div>
|
||||
) : (
|
||||
<Empty className="gap-4 p-6 md:p-6">
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<Captions />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle className="text-base">{m.transcript_empty_title()}</EmptyTitle>
|
||||
<EmptyDescription>{m.transcript_empty_description()}</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
{canGenerate && onJobAccepted && (
|
||||
<EmptyContent>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!canStartGeneration}
|
||||
onClick={() => setGenerateDialogOpen(true)}
|
||||
>
|
||||
{m.generate_transcripts()}
|
||||
</Button>
|
||||
</EmptyContent>
|
||||
)}
|
||||
</Empty>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{transcript.isPending && (
|
||||
<p role="status" className="p-3 text-sm text-muted-foreground">
|
||||
{m.loading()}
|
||||
</p>
|
||||
)}
|
||||
{transcript.isError && (
|
||||
<div className="space-y-2 p-3">
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.transcript_load_failed()}
|
||||
</p>
|
||||
<Button size="sm" variant="outline" onClick={() => void transcript.refetch()}>
|
||||
{m.retry()}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{transcript.data && language && (
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<ScrollArea
|
||||
className="h-full [&>div>div]:block!"
|
||||
viewportProps={{
|
||||
ref: setViewport,
|
||||
tabIndex: 0,
|
||||
className: '[overflow-anchor:none]',
|
||||
onScroll,
|
||||
onWheel,
|
||||
}}
|
||||
>
|
||||
<ol className="space-y-0.5 px-2 pt-2 pb-14">
|
||||
{segments.map((segment) => {
|
||||
const segmentMatches = matches.bySegment.get(segment.id)
|
||||
return (
|
||||
<TranscriptSegmentRow
|
||||
key={segment.id}
|
||||
segment={segment}
|
||||
active={segment.id === activeId}
|
||||
matches={segmentMatches}
|
||||
selectedMatch={
|
||||
segmentMatches?.some(({ index }) => index === selectedMatch)
|
||||
? selectedMatch
|
||||
: undefined
|
||||
}
|
||||
mediaControllerRef={mediaControllerRef}
|
||||
canEdit={canEdit}
|
||||
onEdit={canEdit && !editingId ? startEditing : undefined}
|
||||
editTarget={
|
||||
segment.id === editingId
|
||||
? { assetId, language, onFinish: finishEditing }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</ScrollArea>
|
||||
{!following && !editingId && (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="pointer-events-auto rounded-full shadow-md dark:bg-background dark:hover:bg-accent"
|
||||
onClick={() => {
|
||||
viewportRef.current?.focus({ preventScroll: true })
|
||||
setFollowing(true)
|
||||
}}
|
||||
>
|
||||
{m.transcript_sync_to_playback()}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!hasTranscript && generateDialogOpen && canGenerate && onJobAccepted && (
|
||||
<GenerateTranscriptsDialog
|
||||
assetId={assetId}
|
||||
name={assetName}
|
||||
isTranscribing={isTranscribing}
|
||||
onJobAccepted={onJobAccepted}
|
||||
onClose={() => setGenerateDialogOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
|
||||
export function useServerFeatures() {
|
||||
export function useServerFeatures(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: ['signup-info'],
|
||||
enabled,
|
||||
queryFn: async () => {
|
||||
const res = await client.api['signup-info'].$get()
|
||||
if (!res.ok) return null
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { AssetInfo, TranscriptJobStatus } from '@shumai/dtos'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fileTranscriptionStatusKey, useVideoTranscript } from './use-video-transcript'
|
||||
|
||||
const mockSignupInfoGet = vi.fn()
|
||||
const mockTranscriptsGet = vi.fn()
|
||||
const mockTranscriptionStatusGet = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
'signup-info': {
|
||||
$get: () => mockSignupInfoGet(),
|
||||
},
|
||||
files: {
|
||||
':fileId': {
|
||||
transcripts: {
|
||||
$get: (...args: unknown[]) => mockTranscriptsGet(...args),
|
||||
},
|
||||
'transcription-status': {
|
||||
$get: (...args: unknown[]) => mockTranscriptionStatusGet(...args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
function createWrapper(queryClient: QueryClient) {
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
}
|
||||
}
|
||||
|
||||
const readyVideo: AssetInfo = {
|
||||
id: 'video-1',
|
||||
name: 'demo.mp4',
|
||||
status: 'processed',
|
||||
proxyType: 'video',
|
||||
media: {
|
||||
videoTranscodes: [{ key: 'proxies/720p.mp4', resolution: '720p', width: 1280, height: 720 }],
|
||||
},
|
||||
} as AssetInfo
|
||||
|
||||
describe('useVideoTranscript', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
mockSignupInfoGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ transcriptionEnabled: false }),
|
||||
})
|
||||
mockTranscriptsGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ languages: [] }),
|
||||
})
|
||||
mockTranscriptionStatusGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => null,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
queryClient.clear()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('hides the toggle when there is no transcript and transcription is disabled', async () => {
|
||||
const { result } = renderHook(
|
||||
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce())
|
||||
await waitFor(() => expect(mockSignupInfoGet).toHaveBeenCalledOnce())
|
||||
expect(result.current).toBeUndefined()
|
||||
expect(mockTranscriptionStatusGet).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hides the toggle for read-only users when there is no transcript even if transcription is enabled', async () => {
|
||||
mockSignupInfoGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ transcriptionEnabled: true }),
|
||||
})
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(mockTranscriptsGet).toHaveBeenCalledOnce())
|
||||
expect(result.current).toBeUndefined()
|
||||
expect(mockSignupInfoGet).not.toHaveBeenCalled()
|
||||
expect(mockTranscriptionStatusGet).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the toggle for read-only users when a saved transcript exists', async () => {
|
||||
mockTranscriptsGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ languages: ['en'] }),
|
||||
})
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useVideoTranscript(readyVideo, { canEdit: false, projectId: 'proj-1' }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current).toBeDefined())
|
||||
act(() => result.current?.toggle.onToggle())
|
||||
expect(result.current?.panel?.languages).toEqual(['en'])
|
||||
expect(result.current?.panel?.canGenerate).toBe(false)
|
||||
})
|
||||
|
||||
it('shows the empty panel for editors when transcription is enabled and tracks status until completion', async () => {
|
||||
mockSignupInfoGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ transcriptionEnabled: true }),
|
||||
})
|
||||
let savedLanguages: string[] = []
|
||||
let currentStatus: TranscriptJobStatus | null = null
|
||||
mockTranscriptsGet.mockImplementation(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ languages: savedLanguages }),
|
||||
}))
|
||||
mockTranscriptionStatusGet.mockImplementation(async () => ({
|
||||
ok: true,
|
||||
json: async () => currentStatus,
|
||||
}))
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current).toBeDefined())
|
||||
act(() => result.current?.toggle.onToggle())
|
||||
expect(result.current?.panel).toMatchObject({
|
||||
assetId: 'video-1',
|
||||
assetName: 'demo.mp4',
|
||||
languages: [],
|
||||
canGenerate: true,
|
||||
canStartGeneration: true,
|
||||
isTranscribing: false,
|
||||
})
|
||||
|
||||
currentStatus = { status: 'processing', taskId: 'task-1' }
|
||||
await act(async () => {
|
||||
await result.current?.panel?.onJobAccepted('video-1')
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true))
|
||||
expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([
|
||||
'video-1',
|
||||
])
|
||||
|
||||
savedLanguages = ['en']
|
||||
currentStatus = { status: 'completed', taskId: 'task-1' }
|
||||
await act(async () => {
|
||||
await queryClient.refetchQueries({
|
||||
queryKey: fileTranscriptionStatusKey('video-1'),
|
||||
exact: true,
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current?.panel?.languages).toEqual(['en']))
|
||||
expect(result.current?.panel?.isTranscribing).toBe(false)
|
||||
expect(queryClient.getQueryData(['project-transcription-status', 'proj-1'])).toEqual([])
|
||||
})
|
||||
|
||||
it('returns to idle empty state and invalidates comments when a tracked job fails', async () => {
|
||||
mockSignupInfoGet.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ transcriptionEnabled: true }),
|
||||
})
|
||||
let currentStatus: TranscriptJobStatus | null = { status: 'processing', taskId: 'task-2' }
|
||||
mockTranscriptionStatusGet.mockImplementation(async () => ({
|
||||
ok: true,
|
||||
json: async () => currentStatus,
|
||||
}))
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useVideoTranscript(readyVideo, { canEdit: true, projectId: 'proj-1' }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current).toBeDefined())
|
||||
act(() => result.current?.toggle.onToggle())
|
||||
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(true))
|
||||
|
||||
currentStatus = { status: 'failed', taskId: 'task-2', reason: 'noAudio' }
|
||||
await act(async () => {
|
||||
await queryClient.refetchQueries({
|
||||
queryKey: fileTranscriptionStatusKey('video-1'),
|
||||
exact: true,
|
||||
})
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current?.panel?.isTranscribing).toBe(false))
|
||||
expect(result.current?.panel?.languages).toEqual([])
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['files', 'video-1', 'comments'] })
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,14 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { skipToken, useQuery } from '@tanstack/react-query'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
isTranscriptVideoReady,
|
||||
selectTranscriptVideoProxyKey,
|
||||
type AssetInfo,
|
||||
type TranscriptJobStatus,
|
||||
} from '@shumai/dtos'
|
||||
import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useCallback, useId, useRef, useState } from 'react'
|
||||
import { useServerFeatures } from './use-server-features'
|
||||
|
||||
export const savedTranscriptLanguagesKey = (assetId?: string) =>
|
||||
['files', assetId, 'transcripts'] as const
|
||||
@@ -9,11 +16,39 @@ export const savedTranscriptLanguagesKey = (assetId?: string) =>
|
||||
export const savedTranscriptKey = (assetId: string, language: string) =>
|
||||
[...savedTranscriptLanguagesKey(assetId), language] as const
|
||||
|
||||
export function useVideoTranscript(file?: Pick<AssetInfo, 'id' | 'proxyType' | 'versionStack'>) {
|
||||
const assetId =
|
||||
file?.proxyType === 'video'
|
||||
? (file.versionStack?.versions.find(({ current }) => current)?.id ?? file.id)
|
||||
: undefined
|
||||
export const fileTranscriptionStatusKey = (assetId?: string) =>
|
||||
['files', assetId, 'transcription-status'] as const
|
||||
|
||||
type VideoTranscriptFile = Pick<
|
||||
AssetInfo,
|
||||
'id' | 'name' | 'status' | 'proxyType' | 'media' | 'versionStack'
|
||||
>
|
||||
|
||||
interface UseVideoTranscriptOptions {
|
||||
canEdit?: boolean
|
||||
projectId?: string
|
||||
}
|
||||
|
||||
function isActiveTranscriptJob(status?: TranscriptJobStatus | null): boolean {
|
||||
return status?.status === 'pending' || status?.status === 'processing'
|
||||
}
|
||||
|
||||
export function useVideoTranscript(
|
||||
file?: VideoTranscriptFile,
|
||||
options?: UseVideoTranscriptOptions,
|
||||
) {
|
||||
const queryClient = useQueryClient()
|
||||
const canEdit = Boolean(options?.canEdit)
|
||||
const projectId = options?.projectId
|
||||
const currentVersion = file?.versionStack?.versions.find(({ current }) => current)
|
||||
const assetId = file?.proxyType === 'video' ? (currentVersion?.id ?? file.id) : undefined
|
||||
const assetName = currentVersion?.name || file?.name || ''
|
||||
const assetStatus = currentVersion?.status ?? file?.status ?? ''
|
||||
const canStartGeneration =
|
||||
Boolean(assetId) &&
|
||||
isTranscriptVideoReady(assetStatus) &&
|
||||
Boolean(selectTranscriptVideoProxyKey(file?.media))
|
||||
|
||||
const panelId = useId()
|
||||
const buttonRef = useRef<HTMLButtonElement>(null)
|
||||
const [selection, setSelection] = useState({ assetId, open: false })
|
||||
@@ -21,6 +56,9 @@ export function useVideoTranscript(file?: Pick<AssetInfo, 'id' | 'proxyType' | '
|
||||
setSelection({ assetId, open: false })
|
||||
}
|
||||
|
||||
const serverFeatures = useServerFeatures(Boolean(assetId && canEdit))
|
||||
const canGenerate = Boolean(assetId && canEdit && serverFeatures.data?.transcriptionEnabled)
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: savedTranscriptLanguagesKey(assetId),
|
||||
queryFn: assetId
|
||||
@@ -35,16 +73,109 @@ export function useVideoTranscript(file?: Pick<AssetInfo, 'id' | 'proxyType' | '
|
||||
: skipToken,
|
||||
})
|
||||
|
||||
const languages = data?.languages
|
||||
const hasTranscript = Boolean(languages?.length)
|
||||
const shouldTrackStatus = Boolean(
|
||||
assetId && canGenerate && languages !== undefined && !hasTranscript,
|
||||
)
|
||||
|
||||
const statusQuery = useQuery({
|
||||
queryKey: fileTranscriptionStatusKey(assetId),
|
||||
enabled: shouldTrackStatus,
|
||||
queryFn: assetId
|
||||
? async ({ signal }) => {
|
||||
const statusKey = fileTranscriptionStatusKey(assetId)
|
||||
const response = await client.api.files[':fileId']['transcription-status'].$get(
|
||||
{ param: { fileId: assetId } },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!response.ok) throw new Error(m.transcript_status_unavailable())
|
||||
const next = (await response.json()) as TranscriptJobStatus | null
|
||||
signal.throwIfAborted()
|
||||
|
||||
const previous = queryClient.getQueryData<TranscriptJobStatus | null>(statusKey)
|
||||
const wasActive = isActiveTranscriptJob(previous)
|
||||
const isActive = isActiveTranscriptJob(next)
|
||||
|
||||
if ((wasActive || previous === undefined) && next?.status === 'completed') {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: savedTranscriptLanguagesKey(assetId),
|
||||
exact: true,
|
||||
})
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
|
||||
if (wasActive && !isActive) {
|
||||
if (next?.status === 'failed') {
|
||||
void queryClient.invalidateQueries({ queryKey: ['files', assetId, 'comments'] })
|
||||
if (file?.id && file.id !== assetId) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['files', file.id, 'comments'] })
|
||||
}
|
||||
}
|
||||
if (projectId) {
|
||||
const projectStatusKey = ['project-transcription-status', projectId] as const
|
||||
queryClient.setQueryData<string[]>(projectStatusKey, (current) =>
|
||||
current?.filter((id) => id !== assetId),
|
||||
)
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: projectStatusKey,
|
||||
exact: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
: skipToken,
|
||||
refetchInterval: ({ state }) => (isActiveTranscriptJob(state.data) ? 2000 : false),
|
||||
})
|
||||
|
||||
const isTranscribing = shouldTrackStatus && isActiveTranscriptJob(statusQuery.data)
|
||||
|
||||
const trackJob = useCallback(
|
||||
async (targetAssetId: string) => {
|
||||
const statusKey = fileTranscriptionStatusKey(targetAssetId)
|
||||
// Discard any status request that started before the job was accepted.
|
||||
await queryClient.cancelQueries({ queryKey: statusKey, exact: true })
|
||||
queryClient.setQueryData<TranscriptJobStatus | null>(statusKey, (current) =>
|
||||
isActiveTranscriptJob(current) ? current : { status: 'pending', taskId: '' },
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: statusKey, exact: true })
|
||||
|
||||
if (projectId) {
|
||||
const projectStatusKey = ['project-transcription-status', projectId] as const
|
||||
await queryClient.cancelQueries({ queryKey: projectStatusKey, exact: true })
|
||||
queryClient.setQueryData<string[]>(projectStatusKey, (current) =>
|
||||
current?.includes(targetAssetId) ? current : [...(current ?? []), targetAssetId],
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: projectStatusKey, exact: true })
|
||||
}
|
||||
},
|
||||
[projectId, queryClient],
|
||||
)
|
||||
|
||||
const close = useCallback(() => {
|
||||
setSelection({ assetId, open: false })
|
||||
buttonRef.current?.focus({ preventScroll: true })
|
||||
}, [assetId])
|
||||
|
||||
if (!assetId || !data?.languages.length) return undefined
|
||||
if (!assetId || languages === undefined || (!hasTranscript && !canGenerate)) return undefined
|
||||
|
||||
const open = selection.assetId === assetId && selection.open
|
||||
return {
|
||||
panel: open ? { id: panelId, assetId, languages: data.languages, onClose: close } : undefined,
|
||||
panel: open
|
||||
? {
|
||||
id: panelId,
|
||||
assetId,
|
||||
assetName,
|
||||
languages,
|
||||
canGenerate,
|
||||
canStartGeneration,
|
||||
isTranscribing,
|
||||
onJobAccepted: trackJob,
|
||||
onClose: close,
|
||||
}
|
||||
: undefined,
|
||||
toggle: {
|
||||
panelId,
|
||||
open,
|
||||
|
||||
@@ -1847,5 +1847,7 @@
|
||||
"transcript_sync_to_playback": "Sync to playback",
|
||||
"transcript_load_failed": "Could not load this transcript.",
|
||||
"transcript_edit_segment": "Edit segment text",
|
||||
"transcript_save_failed": "Could not save this segment."
|
||||
"transcript_save_failed": "Could not save this segment.",
|
||||
"transcript_empty_title": "No transcript yet",
|
||||
"transcript_empty_description": "Generate a transcript to read, search, and jump through this video."
|
||||
}
|
||||
|
||||
@@ -1777,5 +1777,7 @@
|
||||
"transcript_sync_to_playback": "재생 위치에 맞추기",
|
||||
"transcript_load_failed": "이 전사를 불러올 수 없습니다.",
|
||||
"transcript_edit_segment": "구간 텍스트 편집",
|
||||
"transcript_save_failed": "이 구간을 저장할 수 없습니다."
|
||||
"transcript_save_failed": "이 구간을 저장할 수 없습니다.",
|
||||
"transcript_empty_title": "아직 전사가 없습니다",
|
||||
"transcript_empty_description": "전사를 생성하여 동영상 내용을 읽고 검색하며 원하는 위치로 이동하세요."
|
||||
}
|
||||
|
||||
@@ -1847,5 +1847,7 @@
|
||||
"transcript_sync_to_playback": "同步到播放位置",
|
||||
"transcript_load_failed": "无法加载此转录。",
|
||||
"transcript_edit_segment": "编辑片段文本",
|
||||
"transcript_save_failed": "无法保存此片段。"
|
||||
"transcript_save_failed": "无法保存此片段。",
|
||||
"transcript_empty_title": "暂无转录",
|
||||
"transcript_empty_description": "生成转录后,即可阅读、搜索并跳转到视频对应位置。"
|
||||
}
|
||||
|
||||
@@ -216,6 +216,7 @@ function FileViewPage() {
|
||||
const fileData = versionData || stackData
|
||||
const transcript = useVideoTranscript(
|
||||
!isMobile && !isCompareMode && fileData?.id === activeFileId ? fileData : undefined,
|
||||
{ canEdit, projectId },
|
||||
)
|
||||
const versionsDataList = versionAssetId ? versionsList : stackData?.versionStack?.versions
|
||||
|
||||
|
||||
Reference in New Issue
Block a user