Compare commits

...
Author SHA1 Message Date
yiling e806435e49 feat(video): generate transcripts with the local embedding server 2026-12-02 22:12:33 +08:00
46 changed files with 5233 additions and 88 deletions
+1
View File
@@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens. - **sessions**: See total tokens and estimated cost in the session logs footer, with a breakdown of input, output, and cached tokens.
- **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open. - **projects**: Middle-click or Command/Ctrl-click a project to open it in a new tab. Use **Open in new tab** in a file or folder's context menu to keep your current view open.
- **video**: Use **Generate Transcripts** in a video's context menu to save a transcript with the local embedding server. Choose a language or let the server detect it automatically.
### Fixed ### Fixed
+1
View File
@@ -76,6 +76,7 @@ apps/web/e2e/
| Owner creates a project with a cover image | `tests/project/create-project.spec.ts` | | Owner creates a project with a cover image | `tests/project/create-project.spec.ts` |
| Owner opens project cards in new tabs with middle-click and modifier-click | `tests/project/open-in-new-tab.spec.ts` | | Owner opens project cards in new tabs with middle-click and modifier-click | `tests/project/open-in-new-tab.spec.ts` |
| Owner opens a folder card and a file row in new tabs from the context menu | `tests/project/open-in-new-tab.spec.ts` | | Owner opens a folder card and a file row in new tabs from the context menu | `tests/project/open-in-new-tab.spec.ts` |
| Owner opens transcript generation from a video context menu, selects a language, and sees completion | `tests/project/generate-transcripts.spec.ts` |
| Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` | | Owner uploads a file or an unsupported file via the "Upload File" context menu action | `tests/project/upload-file.spec.ts` |
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` | | Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` | | Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
@@ -0,0 +1,62 @@
import { expect, test } from '../../fixtures'
import { fileCard } from '../../helpers/files'
test.use({ fileOptions: { mediaType: 'video' } })
test('selects a transcription language from the video context menu and tracks the job', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, fileName } = file
let submitted = false
await page.route('**/api/signup-info', async (route) => {
const response = await route.fetch()
await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled: true } })
})
await page.route('**/api/transcription/languages', (route) =>
route.fulfill({
json: {
model: 'whisper-tiny',
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
},
}),
)
await page.route(`**/api/files/${fileId}/transcription-status`, (route) =>
route.fulfill({
body: JSON.stringify(submitted ? { taskId: 'transcript-task', status: 'completed' } : null),
contentType: 'application/json',
}),
)
await page.route(`**/api/files/${fileId}/transcripts`, async (route) => {
expect(route.request().postDataJSON()).toEqual({ language: 'zh' })
submitted = true
await route.fulfill({ status: 202, json: { kind: 'queued', taskId: 'transcript-task' } })
})
await expect
.poll(() =>
prisma.asset.findUnique({
where: { id: fileId },
select: { status: true, media: true },
}),
)
.toMatchObject({ status: 'processed', media: { proxyType: 'video' } })
const [signupInfo] = await Promise.all([
page.waitForResponse('**/api/signup-info'),
page.goto(`/projects/${projectId}`),
])
expect(await signupInfo.json()).toMatchObject({ transcriptionEnabled: true })
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Generate Transcripts' }).click()
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
const language = dialog.getByRole('combobox', { name: 'Language' })
await expect(language).toHaveValue('Auto')
await language.fill('Chi')
await dialog.getByRole('option', { name: 'Chinese' }).click()
await expect(language).toHaveValue('Chinese')
await dialog.getByRole('button', { name: 'Generate', exact: true }).click()
await expect(dialog.getByRole('status')).toHaveText('Transcript generated.')
})
@@ -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 })
}
})
+2
View File
@@ -3,9 +3,11 @@ import { registerWorkflow } from '@shumai/workflow-core'
import { agentAutofillMedia } from './workflows/agent-autofill' import { agentAutofillMedia } from './workflows/agent-autofill'
import { agentChat } from './workflows/agent-chat' import { agentChat } from './workflows/agent-chat'
import { agentEmbeddingMedia } from './workflows/agent-embedding' import { agentEmbeddingMedia } from './workflows/agent-embedding'
import { transcribeVideoWorkflow } from './workflows/transcribe-video'
export function initAgentWorkflows() { export function initAgentWorkflows() {
registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia) registerWorkflow(WorkflowTaskType.ai_embedding, agentEmbeddingMedia)
registerWorkflow(WorkflowTaskType.ai_transcription, transcribeVideoWorkflow)
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia) registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
registerWorkflow(WorkflowTaskType.chat, agentChat) 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')
}
}
}
+12
View File
@@ -13,9 +13,11 @@ describe('authn api', () => {
afterEach(() => { afterEach(() => {
vi.restoreAllMocks() vi.restoreAllMocks()
vi.unstubAllEnvs()
}) })
it('GET /signup-info', async () => { it('GET /signup-info', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
mockGetSignupInfo.mockResolvedValue({ mockGetSignupInfo.mockResolvedValue({
initialized: true, initialized: true,
demoMode: false, demoMode: false,
@@ -29,6 +31,16 @@ describe('authn api', () => {
initialized: true, initialized: true,
demoMode: false, demoMode: false,
archiveStorageEnabled: false, archiveStorageEnabled: false,
transcriptionEnabled: false,
}) })
}) })
it('advertises transcription with the local embedding provider', async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
mockGetSignupInfo.mockResolvedValue({ initialized: true, demoMode: false })
const res = await new Hono().route('/', authnRoute).request('/signup-info')
expect(await res.json()).toMatchObject({ transcriptionEnabled: true })
})
}) })
+2
View File
@@ -4,6 +4,7 @@ import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth' import { auth } from '@shumai/core/src/auth/auth'
import { createGuestToken } from '@shumai/core/src/auth/guest-token' import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage' import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { isLocalTranscriptionEnabled } from '@shumai/core/src/transcript/local-transcription'
import { z } from 'zod' import { z } from 'zod'
import { zValidator } from '@hono/zod-validator' import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid' import { ulid } from 'ulid'
@@ -24,6 +25,7 @@ const route = app
initialized: info.initialized, initialized: info.initialized,
demoMode: info.demoMode, demoMode: info.demoMode,
archiveStorageEnabled: isArchiveStorageEnabled(), archiveStorageEnabled: isArchiveStorageEnabled(),
transcriptionEnabled: isLocalTranscriptionEnabled(),
}) })
}) })
.get('/me', async (c) => { .get('/me', async (c) => {
+2
View File
@@ -31,6 +31,7 @@ import versionStackRoute from './versionStack'
import kanbanRoute from './kanban' import kanbanRoute from './kanban'
import mediaGenerationRoute from './media-generation' import mediaGenerationRoute from './media-generation'
import runnerWsRoute, { runnerWebsocket } from './runner-ws' import runnerWsRoute, { runnerWebsocket } from './runner-ws'
import transcriptRoute from './transcript'
export { runnerWebsocket } export { runnerWebsocket }
@@ -72,6 +73,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', teamRoute) .route('/', teamRoute)
.route('/', versionStackRoute) .route('/', versionStackRoute)
.route('/', fileRoute) .route('/', fileRoute)
.route('/', transcriptRoute)
.route('/', folderRoute) .route('/', folderRoute)
.route('/', agentRoute) .route('/', agentRoute)
.route('/', chatRoute) .route('/', chatRoute)
+69
View File
@@ -0,0 +1,69 @@
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { afterEach, describe, expect, it, vi } from 'vitest'
import transcriptRoute from './transcript'
describe('Transcript API', () => {
const app = new Hono().route('/', transcriptRoute)
const submit = (body: { language?: string }) =>
app.request('/files/file-id/transcripts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
afterEach(() => vi.restoreAllMocks())
it('proxies the server language list', async () => {
const list = { model: 'whisper-tiny', languages: [{ code: 'en', name: 'English' }] }
vi.spyOn(transcriptService, 'listLanguages').mockResolvedValue(list)
const response = await app.request('/transcription/languages')
expect(await response.json()).toEqual(list)
})
it('requires asset edit permission and returns a queued Auto job', async () => {
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const generate = vi
.spyOn(transcriptService, 'generate')
.mockResolvedValue({ kind: 'queued', taskId: 'task-id' })
const response = await submit({})
expect(response.status).toBe(202)
expect(await response.json()).toEqual({ kind: 'queued', taskId: 'task-id' })
expect(generate).toHaveBeenCalledWith('file-id', null)
expect(permission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Asset,
permission: Permission.Edit,
id: 'file-id',
}),
)
})
it('returns a saved transcript for an explicit language', async () => {
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
const saved = { kind: 'existing', transcriptId: 'transcript-id', language: 'en' } as const
vi.spyOn(transcriptService, 'generate').mockResolvedValue(saved)
const response = await submit({ language: 'en' })
expect(response.status).toBe(200)
expect(await response.json()).toEqual(saved)
expect(transcriptService.generate).toHaveBeenCalledWith('file-id', 'en')
})
it('rejects invalid language codes and denies reads and writes without edit permission', async () => {
vi.spyOn(authzService, 'hasPermission').mockRejectedValue(new HTTPException(403))
const generate = vi.spyOn(transcriptService, 'generate')
const status = vi.spyOn(transcriptService, 'getStatus')
expect((await submit({ language: 'auto' })).status).toBe(400)
expect((await submit({ language: 'en' })).status).toBe(403)
expect((await app.request('/files/file-id/transcription-status')).status).toBe(403)
expect(generate).not.toHaveBeenCalled()
expect(status).not.toHaveBeenCalled()
})
})
+38
View File
@@ -0,0 +1,38 @@
import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import type { User } from '@shumai/db'
import { generateTranscriptRequestSchema } from '@shumai/dtos'
import { Hono } from 'hono'
const route = new Hono<{ Variables: { user: User } }>()
.get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages()))
.post(
'/files/:fileId/transcripts',
zValidator('json', generateTranscriptRequestSchema),
async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
const { language } = c.req.valid('json')
const result = await transcriptService.generate(assetId, language ?? null)
return c.json(result, result.kind === 'queued' || result.kind === 'busy' ? 202 : 200)
},
)
.get('/files/:fileId/transcription-status', async (c) => {
const assetId = c.req.param('fileId')
await authzService.hasPermission({
user: c.get('user'),
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
return c.json(await transcriptService.getStatus(assetId))
})
export default route
@@ -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 baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
const url = baseUrl.replace(/\/+$/, '') const url = baseUrl.replace(/\/+$/, '').replace(/\/embeddings$/, '')
if (url.endsWith('/embeddings')) return url return url.endsWith('/v1') ? url : `${url}/v1`
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings` }
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)
})
})
+232
View File
@@ -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()
@@ -0,0 +1,39 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'ai_transcription';
-- CreateTable
CREATE TABLE "asset_transcripts" (
"id" TEXT NOT NULL,
"asset_id" TEXT NOT NULL,
"language" TEXT NOT NULL,
"model" TEXT NOT NULL,
"workflow_task_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "asset_transcripts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "asset_transcript_segments" (
"id" TEXT NOT NULL,
"transcript_id" TEXT NOT NULL,
"position" INTEGER NOT NULL,
"start_ms" INTEGER NOT NULL,
"end_ms" INTEGER NOT NULL,
"text" TEXT NOT NULL,
CONSTRAINT "asset_transcript_segments_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "asset_transcripts_asset_id_language_key" ON "asset_transcripts"("asset_id", "language");
-- CreateIndex
CREATE UNIQUE INDEX "asset_transcript_segments_transcript_id_position_key" ON "asset_transcript_segments"("transcript_id", "position");
-- AddForeignKey
ALTER TABLE "asset_transcripts" ADD CONSTRAINT "asset_transcripts_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "asset_transcript_segments" ADD CONSTRAINT "asset_transcript_segments_transcript_id_fkey" FOREIGN KEY ("transcript_id") REFERENCES "asset_transcripts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+30
View File
@@ -129,6 +129,7 @@ enum WorkflowTaskType {
ai_metadata_autofill ai_metadata_autofill
chat chat
ai_embedding ai_embedding
ai_transcription
query_embedding_for_search query_embedding_for_search
agent_tool_call // @deprecated: Agent tools now execute directly in-process via Core services agent_tool_call // @deprecated: Agent tools now execute directly in-process via Core services
kanban_agent_run kanban_agent_run
@@ -619,6 +620,7 @@ model Asset {
commentAttachments AssetCommentAttachment[] @relation("AssetToCommentAttachment") commentAttachments AssetCommentAttachment[] @relation("AssetToCommentAttachment")
notifications Notification[] @relation("AssetToNotification") notifications Notification[] @relation("AssetToNotification")
embeddings AssetEmbedding[] @relation("AssetToEmbedding") embeddings AssetEmbedding[] @relation("AssetToEmbedding")
transcripts AssetTranscript[]
teamRootFolder Team? @relation("TeamToRootFolder") teamRootFolder Team? @relation("TeamToRootFolder")
projectRootFolder Project? @relation("ProjectToRootFolder") projectRootFolder Project? @relation("ProjectToRootFolder")
@@ -775,6 +777,34 @@ model AssetEmbedding {
@@map("asset_embeddings") @@map("asset_embeddings")
} }
model AssetTranscript {
id String @id @default(ulid())
assetId String @map("asset_id")
asset Asset @relation(fields: [assetId], references: [id], onDelete: Cascade)
language String
model String
workflowTaskId String @map("workflow_task_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
segments AssetTranscriptSegment[]
@@unique([assetId, language], name: "assetIdLanguage")
@@map("asset_transcripts")
}
model AssetTranscriptSegment {
id String @id @default(ulid())
transcriptId String @map("transcript_id")
transcript AssetTranscript @relation(fields: [transcriptId], references: [id], onDelete: Cascade)
position Int
startMs Int @map("start_ms")
endMs Int @map("end_ms")
text String @db.Text
@@unique([transcriptId, position], name: "transcriptIdPosition")
@@map("asset_transcript_segments")
}
model Invite { model Invite {
id String @id @default(ulid()) id String @id @default(ulid())
code String @unique code String @unique
+10
View File
@@ -137,6 +137,16 @@ export type AssetCommentReaction = Prisma.AssetCommentReactionModel
* *
*/ */
export type AssetEmbedding = Prisma.AssetEmbeddingModel export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model AssetTranscript
*
*/
export type AssetTranscript = Prisma.AssetTranscriptModel
/**
* Model AssetTranscriptSegment
*
*/
export type AssetTranscriptSegment = Prisma.AssetTranscriptSegmentModel
/** /**
* Model Invite * Model Invite
* *
+10
View File
@@ -161,6 +161,16 @@ export type AssetCommentReaction = Prisma.AssetCommentReactionModel
* *
*/ */
export type AssetEmbedding = Prisma.AssetEmbeddingModel export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model AssetTranscript
*
*/
export type AssetTranscript = Prisma.AssetTranscriptModel
/**
* Model AssetTranscriptSegment
*
*/
export type AssetTranscriptSegment = Prisma.AssetTranscriptSegmentModel
/** /**
* Model Invite * Model Invite
* *
+1
View File
@@ -158,6 +158,7 @@ export const WorkflowTaskType = {
ai_metadata_autofill: 'ai_metadata_autofill', ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat', chat: 'chat',
ai_embedding: 'ai_embedding', ai_embedding: 'ai_embedding',
ai_transcription: 'ai_transcription',
query_embedding_for_search: 'query_embedding_for_search', query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call', agent_tool_call: 'agent_tool_call',
kanban_agent_run: 'kanban_agent_run', kanban_agent_run: 'kanban_agent_run',
File diff suppressed because one or more lines are too long
+178 -1
View File
@@ -421,6 +421,8 @@ export const ModelName = {
AssetCommentAttachment: 'AssetCommentAttachment', AssetCommentAttachment: 'AssetCommentAttachment',
AssetCommentReaction: 'AssetCommentReaction', AssetCommentReaction: 'AssetCommentReaction',
AssetEmbedding: 'AssetEmbedding', AssetEmbedding: 'AssetEmbedding',
AssetTranscript: 'AssetTranscript',
AssetTranscriptSegment: 'AssetTranscriptSegment',
Invite: 'Invite', Invite: 'Invite',
MetadataField: 'MetadataField', MetadataField: 'MetadataField',
Notification: 'Notification', Notification: 'Notification',
@@ -474,7 +476,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
omit: GlobalOmitOptions omit: GlobalOmitOptions
} }
meta: { meta: {
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion" modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "shareActivity" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "assetTranscript" | "assetTranscriptSegment" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
txIsolationLevel: TransactionIsolationLevel txIsolationLevel: TransactionIsolationLevel
} }
model: { model: {
@@ -2254,6 +2256,154 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
} }
} }
} }
AssetTranscript: {
payload: Prisma.$AssetTranscriptPayload<ExtArgs>
fields: Prisma.AssetTranscriptFieldRefs
operations: {
findUnique: {
args: Prisma.AssetTranscriptFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload> | null
}
findUniqueOrThrow: {
args: Prisma.AssetTranscriptFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
findFirst: {
args: Prisma.AssetTranscriptFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload> | null
}
findFirstOrThrow: {
args: Prisma.AssetTranscriptFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
findMany: {
args: Prisma.AssetTranscriptFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
create: {
args: Prisma.AssetTranscriptCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
createMany: {
args: Prisma.AssetTranscriptCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.AssetTranscriptCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
delete: {
args: Prisma.AssetTranscriptDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
update: {
args: Prisma.AssetTranscriptUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
deleteMany: {
args: Prisma.AssetTranscriptDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.AssetTranscriptUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.AssetTranscriptUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>[]
}
upsert: {
args: Prisma.AssetTranscriptUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptPayload>
}
aggregate: {
args: Prisma.AssetTranscriptAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateAssetTranscript>
}
groupBy: {
args: Prisma.AssetTranscriptGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptGroupByOutputType>[]
}
count: {
args: Prisma.AssetTranscriptCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptCountAggregateOutputType> | number
}
}
}
AssetTranscriptSegment: {
payload: Prisma.$AssetTranscriptSegmentPayload<ExtArgs>
fields: Prisma.AssetTranscriptSegmentFieldRefs
operations: {
findUnique: {
args: Prisma.AssetTranscriptSegmentFindUniqueArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload> | null
}
findUniqueOrThrow: {
args: Prisma.AssetTranscriptSegmentFindUniqueOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
findFirst: {
args: Prisma.AssetTranscriptSegmentFindFirstArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload> | null
}
findFirstOrThrow: {
args: Prisma.AssetTranscriptSegmentFindFirstOrThrowArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
findMany: {
args: Prisma.AssetTranscriptSegmentFindManyArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
create: {
args: Prisma.AssetTranscriptSegmentCreateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
createMany: {
args: Prisma.AssetTranscriptSegmentCreateManyArgs<ExtArgs>
result: BatchPayload
}
createManyAndReturn: {
args: Prisma.AssetTranscriptSegmentCreateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
delete: {
args: Prisma.AssetTranscriptSegmentDeleteArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
update: {
args: Prisma.AssetTranscriptSegmentUpdateArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
deleteMany: {
args: Prisma.AssetTranscriptSegmentDeleteManyArgs<ExtArgs>
result: BatchPayload
}
updateMany: {
args: Prisma.AssetTranscriptSegmentUpdateManyArgs<ExtArgs>
result: BatchPayload
}
updateManyAndReturn: {
args: Prisma.AssetTranscriptSegmentUpdateManyAndReturnArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>[]
}
upsert: {
args: Prisma.AssetTranscriptSegmentUpsertArgs<ExtArgs>
result: runtime.Types.Utils.PayloadToResult<Prisma.$AssetTranscriptSegmentPayload>
}
aggregate: {
args: Prisma.AssetTranscriptSegmentAggregateArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AggregateAssetTranscriptSegment>
}
groupBy: {
args: Prisma.AssetTranscriptSegmentGroupByArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptSegmentGroupByOutputType>[]
}
count: {
args: Prisma.AssetTranscriptSegmentCountArgs<ExtArgs>
result: runtime.Types.Utils.Optional<Prisma.AssetTranscriptSegmentCountAggregateOutputType> | number
}
}
}
Invite: { Invite: {
payload: Prisma.$InvitePayload<ExtArgs> payload: Prisma.$InvitePayload<ExtArgs>
fields: Prisma.InviteFieldRefs fields: Prisma.InviteFieldRefs
@@ -5455,6 +5605,31 @@ export const AssetEmbeddingScalarFieldEnum = {
export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum] export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const AssetTranscriptScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
language: 'language',
model: 'model',
workflowTaskId: 'workflowTaskId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AssetTranscriptScalarFieldEnum = (typeof AssetTranscriptScalarFieldEnum)[keyof typeof AssetTranscriptScalarFieldEnum]
export const AssetTranscriptSegmentScalarFieldEnum = {
id: 'id',
transcriptId: 'transcriptId',
position: 'position',
startMs: 'startMs',
endMs: 'endMs',
text: 'text'
} as const
export type AssetTranscriptSegmentScalarFieldEnum = (typeof AssetTranscriptSegmentScalarFieldEnum)[keyof typeof AssetTranscriptSegmentScalarFieldEnum]
export const InviteScalarFieldEnum = { export const InviteScalarFieldEnum = {
id: 'id', id: 'id',
code: 'code', code: 'code',
@@ -6747,6 +6922,8 @@ export type GlobalOmitConfig = {
assetCommentAttachment?: Prisma.AssetCommentAttachmentOmit assetCommentAttachment?: Prisma.AssetCommentAttachmentOmit
assetCommentReaction?: Prisma.AssetCommentReactionOmit assetCommentReaction?: Prisma.AssetCommentReactionOmit
assetEmbedding?: Prisma.AssetEmbeddingOmit assetEmbedding?: Prisma.AssetEmbeddingOmit
assetTranscript?: Prisma.AssetTranscriptOmit
assetTranscriptSegment?: Prisma.AssetTranscriptSegmentOmit
invite?: Prisma.InviteOmit invite?: Prisma.InviteOmit
metadataField?: Prisma.MetadataFieldOmit metadataField?: Prisma.MetadataFieldOmit
notification?: Prisma.NotificationOmit notification?: Prisma.NotificationOmit
@@ -75,6 +75,8 @@ export const ModelName = {
AssetCommentAttachment: 'AssetCommentAttachment', AssetCommentAttachment: 'AssetCommentAttachment',
AssetCommentReaction: 'AssetCommentReaction', AssetCommentReaction: 'AssetCommentReaction',
AssetEmbedding: 'AssetEmbedding', AssetEmbedding: 'AssetEmbedding',
AssetTranscript: 'AssetTranscript',
AssetTranscriptSegment: 'AssetTranscriptSegment',
Invite: 'Invite', Invite: 'Invite',
MetadataField: 'MetadataField', MetadataField: 'MetadataField',
Notification: 'Notification', Notification: 'Notification',
@@ -481,6 +483,31 @@ export const AssetEmbeddingScalarFieldEnum = {
export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum] export type AssetEmbeddingScalarFieldEnum = (typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const AssetTranscriptScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
language: 'language',
model: 'model',
workflowTaskId: 'workflowTaskId',
createdAt: 'createdAt',
updatedAt: 'updatedAt'
} as const
export type AssetTranscriptScalarFieldEnum = (typeof AssetTranscriptScalarFieldEnum)[keyof typeof AssetTranscriptScalarFieldEnum]
export const AssetTranscriptSegmentScalarFieldEnum = {
id: 'id',
transcriptId: 'transcriptId',
position: 'position',
startMs: 'startMs',
endMs: 'endMs',
text: 'text'
} as const
export type AssetTranscriptSegmentScalarFieldEnum = (typeof AssetTranscriptSegmentScalarFieldEnum)[keyof typeof AssetTranscriptSegmentScalarFieldEnum]
export const InviteScalarFieldEnum = { export const InviteScalarFieldEnum = {
id: 'id', id: 'id',
code: 'code', code: 'code',
+2
View File
@@ -32,6 +32,8 @@ export type * from './models/AssetComment.ts'
export type * from './models/AssetCommentAttachment.ts' export type * from './models/AssetCommentAttachment.ts'
export type * from './models/AssetCommentReaction.ts' export type * from './models/AssetCommentReaction.ts'
export type * from './models/AssetEmbedding.ts' export type * from './models/AssetEmbedding.ts'
export type * from './models/AssetTranscript.ts'
export type * from './models/AssetTranscriptSegment.ts'
export type * from './models/Invite.ts' export type * from './models/Invite.ts'
export type * from './models/MetadataField.ts' export type * from './models/MetadataField.ts'
export type * from './models/Notification.ts' export type * from './models/Notification.ts'
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+5 -3
View File
@@ -18,6 +18,10 @@ export function registerWorkflowTrigger(cb: WorkflowTriggerCallback) {
onWorkflowTaskCreated = cb onWorkflowTaskCreated = cb
} }
export async function notifyWorkflowTaskCreated(task: WorkflowTask): Promise<void> {
if (task.status === 'pending') await onWorkflowTaskCreated?.(task)
}
// Global callback for workflow task cancellation (decouples db/core packages from workflow engine) // Global callback for workflow task cancellation (decouples db/core packages from workflow engine)
type WorkflowCancelCallback = (taskId: string) => Promise<void> type WorkflowCancelCallback = (taskId: string) => Promise<void>
let onWorkflowTaskCancelled: WorkflowCancelCallback | null = null let onWorkflowTaskCancelled: WorkflowCancelCallback | null = null
@@ -149,9 +153,7 @@ function createPrismaClient() {
workflowTask: { workflowTask: {
async create({ args, query }) { async create({ args, query }) {
const result = await query(args) const result = await query(args)
if (onWorkflowTaskCreated && (result as WorkflowTask).status === 'pending') { notifyWorkflowTaskCreated(result as WorkflowTask).catch(console.error)
onWorkflowTaskCreated(result as WorkflowTask).catch(console.error)
}
return result return result
}, },
}, },
+2
View File
@@ -377,6 +377,7 @@ declare global {
imageAnnotation?: ImageAnnotationSpec imageAnnotation?: ImageAnnotationSpec
pdfPages?: PdfPagesSpec pdfPages?: PdfPagesSpec
videoChunks?: VideoChunksSpec videoChunks?: VideoChunksSpec
transcription?: { language: string | null; model: string }
/** Render that produced this result, if any (set by the read_asset pipeline). */ /** Render that produced this result, if any (set by the read_asset pipeline). */
assetRead?: AssetReadRequest assetRead?: AssetReadRequest
watermark?: WatermarkTaskPayload watermark?: WatermarkTaskPayload
@@ -403,6 +404,7 @@ declare global {
export interface WorkflowTaskOutput { export interface WorkflowTaskOutput {
error?: string error?: string
transcription?: { transcriptId: string; language: string } | { noSpeech: true }
recoveryAttempts?: number recoveryAttempts?: number
[key: string]: unknown [key: string]: unknown
} }
+1
View File
@@ -26,6 +26,7 @@ export * from './search'
export * from './share' export * from './share'
export * from './skill' export * from './skill'
export * from './team' export * from './team'
export * from './transcript'
export * from './upload' export * from './upload'
export * from './user-metadata' export * from './user-metadata'
export * from './versionStack' export * from './versionStack'
+26
View File
@@ -0,0 +1,26 @@
import { z } from 'zod'
export const transcriptLanguageCodeSchema = z.string().regex(/^[a-z]{2,3}$/)
export const generateTranscriptRequestSchema = z.object({
language: transcriptLanguageCodeSchema.optional(),
})
export const transcriptLanguagesSchema = z.object({
model: z.string().min(1),
languages: z.array(z.object({ code: transcriptLanguageCodeSchema, name: z.string().min(1) })),
})
export const transcriptionErrors = {
noAudio: 'The video does not contain an audio track',
tooLarge: 'Audio exceeds the embedding server upload limit',
} as const
export type GenerateTranscriptResult =
| { kind: 'queued' | 'busy'; taskId: string }
| { kind: 'existing'; transcriptId: string; language: string }
| { kind: 'no_speech' }
export type TranscriptJobStatus =
| { status: 'pending' | 'processing' | 'completed' | 'no_speech'; taskId: string }
| { status: 'failed'; taskId: string; reason: keyof typeof transcriptionErrors | 'unknown' }
@@ -0,0 +1,213 @@
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 { initAgentWorkflows } from '@shumai/agent'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcriptService } from '@shumai/core/src/transcript/transcript'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
const execFileAsync = promisify(execFile)
const bucket = 'shumai-e2e-transcript'
const languages = {
model: 'whisper-tiny',
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
}
describe('Transcribe video workflow', () => {
setupTestDbHooks()
let directory: string
let provider: ReturnType<typeof Bun.serve>
let responseStatus = 200
let firstRequestBusy = false
let uploads: Array<{
language: FormDataEntryValue | null
length: string | null
hasTransferEncoding: boolean
model: FormDataEntryValue | null
format: FormDataEntryValue | null
audio: Buffer
}> = []
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), 'shumai-e2e-transcripts-'))
await execFileAsync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=size=64x64:duration=2',
'-itsoffset',
'1',
'-f',
'lavfi',
'-i',
'sine=frequency=440:duration=1',
'-c:v',
'mpeg4',
'-c:a',
'pcm_s16le',
join(directory, 'audio.mkv'),
])
await execFileAsync('ffmpeg', [
'-v',
'error',
'-f',
'lavfi',
'-i',
'color=size=64x64:duration=1',
'-c:v',
'mpeg4',
join(directory, 'silent.mkv'),
])
// Replace only the inference server and inspect what the worker sends over HTTP.
provider = Bun.serve({
hostname: '127.0.0.1',
port: 0,
async fetch(request) {
const path = new URL(request.url).pathname
if (path === '/v1/audio/transcriptions/languages') return Response.json(languages)
if (path !== '/v1/audio/transcriptions' || request.method !== 'POST')
return new Response(null, { status: 404 })
const form = await request.formData()
const file = form.get('file')
if (!(file instanceof File)) return new Response(null, { status: 400 })
uploads.push({
language: form.get('language'),
length: request.headers.get('content-length'),
hasTransferEncoding: request.headers.has('transfer-encoding'),
model: form.get('model'),
format: form.get('response_format'),
audio: Buffer.from(await file.arrayBuffer()),
})
if (firstRequestBusy && uploads.length === 1) return new Response(null, { status: 429 })
if (responseStatus !== 200) return new Response(null, { status: responseStatus })
return Response.json({
language: form.get('language') ?? 'en',
text: 'Hello',
segments: [{ start: 1.012, end: 1.875, text: 'Hello' }],
})
},
})
vi.stubEnv('S3_BUCKET', bucket)
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', `${provider.url}v1/embeddings/`)
initAgentWorkflows()
await workflowService.startWorkers(TaskQueueAgent)
})
beforeEach(() => {
uploads = []
responseStatus = 200
firstRequestBusy = false
})
afterAll(async () => {
await workflowService.shutdownWorkers()
workflowService.close()
await provider?.stop(true)
await s3Service.deletePrefix(bucket, '')
if (directory) await rm(directory, { recursive: true, force: true })
vi.unstubAllEnvs()
})
async function submitVideo(name: string, language: string | null) {
const team = await prisma.team.create({ data: { name: 'Transcription E2E' } })
const project = await prisma.project.create({ data: { name: 'Videos', teamId: team.id } })
const key = `video/${name}`
await s3Service.uploadFileToKey(join(directory, name), key, 'video/x-matroska')
const asset = await prisma.asset.create({
data: {
name,
type: 'file',
status: 'processed',
project: { connect: { id: project.id } },
mediaType: 'video/x-matroska',
storageKey: { create: { key } },
},
})
const result = await transcriptService.generate(asset.id, language)
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
return {
assetId: asset.id,
task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }),
}
}
it('sends a timeline-aligned WAV and saves the detected language and segments after retrying a busy server', async () => {
firstRequestBusy = true
const { task, assetId } = await submitVideo('audio.mkv', null)
await workflowService.executeWait(task, 20_000)
expect(uploads).toHaveLength(2)
const upload = uploads[1]
expect(upload).toMatchObject({
language: null,
hasTransferEncoding: false,
model: 'whisper-tiny',
format: 'verbose_json',
})
expect(Number(upload.length)).toBeGreaterThan(upload.audio.length)
expect(upload.audio.toString('ascii', 0, 4)).toBe('RIFF')
expect(upload.audio.readUInt16LE(22)).toBe(1)
expect(upload.audio.readUInt32LE(24)).toBe(16_000)
expect(upload.audio.readUInt16LE(34)).toBe(16)
const pcm = upload.audio.indexOf('data', 36) + 8
expect(upload.audio.subarray(pcm, pcm + 30_000).every((sample) => sample === 0)).toBe(true)
expect(upload.audio.subarray(pcm + 34_000).some((sample) => sample !== 0)).toBe(true)
const transcript = await prisma.assetTranscript.findUniqueOrThrow({
where: { assetIdLanguage: { assetId, language: 'en' } },
include: { segments: true },
})
expect(transcript).toMatchObject({
model: 'whisper-tiny',
workflowTaskId: task.id,
segments: [{ position: 0, startMs: 1012, endMs: 1875, text: 'Hello' }],
})
await vi.waitFor(async () =>
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
)
}, 24_000)
it('passes an explicit language and treats an upload limit error as permanent', async () => {
responseStatus = 413
const { task, assetId } = await submitVideo('audio.mkv', 'zh')
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'Audio exceeds the embedding server upload limit',
)
expect(uploads).toHaveLength(1)
expect(uploads[0].language).toBe('zh')
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: task.id,
status: 'failed',
reason: 'tooLarge',
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
await vi.waitFor(async () =>
expect(await s3Service.listObjects(bucket, 'temp/transcripts/')).toEqual([]),
)
}, 24_000)
it('fails with a clear message when the video has no audio track', async () => {
const { task, assetId } = await submitVideo('silent.mkv', null)
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
'The video does not contain an audio track',
)
expect(uploads).toHaveLength(0)
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: task.id,
status: 'failed',
reason: 'noAudio',
})
}, 24_000)
})
+9 -54
View File
@@ -34,7 +34,15 @@ import { execFile } from 'child_process'
import { promisify } from 'util' import { promisify } from 'util'
import { ulid } from 'ulid' import { ulid } from 'ulid'
import { logger } from '@shumai/core/src/logger' import { logger } from '@shumai/core/src/logger'
import { ApplicationFailure, defineStep, getLocalTaskAbortSignal } from '@shumai/workflow-core' import {
ApplicationFailure,
defineStep,
ensureLocalMediaFile,
getErrorDetails,
getLocalTaskAbortSignal,
} from '@shumai/workflow-core'
export { ensureLocalMediaFile } from '@shumai/workflow-core'
const execFileAsync = promisify(execFile) const execFileAsync = promisify(execFile)
@@ -42,59 +50,6 @@ function getActivityCancellationSignal(taskId?: string): AbortSignal | undefined
return getLocalTaskAbortSignal(taskId) return getLocalTaskAbortSignal(taskId)
} }
function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
if (err && typeof err === 'object') {
const record = err as Record<string, unknown>
return {
code: typeof record.code === 'string' ? record.code : undefined,
message:
typeof record.message === 'string'
? record.message
: err instanceof Error
? err.message
: String(err),
name: typeof record.name === 'string' ? record.name : undefined,
}
}
return {
message: String(err),
}
}
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
if (fs.existsSync(filePath)) {
return filePath
}
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.downloadToFile(bucket, assetKey, filePath)
} catch (err) {
const { code, message, name } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
const lowerCode = (code || '').toLowerCase()
const lowerName = (name || '').toLowerCase()
if (
lowerCode === 'enoent' ||
lowerCode === 'nosuchkey' ||
lowerName === 'nosuchkey' ||
lowerMsg.includes('enoent') ||
lowerMsg.includes('nosuchkey')
) {
throw ApplicationFailure.create({
message: `Failed to download media to local file: ${message}`,
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw err
}
return filePath
}
export interface GetMediaInfoActivityParams { export interface GetMediaInfoActivityParams {
assetId: string assetId: string
assetKey: string assetKey: string
@@ -87,6 +87,47 @@ describe('FileBrowserContextMenu', () => {
expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull() expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull()
}) })
it('starts transcription on the displayed video file in a stack', () => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{
...stackItem,
proxyType: 'video',
versionStack: {
id: stackItem.id,
versions: [
{ id: 'old', name: 'old.mp4', version: 1, current: false },
{ id: 'current', name: 'current.mp4', version: 2, current: true },
],
},
},
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
fireEvent.click(screen.getByRole('menuitem', { name: 'Generate Transcripts' }))
expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4')
})
it.each([
{
label: 'a read-only member',
item: { ...fileItem, proxyType: 'video' as const },
canEdit: false,
},
{ label: 'a non-video asset', item: fileItem, canEdit: true },
{
label: 'an archived video',
item: { ...fileItem, proxyType: 'video' as const, status: 'archived' },
canEdit: true,
},
])('hides the action for $label', ({ item, canEdit }) => {
renderWithMenu(item, { canEdit, onGenerateTranscripts: vi.fn() })
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
expect(screen.queryByRole('menuitem', { name: 'Generate Transcripts' })).toBeNull()
})
it('renders Manage versions for version_stack item when canEdit is true', () => { it('renders Manage versions for version_stack item when canEdit is true', () => {
const onManageVersions = vi.fn() const onManageVersions = vi.fn()
renderWithMenu(stackItem, { onManageVersions }) renderWithMenu(stackItem, { onManageVersions })
@@ -27,6 +27,7 @@ import {
Copy, Copy,
Layers, Layers,
ScanSearch, ScanSearch,
Captions,
} from 'lucide-react' } from 'lucide-react'
import { CopyContextMenuSub } from './copy-submenu' import { CopyContextMenuSub } from './copy-submenu'
import { isImageItem, type CopyKind } from './copy-options' import { isImageItem, type CopyKind } from './copy-options'
@@ -40,6 +41,7 @@ interface FileBrowserContextMenuProps {
onDownload: (items: AssetInfo[]) => void onDownload: (items: AssetInfo[]) => void
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
onFindSimilar?: (item: AssetInfo) => void onFindSimilar?: (item: AssetInfo) => void
onGenerateTranscripts?: (assetId: string, name: string) => void
onRestore: (items: AssetInfo[]) => void onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void onRestoreArchive?: (items: AssetInfo[]) => void
@@ -75,6 +77,7 @@ export function FileBrowserContextMenu({
onDownload, onDownload,
onCopy, onCopy,
onFindSimilar, onFindSimilar,
onGenerateTranscripts,
onRestore, onRestore,
onArchive, onArchive,
onRestoreArchive, onRestoreArchive,
@@ -237,6 +240,12 @@ export function FileBrowserContextMenu({
</ContextMenuItem> </ContextMenuItem>
) )
const videoVersion =
item.type === 'version_stack'
? item.versionStack?.versions.find((version) => version.current)
: undefined
const transcriptAssetId = item.type === 'file' ? item.id : videoVersion?.id
const contextMenuContent = const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? ( isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent <ContextMenuContent
@@ -360,6 +369,20 @@ export function FileBrowserContextMenu({
<span>{m.download()}</span> <span>{m.download()}</span>
</ContextMenuItem> </ContextMenuItem>
{findSimilarItem} {findSimilarItem}
{canEdit &&
onGenerateTranscripts &&
transcriptAssetId &&
item.status === 'processed' &&
item.proxyType === 'video' && (
<ContextMenuItem
onSelect={() =>
onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name)
}
>
<Captions className="mr-2 h-4 w-4" />
<span>{m.generate_transcripts()}</span>
</ContextMenuItem>
)}
<CopyContextMenuSub <CopyContextMenuSub
items={itemsToModify} items={itemsToModify}
context={{ context={{
@@ -30,6 +30,7 @@ import { FilePreviewDialog } from '../file-preview-dialog'
import { ShareLinkCreatedDialog } from '../share-link-created-dialog' import { ShareLinkCreatedDialog } from '../share-link-created-dialog'
import { FileBrowserContentSkeleton } from '../loading-skeletons' import { FileBrowserContentSkeleton } from '../loading-skeletons'
import { FileBrowserContextMenu } from './context-menu' import { FileBrowserContextMenu } from './context-menu'
import { GenerateTranscriptsDialog } from './generate-transcripts-dialog'
import { getItemInAppUrl } from './copy-options' import { getItemInAppUrl } from './copy-options'
import { FindSimilarDialog } from '../search/find-similar-dialog' import { FindSimilarDialog } from '../search/find-similar-dialog'
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled' import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
@@ -63,6 +64,7 @@ import { FileBrowserToolbar } from './toolbar'
import { useFileActions } from './use-file-actions' import { useFileActions } from './use-file-actions'
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status' import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config' import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useServerFeatures } from '@/ui/hooks/use-server-features'
import { ArchiveConfirmDialog } from '../archive-confirm-dialog' import { ArchiveConfirmDialog } from '../archive-confirm-dialog'
interface FileBrowserProps { interface FileBrowserProps {
@@ -161,6 +163,8 @@ export function FileBrowser({
}: FileBrowserProps) { }: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null) const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null) const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
const [transcriptVideo, setTranscriptVideo] = useState<{ id: string; name: string } | null>(null)
const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled
const semanticSearchEnabled = useSemanticSearchEnabled( const semanticSearchEnabled = useSemanticSearchEnabled(
teamId, teamId,
Boolean( Boolean(
@@ -1122,6 +1126,11 @@ export function FileBrowser({
onDownload={handleDownload} onDownload={handleDownload}
onCopy={handleCopy} onCopy={handleCopy}
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined} onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
onGenerateTranscripts={
transcriptionEnabled && !isShareView && !isPublic
? (id, name) => setTranscriptVideo({ id, name })
: undefined
}
onNewFolder={handleNewFolder} onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick} onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick} onUploadFolder={handleUploadFolderClick}
@@ -1182,6 +1191,15 @@ export function FileBrowser({
)} )}
{renderContent()} {renderContent()}
{transcriptVideo && (
<GenerateTranscriptsDialog
key={transcriptVideo.id}
assetId={transcriptVideo.id}
name={transcriptVideo.name}
onClose={() => setTranscriptVideo(null)}
/>
)}
{semanticSearchEnabled && similarImage && rootFolderId && ( {semanticSearchEnabled && similarImage && rootFolderId && (
<FindSimilarDialog <FindSimilarDialog
image={similarImage} image={similarImage}
@@ -0,0 +1,202 @@
import { useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { TranscriptJobStatus } from '@shumai/dtos'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { Button } from '@/ui/components/ui/button'
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from '@/ui/components/ui/combobox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
function isActive(status?: TranscriptJobStatus | null) {
return status?.status === 'pending' || status?.status === 'processing'
}
function statusMessage(job: TranscriptJobStatus) {
switch (job.status) {
case 'pending':
return m.transcript_queued()
case 'processing':
return m.transcript_generating()
case 'completed':
return m.transcript_completed()
case 'no_speech':
return m.transcript_no_speech()
case 'failed':
if (job.reason === 'tooLarge') return m.transcript_audio_too_large()
if (job.reason === 'noAudio') return m.transcript_no_audio()
return m.transcript_failed()
}
}
export function GenerateTranscriptsDialog({
assetId,
name,
onClose,
}: {
assetId: string
name: string
onClose: () => void
}) {
const dialogRef = useRef<HTMLDivElement>(null)
const queryClient = useQueryClient()
const [language, setLanguage] = useState('')
const param = { fileId: assetId }
const statusKey = ['transcription-status', assetId]
const languages = useQuery({
queryKey: ['transcription-languages'],
queryFn: async () => {
const response = await client.api.transcription.languages.$get()
if (!response.ok) throw new Error(m.transcript_languages_unavailable())
return await response.json()
},
staleTime: 5 * 60 * 1000,
retry: false,
})
const job = useQuery({
queryKey: statusKey,
queryFn: async () => {
const response = await client.api.files[':fileId']['transcription-status'].$get({ param })
if (!response.ok) throw new Error(m.transcript_status_unavailable())
return await response.json()
},
refetchInterval: (query) => (isActive(query.state.data) ? 2_000 : false),
})
const generate = useMutation({
mutationFn: async () => {
const response = await client.api.files[':fileId'].transcripts.$post({
param,
json: { language: language || undefined },
})
if (!response.ok) throw new Error(m.transcript_submit_failed())
return await response.json()
},
onSuccess: (result) => {
if (result.kind === 'existing' || result.kind === 'no_speech') {
toast.info(
result.kind === 'existing' ? m.transcript_already_exists() : m.transcript_no_speech(),
)
return
}
queryClient.setQueryData<TranscriptJobStatus>(statusKey, {
status: 'pending',
taskId: result.taskId,
})
void queryClient.invalidateQueries({ queryKey: statusKey })
if (result.kind === 'queued') toast.success(m.transcript_queued())
},
})
const choices = [
{ code: '', name: m.transcript_language_auto() },
...(languages.data?.languages ?? []),
]
const busy = generate.isPending || isActive(job.data)
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) onClose()
}}
>
<DialogContent ref={dialogRef} showCloseButton={false}>
<DialogHeader>
<DialogTitle>{m.generate_transcripts()}</DialogTitle>
<DialogDescription>{name}</DialogDescription>
</DialogHeader>
<Combobox
items={choices}
value={choices.find((choice) => choice.code === language)}
onValueChange={(choice) => setLanguage(choice?.code ?? '')}
itemToStringLabel={(choice) => choice.name}
isItemEqualToValue={(choice, value) => choice.code === value.code}
disabled={busy || languages.isPending || languages.isError}
>
<label htmlFor="transcript-language" className="text-sm font-medium">
{m.language()}
</label>
<ComboboxInput id="transcript-language" />
<ComboboxContent container={dialogRef}>
<ComboboxEmpty>{m.transcript_no_languages_found()}</ComboboxEmpty>
<ComboboxList>
{(choice) => (
<ComboboxItem key={choice.code} value={choice}>
{choice.name}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
{languages.isPending && (
<p role="status" className="text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{languages.isError && (
<div className="flex items-center justify-between gap-2">
<p role="alert" className="text-sm text-destructive">
{m.transcript_languages_unavailable()}
</p>
<Button variant="outline" size="sm" onClick={() => languages.refetch()}>
{m.retry()}
</Button>
</div>
)}
{generate.isError && (
<p role="alert" className="text-sm text-destructive">
{generate.error.message}
</p>
)}
{job.isError && (
<p role="alert" className="text-sm text-destructive">
{m.transcript_status_unavailable()}
</p>
)}
{job.data && (
<p
role="status"
className={
job.data.status === 'failed'
? 'text-sm text-destructive'
: 'text-sm text-muted-foreground'
}
>
{statusMessage(job.data)}
</p>
)}
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{m.close()}
</Button>
<Button
disabled={busy || !languages.data || job.isPending}
onClick={() => generate.mutate()}
>
{m.generate()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+4 -2
View File
@@ -89,14 +89,16 @@ function ComboboxContent({
align = 'start', align = 'start',
alignOffset = 0, alignOffset = 0,
anchor, anchor,
container,
...props ...props
}: ComboboxPrimitive.Popup.Props & }: ComboboxPrimitive.Popup.Props &
Pick< Pick<
ComboboxPrimitive.Positioner.Props, ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor' 'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
>) { > &
Pick<ComboboxPrimitive.Portal.Props, 'container'>) {
return ( return (
<ComboboxPrimitive.Portal> <ComboboxPrimitive.Portal container={container}>
<ComboboxPrimitive.Positioner <ComboboxPrimitive.Positioner
side={side} side={side}
sideOffset={sideOffset} sideOffset={sideOffset}
+2 -17
View File
@@ -1,5 +1,4 @@
import { useQuery } from '@tanstack/react-query' import { useServerFeatures } from './use-server-features'
import { client } from '@/ui/api/client'
export interface ArchiveConfig { export interface ArchiveConfig {
archiveStorageEnabled: boolean archiveStorageEnabled: boolean
@@ -7,21 +6,7 @@ export interface ArchiveConfig {
} }
export function useArchiveConfig(): ArchiveConfig { export function useArchiveConfig(): ArchiveConfig {
const { data, isLoading } = useQuery({ const { data, isLoading } = useServerFeatures()
queryKey: ['signup-info'],
queryFn: async () => {
const res = await client.api['signup-info'].$get()
if (!res.ok) {
return { initialized: true, demoMode: false, archiveStorageEnabled: false }
}
return (await res.json()) as {
initialized?: boolean
demoMode?: boolean
archiveStorageEnabled?: boolean
}
},
staleTime: 5 * 60 * 1000,
})
return { return {
archiveStorageEnabled: Boolean(data?.archiveStorageEnabled), archiveStorageEnabled: Boolean(data?.archiveStorageEnabled),
@@ -0,0 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
export function useServerFeatures() {
return useQuery({
queryKey: ['signup-info'],
queryFn: async () => {
const res = await client.api['signup-info'].$get()
if (!res.ok) return null
return await res.json()
},
staleTime: 5 * 60 * 1000,
})
}
+15 -1
View File
@@ -1810,5 +1810,19 @@
"internal_comment_tooltip": "Internal comment — hidden from public share links", "internal_comment_tooltip": "Internal comment — hidden from public share links",
"internal_reply_locked_tooltip": "Replies to internal comments are always internal", "internal_reply_locked_tooltip": "Replies to internal comments are always internal",
"remove_timestamp": "Remove timestamp", "remove_timestamp": "Remove timestamp",
"failed_to_update_comment": "Failed to update comment" "failed_to_update_comment": "Failed to update comment",
"generate_transcripts": "Generate Transcripts",
"transcript_language_auto": "Auto",
"transcript_queued": "Transcript generation queued.",
"transcript_generating": "Generating transcript…",
"transcript_completed": "Transcript generated.",
"transcript_no_speech": "No speech detected.",
"transcript_no_audio": "This video has no audio track.",
"transcript_audio_too_large": "The audio exceeds the embedding server’s upload limit.",
"transcript_failed": "Transcript generation failed.",
"transcript_submit_failed": "Could not start transcript generation.",
"transcript_already_exists": "A transcript already exists for this language.",
"transcript_languages_unavailable": "Could not load transcription languages.",
"transcript_no_languages_found": "No matching languages.",
"transcript_status_unavailable": "Could not check transcript status."
} }
+15 -1
View File
@@ -1740,5 +1740,19 @@
"internal_comment_tooltip": "내부 댓글 — 공개 공유 링크에는 표시되지 않음", "internal_comment_tooltip": "내부 댓글 — 공개 공유 링크에는 표시되지 않음",
"internal_reply_locked_tooltip": "내부 댓글에 대한 답글은 항상 내부 댓글로 작성됩니다", "internal_reply_locked_tooltip": "내부 댓글에 대한 답글은 항상 내부 댓글로 작성됩니다",
"remove_timestamp": "타임스탬프 제거", "remove_timestamp": "타임스탬프 제거",
"failed_to_update_comment": "댓글을 수정하지 못했습니다" "failed_to_update_comment": "댓글을 수정하지 못했습니다",
"generate_transcripts": "전사 생성",
"transcript_language_auto": "자동 감지",
"transcript_queued": "전사 작업이 대기열에 추가되었습니다.",
"transcript_generating": "전사를 생성하는 중…",
"transcript_completed": "전사를 생성했습니다.",
"transcript_no_speech": "음성이 감지되지 않았습니다.",
"transcript_no_audio": "이 동영상에는 오디오 트랙이 없습니다.",
"transcript_audio_too_large": "오디오가 임베딩 서버의 업로드 한도를 초과합니다.",
"transcript_failed": "전사 생성에 실패했습니다.",
"transcript_submit_failed": "전사 생성을 시작할 수 없습니다.",
"transcript_already_exists": "이 언어의 전사가 이미 있습니다.",
"transcript_languages_unavailable": "전사 언어를 불러올 수 없습니다.",
"transcript_no_languages_found": "일치하는 언어가 없습니다.",
"transcript_status_unavailable": "전사 상태를 확인할 수 없습니다."
} }
+15 -1
View File
@@ -1810,5 +1810,19 @@
"internal_comment_tooltip": "内部评论 — 不会在公开分享链接中显示", "internal_comment_tooltip": "内部评论 — 不会在公开分享链接中显示",
"internal_reply_locked_tooltip": "回复内部评论时只能发送内部评论", "internal_reply_locked_tooltip": "回复内部评论时只能发送内部评论",
"remove_timestamp": "移除时间戳", "remove_timestamp": "移除时间戳",
"failed_to_update_comment": "更新评论失败" "failed_to_update_comment": "更新评论失败",
"generate_transcripts": "生成转录",
"transcript_language_auto": "自动检测",
"transcript_queued": "转录任务已加入队列。",
"transcript_generating": "正在生成转录…",
"transcript_completed": "转录已生成。",
"transcript_no_speech": "未检测到语音。",
"transcript_no_audio": "此视频没有音轨。",
"transcript_audio_too_large": "音频超出嵌入服务器的上传大小限制。",
"transcript_failed": "转录生成失败。",
"transcript_submit_failed": "无法启动转录生成。",
"transcript_already_exists": "此语言的转录已存在。",
"transcript_languages_unavailable": "无法加载转录语言。",
"transcript_no_languages_found": "没有匹配的语言。",
"transcript_status_unavailable": "无法获取转录状态。"
} }
@@ -0,0 +1,57 @@
import { s3Service } from '@shumai/core/src/s3/s3'
import * as fs from 'node:fs'
import * as path from 'node:path'
import { ApplicationFailure } from '../workflow-utils'
export function getErrorDetails(err: unknown): { code?: string; message: string; name?: string } {
if (err && typeof err === 'object') {
const record = err as Record<string, unknown>
return {
code: typeof record.code === 'string' ? record.code : undefined,
message:
typeof record.message === 'string'
? record.message
: err instanceof Error
? err.message
: String(err),
name: typeof record.name === 'string' ? record.name : undefined,
}
}
return {
message: String(err),
}
}
export async function ensureLocalMediaFile(assetKey: string, filePath: string): Promise<string> {
if (fs.existsSync(filePath)) {
return filePath
}
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
const bucket = process.env.S3_BUCKET || 'shumai'
try {
await s3Service.downloadToFile(bucket, assetKey, filePath)
} catch (err) {
const { code, message, name } = getErrorDetails(err)
const lowerMsg = message.toLowerCase()
const lowerCode = (code || '').toLowerCase()
const lowerName = (name || '').toLowerCase()
if (
lowerCode === 'enoent' ||
lowerCode === 'nosuchkey' ||
lowerName === 'nosuchkey' ||
lowerMsg.includes('enoent') ||
lowerMsg.includes('nosuchkey')
) {
throw ApplicationFailure.create({
message: `Failed to download media to local file: ${message}`,
nonRetryable: true,
cause: err instanceof Error ? err : undefined,
})
}
throw err
}
return filePath
}
@@ -57,6 +57,7 @@ export function getDbosDatabaseUrl(rawUrl?: string): string {
export function getQueueForTaskType(type: string | null | undefined): string { export function getQueueForTaskType(type: string | null | undefined): string {
switch (type) { switch (type) {
case WorkflowTaskType.ai_embedding: case WorkflowTaskType.ai_embedding:
case WorkflowTaskType.ai_transcription:
case WorkflowTaskType.ai_metadata_autofill: case WorkflowTaskType.ai_metadata_autofill:
case WorkflowTaskType.chat: case WorkflowTaskType.chat:
return TaskQueueAgent return TaskQueueAgent
+1
View File
@@ -2,4 +2,5 @@ export * from './dbos-executor'
export * from './workflow-utils' export * from './workflow-utils'
export * from './workflow' export * from './workflow'
export * from './activities/task' export * from './activities/task'
export * from './activities/media'
export * from './local-task-storage' export * from './local-task-storage'