mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
223 lines
6.6 KiB
TypeScript
223 lines
6.6 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 { 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 {
|
|
selectTranscriptVideoProxyKey,
|
|
transcriptionErrors,
|
|
transcriptVideoStatuses,
|
|
} 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,
|
|
teamId,
|
|
}: {
|
|
assetId: string
|
|
taskId: string
|
|
audioKey: string
|
|
teamId?: string
|
|
}): Promise<void> {
|
|
if (!(await isLocalTranscriptionEnabled(teamId))) {
|
|
throw ApplicationFailure.create({
|
|
message: 'Local transcription is disabled',
|
|
nonRetryable: true,
|
|
})
|
|
}
|
|
|
|
const asset = await prisma.asset.findFirst({
|
|
where: {
|
|
id: assetId,
|
|
type: 'file',
|
|
status: { in: [...transcriptVideoStatuses] },
|
|
isDeleted: false,
|
|
mediaType: { startsWith: 'video/' },
|
|
},
|
|
select: { media: 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(proxyKey, join(directory, 'video.mp4'))
|
|
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({
|
|
teamId,
|
|
taskId,
|
|
audioKey,
|
|
language,
|
|
model,
|
|
}: {
|
|
teamId?: string
|
|
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({
|
|
teamId,
|
|
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 })
|
|
}
|
|
})
|
|
|
|
export const reportTranscriptionFailureActivity = defineStep(
|
|
async function reportTranscriptionFailureActivity(taskId: string, reason: string | undefined) {
|
|
if (getLocalTaskAbortSignal(taskId)?.aborted) return
|
|
|
|
const task = await prisma.workflowTask.findUnique({
|
|
where: { id: taskId, type: 'ai_transcription', status: 'processing' },
|
|
select: { assetId: true, teamId: true },
|
|
})
|
|
if (!task?.teamId) return
|
|
|
|
const asset = await prisma.asset.findFirst({
|
|
where: { id: task.assetId, isDeleted: false, project: { teamId: task.teamId } },
|
|
select: { id: true },
|
|
})
|
|
if (!asset) return
|
|
|
|
const agent = await transcriptService.findEnabledAgent(task.teamId)
|
|
if (!agent || getLocalTaskAbortSignal(taskId)?.aborted) return
|
|
|
|
const detail = Object.values(transcriptionErrors).find((message) => message === reason)
|
|
await prisma.assetComment.upsert({
|
|
where: { transcriptionTaskId: taskId },
|
|
update: {},
|
|
create: {
|
|
assetId: asset.id,
|
|
creatorId: agent.id,
|
|
transcriptionTaskId: taskId,
|
|
isInternal: true,
|
|
message: detail
|
|
? `Transcription failed. ${detail}.`
|
|
: 'Transcription failed. Try generating the transcript again.',
|
|
},
|
|
})
|
|
},
|
|
)
|