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
This commit is contained in:
Yiling-J
2026-12-04 13:49:25 +08:00
committed by GitHub
parent e420f03b35
commit d3899d1257
69 changed files with 7635 additions and 174 deletions
@@ -0,0 +1,352 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import type { MediaController } from '@/ui/components/viewers/types'
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
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 {
memo,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type RefObject,
} from 'react'
import { TranscriptSegmentRow, type TextMatch } from './transcript-segment-row'
import { createTranscriptTimeline } from './transcript-timeline'
import { useTranscriptScroll } from './use-transcript-scroll'
interface TranscriptPanelProps {
id: string
assetId: string
languages: string[]
canEdit: boolean
mediaControllerRef: RefObject<MediaController | null>
onClose: () => void
className?: string
}
const noSegments: TranscriptSegment[] = []
function findMatches(segments: TranscriptSegment[], search: string) {
const bySegment = new Map<string, TextMatch[]>()
let total = 0
const query = search.trim()
if (!query) return { bySegment, total }
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const expression = new RegExp(literal, 'giu')
for (const segment of segments) {
const matches = Array.from(segment.text.matchAll(expression), ({ index, 0: text }) => ({
index: total++,
start: index,
end: index + text.length,
}))
if (matches.length) bySegment.set(segment.id, matches)
}
return { bySegment, total }
}
export const TranscriptPanel = memo(function TranscriptPanel({
id,
assetId,
languages,
canEdit,
mediaControllerRef,
onClose,
className,
}: TranscriptPanelProps) {
const locale = getLocale()
const options = useMemo(() => {
const names = new Intl.DisplayNames(locale, { type: 'language' })
return languages
.map((code) => ({ code, name: names.of(code) ?? code }))
.sort((a, b) => a.name.localeCompare(b.name, locale))
}, [languages, locale])
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
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 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()
},
retry: false,
})
const segments = transcript.data?.segments ?? noSegments
const activeAt = useMemo(() => createTranscriptTimeline(segments), [segments])
const matches = useMemo(() => findMatches(segments, search), [segments, search])
const selectedMatch = matches.total ? matchIndex % matches.total : undefined
const startEditing = useCallback(
(segmentId: string) => {
mediaControllerRef.current?.pause()
cancelScroll()
setEditingId(segmentId)
},
[cancelScroll, mediaControllerRef],
)
const finishEditing = useCallback(() => setEditingId(undefined), [])
useEffect(() => closeRef.current?.focus({ preventScroll: true }), [])
useEffect(() => {
let active: string | undefined
setActiveId(undefined)
return mediaControllerRef.current?.subscribeToPlaybackTime?.((second) => {
const segmentId = activeAt(second * 1000)
if (segmentId === active) return
active = segmentId
setActiveId(segmentId)
})
}, [activeAt, mediaControllerRef])
useLayoutEffect(() => {
if (editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(editingId)}"]`))
}
}, [editingId])
useLayoutEffect(() => {
if (following && activeId && !editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(activeId)}"]`), {
followPlayback: true,
})
}
}, [activeId, following, editingId])
useLayoutEffect(() => {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}, [matches, selectedMatch, editingId])
function toggleSearch() {
if (searchOpen) {
setSearch('')
setMatchIndex(0)
toggleSearchRef.current?.focus({ preventScroll: true })
}
setSearchOpen(!searchOpen)
}
function moveMatch(step: number) {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
setMatchIndex((selectedMatch + step + matches.total) % matches.total)
if (matches.total === 1) {
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}
}
return (
<aside
id={id}
aria-label={m.transcript_title()}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') event.stopPropagation()
}}
className={cn(
'flex min-h-0 shrink-0 flex-col overflow-hidden bg-background text-foreground',
className,
)}
>
<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>
<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>
<Button
ref={closeRef}
size="icon-sm"
variant="ghost"
aria-label={m.transcript_close()}
title={m.transcript_close()}
onClick={onClose}
>
<X />
</Button>
</div>
</div>
{searchOpen && (
<div className="flex items-center gap-1">
<Input
autoFocus
type="search"
className="h-8 min-w-0 px-2"
aria-label={m.transcript_search()}
placeholder={m.transcript_search()}
value={search}
onChange={(event) => {
setSearch(event.target.value)
setMatchIndex(0)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
if (event.key === 'Escape') toggleSearch()
else moveMatch(event.shiftKey ? -1 : 1)
}
}}
/>
{search.trim() && (
<output className="shrink-0 px-1 text-xs tabular-nums text-muted-foreground">
{m.transcript_search_count({
current: selectedMatch === undefined ? 0 : selectedMatch + 1,
total: matches.total,
})}
</output>
)}
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_previous_match()}
title={m.transcript_previous_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(-1)}
>
<ChevronUp />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_next_match()}
title={m.transcript_next_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(1)}
>
<ChevronDown />
</Button>
</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,
}}
>
<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>
)}
</aside>
)
})