fix(video): transcribe from the smallest full proxy

This commit is contained in:
yiling
2026-12-03 21:05:40 +08:00
parent cdd45429c4
commit 659ed5dab4
15 changed files with 210 additions and 53 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
- **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open.
- **video**: Use **Generate Transcripts** in a video's context menu to save a transcript with the local embedding server. Choose a language or let the server detect it automatically. The dialog closes when the transcript is ready.
- **video**: Once a video's full proxy is ready, use **Generate Transcripts** in its context menu to transcribe the audio with the local embedding server. Choose a language or let the server detect it automatically. The dialog closes when the transcript is ready.
- **video**: Open saved transcripts from the video player, switch languages, search the text, and jump to the exact start of a segment by selecting it. Drag the divider to resize the transcript panel on desktop. As the video plays, the panel scrolls smoothly to keep upcoming segments in view.
### Fixed
@@ -45,14 +45,20 @@ test('selects a transcription language from the video context menu and tracks th
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processing' } })
const [signupInfo] = await Promise.all([
page.waitForResponse('**/api/signup-info'),
page.goto(`/projects/${projectId}`),
])
expect(await signupInfo.json()).toMatchObject({ transcriptionEnabled: true })
const action = page.getByRole('menuitem', { name: 'Generate Transcripts' })
await fileCard(page, fileName).click({ button: 'right' })
await expect(action).toBeDisabled()
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processed' } })
await page.reload()
const openDialog = async () => {
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Generate Transcripts' }).click()
await action.click()
}
await openDialog()
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
@@ -13,7 +13,7 @@ import {
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { selectPrimaryAudioStream } from '@shumai/core/src/transcode/transcode'
import { prisma } from '@shumai/db'
import { transcriptionErrors } from '@shumai/dtos'
import { selectTranscriptVideoProxyKey, transcriptionErrors } from '@shumai/dtos'
import {
ApplicationFailure,
defineStep,
@@ -69,21 +69,18 @@ export const extractTranscriptAudioActivity = defineStep(
status: 'processed',
isDeleted: false,
mediaType: { startsWith: 'video/' },
storageKey: { status: 'active', isArchived: false },
},
select: { storageKey: { select: { key: true } } },
select: { media: true },
})
if (!asset?.storageKey) {
throw ApplicationFailure.create({
message: 'Video is no longer available',
nonRetryable: true,
})
const proxyKey = selectTranscriptVideoProxyKey(asset?.media)
if (!proxyKey) {
throw ApplicationFailure.create({ message: transcriptionErrors.noProxy, nonRetryable: true })
}
const signal = getLocalTaskAbortSignal(taskId)
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
try {
const video = await ensureLocalMediaFile(asset.storageKey.key, join(directory, 'video'))
const video = await ensureLocalMediaFile(proxyKey, join(directory, 'video.mp4'))
const { stdout } = await execFileAsync(
'ffprobe',
['-v', 'error', '-select_streams', 'a', '-show_streams', '-of', 'json', video],
+1
View File
@@ -2938,6 +2938,7 @@ export class AssetService {
type: a.type,
targetType: a.type === AssetType.symlink ? a.target?.type : null,
status: latestVersion.status,
mediaType: latestVersion.mediaType,
proxyType,
latestChildren,
preview,
+68 -16
View File
@@ -10,6 +10,17 @@ describe('TranscriptService', () => {
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')
@@ -24,6 +35,7 @@ describe('TranscriptService', () => {
type: 'file',
status: 'processed',
mediaType: 'video/mp4',
media,
project: { connect: { id: projectId } },
storageKey: { create: { key: 'files/transcript-video.mp4' } },
},
@@ -146,6 +158,43 @@ describe('TranscriptService', () => {
})
})
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 }
@@ -204,21 +253,24 @@ describe('TranscriptService', () => {
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
})
it('preserves a failed job and translates known failure reasons', async () => {
const taskId = await generateAndStart(null)
await prisma.workflowTask.update({
where: { id: taskId },
data: {
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',
output: { error: transcriptionErrors.tooLarge },
},
})
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId,
status: 'failed',
reason: 'tooLarge',
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
})
reason,
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
},
)
})
+8 -3
View File
@@ -7,6 +7,7 @@ import {
type WorkflowTask,
} from '@shumai/db'
import {
selectTranscriptVideoProxyKey,
transcriptionErrors,
type GenerateTranscriptResult,
type SavedTranscript,
@@ -81,13 +82,15 @@ export class TranscriptService {
status: 'processed',
isDeleted: false,
mediaType: { startsWith: 'video/' },
storageKey: { status: 'active', isArchived: false },
},
select: { project: { select: { id: true, teamId: true } } },
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'] } },
@@ -138,7 +141,9 @@ export class TranscriptService {
? 'tooLarge'
: error.includes(transcriptionErrors.noAudio)
? 'noAudio'
: 'unknown'
: error.includes(transcriptionErrors.noProxy)
? 'noProxy'
: 'unknown'
return { status: 'failed', taskId: task.id, reason }
}
const transcript = task.output?.transcription
+1
View File
@@ -86,6 +86,7 @@ export const assetInfoSchema = z.object({
type: z.string(),
targetType: z.string().optional().nullable(),
status: z.string(),
mediaType: z.string().nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
latestChildren: z.array(childPreviewSchema).optional(),
preview: previewInfoSchema.nullable().optional(),
+27
View File
@@ -26,8 +26,35 @@ export const transcriptLanguagesSchema = z.object({
languages: z.array(z.object({ code: transcriptLanguageCodeSchema, name: z.string().min(1) })),
})
interface TranscriptVideoProxy {
key?: string
resolution?: string
width: number
height: number
}
export function selectTranscriptVideoProxyKey(
media?: { videoTranscodes?: TranscriptVideoProxy[]; videoPreview?: { key?: string } } | null,
): string | undefined {
let selectedKey: string | undefined
let smallestArea = Infinity
for (const proxy of media?.videoTranscodes ?? []) {
if (!proxy.key || proxy.key === media?.videoPreview?.key || proxy.resolution === '180p') {
continue
}
const area = proxy.width > 0 && proxy.height > 0 ? proxy.width * proxy.height : Infinity
if (area < smallestArea) {
selectedKey = proxy.key
smallestArea = area
}
}
return selectedKey
}
export const transcriptionErrors = {
noAudio: 'The video does not contain an audio track',
noProxy: 'A completed full video proxy is required to generate transcripts',
tooLarge: 'Audio exceeds the embedding server upload limit',
} as const
+44 -19
View File
@@ -1,11 +1,12 @@
import { execFile } from 'node:child_process'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { basename, join } from 'node:path'
import { promisify } from 'node:util'
import { initAgentWorkflows } from '@shumai/agent'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
@@ -13,6 +14,8 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
const execFileAsync = promisify(execFile)
const bucket = 'shumai-e2e-transcript'
const preview = { key: 'video/180p.mp4', resolution: '180p', width: 32, height: 32 }
const largerProxy = { key: 'video/720p.mp4', resolution: '720p', width: 96, height: 96 }
const languages = {
model: 'whisper-tiny',
languages: [
@@ -57,17 +60,23 @@ describe('Transcribe video workflow', () => {
'pcm_s16le',
join(directory, 'audio.mkv'),
])
await execFileAsync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=size=64x64:duration=1',
'-c:v',
'mpeg4',
join(directory, 'silent.mkv'),
])
const fullProxy = { width: 64, height: 64 }
for (const [fileName, { width, height }, disableAudio] of [
['audio.mp4', fullProxy, false],
['silent.mp4', fullProxy, true],
['720p.mp4', largerProxy, true],
['180p.mp4', preview, true],
] as const) {
await transcodeService.transcodeVideo({
inputFile: join(directory, 'audio.mkv'),
outputFile: join(directory, fileName),
width,
height,
frameRate: 25,
disableAudio,
hardwareAcceleration: 'off',
})
}
// Replace only the inference server and inspect what the worker sends over HTTP.
provider = Bun.serve({
hostname: '127.0.0.1',
@@ -123,8 +132,12 @@ describe('Transcribe video workflow', () => {
async function submitVideo(name: string, language: string | null) {
const team = await prisma.team.create({ data: { name: 'Transcription E2E' } })
const project = await prisma.project.create({ data: { name: 'Videos', teamId: team.id } })
const key = `video/${name}`
await s3Service.uploadFileToKey(join(directory, name), key, 'video/x-matroska')
const fullProxy = { key: `video/${name}`, resolution: '480p', width: 64, height: 64 }
await Promise.all(
[preview, largerProxy, fullProxy].map(({ key }) =>
s3Service.uploadFileToKey(join(directory, basename(key)), key, 'video/mp4'),
),
)
const asset = await prisma.asset.create({
data: {
name,
@@ -132,7 +145,19 @@ describe('Transcribe video workflow', () => {
status: 'processed',
project: { connect: { id: project.id } },
mediaType: 'video/x-matroska',
storageKey: { create: { key } },
storageKey: { create: { key: 'video/unavailable-original.mkv' } },
media: {
proxyType: 'video',
videoTranscodes: [largerProxy, preview, fullProxy],
videoPreview: preview,
imageTranscodes: [],
duration: 2,
filesize: 0,
frames: 50,
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const result = await transcriptService.generate(asset.id, language)
@@ -143,9 +168,9 @@ describe('Transcribe video workflow', () => {
}
}
it('sends a timeline-aligned WAV and saves the detected language and segments after retrying a busy server', async () => {
it('uses the smallest full proxy to send a timeline-aligned WAV and saves the detected language and segments after retrying a busy server', async () => {
firstRequestBusy = true
const { task, assetId } = await submitVideo('audio.mkv', null)
const { task, assetId } = await submitVideo('audio.mp4', null)
await workflowService.executeWait(task, 20_000)
expect(uploads).toHaveLength(2)
@@ -181,7 +206,7 @@ describe('Transcribe video workflow', () => {
it('passes an explicit language and treats an upload limit error as permanent', async () => {
responseStatus = 413
const { task, assetId } = await submitVideo('audio.mkv', 'zh')
const { task, assetId } = await submitVideo('audio.mp4', 'zh')
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'Audio exceeds the embedding server upload limit',
)
@@ -199,7 +224,7 @@ describe('Transcribe video workflow', () => {
}, 24_000)
it('fails with a clear message when the video has no audio track', async () => {
const { task, assetId } = await submitVideo('silent.mkv', null)
const { task, assetId } = await submitVideo('silent.mp4', null)
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'The video does not contain an audio track',
)
@@ -31,6 +31,15 @@ describe('FileBrowserContextMenu', () => {
updatedAt: '2026-01-01T00:00:00Z',
} as AssetInfo
const fullProxy = {
id: 'proxy-480p',
url: '/video-480p.mp4',
key: 'video-480p.mp4',
width: 854,
height: 480,
size: 100,
}
const renderWithMenu = (
item: AssetInfo,
props: Partial<React.ComponentProps<typeof FileBrowserContextMenu>> = {},
@@ -93,6 +102,7 @@ describe('FileBrowserContextMenu', () => {
{
...stackItem,
proxyType: 'video',
media: { videoTranscodes: [fullProxy] },
versionStack: {
id: stackItem.id,
versions: [
@@ -110,6 +120,24 @@ describe('FileBrowserContextMenu', () => {
expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4')
})
it.each([
{ status: 'uploaded', media: undefined },
{ status: 'processing', media: { videoTranscodes: [fullProxy] } },
{ status: 'processed', media: { videoPreview: { url: '/preview.mp4', key: 'preview.mp4' } } },
])('disables generation for a $status video until a full proxy is ready', ({ status, media }) => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{ ...fileItem, mediaType: 'video/mp4', status, media },
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
const action = screen.getByRole('menuitem', { name: 'Generate Transcripts' })
expect(action.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(action)
expect(onGenerateTranscripts).not.toHaveBeenCalled()
})
it.each([
{
label: 'a read-only member',
@@ -117,6 +145,11 @@ describe('FileBrowserContextMenu', () => {
canEdit: false,
},
{ label: 'a non-video asset', item: fileItem, canEdit: true },
{
label: 'an audio-only upload with a video MIME type',
item: { ...fileItem, proxyType: 'audio' as const, mediaType: 'video/mp4' },
canEdit: true,
},
{
label: 'an archived video',
item: { ...fileItem, proxyType: 'video' as const, status: 'archived' },
@@ -1,5 +1,4 @@
import type { AssetInfo } from '@shumai/dtos'
import type { ShareLinkInfo } from '@shumai/dtos'
import { selectTranscriptVideoProxyKey, type AssetInfo, type ShareLinkInfo } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import {
ContextMenuContent,
@@ -245,6 +244,12 @@ export function FileBrowserContextMenu({
? item.versionStack?.versions.find((version) => version.current)
: undefined
const transcriptAssetId = item.type === 'file' ? item.id : videoVersion?.id
const transcriptAssetStatus = videoVersion?.status ?? item.status
const isTranscriptVideo = item.proxyType
? item.proxyType === 'video'
: item.mediaType?.startsWith('video/')
const transcriptReady =
transcriptAssetStatus === 'processed' && Boolean(selectTranscriptVideoProxyKey(item.media))
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
@@ -372,9 +377,10 @@ export function FileBrowserContextMenu({
{canEdit &&
onGenerateTranscripts &&
transcriptAssetId &&
item.status === 'processed' &&
item.proxyType === 'video' && (
['uploading', 'uploaded', 'processing', 'processed'].includes(transcriptAssetStatus) &&
isTranscriptVideo && (
<ContextMenuItem
disabled={!transcriptReady}
onSelect={() =>
onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name)
}
@@ -40,6 +40,7 @@ function statusMessage(job: TranscriptJobStatus) {
case 'failed':
if (job.reason === 'tooLarge') return m.transcript_audio_too_large()
if (job.reason === 'noAudio') return m.transcript_no_audio()
if (job.reason === 'noProxy') return m.transcript_proxy_required()
return m.transcript_failed()
}
}
+1
View File
@@ -1818,6 +1818,7 @@
"transcript_completed": "Transcript generated.",
"transcript_no_speech": "No speech detected.",
"transcript_no_audio": "This video has no audio track.",
"transcript_proxy_required": "A full video proxy must be ready before you can generate transcripts.",
"transcript_audio_too_large": "The audio exceeds the embedding server’s upload limit.",
"transcript_failed": "Transcript generation failed.",
"transcript_submit_failed": "Could not start transcript generation.",
+1
View File
@@ -1748,6 +1748,7 @@
"transcript_completed": "전사를 생성했습니다.",
"transcript_no_speech": "음성이 감지되지 않았습니다.",
"transcript_no_audio": "이 동영상에는 오디오 트랙이 없습니다.",
"transcript_proxy_required": "전체 동영상 프록시 준비가 완료되면 전사를 생성할 수 있습니다.",
"transcript_audio_too_large": "오디오가 임베딩 서버의 업로드 한도를 초과합니다.",
"transcript_failed": "전사 생성에 실패했습니다.",
"transcript_submit_failed": "전사 생성을 시작할 수 없습니다.",
+1
View File
@@ -1818,6 +1818,7 @@
"transcript_completed": "转录已生成。",
"transcript_no_speech": "未检测到语音。",
"transcript_no_audio": "此视频没有音轨。",
"transcript_proxy_required": "视频代理转码完成后才能生成转录。",
"transcript_audio_too_large": "音频超出嵌入服务器的上传大小限制。",
"transcript_failed": "转录生成失败。",
"transcript_submit_failed": "无法启动转录生成。",