mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 22:14:50 +00:00
feat(video): generate transcripts with the local embedding server
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
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 { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
isLocalTranscriptionEnabled,
|
||||
LocalTranscriptionError,
|
||||
transcribeLocalAudio,
|
||||
} from '@shumai/core/src/transcript/local-transcription'
|
||||
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 {
|
||||
ApplicationFailure,
|
||||
defineStep,
|
||||
ensureLocalMediaFile,
|
||||
getLocalTaskAbortSignal,
|
||||
} from '@shumai/workflow-core'
|
||||
import { z } from 'zod'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const audioProbeSchema = z.object({
|
||||
streams: z.array(
|
||||
z.object({
|
||||
index: z.number().int().nonnegative(),
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
|
||||
codec_type: z.string(),
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- ffprobe field
|
||||
bit_rate: z.string().optional(),
|
||||
disposition: z.record(z.string(), z.number()).optional(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
async function removeTempDirectory(directory: string): Promise<void> {
|
||||
try {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
} catch (error) {
|
||||
logger.warn({ err: error, directory }, 'Failed to remove local transcription files')
|
||||
}
|
||||
}
|
||||
|
||||
export const extractTranscriptAudioActivity = defineStep(
|
||||
async function extractTranscriptAudioActivity({
|
||||
assetId,
|
||||
taskId,
|
||||
audioKey,
|
||||
}: {
|
||||
assetId: string
|
||||
taskId: string
|
||||
audioKey: string
|
||||
}): Promise<void> {
|
||||
if (!isLocalTranscriptionEnabled()) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Local transcription is disabled',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const asset = await prisma.asset.findFirst({
|
||||
where: {
|
||||
id: assetId,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
isDeleted: false,
|
||||
mediaType: { startsWith: 'video/' },
|
||||
storageKey: { status: 'active', isArchived: false },
|
||||
},
|
||||
select: { storageKey: { select: { key: true } } },
|
||||
})
|
||||
if (!asset?.storageKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Video is no longer available',
|
||||
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 { stdout } = await execFileAsync(
|
||||
'ffprobe',
|
||||
['-v', 'error', '-select_streams', 'a', '-show_streams', '-of', 'json', video],
|
||||
{ signal },
|
||||
)
|
||||
const stream = selectPrimaryAudioStream(audioProbeSchema.parse(JSON.parse(stdout)).streams)
|
||||
if (!stream) {
|
||||
throw ApplicationFailure.create({
|
||||
message: transcriptionErrors.noAudio,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const wav = join(directory, 'audio.wav')
|
||||
// Keep the container timeline and fill any leading gap before the primary audio starts.
|
||||
await execFileAsync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-nostdin',
|
||||
'-v',
|
||||
'error',
|
||||
'-copyts',
|
||||
'-start_at_zero',
|
||||
'-i',
|
||||
video,
|
||||
'-map',
|
||||
`0:${stream.index}`,
|
||||
'-af',
|
||||
'aresample=16000:async=1:first_pts=0',
|
||||
'-ac',
|
||||
'1',
|
||||
'-c:a',
|
||||
'pcm_s16le',
|
||||
wav,
|
||||
],
|
||||
{ signal },
|
||||
)
|
||||
signal?.throwIfAborted()
|
||||
await s3Service.uploadFileToKey(wav, audioKey, 'audio/wav')
|
||||
} finally {
|
||||
await removeTempDirectory(directory)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export const transcribeAudioActivity = defineStep(async function transcribeAudioActivity({
|
||||
taskId,
|
||||
audioKey,
|
||||
language,
|
||||
model,
|
||||
}: {
|
||||
taskId: string
|
||||
audioKey: string
|
||||
language: string | null
|
||||
model: string
|
||||
}) {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'shumai-transcript-'))
|
||||
try {
|
||||
const path = await ensureLocalMediaFile(audioKey, join(directory, 'audio.wav'))
|
||||
return await transcribeLocalAudio({
|
||||
audio: Bun.file(path),
|
||||
language,
|
||||
model,
|
||||
signal: getLocalTaskAbortSignal(taskId),
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof LocalTranscriptionError) {
|
||||
const { status } = error
|
||||
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
||||
throw ApplicationFailure.create({
|
||||
message: status === 413 ? transcriptionErrors.tooLarge : error.message,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Invalid transcription response',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
await removeTempDirectory(directory)
|
||||
}
|
||||
})
|
||||
|
||||
export const saveTranscriptActivity = defineStep(async function saveTranscriptActivity(
|
||||
params: Parameters<typeof transcriptService.saveResult>[0],
|
||||
): Promise<void> {
|
||||
if (!(await transcriptService.saveResult(params))) {
|
||||
throw ApplicationFailure.create({ message: 'Video is no longer available', nonRetryable: true })
|
||||
}
|
||||
})
|
||||
@@ -3,9 +3,11 @@ import { registerWorkflow } from '@shumai/workflow-core'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
import { transcribeVideoWorkflow } from './workflows/transcribe-video'
|
||||
|
||||
export function initAgentWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
|
||||
registerWorkflow(WorkflowTaskType.ai_transcription, transcribeVideoWorkflow)
|
||||
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
|
||||
registerWorkflow(WorkflowTaskType.chat, agentChat)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity } from '../activities/ai'
|
||||
import {
|
||||
extractTranscriptAudioActivity,
|
||||
saveTranscriptActivity,
|
||||
transcribeAudioActivity,
|
||||
} from '../activities/transcription'
|
||||
|
||||
export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const request = task.payload?.transcription
|
||||
if (!request) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Missing transcription request',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const taskId = task.id
|
||||
const assetId = task.assetId
|
||||
const audioKey = `temp/transcripts/${taskId}.wav`
|
||||
try {
|
||||
await extractTranscriptAudioActivity({ assetId, taskId, audioKey })
|
||||
const transcript = await transcribeAudioActivity({ taskId, audioKey, ...request })
|
||||
if (request.language && transcript.language && request.language !== transcript.language) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Transcription returned an unexpected language',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
await saveTranscriptActivity({
|
||||
taskId,
|
||||
assetId,
|
||||
model: request.model,
|
||||
language: transcript.language,
|
||||
segments: transcript.segments.map((segment) => ({
|
||||
startMs: Math.round(segment.start * 1000),
|
||||
endMs: Math.round(segment.end * 1000),
|
||||
text: segment.text,
|
||||
})),
|
||||
})
|
||||
} finally {
|
||||
try {
|
||||
await deleteS3ObjectActivity({ key: audioKey })
|
||||
} catch (error) {
|
||||
logger.error({ err: error, taskId, audioKey }, 'Failed to delete staged transcript audio')
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user