mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 22:14:50 +00:00
214 lines
7.5 KiB
TypeScript
214 lines
7.5 KiB
TypeScript
import { execFile } from 'node:child_process'
|
|
import { mkdtemp, rm } from 'node:fs/promises'
|
|
import { tmpdir } from 'node:os'
|
|
import { 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 { prisma } from '@shumai/db'
|
|
import { setupTestDbHooks } from '@shumai/db/test'
|
|
import { TaskQueueAgent, 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 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'),
|
|
])
|
|
await execFileAsync('ffmpeg', [
|
|
'-v',
|
|
'error',
|
|
'-f',
|
|
'lavfi',
|
|
'-i',
|
|
'color=size=64x64:duration=1',
|
|
'-c:v',
|
|
'mpeg4',
|
|
join(directory, 'silent.mkv'),
|
|
])
|
|
// 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/`)
|
|
initAgentWorkflows()
|
|
await workflowService.startWorkers(TaskQueueAgent)
|
|
})
|
|
|
|
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 })
|
|
vi.unstubAllEnvs()
|
|
})
|
|
|
|
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 asset = await prisma.asset.create({
|
|
data: {
|
|
name,
|
|
type: 'file',
|
|
status: 'processed',
|
|
project: { connect: { id: project.id } },
|
|
mediaType: 'video/x-matroska',
|
|
storageKey: { create: { key } },
|
|
},
|
|
})
|
|
const result = await transcriptService.generate(asset.id, language)
|
|
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
|
|
return {
|
|
assetId: asset.id,
|
|
task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }),
|
|
}
|
|
}
|
|
|
|
it('sends 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)
|
|
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.mkv', '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.mkv', 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)
|
|
})
|