import { logger } from '@shumai/core/src/logger' import { notifyWorkflowTaskCreated, prisma, Prisma, WorkflowTaskType, type WorkflowTask, } from '@shumai/db' import { selectTranscriptVideoProxyKey, transcriptionErrors, type GenerateTranscriptResult, type SavedTranscript, type SavedTranscriptLanguages, type TranscriptJobStatus, type TranscriptSegment, } from '@shumai/dtos' import { HTTPException } from 'hono/http-exception' import { isLocalTranscriptionEnabled, listLocalTranscriptionLanguages } from './local-transcription' const type = WorkflowTaskType.ai_transcription const transcriptSelection = { id: true, language: true } as const const segmentSelection = { id: true, startMs: true, endMs: true, text: true } as const type Segment = { startMs: number; endMs: number; text: string } export class TranscriptService { async listLanguages() { this.requireEnabled() try { return await listLocalTranscriptionLanguages() } catch (error) { logger.warn({ err: error }, 'Failed to load local transcription languages') throw new HTTPException(503, { message: 'Transcription languages are unavailable' }) } } async listSavedLanguages(assetId: string): Promise { const transcripts = await prisma.assetTranscript.findMany({ where: { assetId, asset: { isDeleted: false } }, orderBy: { id: 'desc' }, select: { language: true }, }) return { languages: transcripts.map(({ language }) => language) } } async getSavedTranscript(assetId: string, language: string): Promise { const transcript = await prisma.assetTranscript.findUnique({ where: { assetIdLanguage: { assetId, language }, asset: { isDeleted: false } }, select: { ...transcriptSelection, segments: { orderBy: { position: 'asc' }, select: segmentSelection, }, }, }) if (!transcript) throw new HTTPException(404, { message: 'Transcript not found' }) return transcript } async updateSegmentText( assetId: string, language: string, segmentId: string, text: string, ): Promise { const [segment] = await prisma.assetTranscriptSegment.updateManyAndReturn({ where: { id: segmentId, transcript: { assetId, language, asset: { isDeleted: false } } }, data: { text }, select: segmentSelection, }) if (!segment) throw new HTTPException(404, { message: 'Transcript segment not found' }) return segment } async generate(assetId: string, language: string | null): Promise { this.requireEnabled() const saved = await this.findSaved(prisma, assetId, language) if (saved) return saved const { model, languages } = await this.listLanguages() if (language && !languages.some((entry) => entry.code === language)) { throw new HTTPException(400, { message: 'Unsupported transcription language' }) } const { result, task } = await prisma.$transaction( async (tx): Promise<{ result: GenerateTranscriptResult; task?: WorkflowTask }> => { // Serialize submissions and result commits for a single video asset. await tx.$queryRaw`SELECT id FROM assets WHERE id = ${assetId} FOR UPDATE` const savedAfterLock = await this.findSaved(tx, assetId, language) if (savedAfterLock) return { result: savedAfterLock } const asset = await tx.asset.findFirst({ where: { id: assetId, type: 'file', status: 'processed', isDeleted: false, mediaType: { startsWith: 'video/' }, }, select: { media: true, project: { select: { id: true, teamId: true } } }, }) if (!asset?.project) { throw new HTTPException(400, { message: 'Transcripts require a processed video file' }) } if (!selectTranscriptVideoProxyKey(asset.media)) { throw new HTTPException(400, { message: transcriptionErrors.noProxy }) } const active = await tx.workflowTask.findFirst({ where: { assetId, type, status: { in: ['pending', 'processing'] } }, orderBy: { id: 'desc' }, }) if (active) return { result: { kind: 'busy', taskId: active.id }, task: active } // Notify the worker after commit so it can observe the task row as soon as it starts. const [created] = await tx.workflowTask.createManyAndReturn({ data: { assetId, teamId: asset.project.teamId, projectId: asset.project.id, type, status: 'pending', payload: { projectId: asset.project.id, transcription: { language, model } }, }, }) return { result: { kind: 'queued', taskId: created.id }, task: created } }, ) if (task?.status === 'pending') { try { await notifyWorkflowTaskCreated(task) } catch (error) { logger.error({ err: error, taskId: task.id }, 'Failed to queue transcript generation') await prisma.workflowTask.updateMany({ where: { id: task.id, status: 'pending' }, data: { status: 'failed', output: { error: 'Failed to queue transcript generation' } }, }) throw new HTTPException(503, { message: 'Could not queue transcript generation' }) } } return result } async getStatus(assetId: string): Promise { const task = await prisma.workflowTask.findFirst({ where: { assetId, type }, orderBy: { id: 'desc' }, select: { id: true, status: true, output: true }, }) if (!task?.status) return null if (task.status === 'failed') { const error = task.output?.error ?? '' const reason = error.includes(transcriptionErrors.tooLarge) ? 'tooLarge' : error.includes(transcriptionErrors.noAudio) ? 'noAudio' : error.includes(transcriptionErrors.noProxy) ? 'noProxy' : 'unknown' return { status: 'failed', taskId: task.id, reason } } const transcript = task.output?.transcription return { taskId: task.id, status: task.status === 'completed' && transcript && 'noSpeech' in transcript ? 'no_speech' : task.status, } } async saveResult(params: { taskId: string assetId: string model: string language: string | null segments: Segment[] }): Promise { const { taskId, assetId, model, language, segments } = params return await prisma.$transaction(async (tx) => { const [asset] = await tx.$queryRaw<{ id: string }[]>` SELECT id FROM assets WHERE id = ${assetId} AND NOT is_deleted AND status = 'processed' FOR UPDATE ` if (!asset) return false const task = await tx.workflowTask.updateMany({ where: { id: taskId, assetId, type, status: 'processing' }, data: { status: 'completed', model }, }) if (task.count === 0) return true const existing = language ? await tx.assetTranscript.findUnique({ where: { assetIdLanguage: { assetId, language } }, select: transcriptSelection, }) : null const transcript = existing ?? (language && segments.length > 0 ? await tx.assetTranscript.create({ data: { assetId, language, model, workflowTaskId: taskId, segments: { createMany: { data: segments.map((segment, position) => ({ ...segment, position })), }, }, }, select: transcriptSelection, }) : null) await tx.workflowTask.update({ where: { id: taskId }, data: { output: { transcription: transcript ? { transcriptId: transcript.id, language: transcript.language } : { noSpeech: true }, }, }, }) return true }) } private requireEnabled(): void { if (!isLocalTranscriptionEnabled()) { throw new HTTPException(503, { message: 'Local transcription is disabled' }) } } private async findSaved( db: Pick, assetId: string, language: string | null, ): Promise { if (language) { const transcript = await db.assetTranscript.findUnique({ where: { assetIdLanguage: { assetId, language } }, select: transcriptSelection, }) return transcript ? { kind: 'existing', transcriptId: transcript.id, language } : null } const auto = await db.workflowTask.findFirst({ where: { assetId, type, status: 'completed', payload: { path: ['transcription', 'language'], equals: Prisma.JsonNull }, }, select: { output: true }, orderBy: { id: 'desc' }, }) const result = auto?.output?.transcription if (!result) return null if ('noSpeech' in result) return { kind: 'no_speech' } const transcript = await db.assetTranscript.findUnique({ where: { id: result.transcriptId }, select: transcriptSelection, }) return transcript ? { kind: 'existing', transcriptId: transcript.id, language: transcript.language } : null } } export const transcriptService = new TranscriptService()