Files
shumai/packages/core/src/transcript/transcript.test.ts
T

323 lines
12 KiB
TypeScript
Raw Normal View History

2026-12-04 13:49:25 +08:00
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)
},
)
})