mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
283 lines
11 KiB
TypeScript
283 lines
11 KiB
TypeScript
import { execFile } from 'node:child_process'
|
|
import { mkdtemp, rm } from 'node:fs/promises'
|
|
import { tmpdir } from 'node:os'
|
|
import { basename, join } from 'node:path'
|
|
import { promisify } from 'node:util'
|
|
import { initAgentWorkflows } from '@shumai/agent'
|
|
import { assetService } from '@shumai/core/src/asset/asset'
|
|
import {
|
|
getArchiveStorageService,
|
|
resetArchiveStorageServiceForTests,
|
|
} from '@shumai/core/src/s3/archive-storage'
|
|
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 { initTranscodeWorkflows } from '@shumai/transcode'
|
|
import { TaskQueueAgent, TaskQueueArchive, workflowService } from '@shumai/workflow-core'
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
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: [
|
|
{ code: 'en', name: 'English' },
|
|
{ code: 'zh', name: 'Chinese' },
|
|
],
|
|
}
|
|
|
|
describe('Transcribe video workflow', () => {
|
|
setupTestDbHooks()
|
|
let directory: string
|
|
let provider: ReturnType<typeof Bun.serve>
|
|
let responseStatus = 200
|
|
let firstRequestBusy = false
|
|
let uploads: Array<{
|
|
language: FormDataEntryValue | null
|
|
length: string | null
|
|
hasTransferEncoding: boolean
|
|
model: FormDataEntryValue | null
|
|
format: FormDataEntryValue | null
|
|
audio: Buffer
|
|
}> = []
|
|
|
|
beforeAll(async () => {
|
|
directory = await mkdtemp(join(tmpdir(), 'shumai-e2e-transcripts-'))
|
|
await execFileAsync('ffmpeg', [
|
|
'-v',
|
|
'error',
|
|
'-f',
|
|
'lavfi',
|
|
'-i',
|
|
'color=size=64x64:duration=2',
|
|
'-itsoffset',
|
|
'1',
|
|
'-f',
|
|
'lavfi',
|
|
'-i',
|
|
'sine=frequency=440:duration=1',
|
|
'-c:v',
|
|
'mpeg4',
|
|
'-c:a',
|
|
'pcm_s16le',
|
|
join(directory, 'audio.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',
|
|
port: 0,
|
|
async fetch(request) {
|
|
const path = new URL(request.url).pathname
|
|
if (path === '/v1/audio/transcriptions/languages') return Response.json(languages)
|
|
if (path !== '/v1/audio/transcriptions' || request.method !== 'POST')
|
|
return new Response(null, { status: 404 })
|
|
|
|
const form = await request.formData()
|
|
const file = form.get('file')
|
|
if (!(file instanceof File)) return new Response(null, { status: 400 })
|
|
uploads.push({
|
|
language: form.get('language'),
|
|
length: request.headers.get('content-length'),
|
|
hasTransferEncoding: request.headers.has('transfer-encoding'),
|
|
model: form.get('model'),
|
|
format: form.get('response_format'),
|
|
audio: Buffer.from(await file.arrayBuffer()),
|
|
})
|
|
if (firstRequestBusy && uploads.length === 1) return new Response(null, { status: 429 })
|
|
if (responseStatus !== 200) return new Response(null, { status: responseStatus })
|
|
return Response.json({
|
|
language: form.get('language') ?? 'en',
|
|
text: 'Hello',
|
|
segments: [{ start: 1.012, end: 1.875, text: 'Hello' }],
|
|
})
|
|
},
|
|
})
|
|
vi.stubEnv('S3_BUCKET', bucket)
|
|
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
|
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', `${provider.url}v1/embeddings/`)
|
|
vi.stubEnv('ARCHIVE_STORAGE_BACKEND', 'local')
|
|
vi.stubEnv('ARCHIVE_LOCAL_ROOT', join(directory, 'archive'))
|
|
resetArchiveStorageServiceForTests()
|
|
initAgentWorkflows()
|
|
initTranscodeWorkflows()
|
|
await workflowService.startWorkers([TaskQueueAgent, TaskQueueArchive])
|
|
})
|
|
|
|
beforeEach(() => {
|
|
uploads = []
|
|
responseStatus = 200
|
|
firstRequestBusy = false
|
|
})
|
|
|
|
afterAll(async () => {
|
|
await workflowService.shutdownWorkers()
|
|
workflowService.close()
|
|
await provider?.stop(true)
|
|
await s3Service.deletePrefix(bucket, '')
|
|
if (directory) await rm(directory, { recursive: true, force: true })
|
|
resetArchiveStorageServiceForTests()
|
|
vi.unstubAllEnvs()
|
|
})
|
|
|
|
async function createVideo(name: string, originalKey = 'video/unavailable-original.mkv') {
|
|
const team = await prisma.team.create({ data: { name: 'Transcription E2E' } })
|
|
const project = await prisma.project.create({ data: { name: 'Videos', teamId: team.id } })
|
|
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'),
|
|
),
|
|
)
|
|
return await prisma.asset.create({
|
|
data: {
|
|
name,
|
|
type: 'file',
|
|
status: 'processed',
|
|
project: { connect: { id: project.id } },
|
|
mediaType: 'video/x-matroska',
|
|
storageKey: { create: { key: originalKey } },
|
|
media: {
|
|
proxyType: 'video',
|
|
videoTranscodes: [largerProxy, preview, fullProxy],
|
|
videoPreview: preview,
|
|
imageTranscodes: [],
|
|
duration: 2,
|
|
filesize: 0,
|
|
frames: 50,
|
|
finishedAt: new Date().toISOString(),
|
|
metadata: null,
|
|
original: null,
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
async function startTranscript(assetId: string, language: string | null) {
|
|
const result = await transcriptService.generate(assetId, language)
|
|
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
|
|
return {
|
|
assetId,
|
|
task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }),
|
|
}
|
|
}
|
|
|
|
async function submitVideo(name: string, language: string | null) {
|
|
const asset = await createVideo(name)
|
|
return await startTranscript(asset.id, language)
|
|
}
|
|
|
|
it('generates and saves a transcript after the archive workflow moves the original', async () => {
|
|
const originalKey = 'video/archive-original.mkv'
|
|
await s3Service.uploadFileToKey(join(directory, 'audio.mkv'), originalKey, 'video/x-matroska')
|
|
const asset = await createVideo('audio.mp4', originalKey)
|
|
const { taskIds } = await assetService.archiveAssets([asset.id])
|
|
expect(taskIds).toHaveLength(1)
|
|
const archiveTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: taskIds[0] } })
|
|
await workflowService.executeWait(archiveTask, 20_000)
|
|
await expect(prisma.asset.findUnique({ where: { id: asset.id } })).resolves.toMatchObject({
|
|
status: 'archived',
|
|
})
|
|
await expect(s3Service.headObject(bucket, originalKey)).rejects.toThrow('NoSuchKey')
|
|
await expect(getArchiveStorageService().headObject(originalKey)).resolves.toMatchObject({
|
|
size: expect.any(Number),
|
|
})
|
|
|
|
const { task } = await startTranscript(asset.id, 'en')
|
|
await workflowService.executeWait(task, 20_000)
|
|
|
|
expect(uploads).toHaveLength(1)
|
|
await expect(transcriptService.getSavedTranscript(asset.id, 'en')).resolves.toMatchObject({
|
|
segments: [{ startMs: 1012, endMs: 1875, text: 'Hello' }],
|
|
})
|
|
}, 45_000)
|
|
|
|
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.mp4', null)
|
|
await workflowService.executeWait(task, 20_000)
|
|
|
|
expect(uploads).toHaveLength(2)
|
|
const upload = uploads[1]
|
|
expect(upload).toMatchObject({
|
|
language: null,
|
|
hasTransferEncoding: false,
|
|
model: 'whisper-tiny',
|
|
format: 'verbose_json',
|
|
})
|
|
expect(Number(upload.length)).toBeGreaterThan(upload.audio.length)
|
|
expect(upload.audio.toString('ascii', 0, 4)).toBe('RIFF')
|
|
expect(upload.audio.readUInt16LE(22)).toBe(1)
|
|
expect(upload.audio.readUInt32LE(24)).toBe(16_000)
|
|
expect(upload.audio.readUInt16LE(34)).toBe(16)
|
|
const pcm = upload.audio.indexOf('data', 36) + 8
|
|
expect(upload.audio.subarray(pcm, pcm + 30_000).every((sample) => sample === 0)).toBe(true)
|
|
expect(upload.audio.subarray(pcm + 34_000).some((sample) => sample !== 0)).toBe(true)
|
|
|
|
const transcript = await prisma.assetTranscript.findUniqueOrThrow({
|
|
where: { assetIdLanguage: { assetId, language: 'en' } },
|
|
include: { segments: true },
|
|
})
|
|
expect(transcript).toMatchObject({
|
|
model: 'whisper-tiny',
|
|
workflowTaskId: task.id,
|
|
segments: [{ position: 0, startMs: 1012, endMs: 1875, text: 'Hello' }],
|
|
})
|
|
await vi.waitFor(async () =>
|
|
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
|
|
)
|
|
}, 24_000)
|
|
|
|
it('passes an explicit language and treats an upload limit error as permanent', async () => {
|
|
responseStatus = 413
|
|
const { task, assetId } = await submitVideo('audio.mp4', 'zh')
|
|
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
|
|
'Audio exceeds the embedding server upload limit',
|
|
)
|
|
expect(uploads).toHaveLength(1)
|
|
expect(uploads[0].language).toBe('zh')
|
|
expect(await transcriptService.getStatus(assetId)).toEqual({
|
|
taskId: task.id,
|
|
status: 'failed',
|
|
reason: 'tooLarge',
|
|
})
|
|
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
|
|
await vi.waitFor(async () =>
|
|
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
|
|
)
|
|
}, 24_000)
|
|
|
|
it('fails with a clear message when the video has no audio track', async () => {
|
|
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',
|
|
)
|
|
expect(uploads).toHaveLength(0)
|
|
expect(await transcriptService.getStatus(assetId)).toEqual({
|
|
taskId: task.id,
|
|
status: 'failed',
|
|
reason: 'noAudio',
|
|
})
|
|
}, 24_000)
|
|
})
|