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,66 @@
import { getGemmaOpenAiBaseUrl } from '@shumai/core/src/search/gemma-embedding-endpoint'
import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos'
import { z } from 'zod'
const transcriptEndpoint = () => `${getGemmaOpenAiBaseUrl()}/audio/transcriptions`
export function isLocalTranscriptionEnabled(): boolean {
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai'
}
export async function listLocalTranscriptionLanguages() {
const response = await fetch(`${transcriptEndpoint()}/languages`, {
signal: AbortSignal.timeout(5_000),
})
if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`)
return transcriptLanguagesSchema.parse(await response.json())
}
const transcriptResponseSchema = z
.object({
language: transcriptLanguageCodeSchema.nullable(),
segments: z.array(
z
.object({ start: z.number().min(0), end: z.number().min(0), text: z.string().min(1) })
.refine((segment) => segment.end >= segment.start && segment.end < 2_147_483),
),
})
.refine((result) => result.language !== null || result.segments.length === 0)
export class LocalTranscriptionError extends Error {
constructor(readonly status: number) {
super(`Transcription server returned HTTP ${status}`)
}
}
export async function transcribeLocalAudio({
audio,
language,
model,
signal,
}: {
audio: Blob
language: string | null
model: string
signal?: AbortSignal
}) {
const form = new FormData()
form.set('file', audio, 'audio.wav')
form.set('model', model)
form.set('response_format', 'verbose_json')
if (language) form.set('language', language)
const timeout = AbortSignal.timeout(90 * 60 * 1000)
const response = await fetch(transcriptEndpoint(), {
method: 'POST',
body: form,
redirect: 'error',
timeout: false,
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
})
if (!response.ok) {
await response.body?.cancel()
throw new LocalTranscriptionError(response.status)
}
return transcriptResponseSchema.parse(await response.json())
}
@@ -0,0 +1,322 @@
import { prisma, WorkflowTaskType } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { transcriptionErrors } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { transcriptService } from './transcript'
describe('TranscriptService', () => {
setupTestDbHooks()
let assetId: string
let projectId: string
const model = 'whisper-tiny'
const segments = [{ startMs: 125, endMs: 1425, text: 'Original segment' }]
const media: PrismaJson.MediaInfo = {
proxyType: 'video',
duration: 2,
filesize: 0,
frames: 50,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/transcript-video-480p.mp4', width: 854, height: 480 }],
finishedAt: '2026-01-01T00:00:00Z',
metadata: null,
original: null,
}
beforeEach(async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
const team = await prisma.team.create({ data: { name: 'Transcript test' } })
const project = await prisma.project.create({
data: { name: 'Transcript test', teamId: team.id },
})
projectId = project.id
const asset = await prisma.asset.create({
data: {
name: 'Video',
type: 'file',
status: 'processed',
mediaType: 'video/mp4',
media,
project: { connect: { id: projectId } },
storageKey: { create: { key: 'files/transcript-video.mp4' } },
},
})
assetId = asset.id
vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
Response.json({
model,
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
}),
)
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
async function generateAndStart(language: string | null) {
const result = await transcriptService.generate(assetId, language)
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
await prisma.workflowTask.update({
where: { id: result.taskId },
data: { status: 'processing' },
})
return result.taskId
}
it('lists only the asset’s saved languages and reads every segment in position order', async () => {
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const save = (id: string, language: string) =>
prisma.assetTranscript.create({
data: {
assetId: id,
language,
model,
workflowTaskId: 'test-task',
segments: {
create: [
{ position: 1, startMs: 2000, endMs: 3000, text: 'Second' },
{ position: 0, startMs: 125, endMs: 1425, text: 'First' },
],
},
},
include: { segments: true },
})
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
const english = await save(assetId, 'en')
await save(assetId, 'zh')
await save(otherAsset.id, 'ko')
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
const savedLanguages = await transcriptService.listSavedLanguages(assetId)
expect(savedLanguages.languages.sort()).toEqual(['en', 'zh'])
const transcript = await transcriptService.getSavedTranscript(assetId, 'en')
expect(transcript).toEqual({
id: english.id,
language: 'en',
segments: [
{
id: english.segments.find(({ position }) => position === 0)?.id,
startMs: 125,
endMs: 1425,
text: 'First',
},
{
id: english.segments.find(({ position }) => position === 1)?.id,
startMs: 2000,
endMs: 3000,
text: 'Second',
},
],
})
await expect(transcriptService.getSavedTranscript(assetId, 'ko')).rejects.toMatchObject({
status: 404,
})
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
await expect(transcriptService.getSavedTranscript(assetId, 'en')).rejects.toMatchObject({
status: 404,
})
expect(fetch).not.toHaveBeenCalled()
})
it('validates provider capability, language and asset eligibility before queuing', async () => {
await expect(transcriptService.listLanguages()).resolves.toMatchObject({ model })
await expect(transcriptService.generate(assetId, 'xx')).rejects.toMatchObject({ status: 400 })
await prisma.asset.update({ where: { id: assetId }, data: { mediaType: 'image/png' } })
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({ status: 400 })
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('serializes requests for an asset and uses its project and workflow type', async () => {
const results = await Promise.all([
transcriptService.generate(assetId, 'en'),
transcriptService.generate(assetId, 'zh'),
])
expect(results.map((result) => result.kind).sort()).toEqual(['busy', 'queued'])
const tasks = await prisma.workflowTask.findMany({ where: { assetId } })
expect(tasks).toHaveLength(1)
expect(tasks[0]).toMatchObject({
projectId,
type: WorkflowTaskType.ai_transcription,
status: 'pending',
})
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: tasks[0].id,
status: 'pending',
})
})
it('requires completed transcoding and a full proxy before queuing', async () => {
await prisma.asset.update({ where: { id: assetId }, data: { status: 'processing' } })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 400 })
const preview = { key: 'files/transcript-video-180p.mp4', width: 320, height: 180 }
await prisma.asset.update({
where: { id: assetId },
data: {
status: 'processed',
media: { ...media, videoTranscodes: [], videoPreview: preview },
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('rejects an audio-only proxy even when the file was uploaded with a video MIME type', async () => {
await prisma.asset.update({
where: { id: assetId },
data: {
media: {
...media,
proxyType: 'audio',
videoTranscodes: [{ key: 'files/transcript-video-audio-proxy.mp4', width: 0, height: 0 }],
},
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('persists languages independently and preserves saved text on replay and requests for an existing language', async () => {
const enTaskId = await generateAndStart('en')
const first = { taskId: enTaskId, assetId, model, language: 'en', segments }
await transcriptService.saveResult(first)
const en = await prisma.assetTranscript.findUniqueOrThrow({
where: { assetIdLanguage: { assetId, language: 'en' } },
})
const segment = await prisma.assetTranscriptSegment.findUniqueOrThrow({
where: { transcriptIdPosition: { transcriptId: en.id, position: 0 } },
})
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Edited'),
).resolves.toEqual({
id: segment.id,
startMs: 125,
endMs: 1425,
text: 'Edited',
})
await transcriptService.saveResult(first)
expect(await transcriptService.generate(assetId, 'en')).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
const autoTaskId = await generateAndStart(null)
await transcriptService.saveResult({ ...first, taskId: autoTaskId })
expect(await transcriptService.generate(assetId, null)).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
expect(
await prisma.assetTranscriptSegment.findMany({ where: { transcriptId: en.id } }),
).toMatchObject([
{
position: 0,
startMs: 125,
endMs: 1425,
text: 'Edited',
},
])
const zhTaskId = await generateAndStart('zh')
await transcriptService.saveResult({ ...first, taskId: zhTaskId, language: 'zh' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(2)
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(3)
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: zhTaskId,
status: 'completed',
})
await prisma.asset.delete({ where: { id: assetId } })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
expect(await prisma.assetTranscriptSegment.count({ where: { transcriptId: en.id } })).toBe(0)
})
it('saves empty segment text with generation disabled and scopes writes to the asset and language', async () => {
const taskId = await generateAndStart('en')
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const [segment] = (await transcriptService.getSavedTranscript(assetId, 'en')).segments
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
for (const [fileId, language, segmentId] of [
[otherAsset.id, 'en', segment.id],
[assetId, 'zh', segment.id],
[assetId, 'en', 'missing-segment'],
]) {
await expect(
transcriptService.updateSegmentText(fileId, language, segmentId, 'Unexpected edit'),
).rejects.toMatchObject({ status: 404 })
}
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(segment)
const cleared = { ...segment, text: '' }
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, ''),
).resolves.toEqual(cleared)
expect((await transcriptService.getSavedTranscript(assetId, 'en')).segments).toEqual([cleared])
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Restored'),
).rejects.toMatchObject({
status: 404,
})
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(cleared)
})
it('completes silence without creating a row for an unknown language', async () => {
const taskId = await generateAndStart(null)
await transcriptService.saveResult({ taskId, assetId, model, language: null, segments: [] })
expect(await transcriptService.getStatus(assetId)).toEqual({ taskId, status: 'no_speech' })
expect(await transcriptService.generate(assetId, null)).toEqual({ kind: 'no_speech' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
})
it.each(['tooLarge', 'noProxy'] as const)(
'preserves a failed job with reason %s',
async (reason) => {
const taskId = await generateAndStart(null)
await prisma.workflowTask.update({
where: { id: taskId },
data: {
status: 'failed',
output: { error: transcriptionErrors[reason] },
},
})
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId,
status: 'failed',
reason,
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
},
)
})
+280
View File
@@ -0,0 +1,280 @@
import { logger } from '@shumai/core/src/logger'
import {
notifyWorkflowTaskCreated,
prisma,
Prisma,
WorkflowTaskType,
type WorkflowTask,
} from '@shumai/db'
import {
selectTranscriptVideoProxyKey,
transcriptionErrors,
type GenerateTranscriptResult,
type SavedTranscript,
type SavedTranscriptLanguages,
type TranscriptJobStatus,
type TranscriptSegment,
} from '@shumai/dtos'
import { HTTPException } from 'hono/http-exception'
import { isLocalTranscriptionEnabled, listLocalTranscriptionLanguages } from './local-transcription'
const type = WorkflowTaskType.ai_transcription
const transcriptSelection = { id: true, language: true } as const
const segmentSelection = { id: true, startMs: true, endMs: true, text: true } as const
type Segment = { startMs: number; endMs: number; text: string }
export class TranscriptService {
async listLanguages() {
this.requireEnabled()
try {
return await listLocalTranscriptionLanguages()
} catch (error) {
logger.warn({ err: error }, 'Failed to load local transcription languages')
throw new HTTPException(503, { message: 'Transcription languages are unavailable' })
}
}
async listSavedLanguages(assetId: string): Promise<SavedTranscriptLanguages> {
const transcripts = await prisma.assetTranscript.findMany({
where: { assetId, asset: { isDeleted: false } },
orderBy: { id: 'desc' },
select: { language: true },
})
return { languages: transcripts.map(({ language }) => language) }
}
async getSavedTranscript(assetId: string, language: string): Promise<SavedTranscript> {
const transcript = await prisma.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language }, asset: { isDeleted: false } },
select: {
...transcriptSelection,
segments: {
orderBy: { position: 'asc' },
select: segmentSelection,
},
},
})
if (!transcript) throw new HTTPException(404, { message: 'Transcript not found' })
return transcript
}
async updateSegmentText(
assetId: string,
language: string,
segmentId: string,
text: string,
): Promise<TranscriptSegment> {
const [segment] = await prisma.assetTranscriptSegment.updateManyAndReturn({
where: { id: segmentId, transcript: { assetId, language, asset: { isDeleted: false } } },
data: { text },
select: segmentSelection,
})
if (!segment) throw new HTTPException(404, { message: 'Transcript segment not found' })
return segment
}
async generate(assetId: string, language: string | null): Promise<GenerateTranscriptResult> {
this.requireEnabled()
const saved = await this.findSaved(prisma, assetId, language)
if (saved) return saved
const { model, languages } = await this.listLanguages()
if (language && !languages.some((entry) => entry.code === language)) {
throw new HTTPException(400, { message: 'Unsupported transcription language' })
}
const { result, task } = await prisma.$transaction(
async (tx): Promise<{ result: GenerateTranscriptResult; task?: WorkflowTask }> => {
// Serialize submissions and result commits for a single video asset.
await tx.$queryRaw`SELECT id FROM assets WHERE id = ${assetId} FOR UPDATE`
const savedAfterLock = await this.findSaved(tx, assetId, language)
if (savedAfterLock) return { result: savedAfterLock }
const asset = await tx.asset.findFirst({
where: {
id: assetId,
type: 'file',
status: 'processed',
isDeleted: false,
mediaType: { startsWith: 'video/' },
},
select: { media: true, project: { select: { id: true, teamId: true } } },
})
if (!asset?.project) {
throw new HTTPException(400, { message: 'Transcripts require a processed video file' })
}
if (!selectTranscriptVideoProxyKey(asset.media)) {
throw new HTTPException(400, { message: transcriptionErrors.noProxy })
}
const active = await tx.workflowTask.findFirst({
where: { assetId, type, status: { in: ['pending', 'processing'] } },
orderBy: { id: 'desc' },
})
if (active) return { result: { kind: 'busy', taskId: active.id }, task: active }
// Notify the worker after commit so it can observe the task row as soon as it starts.
const [created] = await tx.workflowTask.createManyAndReturn({
data: {
assetId,
teamId: asset.project.teamId,
projectId: asset.project.id,
type,
status: 'pending',
payload: { projectId: asset.project.id, transcription: { language, model } },
},
})
return { result: { kind: 'queued', taskId: created.id }, task: created }
},
)
if (task?.status === 'pending') {
try {
await notifyWorkflowTaskCreated(task)
} catch (error) {
logger.error({ err: error, taskId: task.id }, 'Failed to queue transcript generation')
await prisma.workflowTask.updateMany({
where: { id: task.id, status: 'pending' },
data: { status: 'failed', output: { error: 'Failed to queue transcript generation' } },
})
throw new HTTPException(503, { message: 'Could not queue transcript generation' })
}
}
return result
}
async getStatus(assetId: string): Promise<TranscriptJobStatus | null> {
const task = await prisma.workflowTask.findFirst({
where: { assetId, type },
orderBy: { id: 'desc' },
select: { id: true, status: true, output: true },
})
if (!task?.status) return null
if (task.status === 'failed') {
const error = task.output?.error ?? ''
const reason = error.includes(transcriptionErrors.tooLarge)
? 'tooLarge'
: error.includes(transcriptionErrors.noAudio)
? 'noAudio'
: error.includes(transcriptionErrors.noProxy)
? 'noProxy'
: 'unknown'
return { status: 'failed', taskId: task.id, reason }
}
const transcript = task.output?.transcription
return {
taskId: task.id,
status:
task.status === 'completed' && transcript && 'noSpeech' in transcript
? 'no_speech'
: task.status,
}
}
async saveResult(params: {
taskId: string
assetId: string
model: string
language: string | null
segments: Segment[]
}): Promise<boolean> {
const { taskId, assetId, model, language, segments } = params
return await prisma.$transaction(async (tx) => {
const [asset] = await tx.$queryRaw<{ id: string }[]>`
SELECT id FROM assets
WHERE id = ${assetId} AND NOT is_deleted AND status = 'processed'
FOR UPDATE
`
if (!asset) return false
const task = await tx.workflowTask.updateMany({
where: { id: taskId, assetId, type, status: 'processing' },
data: { status: 'completed', model },
})
if (task.count === 0) return true
const existing = language
? await tx.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language } },
select: transcriptSelection,
})
: null
const transcript =
existing ??
(language && segments.length > 0
? await tx.assetTranscript.create({
data: {
assetId,
language,
model,
workflowTaskId: taskId,
segments: {
createMany: {
data: segments.map((segment, position) => ({ ...segment, position })),
},
},
},
select: transcriptSelection,
})
: null)
await tx.workflowTask.update({
where: { id: taskId },
data: {
output: {
transcription: transcript
? { transcriptId: transcript.id, language: transcript.language }
: { noSpeech: true },
},
},
})
return true
})
}
private requireEnabled(): void {
if (!isLocalTranscriptionEnabled()) {
throw new HTTPException(503, { message: 'Local transcription is disabled' })
}
}
private async findSaved(
db: Pick<Prisma.TransactionClient, 'assetTranscript' | 'workflowTask'>,
assetId: string,
language: string | null,
): Promise<GenerateTranscriptResult | null> {
if (language) {
const transcript = await db.assetTranscript.findUnique({
where: { assetIdLanguage: { assetId, language } },
select: transcriptSelection,
})
return transcript ? { kind: 'existing', transcriptId: transcript.id, language } : null
}
const auto = await db.workflowTask.findFirst({
where: {
assetId,
type,
status: 'completed',
payload: { path: ['transcription', 'language'], equals: Prisma.JsonNull },
},
select: { output: true },
orderBy: { id: 'desc' },
})
const result = auto?.output?.transcription
if (!result) return null
if ('noSpeech' in result) return { kind: 'no_speech' }
const transcript = await db.assetTranscript.findUnique({
where: { id: result.transcriptId },
select: transcriptSelection,
})
return transcript
? { kind: 'existing', transcriptId: transcript.id, language: transcript.language }
: null
}
}
export const transcriptService = new TranscriptService()