mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
fix(video): transcribe archived videos and show progress (#560)
This commit is contained in:
@@ -76,7 +76,7 @@ apps/web/e2e/
|
||||
| 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 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 generates a transcript from an archived video's context menu, sees progress in card and list metadata across a refresh, and reuses the project status across folders | `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 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` |
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { seedFolder } from '../../helpers/assets'
|
||||
import { fileCard } from '../../helpers/files'
|
||||
import type { TranscriptJobStatus } from '@shumai/dtos'
|
||||
|
||||
test.use({ fileOptions: { mediaType: 'video' } })
|
||||
|
||||
test('selects a transcription language from the video context menu and tracks the job', async ({
|
||||
test('starts a transcript for an archived video and tracks it in the file metadata', async ({
|
||||
file,
|
||||
prisma,
|
||||
}) => {
|
||||
const { page, projectId, fileId, fileName } = file
|
||||
let status: TranscriptJobStatus = { taskId: 'previous-transcript', status: 'completed' }
|
||||
const { page, projectId, rootFolderId, fileId, fileName } = file
|
||||
const projectPath = `/projects/${projectId}`
|
||||
const statusPath = `/api${projectPath}/transcription-status`
|
||||
const folder = await seedFolder(prisma, projectId, rootFolderId, 'Other folder')
|
||||
const expectedLanguages = ['zh', 'en']
|
||||
let submissions = 0
|
||||
let rejectSubmission = true
|
||||
let statusRequests = 0
|
||||
page.on('request', (request) => {
|
||||
if (new URL(request.url()).pathname === statusPath) {
|
||||
expect(request.method()).toBe('GET')
|
||||
expect(request.postData()).toBeNull()
|
||||
statusRequests++
|
||||
}
|
||||
})
|
||||
await page.route('**/api/signup-info', async (route) => {
|
||||
const response = await route.fetch()
|
||||
await route.fulfill({ json: { ...(await response.json()), transcriptionEnabled: true } })
|
||||
@@ -27,14 +38,18 @@ test('selects a transcription language from the video context menu and tracks th
|
||||
},
|
||||
}),
|
||||
)
|
||||
await page.route(`**/api/files/${fileId}/transcription-status`, (route) =>
|
||||
route.fulfill({ json: status }),
|
||||
)
|
||||
await page.route(`**/api/files/${fileId}/transcripts`, async (route) => {
|
||||
expect(route.request().postDataJSON()).toEqual({ language: expectedLanguages[submissions] })
|
||||
const taskId = `transcript-task-${++submissions}`
|
||||
status = { taskId, status: 'processing' }
|
||||
await route.fulfill({ status: 202, json: { kind: 'queued', taskId } })
|
||||
if (rejectSubmission) {
|
||||
rejectSubmission = false
|
||||
await route.fulfill({ status: 503 })
|
||||
return
|
||||
}
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: { projectId, assetId: fileId, type: 'ai_transcription', status: 'processing' },
|
||||
})
|
||||
submissions++
|
||||
await route.fulfill({ status: 202, json: { kind: 'queued', taskId: task.id } })
|
||||
})
|
||||
|
||||
await expect
|
||||
@@ -48,14 +63,21 @@ test('selects a transcription language from the video context menu and tracks th
|
||||
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processing' } })
|
||||
const [signupInfo] = await Promise.all([
|
||||
page.waitForResponse('**/api/signup-info'),
|
||||
page.goto(`/projects/${projectId}`),
|
||||
page.goto(projectPath),
|
||||
])
|
||||
expect(await signupInfo.json()).toMatchObject({ transcriptionEnabled: true })
|
||||
const action = page.getByRole('menuitem', { name: 'Generate Transcripts' })
|
||||
await fileCard(page, fileName).click({ button: 'right' })
|
||||
await expect(action).toBeDisabled()
|
||||
await prisma.asset.update({ where: { id: fileId }, data: { status: 'processed' } })
|
||||
await page.reload()
|
||||
await prisma.asset.update({ where: { id: fileId }, data: { status: 'archived' } })
|
||||
const [idleStatus] = await Promise.all([page.waitForResponse(`**${statusPath}`), page.reload()])
|
||||
expect(await idleStatus.json()).toEqual({ assetIds: [] })
|
||||
const idleRequests = statusRequests
|
||||
await fileCard(page, folder.name).dblclick()
|
||||
await expect(page).toHaveURL(`${projectPath}/folders/${folder.id}`)
|
||||
await page.goBack()
|
||||
await expect(fileCard(page, fileName)).toBeVisible()
|
||||
expect(statusRequests).toBe(idleRequests)
|
||||
const openDialog = async () => {
|
||||
await fileCard(page, fileName).click({ button: 'right' })
|
||||
await action.click()
|
||||
@@ -64,24 +86,40 @@ test('selects a transcription language from the video context menu and tracks th
|
||||
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
|
||||
const language = dialog.getByRole('combobox', { name: 'Language' })
|
||||
const generate = dialog.getByRole('button', { name: 'Generate', exact: true })
|
||||
await expect(dialog.getByRole('status')).toHaveText('Transcript generated.')
|
||||
const metadata = fileCard(page, fileName).getByTestId('file-card-metadata')
|
||||
await expect(language).toHaveValue('Auto')
|
||||
await language.fill('Chi')
|
||||
await dialog.getByRole('option', { name: 'Chinese' }).click()
|
||||
await expect(language).toHaveValue('Chinese')
|
||||
await generate.click()
|
||||
await expect(dialog.getByRole('status')).toHaveText('Generating transcript…')
|
||||
await dialog.getByRole('button', { name: 'Close', exact: true }).click()
|
||||
await expect(dialog.getByRole('alert')).toBeVisible()
|
||||
await expect(language).toHaveValue('Chinese')
|
||||
await generate.click()
|
||||
await expect(dialog).toBeHidden()
|
||||
status = { taskId: status.taskId, status: 'completed' }
|
||||
await expect(metadata).toHaveText('Transcribing…')
|
||||
|
||||
await page.reload()
|
||||
await expect(metadata).toHaveText('Transcribing…')
|
||||
await page.getByRole('button', { name: 'List View' }).click()
|
||||
const dateCell = fileCard(page, fileName).getByTestId('file-list-item-date')
|
||||
await expect(dateCell).toHaveText('Transcribing…')
|
||||
const activeTranscript = {
|
||||
assetId: fileId,
|
||||
type: 'ai_transcription',
|
||||
status: 'processing',
|
||||
} as const
|
||||
await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'completed' } })
|
||||
await expect(dateCell).toHaveText(/\d/)
|
||||
const modifiedDate = await dateCell.innerText()
|
||||
|
||||
await openDialog()
|
||||
await expect(generate).toBeEnabled()
|
||||
await language.fill('Eng')
|
||||
await dialog.getByRole('option', { name: 'English' }).click()
|
||||
await generate.click()
|
||||
await expect(dialog.getByRole('status')).toHaveText('Generating transcript…')
|
||||
status = { taskId: status.taskId, status: 'completed' }
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(page.getByText('Transcript generated.', { exact: true })).toBeVisible()
|
||||
await expect(dateCell).toHaveText('Transcribing…')
|
||||
await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'failed' } })
|
||||
await expect(dateCell).toHaveText(modifiedDate)
|
||||
await expect(page.getByText('Transcript generation failed.', { exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
import { transcriptService } from '@shumai/core/src/transcript/transcript'
|
||||
import { selectPrimaryAudioStream } from '@shumai/core/src/transcode/transcode'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { selectTranscriptVideoProxyKey, transcriptionErrors } from '@shumai/dtos'
|
||||
import {
|
||||
selectTranscriptVideoProxyKey,
|
||||
transcriptionErrors,
|
||||
transcriptVideoStatuses,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
defineStep,
|
||||
@@ -66,7 +70,7 @@ export const extractTranscriptAudioActivity = defineStep(
|
||||
where: {
|
||||
id: assetId,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
status: { in: [...transcriptVideoStatuses] },
|
||||
isDeleted: false,
|
||||
mediaType: { startsWith: 'video/' },
|
||||
},
|
||||
|
||||
@@ -29,6 +29,30 @@ describe('Transcript API', () => {
|
||||
expect(await response.json()).toEqual(list)
|
||||
})
|
||||
|
||||
it('requires project edit access to list file IDs with active transcription', async () => {
|
||||
const request = () => app.request('/projects/project-id/transcription-status')
|
||||
const permission = vi
|
||||
.spyOn(authzService, 'hasPermission')
|
||||
.mockRejectedValue(new HTTPException(403))
|
||||
const list = vi.spyOn(transcriptService, 'listActiveAssetIds').mockResolvedValue(['file-id'])
|
||||
|
||||
expect((await request()).status).toBe(403)
|
||||
expect(list).not.toHaveBeenCalled()
|
||||
|
||||
permission.mockResolvedValue(undefined)
|
||||
const response = await request()
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toEqual({ assetIds: ['file-id'] })
|
||||
expect(permission).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
permission: Permission.Edit,
|
||||
id: 'project-id',
|
||||
}),
|
||||
)
|
||||
expect(list).toHaveBeenCalledWith('project-id')
|
||||
})
|
||||
|
||||
it('returns saved languages and segments with asset read access', async () => {
|
||||
const permission = vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
const list = vi
|
||||
|
||||
@@ -12,6 +12,16 @@ import { z } from 'zod'
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/transcription/languages', async (c) => c.json(await transcriptService.listLanguages()))
|
||||
.get('/projects/:projectId/transcription-status', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
await authzService.hasPermission({
|
||||
user: c.get('user'),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
return c.json({ assetIds: await transcriptService.listActiveAssetIds(projectId) })
|
||||
})
|
||||
.get('/files/:fileId/transcripts', async (c) => {
|
||||
const assetId = c.req.param('fileId')
|
||||
await authzService.hasPermission({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { prisma, WorkflowTaskType } from '@shumai/db'
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { transcriptionErrors } from '@shumai/dtos'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
@@ -177,6 +177,85 @@ describe('TranscriptService', () => {
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it.each(['archiving', 'archived', 'restoring'] as const)(
|
||||
'queues generation from a full proxy while the video is %s',
|
||||
async (status) => {
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { status } })
|
||||
await expect(transcriptService.generate(assetId, 'en')).resolves.toMatchObject({
|
||||
kind: 'queued',
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
it('lists each live project file with a pending or running transcription once', async () => {
|
||||
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
|
||||
const otherProject = await prisma.project.create({
|
||||
data: { name: 'Another project', teamId: project.teamId },
|
||||
})
|
||||
const [running, finished, deleted, external, transcoding] = await Promise.all(
|
||||
[
|
||||
{ projectId, name: 'Running video' },
|
||||
{ projectId, name: 'Finished video' },
|
||||
{ projectId, name: 'Deleted video', isDeleted: true },
|
||||
{ projectId: otherProject.id, name: 'External video' },
|
||||
{ projectId, name: 'Transcoding video' },
|
||||
].map((file) =>
|
||||
prisma.asset.create({ data: { ...file, type: 'file', status: 'processed' } }),
|
||||
),
|
||||
)
|
||||
await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual([])
|
||||
|
||||
await prisma.workflowTask.createMany({
|
||||
data: [
|
||||
{ assetId, status: WorkflowTaskStatus.pending },
|
||||
{ assetId, status: WorkflowTaskStatus.processing },
|
||||
{ assetId, status: WorkflowTaskStatus.failed },
|
||||
{ assetId: running.id, status: WorkflowTaskStatus.processing },
|
||||
{ assetId: finished.id, status: WorkflowTaskStatus.completed },
|
||||
{ assetId: finished.id, status: WorkflowTaskStatus.failed },
|
||||
{ assetId: deleted.id, status: WorkflowTaskStatus.pending },
|
||||
{ assetId: external.id, status: WorkflowTaskStatus.processing },
|
||||
{
|
||||
assetId: transcoding.id,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
type: WorkflowTaskType.transcode_video,
|
||||
},
|
||||
].map((job) => ({ type: WorkflowTaskType.ai_transcription, ...job })),
|
||||
})
|
||||
await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual(
|
||||
[assetId, running.id].sort().reverse(),
|
||||
)
|
||||
await expect(transcriptService.listActiveAssetIds(otherProject.id)).resolves.toEqual([
|
||||
external.id,
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects an archived video without a full proxy', async () => {
|
||||
await prisma.asset.update({
|
||||
where: { id: assetId },
|
||||
data: { status: 'archived', media: { ...media, videoTranscodes: [] } },
|
||||
})
|
||||
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: transcriptionErrors.noProxy,
|
||||
})
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it.each(['archiving', 'archived', 'restoring'] as const)(
|
||||
'saves a transcript when the video has become %s while the job runs',
|
||||
async (status) => {
|
||||
const taskId = await generateAndStart('en')
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { status } })
|
||||
await expect(
|
||||
transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments }),
|
||||
).resolves.toBe(true)
|
||||
await expect(transcriptService.getSavedTranscript(assetId, 'en')).resolves.toMatchObject({
|
||||
segments,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
it('rejects an audio-only proxy even when the file was uploaded with a video MIME type', async () => {
|
||||
await prisma.asset.update({
|
||||
where: { id: assetId },
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import {
|
||||
selectTranscriptVideoProxyKey,
|
||||
transcriptionErrors,
|
||||
transcriptVideoStatuses,
|
||||
type GenerateTranscriptResult,
|
||||
type SavedTranscript,
|
||||
type SavedTranscriptLanguages,
|
||||
@@ -96,7 +97,7 @@ export class TranscriptService {
|
||||
where: {
|
||||
id: assetId,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
status: { in: [...transcriptVideoStatuses] },
|
||||
isDeleted: false,
|
||||
mediaType: { startsWith: 'video/' },
|
||||
},
|
||||
@@ -173,6 +174,18 @@ export class TranscriptService {
|
||||
}
|
||||
}
|
||||
|
||||
async listActiveAssetIds(projectId: string): Promise<string[]> {
|
||||
const assets = await prisma.$queryRaw<{ assetId: string }[]>`
|
||||
SELECT DISTINCT task.asset_id AS "assetId"
|
||||
FROM workflow_tasks task
|
||||
JOIN assets asset ON asset.id = task.asset_id
|
||||
WHERE asset.project_id = ${projectId} AND NOT asset.is_deleted AND asset.type = 'file'
|
||||
AND task.type = ${type}::"WorkflowTaskType" AND task.status IN ('pending', 'processing')
|
||||
ORDER BY task.asset_id DESC
|
||||
`
|
||||
return assets.map(({ assetId }) => assetId)
|
||||
}
|
||||
|
||||
async saveResult(params: {
|
||||
taskId: string
|
||||
assetId: string
|
||||
@@ -184,7 +197,7 @@ export class TranscriptService {
|
||||
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'
|
||||
WHERE id = ${assetId} AND NOT is_deleted AND status::text IN (${Prisma.join(transcriptVideoStatuses)})
|
||||
FOR UPDATE
|
||||
`
|
||||
if (!asset) return false
|
||||
|
||||
@@ -37,6 +37,13 @@ interface TranscriptVideoProxy {
|
||||
height: number
|
||||
}
|
||||
|
||||
// Archive and restore move the original while the full video proxy stays available.
|
||||
export const transcriptVideoStatuses = ['processed', 'archiving', 'archived', 'restoring'] as const
|
||||
|
||||
export function isTranscriptVideoReady(status: string) {
|
||||
return transcriptVideoStatuses.some((readyStatus) => readyStatus === status)
|
||||
}
|
||||
|
||||
export function selectTranscriptVideoProxyKey(
|
||||
media?: { videoTranscodes?: TranscriptVideoProxy[]; videoPreview?: { key?: string } } | null,
|
||||
): string | undefined {
|
||||
|
||||
@@ -4,12 +4,18 @@ import { tmpdir } from 'node:os'
|
||||
import { basename, join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import {
|
||||
getArchiveStorageService,
|
||||
resetArchiveStorageServiceForTests,
|
||||
} from '@shumai/core/src/s3/archive-storage'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcriptService } from '@shumai/core/src/transcript/transcript'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { TaskQueueAgent, workflowService } from '@shumai/workflow-core'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { TaskQueueAgent, TaskQueueArchive, workflowService } from '@shumai/workflow-core'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
@@ -110,8 +116,12 @@ describe('Transcribe video workflow', () => {
|
||||
vi.stubEnv('S3_BUCKET', bucket)
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', `${provider.url}v1/embeddings/`)
|
||||
vi.stubEnv('ARCHIVE_STORAGE_BACKEND', 'local')
|
||||
vi.stubEnv('ARCHIVE_LOCAL_ROOT', join(directory, 'archive'))
|
||||
resetArchiveStorageServiceForTests()
|
||||
initAgentWorkflows()
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
initTranscodeWorkflows()
|
||||
await workflowService.startWorkers([TaskQueueAgent, TaskQueueArchive])
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -126,10 +136,11 @@ describe('Transcribe video workflow', () => {
|
||||
await provider?.stop(true)
|
||||
await s3Service.deletePrefix(bucket, '')
|
||||
if (directory) await rm(directory, { recursive: true, force: true })
|
||||
resetArchiveStorageServiceForTests()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
async function submitVideo(name: string, language: string | null) {
|
||||
async function createVideo(name: string, originalKey = 'video/unavailable-original.mkv') {
|
||||
const team = await prisma.team.create({ data: { name: 'Transcription E2E' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Videos', teamId: team.id } })
|
||||
const fullProxy = { key: `video/${name}`, resolution: '480p', width: 64, height: 64 }
|
||||
@@ -138,14 +149,14 @@ describe('Transcribe video workflow', () => {
|
||||
s3Service.uploadFileToKey(join(directory, basename(key)), key, 'video/mp4'),
|
||||
),
|
||||
)
|
||||
const asset = await prisma.asset.create({
|
||||
return await prisma.asset.create({
|
||||
data: {
|
||||
name,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
project: { connect: { id: project.id } },
|
||||
mediaType: 'video/x-matroska',
|
||||
storageKey: { create: { key: 'video/unavailable-original.mkv' } },
|
||||
storageKey: { create: { key: originalKey } },
|
||||
media: {
|
||||
proxyType: 'video',
|
||||
videoTranscodes: [largerProxy, preview, fullProxy],
|
||||
@@ -160,14 +171,47 @@ describe('Transcribe video workflow', () => {
|
||||
},
|
||||
},
|
||||
})
|
||||
const result = await transcriptService.generate(asset.id, language)
|
||||
}
|
||||
|
||||
async function startTranscript(assetId: string, language: string | null) {
|
||||
const result = await transcriptService.generate(assetId, language)
|
||||
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
|
||||
return {
|
||||
assetId: asset.id,
|
||||
assetId,
|
||||
task: await prisma.workflowTask.findUniqueOrThrow({ where: { id: result.taskId } }),
|
||||
}
|
||||
}
|
||||
|
||||
async function submitVideo(name: string, language: string | null) {
|
||||
const asset = await createVideo(name)
|
||||
return await startTranscript(asset.id, language)
|
||||
}
|
||||
|
||||
it('generates and saves a transcript after the archive workflow moves the original', async () => {
|
||||
const originalKey = 'video/archive-original.mkv'
|
||||
await s3Service.uploadFileToKey(join(directory, 'audio.mkv'), originalKey, 'video/x-matroska')
|
||||
const asset = await createVideo('audio.mp4', originalKey)
|
||||
const { taskIds } = await assetService.archiveAssets([asset.id])
|
||||
expect(taskIds).toHaveLength(1)
|
||||
const archiveTask = await prisma.workflowTask.findUniqueOrThrow({ where: { id: taskIds[0] } })
|
||||
await workflowService.executeWait(archiveTask, 20_000)
|
||||
await expect(prisma.asset.findUnique({ where: { id: asset.id } })).resolves.toMatchObject({
|
||||
status: 'archived',
|
||||
})
|
||||
await expect(s3Service.headObject(bucket, originalKey)).rejects.toThrow('NoSuchKey')
|
||||
await expect(getArchiveStorageService().headObject(originalKey)).resolves.toMatchObject({
|
||||
size: expect.any(Number),
|
||||
})
|
||||
|
||||
const { task } = await startTranscript(asset.id, 'en')
|
||||
await workflowService.executeWait(task, 20_000)
|
||||
|
||||
expect(uploads).toHaveLength(1)
|
||||
await expect(transcriptService.getSavedTranscript(asset.id, 'en')).resolves.toMatchObject({
|
||||
segments: [{ startMs: 1012, endMs: 1875, text: 'Hello' }],
|
||||
})
|
||||
}, 45_000)
|
||||
|
||||
it('uses the smallest full proxy to send 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.mp4', null)
|
||||
|
||||
@@ -96,7 +96,7 @@ describe('FileBrowserContextMenu', () => {
|
||||
expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull()
|
||||
})
|
||||
|
||||
it('starts transcription on the displayed video file in a stack', () => {
|
||||
it('starts transcription on the displayed archived video in a stack', () => {
|
||||
const onGenerateTranscripts = vi.fn()
|
||||
renderWithMenu(
|
||||
{
|
||||
@@ -107,7 +107,7 @@ describe('FileBrowserContextMenu', () => {
|
||||
id: stackItem.id,
|
||||
versions: [
|
||||
{ id: 'old', name: 'old.mp4', version: 1, current: false },
|
||||
{ id: 'current', name: 'current.mp4', version: 2, current: true },
|
||||
{ id: 'current', name: 'current.mp4', version: 2, current: true, status: 'archived' },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -120,10 +120,27 @@ describe('FileBrowserContextMenu', () => {
|
||||
expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4')
|
||||
})
|
||||
|
||||
it.each(['archiving', 'archived', 'restoring'])(
|
||||
'starts transcription on a video that is %s',
|
||||
(status) => {
|
||||
const onGenerateTranscripts = vi.fn()
|
||||
renderWithMenu(
|
||||
{ ...fileItem, proxyType: 'video', status, media: { videoTranscodes: [fullProxy] } },
|
||||
{ onGenerateTranscripts },
|
||||
)
|
||||
|
||||
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: 'Generate Transcripts' }))
|
||||
|
||||
expect(onGenerateTranscripts).toHaveBeenCalledWith(fileItem.id, fileItem.name)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
{ status: 'uploaded', media: undefined },
|
||||
{ status: 'processing', media: { videoTranscodes: [fullProxy] } },
|
||||
{ status: 'processed', media: { videoPreview: { url: '/preview.mp4', key: 'preview.mp4' } } },
|
||||
{ status: 'archived', media: undefined },
|
||||
])('disables generation for a $status video until a full proxy is ready', ({ status, media }) => {
|
||||
const onGenerateTranscripts = vi.fn()
|
||||
renderWithMenu(
|
||||
@@ -150,11 +167,6 @@ describe('FileBrowserContextMenu', () => {
|
||||
item: { ...fileItem, proxyType: 'audio' as const, mediaType: 'video/mp4' },
|
||||
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'))
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { selectTranscriptVideoProxyKey, type AssetInfo, type ShareLinkInfo } from '@shumai/dtos'
|
||||
import {
|
||||
isTranscriptVideoReady,
|
||||
selectTranscriptVideoProxyKey,
|
||||
type AssetInfo,
|
||||
type ShareLinkInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { getTranscriptVideo } from '@/ui/lib/transcript'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
ContextMenuContent,
|
||||
@@ -239,17 +245,8 @@ export function FileBrowserContextMenu({
|
||||
</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 transcriptAssetStatus = videoVersion?.status ?? item.status
|
||||
const isTranscriptVideo = item.proxyType
|
||||
? item.proxyType === 'video'
|
||||
: item.mediaType?.startsWith('video/')
|
||||
const transcriptReady =
|
||||
transcriptAssetStatus === 'processed' && Boolean(selectTranscriptVideoProxyKey(item.media))
|
||||
const transcriptVideo = getTranscriptVideo(item)
|
||||
const transcriptReady = transcriptVideo && isTranscriptVideoReady(transcriptVideo.status)
|
||||
|
||||
const contextMenuContent =
|
||||
isItemSelected && selectedIds.size > 1 ? (
|
||||
@@ -376,14 +373,12 @@ export function FileBrowserContextMenu({
|
||||
{findSimilarItem}
|
||||
{canEdit &&
|
||||
onGenerateTranscripts &&
|
||||
transcriptAssetId &&
|
||||
['uploading', 'uploaded', 'processing', 'processed'].includes(transcriptAssetStatus) &&
|
||||
isTranscriptVideo && (
|
||||
transcriptVideo &&
|
||||
(transcriptReady ||
|
||||
['uploading', 'uploaded', 'processing'].includes(transcriptVideo.status)) && (
|
||||
<ContextMenuItem
|
||||
disabled={!transcriptReady}
|
||||
onSelect={() =>
|
||||
onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name)
|
||||
}
|
||||
disabled={!transcriptReady || !selectTranscriptVideoProxyKey(item.media)}
|
||||
onSelect={() => onGenerateTranscripts(transcriptVideo.id, transcriptVideo.name)}
|
||||
>
|
||||
<Captions className="mr-2 h-4 w-4" />
|
||||
<span>{m.generate_transcripts()}</span>
|
||||
|
||||
@@ -7,6 +7,8 @@ import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
|
||||
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { getTranscriptVideo } from '@/ui/lib/transcript'
|
||||
import { useTranscriptionJobs } from '@/ui/hooks/use-transcription-jobs'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
@@ -164,7 +166,6 @@ export function FileBrowser({
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
|
||||
const [transcriptVideo, setTranscriptVideo] = useState<{ id: string; name: string } | null>(null)
|
||||
const closeTranscriptDialog = useCallback(() => setTranscriptVideo(null), [])
|
||||
const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled
|
||||
const semanticSearchEnabled = useSemanticSearchEnabled(
|
||||
teamId,
|
||||
@@ -615,6 +616,8 @@ export function FileBrowser({
|
||||
const [targetVersionFileId, setTargetVersionFileId] = useState<string | null>(null)
|
||||
const fileContextMenu = useRef(false)
|
||||
const { canEdit, canAdmin } = usePermissions(projectId)
|
||||
const canGenerateTranscripts = !!transcriptionEnabled && canEdit && !isShareView && !isPublic
|
||||
const { transcribingAssetIds, trackJob } = useTranscriptionJobs(projectId, canGenerateTranscripts)
|
||||
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
@@ -725,6 +728,7 @@ export function FileBrowser({
|
||||
isPublic,
|
||||
allowDownload,
|
||||
fields: displayedFields,
|
||||
isTranscribing: transcribingAssetIds.has(getTranscriptVideo(item)?.id ?? ''),
|
||||
canEdit,
|
||||
isTeamOwner: canAdmin,
|
||||
onCopy: handleCopy,
|
||||
@@ -1128,9 +1132,7 @@ export function FileBrowser({
|
||||
onCopy={handleCopy}
|
||||
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
|
||||
onGenerateTranscripts={
|
||||
transcriptionEnabled && !isShareView && !isPublic
|
||||
? (id, name) => setTranscriptVideo({ id, name })
|
||||
: undefined
|
||||
canGenerateTranscripts ? (id, name) => setTranscriptVideo({ id, name }) : undefined
|
||||
}
|
||||
onNewFolder={handleNewFolder}
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
@@ -1197,7 +1199,11 @@ export function FileBrowser({
|
||||
key={transcriptVideo.id}
|
||||
assetId={transcriptVideo.id}
|
||||
name={transcriptVideo.name}
|
||||
onClose={closeTranscriptDialog}
|
||||
isTranscribing={transcribingAssetIds.has(transcriptVideo.id)}
|
||||
onJobAccepted={trackJob}
|
||||
onClose={() =>
|
||||
setTranscriptVideo((current) => (current?.id === transcriptVideo.id ? null : current))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ interface FileCardProps {
|
||||
isRecents?: boolean
|
||||
selectedCount?: number
|
||||
fields?: MetadataFieldInfo[]
|
||||
isTranscribing?: boolean
|
||||
isShareView?: boolean
|
||||
isPublic?: boolean
|
||||
canEdit?: boolean
|
||||
@@ -122,6 +123,7 @@ export function FileCard({
|
||||
isRecents,
|
||||
selectedCount,
|
||||
fields = [],
|
||||
isTranscribing = false,
|
||||
isShareView,
|
||||
isPublic = false,
|
||||
canEdit = true,
|
||||
@@ -343,6 +345,8 @@ export function FileCard({
|
||||
}
|
||||
} else if (isProcessing) {
|
||||
statusText = m.preparing()
|
||||
} else if (isTranscribing) {
|
||||
statusText = m.transcript_generating()
|
||||
}
|
||||
|
||||
const failedErrorMessage = displayItem.media?.error || m.processing_failed()
|
||||
@@ -613,7 +617,11 @@ export function FileCard({
|
||||
}}
|
||||
>
|
||||
<TooltipTrigger asChild>
|
||||
<p ref={creatorRef} className="text-sm line-clamp-2 h-[2lh] text-muted-foreground">
|
||||
<p
|
||||
ref={creatorRef}
|
||||
data-testid="file-card-metadata"
|
||||
className="text-sm line-clamp-2 h-[2lh] text-muted-foreground"
|
||||
>
|
||||
{statusText ?? creatorText}
|
||||
</p>
|
||||
</TooltipTrigger>
|
||||
@@ -622,7 +630,7 @@ export function FileCard({
|
||||
side="bottom"
|
||||
className="max-w-md break-all text-wrap [text-wrap:normal] text-left"
|
||||
>
|
||||
{creatorText}
|
||||
{isTranscribing ? m.transcript_generating() : creatorText}
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
|
||||
@@ -38,6 +38,7 @@ interface FileListItemProps {
|
||||
dragState?: DragState
|
||||
disabled?: boolean
|
||||
fields: MetadataFieldInfo[]
|
||||
isTranscribing?: boolean
|
||||
columnSizing?: Record<string, number>
|
||||
canEdit?: boolean
|
||||
isRecents?: boolean
|
||||
@@ -64,6 +65,7 @@ export function FileListItem({
|
||||
dragState,
|
||||
disabled,
|
||||
fields,
|
||||
isTranscribing = false,
|
||||
columnSizing,
|
||||
canEdit = true,
|
||||
isRecents,
|
||||
@@ -395,8 +397,11 @@ export function FileListItem({
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between overflow-hidden w-full">
|
||||
<span className="text-sm text-muted-foreground truncate">
|
||||
{formatDate(displayItem.updatedAt)}
|
||||
<span
|
||||
data-testid="file-list-item-date"
|
||||
className="text-sm text-muted-foreground truncate"
|
||||
>
|
||||
{isTranscribing ? m.transcript_generating() : formatDate(displayItem.updatedAt)}
|
||||
</span>
|
||||
{!isRecents && (
|
||||
<button
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
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'
|
||||
@@ -23,43 +22,23 @@ import {
|
||||
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()
|
||||
if (job.reason === 'noProxy') return m.transcript_proxy_required()
|
||||
return m.transcript_failed()
|
||||
}
|
||||
}
|
||||
|
||||
export function GenerateTranscriptsDialog({
|
||||
assetId,
|
||||
name,
|
||||
isTranscribing,
|
||||
onJobAccepted,
|
||||
onClose,
|
||||
}: {
|
||||
assetId: string
|
||||
name: string
|
||||
isTranscribing: boolean
|
||||
onJobAccepted: (assetId: string) => Promise<void>
|
||||
onClose: () => void
|
||||
}) {
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const activeTaskId = useRef<string>(undefined)
|
||||
const queryClient = useQueryClient()
|
||||
const [language, setLanguage] = useState('')
|
||||
const param = { fileId: assetId }
|
||||
const statusKey = ['transcription-status', assetId]
|
||||
|
||||
const languages = useQuery({
|
||||
queryKey: ['transcription-languages'],
|
||||
@@ -72,34 +51,6 @@ export function GenerateTranscriptsDialog({
|
||||
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 hasFreshJobStatus = job.isFetchedAfterMount && job.isSuccess
|
||||
|
||||
useEffect(() => {
|
||||
if (!job.data) return
|
||||
if (isActive(job.data)) {
|
||||
// Reopening the dialog can briefly show a cached status for a finished job.
|
||||
if (hasFreshJobStatus) activeTaskId.current = job.data.taskId
|
||||
return
|
||||
}
|
||||
if (job.data.status !== 'completed') return
|
||||
|
||||
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
|
||||
if (activeTaskId.current === job.data.taskId) {
|
||||
activeTaskId.current = undefined
|
||||
toast.success(m.transcript_completed())
|
||||
onClose()
|
||||
}
|
||||
}, [assetId, hasFreshJobStatus, job.data, onClose, queryClient])
|
||||
|
||||
const generate = useMutation({
|
||||
mutationFn: async () => {
|
||||
const response = await client.api.files[':fileId'].transcripts.$post({
|
||||
@@ -109,7 +60,7 @@ export function GenerateTranscriptsDialog({
|
||||
if (!response.ok) throw new Error(m.transcript_submit_failed())
|
||||
return await response.json()
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
onSuccess: async (result) => {
|
||||
if (result.kind === 'existing' || result.kind === 'no_speech') {
|
||||
if (result.kind === 'existing') {
|
||||
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
|
||||
@@ -119,13 +70,8 @@ export function GenerateTranscriptsDialog({
|
||||
)
|
||||
return
|
||||
}
|
||||
activeTaskId.current = result.taskId
|
||||
queryClient.setQueryData<TranscriptJobStatus>(statusKey, {
|
||||
status: 'pending',
|
||||
taskId: result.taskId,
|
||||
})
|
||||
void queryClient.invalidateQueries({ queryKey: statusKey })
|
||||
if (result.kind === 'queued') toast.success(m.transcript_queued())
|
||||
await onJobAccepted(assetId)
|
||||
onClose()
|
||||
},
|
||||
})
|
||||
|
||||
@@ -133,7 +79,7 @@ export function GenerateTranscriptsDialog({
|
||||
{ code: '', name: m.transcript_language_auto() },
|
||||
...(languages.data?.languages ?? []),
|
||||
]
|
||||
const busy = generate.isPending || isActive(job.data)
|
||||
const busy = generate.isPending || isTranscribing
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
@@ -192,21 +138,9 @@ export function GenerateTranscriptsDialog({
|
||||
{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)}
|
||||
{isTranscribing && (
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
{m.transcript_generating()}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -214,10 +148,7 @@ export function GenerateTranscriptsDialog({
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{m.close()}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={busy || !languages.data || job.isPending}
|
||||
onClick={() => generate.mutate()}
|
||||
>
|
||||
<Button disabled={busy || !languages.data} onClick={() => generate.mutate()}>
|
||||
{m.generate()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { useServerFeatures } from '@/ui/hooks/use-server-features'
|
||||
import { useTranscriptionJobs } from '@/ui/hooks/use-transcription-jobs'
|
||||
import { getTranscriptVideo } from '@/ui/lib/transcript'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
@@ -130,6 +133,11 @@ export function MobileFileBrowser({
|
||||
const queryClient = useQueryClient()
|
||||
useBatchFileStatus({ teamId, items: files })
|
||||
const { canEdit, canAdmin } = usePermissions(projectId)
|
||||
const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled
|
||||
const { transcribingAssetIds } = useTranscriptionJobs(
|
||||
projectId,
|
||||
!!transcriptionEnabled && canEdit && !isShareView && !isPublic,
|
||||
)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
@@ -573,6 +581,9 @@ export function MobileFileBrowser({
|
||||
key={file.id}
|
||||
teamId={teamId}
|
||||
item={file}
|
||||
isTranscribing={transcribingAssetIds.has(
|
||||
getTranscriptVideo(file)?.id ?? '',
|
||||
)}
|
||||
isSelected={selectedItem?.id === file.id}
|
||||
isChecked={selectedIds.has(file.id!)}
|
||||
isEditing={editingItemId === file.id}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { savedTranscriptLanguagesKey } from './use-video-transcript'
|
||||
|
||||
export function useTranscriptionJobs(projectId: string, enabled: boolean) {
|
||||
const queryClient = useQueryClient()
|
||||
const queryKey = ['project-transcription-status', projectId] as const
|
||||
const { data } = useQuery({
|
||||
queryKey,
|
||||
enabled,
|
||||
// Folder routes can remount the browser. Reuse the project's cached jobs on navigation.
|
||||
refetchOnMount: false,
|
||||
queryFn: async ({ signal }) => {
|
||||
const response = await client.api.projects[':projectId']['transcription-status'].$get(
|
||||
{ param: { projectId } },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!response.ok) throw new Error(m.transcript_status_unavailable())
|
||||
const { assetIds } = await response.json()
|
||||
signal.throwIfAborted()
|
||||
|
||||
const activeIds = new Set(assetIds)
|
||||
const previousIds = queryClient.getQueryData<string[]>(queryKey) ?? []
|
||||
for (const id of previousIds) {
|
||||
if (!activeIds.has(id)) {
|
||||
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(id) })
|
||||
}
|
||||
}
|
||||
return assetIds
|
||||
},
|
||||
refetchInterval: ({ state }) => (state.data?.length ? 2000 : false),
|
||||
})
|
||||
|
||||
const transcribingAssetIds = useMemo(() => new Set(enabled ? data : undefined), [data, enabled])
|
||||
|
||||
async function trackJob(assetId: string) {
|
||||
// Discard any request that started before the job was accepted.
|
||||
await queryClient.cancelQueries({ queryKey, exact: true })
|
||||
queryClient.setQueryData<string[]>(queryKey, (current) =>
|
||||
current?.includes(assetId) ? current : [...(current ?? []), assetId],
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey, exact: true })
|
||||
}
|
||||
|
||||
return { transcribingAssetIds, trackJob }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
export function getTranscriptVideo(item: AssetInfo) {
|
||||
const isVideo = item.proxyType ? item.proxyType === 'video' : item.mediaType?.startsWith('video/')
|
||||
if (!isVideo) return undefined
|
||||
|
||||
if (item.type === 'version_stack') {
|
||||
const version = item.versionStack?.versions.find(({ current }) => current)
|
||||
if (version) {
|
||||
return {
|
||||
id: version.id,
|
||||
name: version.name || item.name,
|
||||
status: version.status ?? item.status,
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.type === 'file' && item.id) {
|
||||
return { id: item.id, name: item.name, status: item.status }
|
||||
}
|
||||
}
|
||||
@@ -1813,14 +1813,8 @@
|
||||
"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_generating": "Transcribing…",
|
||||
"transcript_no_speech": "No speech detected.",
|
||||
"transcript_no_audio": "This video has no audio track.",
|
||||
"transcript_proxy_required": "A full video proxy must be ready before you can generate transcripts.",
|
||||
"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.",
|
||||
|
||||
@@ -1743,14 +1743,8 @@
|
||||
"failed_to_update_comment": "댓글을 수정하지 못했습니다",
|
||||
"generate_transcripts": "전사 생성",
|
||||
"transcript_language_auto": "자동 감지",
|
||||
"transcript_queued": "전사 작업이 대기열에 추가되었습니다.",
|
||||
"transcript_generating": "전사를 생성하는 중…",
|
||||
"transcript_completed": "전사를 생성했습니다.",
|
||||
"transcript_generating": "전사 중…",
|
||||
"transcript_no_speech": "음성이 감지되지 않았습니다.",
|
||||
"transcript_no_audio": "이 동영상에는 오디오 트랙이 없습니다.",
|
||||
"transcript_proxy_required": "전체 동영상 프록시 준비가 완료되면 전사를 생성할 수 있습니다.",
|
||||
"transcript_audio_too_large": "오디오가 임베딩 서버의 업로드 한도를 초과합니다.",
|
||||
"transcript_failed": "전사 생성에 실패했습니다.",
|
||||
"transcript_submit_failed": "전사 생성을 시작할 수 없습니다.",
|
||||
"transcript_already_exists": "이 언어의 전사가 이미 있습니다.",
|
||||
"transcript_languages_unavailable": "전사 언어를 불러올 수 없습니다.",
|
||||
|
||||
@@ -1813,14 +1813,8 @@
|
||||
"failed_to_update_comment": "更新评论失败",
|
||||
"generate_transcripts": "生成转录",
|
||||
"transcript_language_auto": "自动检测",
|
||||
"transcript_queued": "转录任务已加入队列。",
|
||||
"transcript_generating": "正在生成转录…",
|
||||
"transcript_completed": "转录已生成。",
|
||||
"transcript_generating": "正在转录…",
|
||||
"transcript_no_speech": "未检测到语音。",
|
||||
"transcript_no_audio": "此视频没有音轨。",
|
||||
"transcript_proxy_required": "视频代理转码完成后才能生成转录。",
|
||||
"transcript_audio_too_large": "音频超出嵌入服务器的上传大小限制。",
|
||||
"transcript_failed": "转录生成失败。",
|
||||
"transcript_submit_failed": "无法启动转录生成。",
|
||||
"transcript_already_exists": "此语言的转录已存在。",
|
||||
"transcript_languages_unavailable": "无法加载转录语言。",
|
||||
|
||||
Reference in New Issue
Block a user