2026-12-04 13:49:25 +08:00
|
|
|
import { logger } from '@shumai/core/src/logger'
|
|
|
|
|
import {
|
|
|
|
|
notifyWorkflowTaskCreated,
|
|
|
|
|
prisma,
|
|
|
|
|
Prisma,
|
|
|
|
|
WorkflowTaskType,
|
|
|
|
|
type WorkflowTask,
|
|
|
|
|
} from '@shumai/db'
|
|
|
|
|
import {
|
|
|
|
|
selectTranscriptVideoProxyKey,
|
|
|
|
|
transcriptionErrors,
|
2026-12-04 15:37:58 +08:00
|
|
|
transcriptVideoStatuses,
|
2026-12-04 13:49:25 +08:00
|
|
|
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<SavedTranscriptLanguages> {
|
|
|
|
|
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<SavedTranscript> {
|
|
|
|
|
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<TranscriptSegment> {
|
|
|
|
|
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<GenerateTranscriptResult> {
|
|
|
|
|
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',
|
2026-12-04 15:37:58 +08:00
|
|
|
status: { in: [...transcriptVideoStatuses] },
|
2026-12-04 13:49:25 +08:00
|
|
|
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<TranscriptJobStatus | null> {
|
|
|
|
|
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,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-12-04 15:37:58 +08:00
|
|
|
async listActiveAssetIds(projectId: string): Promise<string[]> {
|
|
|
|
|
const assets = await prisma.$queryRaw<{ assetId: string }[]>`
|
|
|
|
|
SELECT DISTINCT task.asset_id AS "assetId"
|
|
|
|
|
FROM workflow_tasks task
|
|
|
|
|
JOIN assets asset ON asset.id = task.asset_id
|
|
|
|
|
WHERE asset.project_id = ${projectId} AND NOT asset.is_deleted AND asset.type = 'file'
|
|
|
|
|
AND task.type = ${type}::"WorkflowTaskType" AND task.status IN ('pending', 'processing')
|
|
|
|
|
ORDER BY task.asset_id DESC
|
|
|
|
|
`
|
|
|
|
|
return assets.map(({ assetId }) => assetId)
|
|
|
|
|
}
|
|
|
|
|
|
2026-12-04 13:49:25 +08:00
|
|
|
async saveResult(params: {
|
|
|
|
|
taskId: string
|
|
|
|
|
assetId: string
|
|
|
|
|
model: string
|
|
|
|
|
language: string | null
|
|
|
|
|
segments: Segment[]
|
|
|
|
|
}): Promise<boolean> {
|
|
|
|
|
const { taskId, assetId, model, language, segments } = params
|
|
|
|
|
return await prisma.$transaction(async (tx) => {
|
|
|
|
|
const [asset] = await tx.$queryRaw<{ id: string }[]>`
|
|
|
|
|
SELECT id FROM assets
|
2026-12-04 15:37:58 +08:00
|
|
|
WHERE id = ${assetId} AND NOT is_deleted AND status::text IN (${Prisma.join(transcriptVideoStatuses)})
|
2026-12-04 13:49:25 +08:00
|
|
|
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<Prisma.TransactionClient, 'assetTranscript' | 'workflowTask'>,
|
|
|
|
|
assetId: string,
|
|
|
|
|
language: string | null,
|
|
|
|
|
): Promise<GenerateTranscriptResult | null> {
|
|
|
|
|
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()
|