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:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user