Files
shumai/packages/webui/hooks/use-video-transcript.ts
T
Yiling-J d3899d1257 feat(video): add video transcripts (#559)
* feat(video): generate transcripts with the local embedding server

* feat(video): show saved transcripts in the player

* fix(video): preserve transcript seek timestamps

* fix(video): refine transcript viewing and generation

* feat(video): resize transcripts and follow playback earlier

* fix(video): animate transcript playback scrolling

* fix(video): transcribe from the smallest full proxy

* fix(video): refine the sync to playback button

* feat(video): edit transcript segment text inline

* fix(video): keep transcript segment highlighted over edit button

* docs(video): note embedding server version for transcripts
2026-12-04 13:49:25 +08:00

56 lines
1.9 KiB
TypeScript

import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { skipToken, useQuery } from '@tanstack/react-query'
import { useCallback, useId, useRef, useState } from 'react'
export const savedTranscriptLanguagesKey = (assetId?: string) =>
['files', assetId, 'transcripts'] as const
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
const panelId = useId()
const buttonRef = useRef<HTMLButtonElement>(null)
const [selection, setSelection] = useState({ assetId, open: false })
if (selection.assetId !== assetId) {
setSelection({ assetId, open: false })
}
const { data } = useQuery({
queryKey: savedTranscriptLanguagesKey(assetId),
queryFn: assetId
? async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts.$get(
{ param: { fileId: assetId } },
{ init: { signal } },
)
if (!response.ok) throw new Error('Could not fetch saved transcript languages')
return await response.json()
}
: skipToken,
})
const close = useCallback(() => {
setSelection({ assetId, open: false })
buttonRef.current?.focus({ preventScroll: true })
}, [assetId])
if (!assetId || !data?.languages.length) return undefined
const open = selection.assetId === assetId && selection.open
return {
panel: open ? { id: panelId, assetId, languages: data.languages, onClose: close } : undefined,
toggle: {
panelId,
open,
buttonRef,
onToggle: open ? close : () => setSelection({ assetId, open: true }),
},
}
}