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:
@@ -1,6 +1,10 @@
|
||||
export function getGemmaEmbeddingEndpoint(): string {
|
||||
export function getGemmaOpenAiBaseUrl(): string {
|
||||
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
|
||||
const url = baseUrl.replace(/\/+$/, '')
|
||||
if (url.endsWith('/embeddings')) return url
|
||||
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings`
|
||||
const url = baseUrl.replace(/\/+$/, '').replace(/\/embeddings$/, '')
|
||||
return url.endsWith('/v1') ? url : `${url}/v1`
|
||||
}
|
||||
|
||||
export function getGemmaEmbeddingEndpoint(): string {
|
||||
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL?.replace(/\/+$/, '')
|
||||
return baseUrl?.endsWith('/embeddings') ? baseUrl : `${getGemmaOpenAiBaseUrl()}/embeddings`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { getGemmaOpenAiBaseUrl } from '@shumai/core/src/search/gemma-embedding-endpoint'
|
||||
import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
|
||||
const transcriptEndpoint = () => `${getGemmaOpenAiBaseUrl()}/audio/transcriptions`
|
||||
|
||||
export function isLocalTranscriptionEnabled(): boolean {
|
||||
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai'
|
||||
}
|
||||
|
||||
export async function listLocalTranscriptionLanguages() {
|
||||
const response = await fetch(`${transcriptEndpoint()}/languages`, {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`)
|
||||
return transcriptLanguagesSchema.parse(await response.json())
|
||||
}
|
||||
|
||||
const transcriptResponseSchema = z
|
||||
.object({
|
||||
language: transcriptLanguageCodeSchema.nullable(),
|
||||
segments: z.array(
|
||||
z
|
||||
.object({ start: z.number().min(0), end: z.number().min(0), text: z.string().min(1) })
|
||||
.refine((segment) => segment.end >= segment.start && segment.end < 2_147_483),
|
||||
),
|
||||
})
|
||||
.refine((result) => result.language !== null || result.segments.length === 0)
|
||||
|
||||
export class LocalTranscriptionError extends Error {
|
||||
constructor(readonly status: number) {
|
||||
super(`Transcription server returned HTTP ${status}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function transcribeLocalAudio({
|
||||
audio,
|
||||
language,
|
||||
model,
|
||||
signal,
|
||||
}: {
|
||||
audio: Blob
|
||||
language: string | null
|
||||
model: string
|
||||
signal?: AbortSignal
|
||||
}) {
|
||||
const form = new FormData()
|
||||
form.set('file', audio, 'audio.wav')
|
||||
form.set('model', model)
|
||||
form.set('response_format', 'verbose_json')
|
||||
if (language) form.set('language', language)
|
||||
|
||||
const timeout = AbortSignal.timeout(90 * 60 * 1000)
|
||||
const response = await fetch(transcriptEndpoint(), {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
redirect: 'error',
|
||||
timeout: false,
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
})
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel()
|
||||
throw new LocalTranscriptionError(response.status)
|
||||
}
|
||||
return transcriptResponseSchema.parse(await response.json())
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { prisma, WorkflowTaskType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { transcriptionErrors } from '@shumai/dtos'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { transcriptService } from './transcript'
|
||||
|
||||
describe('TranscriptService', () => {
|
||||
setupTestDbHooks()
|
||||
let assetId: string
|
||||
let projectId: string
|
||||
const model = 'whisper-tiny'
|
||||
const segments = [{ startMs: 125, endMs: 1425, text: 'Original segment' }]
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
||||
const team = await prisma.team.create({ data: { name: 'Transcript test' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Transcript test', teamId: team.id },
|
||||
})
|
||||
projectId = project.id
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Video',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
mediaType: 'video/mp4',
|
||||
project: { connect: { id: projectId } },
|
||||
storageKey: { create: { key: 'files/transcript-video.mp4' } },
|
||||
},
|
||||
})
|
||||
assetId = asset.id
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
|
||||
Response.json({
|
||||
model,
|
||||
languages: [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'zh', name: 'Chinese' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
async function generateAndStart(language: string | null) {
|
||||
const result = await transcriptService.generate(assetId, language)
|
||||
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: result.taskId },
|
||||
data: { status: 'processing' },
|
||||
})
|
||||
return result.taskId
|
||||
}
|
||||
|
||||
it('validates provider capability, language and asset eligibility before queuing', async () => {
|
||||
await expect(transcriptService.listLanguages()).resolves.toMatchObject({ model })
|
||||
await expect(transcriptService.generate(assetId, 'xx')).rejects.toMatchObject({ status: 400 })
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { mediaType: 'image/png' } })
|
||||
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({ status: 400 })
|
||||
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
|
||||
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
|
||||
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('serializes requests for an asset and uses its project and workflow type', async () => {
|
||||
const results = await Promise.all([
|
||||
transcriptService.generate(assetId, 'en'),
|
||||
transcriptService.generate(assetId, 'zh'),
|
||||
])
|
||||
|
||||
expect(results.map((result) => result.kind).sort()).toEqual(['busy', 'queued'])
|
||||
const tasks = await prisma.workflowTask.findMany({ where: { assetId } })
|
||||
expect(tasks).toHaveLength(1)
|
||||
expect(tasks[0]).toMatchObject({
|
||||
projectId,
|
||||
type: WorkflowTaskType.ai_transcription,
|
||||
status: 'pending',
|
||||
})
|
||||
expect(await transcriptService.getStatus(assetId)).toEqual({
|
||||
taskId: tasks[0].id,
|
||||
status: 'pending',
|
||||
})
|
||||
})
|
||||
|
||||
it('persists languages independently and preserves saved text on replay and requests for an existing language', async () => {
|
||||
const enTaskId = await generateAndStart('en')
|
||||
const first = { taskId: enTaskId, assetId, model, language: 'en', segments }
|
||||
await transcriptService.saveResult(first)
|
||||
const en = await prisma.assetTranscript.findUniqueOrThrow({
|
||||
where: { assetIdLanguage: { assetId, language: 'en' } },
|
||||
})
|
||||
await prisma.assetTranscriptSegment.update({
|
||||
where: { transcriptIdPosition: { transcriptId: en.id, position: 0 } },
|
||||
data: { text: 'Edited' },
|
||||
})
|
||||
await transcriptService.saveResult(first)
|
||||
expect(await transcriptService.generate(assetId, 'en')).toEqual({
|
||||
kind: 'existing',
|
||||
transcriptId: en.id,
|
||||
language: 'en',
|
||||
})
|
||||
|
||||
const autoTaskId = await generateAndStart(null)
|
||||
await transcriptService.saveResult({ ...first, taskId: autoTaskId })
|
||||
expect(await transcriptService.generate(assetId, null)).toEqual({
|
||||
kind: 'existing',
|
||||
transcriptId: en.id,
|
||||
language: 'en',
|
||||
})
|
||||
expect(
|
||||
await prisma.assetTranscriptSegment.findMany({ where: { transcriptId: en.id } }),
|
||||
).toMatchObject([
|
||||
{
|
||||
position: 0,
|
||||
startMs: 125,
|
||||
endMs: 1425,
|
||||
text: 'Edited',
|
||||
},
|
||||
])
|
||||
|
||||
const zhTaskId = await generateAndStart('zh')
|
||||
await transcriptService.saveResult({ ...first, taskId: zhTaskId, language: 'zh' })
|
||||
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(2)
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(3)
|
||||
expect(await transcriptService.getStatus(assetId)).toEqual({
|
||||
taskId: zhTaskId,
|
||||
status: 'completed',
|
||||
})
|
||||
|
||||
await prisma.asset.delete({ where: { id: assetId } })
|
||||
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
|
||||
expect(await prisma.assetTranscriptSegment.count({ where: { transcriptId: en.id } })).toBe(0)
|
||||
})
|
||||
|
||||
it('completes silence without creating a row for an unknown language', async () => {
|
||||
const taskId = await generateAndStart(null)
|
||||
await transcriptService.saveResult({ taskId, assetId, model, language: null, segments: [] })
|
||||
expect(await transcriptService.getStatus(assetId)).toEqual({ taskId, status: 'no_speech' })
|
||||
expect(await transcriptService.generate(assetId, null)).toEqual({ kind: 'no_speech' })
|
||||
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('preserves a failed job and translates known failure reasons', async () => {
|
||||
const taskId = await generateAndStart(null)
|
||||
await prisma.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: 'failed',
|
||||
output: { error: transcriptionErrors.tooLarge },
|
||||
},
|
||||
})
|
||||
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
|
||||
expect(await transcriptService.getStatus(assetId)).toEqual({
|
||||
taskId,
|
||||
status: 'failed',
|
||||
reason: 'tooLarge',
|
||||
})
|
||||
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,232 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import {
|
||||
notifyWorkflowTaskCreated,
|
||||
prisma,
|
||||
Prisma,
|
||||
WorkflowTaskType,
|
||||
type WorkflowTask,
|
||||
} from '@shumai/db'
|
||||
import {
|
||||
transcriptionErrors,
|
||||
type GenerateTranscriptResult,
|
||||
type TranscriptJobStatus,
|
||||
} 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
|
||||
|
||||
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 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',
|
||||
status: 'processed',
|
||||
isDeleted: false,
|
||||
mediaType: { startsWith: 'video/' },
|
||||
storageKey: { status: 'active', isArchived: false },
|
||||
},
|
||||
select: { project: { select: { id: true, teamId: true } } },
|
||||
})
|
||||
if (!asset?.project) {
|
||||
throw new HTTPException(400, { message: 'Transcripts require a processed video file' })
|
||||
}
|
||||
|
||||
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'
|
||||
: '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<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
|
||||
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<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()
|
||||
Reference in New Issue
Block a user