mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 15:44:28 +00:00
Add Chinese transcript script choices and language search (#562)
* feat(transcript): add Chinese script choices * feat(transcript): add a popup language search
This commit is contained in:
@@ -11,6 +11,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.
|
||||
- **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**: Update your local embedding server to v0.1.3 to generate video transcripts. Choose a language or detect it automatically, then open the transcript in the video player to switch languages, follow playback, search the text, jump to a segment, or edit its text.
|
||||
- **video**: Search for languages when generating video transcripts. You can save and edit Simplified and Traditional Chinese versions on the same video.
|
||||
- **integrations**: Set and test an embedding server URL under **Team Settings → Integrations**. A URL set through environment variables appears read-only. Once the server is configured, enable the Transcript Agent to generate video transcripts and receive an internal comment if a job fails. The updated embedding and full Docker Compose files create and enable the agent automatically with a distinct avatar.
|
||||
|
||||
For an existing deployment, create and enable the Transcript Agent under **Team Settings → Agents**, or add this line to the Shumai service’s `environment` block in your Compose file.
|
||||
|
||||
@@ -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 sees the transcript action only when available, 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 opens the transcript action when available, searches for both Chinese scripts and English without resizing the dialog, tracks progress 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` |
|
||||
|
||||
@@ -12,7 +12,7 @@ test('starts a transcript for an archived video and tracks it in the file metada
|
||||
const projectPath = `/projects/${projectId}`
|
||||
const statusPath = `/api${projectPath}/transcription-status`
|
||||
const folder = await seedFolder(prisma, projectId, rootFolderId, 'Other folder')
|
||||
const expectedLanguages = ['zh', 'en']
|
||||
const expectedLanguages = ['zh-Hans', 'zh-Hant', 'en']
|
||||
let submissions = 0
|
||||
let rejectSubmission = true
|
||||
let statusRequests = 0
|
||||
@@ -34,7 +34,8 @@ test('starts a transcript for an archived video and tracks it in the file metada
|
||||
model: 'whisper-tiny',
|
||||
languages: [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'zh', name: 'Chinese' },
|
||||
{ code: 'zh-Hans', name: 'Simplified Chinese' },
|
||||
{ code: 'zh-Hant', name: 'Traditional Chinese' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
@@ -92,23 +93,43 @@ test('starts a transcript for an archived video and tracks it in the file metada
|
||||
}
|
||||
await openDialog()
|
||||
const dialog = page.getByRole('dialog', { name: 'Generate Transcripts' })
|
||||
const language = dialog.getByRole('combobox', { name: 'Language' })
|
||||
const language = dialog.getByRole('combobox', { name: 'Language', exact: true })
|
||||
const generate = dialog.getByRole('button', { name: 'Generate', exact: true })
|
||||
const metadata = fileCard(page, fileName).getByTestId('file-card-metadata')
|
||||
const searchBox = dialog.getByRole('combobox', { name: 'Search languages' })
|
||||
const dialogHeight = () => dialog.evaluate((element) => element.clientHeight)
|
||||
|
||||
await expect(language).toBeEnabled()
|
||||
const closedHeight = await dialogHeight()
|
||||
await language.press('ArrowDown')
|
||||
await expect(dialog.getByRole('option', { name: 'English' })).toBeVisible()
|
||||
expect(await dialogHeight()).toBe(closedHeight)
|
||||
await expect(searchBox).toBeFocused()
|
||||
await searchBox.fill('unmatched query')
|
||||
await expect(dialog.getByText('No matching languages.')).toBeVisible()
|
||||
expect(await dialogHeight()).toBe(closedHeight)
|
||||
await searchBox.press('Escape')
|
||||
await expect(searchBox).toBeHidden()
|
||||
await expect(language).toBeFocused()
|
||||
await expect(language).toHaveText('Auto')
|
||||
|
||||
const selectLanguage = async (search: string, name: string) => {
|
||||
await language.fill(search)
|
||||
await language.click()
|
||||
await expect(searchBox).toHaveValue('')
|
||||
await searchBox.fill(search)
|
||||
await expect(dialog.getByRole('option')).toHaveCount(1)
|
||||
await expect(dialog.getByRole('option', { name })).toBeVisible()
|
||||
await language.press('ArrowDown')
|
||||
await expect(language).toHaveAttribute('aria-activedescendant', /.+/)
|
||||
await language.press('Enter')
|
||||
await expect(language).toHaveValue(name)
|
||||
await searchBox.press('ArrowDown')
|
||||
await expect(searchBox).toHaveAttribute('aria-activedescendant', /.+/)
|
||||
await searchBox.press('Enter')
|
||||
await expect(searchBox).toBeHidden()
|
||||
await expect(language).toHaveText(name)
|
||||
}
|
||||
|
||||
await expect(language).toHaveValue('Auto')
|
||||
await selectLanguage('Chi', 'Chinese')
|
||||
await selectLanguage('Simplified', 'Chinese (Simplified)')
|
||||
await generate.click()
|
||||
await expect(dialog.getByRole('alert')).toBeVisible()
|
||||
await expect(language).toHaveValue('Chinese')
|
||||
await expect(language).toHaveText('Chinese (Simplified)')
|
||||
await generate.click()
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(metadata).toHaveText('Transcribing…')
|
||||
@@ -127,6 +148,14 @@ test('starts a transcript for an archived video and tracks it in the file metada
|
||||
await expect(dateCell).toHaveText(/\d/)
|
||||
const modifiedDate = await dateCell.innerText()
|
||||
|
||||
await openDialog()
|
||||
await selectLanguage('Traditional', 'Chinese (Traditional)')
|
||||
await generate.click()
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(dateCell).toHaveText('Transcribing…')
|
||||
await prisma.workflowTask.updateMany({ where: activeTranscript, data: { status: 'completed' } })
|
||||
await expect(dateCell).toHaveText(modifiedDate)
|
||||
|
||||
await openDialog()
|
||||
await expect(generate).toBeEnabled()
|
||||
await selectLanguage('Eng', 'English')
|
||||
|
||||
@@ -158,6 +158,7 @@
|
||||
"@shumai/workflow-core": "workspace:*",
|
||||
"adm-zip": "0.6.0",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"opencc-js": "1.4.2",
|
||||
"sharp": "0.35.4",
|
||||
"typebox": "1.3.22",
|
||||
"ulid": "3.0.2",
|
||||
@@ -2500,6 +2501,8 @@
|
||||
|
||||
"openai": ["openai@7.59.0", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "google-auth-library": ">=9.15.1 <12", "undici": ">=5 <9", "ws": "^8.21.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4", "google-auth-library", "undici", "ws", "zod"] }, "sha512-wPYKJkLPFEdNJ2tThSg4jE1Ptsv4X3u8g8LIvu0Qz/UIhsKeCzl73rl48PtQsDVrJL/ku0liXOsbyd2TsRsPJw=="],
|
||||
|
||||
"opencc-js": ["opencc-js@1.4.2", "", {}, "sha512-EdcspgdROiCCZDM+jZR6Pa670xW+EW2QhctPBQ8gRjg6lrx4IHEl+2s+kt5izk/TkxVRgdWuFgaGkaEdIUfdaw=="],
|
||||
|
||||
"optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
|
||||
|
||||
"own-keys": ["own-keys@1.0.2", "", { "dependencies": { "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "object-keys": "^1.1.1", "safe-push-apply": "^1.0.0" } }, "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg=="],
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"@shumai/workflow-core": "workspace:*",
|
||||
"adm-zip": "0.6.0",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"opencc-js": "1.4.2",
|
||||
"sharp": "0.35.4",
|
||||
"typebox": "1.3.22",
|
||||
"ulid": "3.0.2",
|
||||
|
||||
@@ -14,6 +14,7 @@ import { transcriptService } from '@shumai/core/src/transcript/transcript'
|
||||
import { selectPrimaryAudioStream } from '@shumai/core/src/transcode/transcode'
|
||||
import { prisma } from '@shumai/db'
|
||||
import {
|
||||
chineseTranscriptLanguageSchema,
|
||||
selectTranscriptVideoProxyKey,
|
||||
transcriptionErrors,
|
||||
transcriptVideoStatuses,
|
||||
@@ -180,7 +181,17 @@ export const transcribeAudioActivity = defineStep(async function transcribeAudio
|
||||
export const saveTranscriptActivity = defineStep(async function saveTranscriptActivity(
|
||||
params: Parameters<typeof transcriptService.saveResult>[0],
|
||||
): Promise<void> {
|
||||
if (!(await transcriptService.saveResult(params))) {
|
||||
let { segments } = params
|
||||
const script = chineseTranscriptLanguageSchema.safeParse(params.language)
|
||||
if (script.success) {
|
||||
const { Converter } = await import('opencc-js')
|
||||
const convert =
|
||||
script.data === 'zh-Hans'
|
||||
? Converter({ from: 't', to: 'cn' })
|
||||
: Converter({ from: 'cn', to: 't' })
|
||||
segments = segments.map((segment) => ({ ...segment, text: convert(segment.text) }))
|
||||
}
|
||||
if (!(await transcriptService.saveResult({ ...params, segments }))) {
|
||||
throw ApplicationFailure.create({ message: 'Video is no longer available', nonRetryable: true })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { getTranscriptionProviderLanguage } from '@shumai/core/src/transcript/local-transcription'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { ApplicationFailure, isDbosWorkflowCancelledError } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity } from '../activities/ai'
|
||||
@@ -24,8 +25,15 @@ export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
const audioKey = `temp/transcripts/${taskId}.wav`
|
||||
try {
|
||||
await extractTranscriptAudioActivity({ assetId, taskId, audioKey, teamId })
|
||||
const transcript = await transcribeAudioActivity({ taskId, audioKey, teamId, ...request })
|
||||
if (request.language && transcript.language && request.language !== transcript.language) {
|
||||
const providerLanguage = getTranscriptionProviderLanguage(request.language)
|
||||
const transcript = await transcribeAudioActivity({
|
||||
taskId,
|
||||
audioKey,
|
||||
teamId,
|
||||
language: providerLanguage,
|
||||
model: request.model,
|
||||
})
|
||||
if (providerLanguage && transcript.language && providerLanguage !== transcript.language) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Transcription returned an unexpected language',
|
||||
nonRetryable: true,
|
||||
@@ -35,7 +43,7 @@ export async function transcribeVideoWorkflow(task: WorkflowTask): Promise<void>
|
||||
taskId,
|
||||
assetId,
|
||||
model: request.model,
|
||||
language: transcript.language,
|
||||
language: transcript.language === null ? null : (request.language ?? transcript.language),
|
||||
segments: transcript.segments.map((segment) => ({
|
||||
startMs: Math.round(segment.start * 1000),
|
||||
endMs: Math.round(segment.end * 1000),
|
||||
|
||||
@@ -182,6 +182,30 @@ describe('Transcript API', () => {
|
||||
expect(transcriptService.generate).toHaveBeenCalledWith('file-id', 'en')
|
||||
})
|
||||
|
||||
it.each(['zh-Hans', 'zh-Hant'])(
|
||||
'generates, reads and edits a %s transcript',
|
||||
async (language) => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
const segment = { id: 'segment-id', startMs: 0, endMs: 1400, text: '你好' }
|
||||
const generate = vi
|
||||
.spyOn(transcriptService, 'generate')
|
||||
.mockResolvedValue({ kind: 'queued', taskId: 'task-id' })
|
||||
const get = vi.spyOn(transcriptService, 'getSavedTranscript').mockResolvedValue({
|
||||
id: 'transcript-id',
|
||||
language,
|
||||
segments: [segment],
|
||||
})
|
||||
const update = vi.spyOn(transcriptService, 'updateSegmentText').mockResolvedValue(segment)
|
||||
|
||||
expect((await submit({ language })).status).toBe(202)
|
||||
expect((await app.request(`/files/file-id/transcripts/${language}`)).status).toBe(200)
|
||||
expect((await edit({ text: segment.text }, language)).status).toBe(200)
|
||||
expect(generate).toHaveBeenCalledWith('file-id', language)
|
||||
expect(get).toHaveBeenCalledWith('file-id', language)
|
||||
expect(update).toHaveBeenCalledWith('file-id', language, 'segment-id', segment.text)
|
||||
},
|
||||
)
|
||||
|
||||
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')
|
||||
|
||||
@@ -2,9 +2,23 @@ import {
|
||||
embeddingServerService,
|
||||
LOCAL_EMBEDDING_PROVIDER,
|
||||
} from '@shumai/core/src/search/embedding-server'
|
||||
import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos'
|
||||
import {
|
||||
chineseTranscriptLanguageSchema,
|
||||
transcriptionProviderLanguageCodeSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
|
||||
const transcriptionProviderLanguagesSchema = z.object({
|
||||
model: z.string().min(1),
|
||||
languages: z.array(
|
||||
z.object({ code: transcriptionProviderLanguageCodeSchema, name: z.string().min(1) }),
|
||||
),
|
||||
})
|
||||
|
||||
export function getTranscriptionProviderLanguage(language: string | null) {
|
||||
return chineseTranscriptLanguageSchema.options.some((code) => code === language) ? 'zh' : language
|
||||
}
|
||||
|
||||
export async function isLocalTranscriptionEnabled(teamId?: string): Promise<boolean> {
|
||||
const { provider } = await embeddingServerService.resolveRuntimeConfig(teamId)
|
||||
return provider === LOCAL_EMBEDDING_PROVIDER
|
||||
@@ -16,12 +30,12 @@ export async function listLocalTranscriptionLanguages(teamId?: string) {
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
})
|
||||
if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`)
|
||||
return transcriptLanguagesSchema.parse(await response.json())
|
||||
return transcriptionProviderLanguagesSchema.parse(await response.json())
|
||||
}
|
||||
|
||||
const transcriptResponseSchema = z
|
||||
.object({
|
||||
language: transcriptLanguageCodeSchema.nullable(),
|
||||
language: transcriptionProviderLanguageCodeSchema.nullable(),
|
||||
segments: z.array(
|
||||
z
|
||||
.object({ start: z.number().min(0), end: z.number().min(0), text: z.string().min(1) })
|
||||
|
||||
@@ -144,7 +144,14 @@ describe('TranscriptService', () => {
|
||||
})
|
||||
|
||||
it('validates provider capability, language and asset eligibility before queuing', async () => {
|
||||
await expect(transcriptService.listLanguages()).resolves.toMatchObject({ model })
|
||||
await expect(transcriptService.listLanguages()).resolves.toEqual({
|
||||
model,
|
||||
languages: [
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'zh-Hans', name: 'Chinese (Simplified)' },
|
||||
{ code: 'zh-Hant', name: 'Chinese (Traditional)' },
|
||||
],
|
||||
})
|
||||
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 })
|
||||
@@ -155,6 +162,20 @@ describe('TranscriptService', () => {
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('only offers Chinese scripts when the provider supports Chinese', async () => {
|
||||
const list = { model, languages: [{ code: 'en', name: 'English' }] }
|
||||
vi.mocked(fetch).mockImplementation(async () => Response.json(list))
|
||||
|
||||
await expect(transcriptService.listLanguages()).resolves.toEqual(list)
|
||||
await expect(transcriptService.generate(assetId, 'zh-Hans')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
await expect(transcriptService.generate(assetId, 'zh-Hant')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('requires an enabled Transcript Agent before contacting the provider or queuing', async () => {
|
||||
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
|
||||
await expect(transcriptService.isGenerationEnabled()).resolves.toBe(false)
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type WorkflowTask,
|
||||
} from '@shumai/db'
|
||||
import {
|
||||
chineseTranscriptLanguageSchema,
|
||||
selectTranscriptVideoProxyKey,
|
||||
transcriptionErrors,
|
||||
transcriptVideoStatuses,
|
||||
@@ -18,13 +19,22 @@ import {
|
||||
type TranscriptSegment,
|
||||
} from '@shumai/dtos'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { isLocalTranscriptionEnabled, listLocalTranscriptionLanguages } from './local-transcription'
|
||||
import {
|
||||
getTranscriptionProviderLanguage,
|
||||
isLocalTranscriptionEnabled,
|
||||
listLocalTranscriptionLanguages,
|
||||
} from './local-transcription'
|
||||
|
||||
const type = WorkflowTaskType.ai_transcription
|
||||
|
||||
const transcriptSelection = { id: true, language: true } as const
|
||||
const segmentSelection = { id: true, startMs: true, endMs: true, text: true } as const
|
||||
|
||||
const chineseTranscriptLanguageNames = {
|
||||
'zh-Hans': 'Chinese (Simplified)',
|
||||
'zh-Hant': 'Chinese (Traditional)',
|
||||
}
|
||||
|
||||
type Segment = { startMs: number; endMs: number; text: string }
|
||||
|
||||
export class TranscriptService {
|
||||
@@ -46,7 +56,18 @@ export class TranscriptService {
|
||||
|
||||
async listLanguages() {
|
||||
await this.requireEnabled()
|
||||
return this.loadLanguages()
|
||||
const { model, languages } = await this.loadLanguages()
|
||||
return {
|
||||
model,
|
||||
languages: languages.flatMap((language) =>
|
||||
language.code === 'zh'
|
||||
? chineseTranscriptLanguageSchema.options.map((code) => ({
|
||||
code,
|
||||
name: chineseTranscriptLanguageNames[code],
|
||||
}))
|
||||
: [language],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
private async loadLanguages(teamId?: string) {
|
||||
@@ -111,7 +132,8 @@ export class TranscriptService {
|
||||
if (saved) return saved
|
||||
|
||||
const { model, languages } = await this.loadLanguages(teamId)
|
||||
if (language && !languages.some((entry) => entry.code === language)) {
|
||||
const providerLanguage = getTranscriptionProviderLanguage(language)
|
||||
if (providerLanguage && !languages.some((entry) => entry.code === providerLanguage)) {
|
||||
throw new HTTPException(400, { message: 'Unsupported transcription language' })
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const transcriptLanguageCodeSchema = z.string().regex(/^[a-z]{2,3}$/)
|
||||
export const transcriptionProviderLanguageCodeSchema = z.string().regex(/^[a-z]{2,3}$/)
|
||||
export const chineseTranscriptLanguageSchema = z.enum(['zh-Hans', 'zh-Hant'])
|
||||
export const transcriptLanguageCodeSchema = transcriptionProviderLanguageCodeSchema.or(
|
||||
chineseTranscriptLanguageSchema,
|
||||
)
|
||||
|
||||
export type SavedTranscriptLanguages = { languages: string[] }
|
||||
|
||||
@@ -25,11 +29,6 @@ export const updateTranscriptSegmentRequestSchema = z.strictObject({
|
||||
text: z.string().refine((text) => !text.includes('\0')),
|
||||
})
|
||||
|
||||
export const transcriptLanguagesSchema = z.object({
|
||||
model: z.string().min(1),
|
||||
languages: z.array(z.object({ code: transcriptLanguageCodeSchema, name: z.string().min(1) })),
|
||||
})
|
||||
|
||||
interface TranscriptVideoProxy {
|
||||
key?: string
|
||||
resolution?: string
|
||||
|
||||
@@ -36,6 +36,9 @@ describe('Transcribe video workflow', () => {
|
||||
let provider: ReturnType<typeof Bun.serve>
|
||||
let responseStatus = 200
|
||||
let firstRequestBusy = false
|
||||
let transcription:
|
||||
| { language: string | null; segments: Array<{ start: number; end: number; text: string }> }
|
||||
| undefined
|
||||
let uploads: Array<{
|
||||
language: FormDataEntryValue | null
|
||||
length: string | null
|
||||
@@ -106,11 +109,12 @@ describe('Transcribe video workflow', () => {
|
||||
})
|
||||
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' }],
|
||||
})
|
||||
return Response.json(
|
||||
transcription ?? {
|
||||
language: form.get('language') ?? 'en',
|
||||
segments: [{ start: 1.012, end: 1.875, text: 'Hello' }],
|
||||
},
|
||||
)
|
||||
},
|
||||
})
|
||||
vi.stubEnv('S3_BUCKET', bucket)
|
||||
@@ -128,6 +132,7 @@ describe('Transcribe video workflow', () => {
|
||||
uploads = []
|
||||
responseStatus = 200
|
||||
firstRequestBusy = false
|
||||
transcription = undefined
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -292,6 +297,81 @@ describe('Transcribe video workflow', () => {
|
||||
)
|
||||
}, 24_000)
|
||||
|
||||
it('saves both requested Chinese scripts alongside the original auto-detected transcript', async () => {
|
||||
const mixed = '頭髮和头发,软件与軟體,Hello'
|
||||
transcription = {
|
||||
language: 'zh',
|
||||
segments: [
|
||||
{ start: 1.012, end: 1.875, text: mixed },
|
||||
{ start: 1.875, end: 2, text: 'Bye' },
|
||||
],
|
||||
}
|
||||
const { task, assetId } = await submitVideo('audio.mp4', null)
|
||||
await workflowService.executeWait(task, 20_000)
|
||||
|
||||
for (const [language, text] of [
|
||||
['zh-Hans', '头发和头发,软件与软体,Hello'],
|
||||
['zh-Hant', '頭髮和頭髮,軟件與軟體,Hello'],
|
||||
]) {
|
||||
const { task } = await startTranscript(assetId, language)
|
||||
expect(task.payload?.transcription?.language).toBe(language)
|
||||
await workflowService.executeWait(task, 20_000)
|
||||
const saved = await transcriptService.getSavedTranscript(assetId, language)
|
||||
expect(saved).toMatchObject({
|
||||
language,
|
||||
segments: [
|
||||
{ startMs: 1012, endMs: 1875, text },
|
||||
{ startMs: 1875, endMs: 2000, text: 'Bye' },
|
||||
],
|
||||
})
|
||||
await expect(transcriptService.generate(assetId, language)).resolves.toEqual({
|
||||
kind: 'existing',
|
||||
transcriptId: saved.id,
|
||||
language,
|
||||
})
|
||||
}
|
||||
|
||||
expect(uploads.map(({ language }) => language)).toEqual([null, 'zh', 'zh'])
|
||||
const { languages } = await transcriptService.listSavedLanguages(assetId)
|
||||
expect(languages.sort()).toEqual(['zh', 'zh-Hans', 'zh-Hant'])
|
||||
const simplified = await transcriptService.getSavedTranscript(assetId, 'zh-Hans')
|
||||
const traditional = await transcriptService.getSavedTranscript(assetId, 'zh-Hant')
|
||||
await transcriptService.updateSegmentText(assetId, 'zh-Hans', simplified.segments[0].id, '你好')
|
||||
await expect(transcriptService.getSavedTranscript(assetId, 'zh-Hant')).resolves.toEqual(
|
||||
traditional,
|
||||
)
|
||||
await expect(transcriptService.getSavedTranscript(assetId, 'zh')).resolves.toMatchObject({
|
||||
segments: [{ text: mixed }, { text: 'Bye' }],
|
||||
})
|
||||
}, 45_000)
|
||||
|
||||
it('reports no speech for a Chinese script request with no detected language', async () => {
|
||||
transcription = { language: null, segments: [] }
|
||||
const { task, assetId } = await submitVideo('audio.mp4', 'zh-Hans')
|
||||
await workflowService.executeWait(task, 20_000)
|
||||
|
||||
expect(await transcriptService.getStatus(assetId)).toEqual({
|
||||
taskId: task.id,
|
||||
status: 'no_speech',
|
||||
})
|
||||
expect(await transcriptService.listSavedLanguages(assetId)).toEqual({ languages: [] })
|
||||
}, 24_000)
|
||||
|
||||
it.each([
|
||||
['en', 'Transcription returned an unexpected language'],
|
||||
['zh-Hant', 'Invalid transcription response'],
|
||||
])(
|
||||
'rejects a provider language of %s for a Chinese script request',
|
||||
async (language, error) => {
|
||||
transcription = { language, segments: [{ start: 1.012, end: 1.875, text: 'Hello' }] }
|
||||
const { task, assetId } = await submitVideo('audio.mp4', 'zh-Hans')
|
||||
|
||||
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(error)
|
||||
expect(await transcriptService.listSavedLanguages(assetId)).toEqual({ languages: [] })
|
||||
},
|
||||
24_000,
|
||||
)
|
||||
|
||||
it('fails with a clear message when the video has no audio track', async () => {
|
||||
const { task, assetId } = await submitVideo('silent.mp4', null)
|
||||
await expect(workflowService.executeWait(task, 20_000)).rejects.toThrow(
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { toast } from 'sonner'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { getChineseTranscriptLanguageName } from '@/ui/lib/transcript'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { savedTranscriptLanguagesKey } from '@/ui/hooks/use-video-transcript'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
@@ -12,6 +13,8 @@ import {
|
||||
ComboboxInput,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxTrigger,
|
||||
ComboboxValue,
|
||||
} from '@/ui/components/ui/combobox'
|
||||
import {
|
||||
Dialog,
|
||||
@@ -35,9 +38,11 @@ export function GenerateTranscriptsDialog({
|
||||
onJobAccepted: (assetId: string) => Promise<void>
|
||||
onClose: () => void
|
||||
}) {
|
||||
const dialogRef = useRef<HTMLDivElement>(null)
|
||||
const popupContainerRef = useRef<HTMLDivElement>(null)
|
||||
const languageTriggerRef = useRef<HTMLButtonElement>(null)
|
||||
const queryClient = useQueryClient()
|
||||
const [language, setLanguage] = useState('')
|
||||
const [isLanguagePickerOpen, setLanguagePickerOpen] = useState(false)
|
||||
const param = { fileId: assetId }
|
||||
|
||||
const languages = useQuery({
|
||||
@@ -77,9 +82,13 @@ export function GenerateTranscriptsDialog({
|
||||
|
||||
const choices = [
|
||||
{ code: '', name: m.transcript_language_auto() },
|
||||
...(languages.data?.languages ?? []),
|
||||
...(languages.data?.languages ?? []).map(({ code, name }) => ({
|
||||
code,
|
||||
name: getChineseTranscriptLanguageName(code) ?? name,
|
||||
})),
|
||||
]
|
||||
const busy = generate.isPending || isTranscribing
|
||||
const searchLabel = m.transcript_search_languages()
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
@@ -88,7 +97,12 @@ export function GenerateTranscriptsDialog({
|
||||
if (!open) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent ref={dialogRef} showCloseButton={false}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (isLanguagePickerOpen) event.preventDefault()
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.generate_transcripts()}</DialogTitle>
|
||||
<DialogDescription>{name}</DialogDescription>
|
||||
@@ -96,16 +110,24 @@ export function GenerateTranscriptsDialog({
|
||||
|
||||
<Combobox
|
||||
items={choices}
|
||||
onOpenChange={(isOpen, details) => {
|
||||
const activeElement = dialogRef.current?.ownerDocument.activeElement
|
||||
// WebKit can report focus-out after focus has already returned to the input.
|
||||
open={isLanguagePickerOpen}
|
||||
onOpenChange={(open, details) => {
|
||||
const container = popupContainerRef.current
|
||||
const activeElement = container?.ownerDocument.activeElement
|
||||
// WebKit can report focus-out while focus is still within the language picker.
|
||||
if (
|
||||
!isOpen &&
|
||||
!open &&
|
||||
details.reason === 'focus-out' &&
|
||||
activeElement === details.event.target
|
||||
(activeElement === languageTriggerRef.current ||
|
||||
container?.contains(activeElement ?? null))
|
||||
) {
|
||||
details.cancel()
|
||||
return
|
||||
}
|
||||
if (!open && details.reason === 'escape-key') {
|
||||
languageTriggerRef.current?.focus({ preventScroll: true })
|
||||
}
|
||||
setLanguagePickerOpen(open)
|
||||
}}
|
||||
value={choices.find((choice) => choice.code === language)}
|
||||
onValueChange={(choice) => setLanguage(choice?.code ?? '')}
|
||||
@@ -113,20 +135,40 @@ export function GenerateTranscriptsDialog({
|
||||
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>
|
||||
<div className="grid gap-2">
|
||||
<label htmlFor="transcript-language" className="text-sm font-medium">
|
||||
{m.language()}
|
||||
</label>
|
||||
<ComboboxTrigger
|
||||
ref={languageTriggerRef}
|
||||
id="transcript-language"
|
||||
render={<Button variant="outline" className="w-full justify-between font-normal" />}
|
||||
>
|
||||
<ComboboxValue />
|
||||
</ComboboxTrigger>
|
||||
</div>
|
||||
{/* Keep the popup inside the modal focus trap and outside the dialog grid. */}
|
||||
<div ref={popupContainerRef} className="absolute top-0 left-0">
|
||||
<ComboboxContent
|
||||
container={popupContainerRef}
|
||||
className="min-w-0"
|
||||
aria-label={m.language()}
|
||||
>
|
||||
<ComboboxInput
|
||||
aria-label={searchLabel}
|
||||
placeholder={searchLabel}
|
||||
showTrigger={false}
|
||||
/>
|
||||
<ComboboxEmpty>{m.transcript_no_languages_found()}</ComboboxEmpty>
|
||||
<ComboboxList>
|
||||
{(choice) => (
|
||||
<ComboboxItem key={choice.code} value={choice}>
|
||||
{choice.name}
|
||||
</ComboboxItem>
|
||||
)}
|
||||
</ComboboxList>
|
||||
</ComboboxContent>
|
||||
</div>
|
||||
</Combobox>
|
||||
|
||||
{languages.isPending && (
|
||||
|
||||
@@ -5,6 +5,7 @@ import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-sele
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import type { MediaController } from '@/ui/components/viewers/types'
|
||||
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
|
||||
import { getChineseTranscriptLanguageName } from '@/ui/lib/transcript'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { getLocale } from '@/ui/paraglide/runtime.js'
|
||||
@@ -69,7 +70,10 @@ export const TranscriptPanel = memo(function TranscriptPanel({
|
||||
const options = useMemo(() => {
|
||||
const names = new Intl.DisplayNames(locale, { type: 'language' })
|
||||
return languages
|
||||
.map((code) => ({ code, name: names.of(code) ?? code }))
|
||||
.map((code) => ({
|
||||
code,
|
||||
name: getChineseTranscriptLanguageName(code) ?? names.of(code) ?? code,
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, locale))
|
||||
}, [languages, locale])
|
||||
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
export function getChineseTranscriptLanguageName(code: string) {
|
||||
if (code === 'zh-Hans') return m.transcript_language_chinese_simplified()
|
||||
if (code === 'zh-Hant') return m.transcript_language_chinese_traditional()
|
||||
}
|
||||
|
||||
export function getTranscriptVideo(item: AssetInfo) {
|
||||
const isVideo = item.proxyType ? item.proxyType === 'video' : item.mediaType?.startsWith('video/')
|
||||
if (!isVideo) return undefined
|
||||
|
||||
@@ -1826,6 +1826,9 @@
|
||||
"failed_to_update_comment": "Failed to update comment",
|
||||
"generate_transcripts": "Generate Transcripts",
|
||||
"transcript_language_auto": "Auto",
|
||||
"transcript_language_chinese_simplified": "Chinese (Simplified)",
|
||||
"transcript_language_chinese_traditional": "Chinese (Traditional)",
|
||||
"transcript_search_languages": "Search languages",
|
||||
"transcript_generating": "Transcribing…",
|
||||
"transcript_no_speech": "No speech detected.",
|
||||
"transcript_submit_failed": "Could not start transcript generation.",
|
||||
|
||||
@@ -1756,6 +1756,9 @@
|
||||
"failed_to_update_comment": "댓글을 수정하지 못했습니다",
|
||||
"generate_transcripts": "전사 생성",
|
||||
"transcript_language_auto": "자동 감지",
|
||||
"transcript_language_chinese_simplified": "중국어(간체)",
|
||||
"transcript_language_chinese_traditional": "중국어(번체)",
|
||||
"transcript_search_languages": "언어 검색",
|
||||
"transcript_generating": "전사 중…",
|
||||
"transcript_no_speech": "음성이 감지되지 않았습니다.",
|
||||
"transcript_submit_failed": "전사 생성을 시작할 수 없습니다.",
|
||||
|
||||
@@ -1826,6 +1826,9 @@
|
||||
"failed_to_update_comment": "更新评论失败",
|
||||
"generate_transcripts": "生成转录",
|
||||
"transcript_language_auto": "自动检测",
|
||||
"transcript_language_chinese_simplified": "中文(简体)",
|
||||
"transcript_language_chinese_traditional": "中文(繁体)",
|
||||
"transcript_search_languages": "搜索语言",
|
||||
"transcript_generating": "正在转录…",
|
||||
"transcript_no_speech": "未检测到语音。",
|
||||
"transcript_submit_failed": "无法启动转录生成。",
|
||||
|
||||
Reference in New Issue
Block a user