Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Integrate transcription in PeerTube

Chocobozzz1bfb791e0539
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 04bff26aab..1fa7704df7 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -71,6 +71,20 @@ jobs:
${{ runner.OS }}-fixtures-
${{ runner.OS }}-
+ - name: Cache PeerTube pip directory
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cache/pip
+ key: ${{ runner.OS }}-${{ matrix.test_suite }}-pip-v1
+
+ - name: Cache Hugging Face models
+ uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cache/huggingface
+ key: ${{ runner.OS }}-${{ matrix.test_suite }}-hugging-face-v1
+
- name: Set env test variable (schedule)
if: github.event_name != 'schedule'
run: |
diff --git a/.gitignore b/.gitignore
index 6865442eba..cf3b25a1ca 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,8 +12,11 @@ yarn-error.log
/test4/
/test5/
/test6/
+
+# Big fixtures generated/downloaded on-demand
/packages/tests/fixtures/video_high_bitrate_1080p.mp4
/packages/tests/fixtures/video_59fps.mp4
+/packages/tests/fixtures/transcription/models-v1/
# Production
/storage
diff --git a/apps/peertube-runner/src/server/process/process.ts b/apps/peertube-runner/src/server/process/process.ts
index e8a1d7c281..b20c2297d1 100644
--- a/apps/peertube-runner/src/server/process/process.ts
+++ b/apps/peertube-runner/src/server/process/process.ts
@@ -1,6 +1,7 @@
import {
RunnerJobLiveRTMPHLSTranscodingPayload,
RunnerJobStudioTranscodingPayload,
+ RunnerJobTranscriptionPayload,
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODWebVideoTranscodingPayload
@@ -9,25 +10,41 @@ import { logger } from '../../shared/index.js'
import { processAudioMergeTranscoding, processHLSTranscoding, ProcessOptions, processWebVideoTranscoding } from './shared/index.js'
import { ProcessLiveRTMPHLSTranscoding } from './shared/process-live.js'
import { processStudioTranscoding } from './shared/process-studio.js'
+import { processVideoTranscription } from './shared/process-transcription.js'
export async function processJob (options: ProcessOptions) {
const { server, job } = options
logger.info(`[${server.url}] Processing job of type ${job.type}: ${job.uuid}`, { payload: job.payload })
- if (job.type === 'vod-audio-merge-transcoding') {
- await processAudioMergeTranscoding(options as ProcessOptions<RunnerJobVODAudioMergeTranscodingPayload>)
- } else if (job.type === 'vod-web-video-transcoding') {
- await processWebVideoTranscoding(options as ProcessOptions<RunnerJobVODWebVideoTranscodingPayload>)
- } else if (job.type === 'vod-hls-transcoding') {
- await processHLSTranscoding(options as ProcessOptions<RunnerJobVODHLSTranscodingPayload>)
- } else if (job.type === 'live-rtmp-hls-transcoding') {
- await new ProcessLiveRTMPHLSTranscoding(options as ProcessOptions<RunnerJobLiveRTMPHLSTranscodingPayload>).process()
- } else if (job.type === 'video-studio-transcoding') {
- await processStudioTranscoding(options as ProcessOptions<RunnerJobStudioTranscodingPayload>)
- } else {
- logger.error(`Unknown job ${job.type} to process`)
- return
+ switch (job.type) {
+ case 'vod-audio-merge-transcoding':
+ await processAudioMergeTranscoding(options as ProcessOptions<RunnerJobVODAudioMergeTranscodingPayload>)
+ break
+
+ case 'vod-web-video-transcoding':
+ await processWebVideoTranscoding(options as ProcessOptions<RunnerJobVODWebVideoTranscodingPayload>)
+ break
+
+ case 'vod-hls-transcoding':
+ await processHLSTranscoding(options as ProcessOptions<RunnerJobVODHLSTranscodingPayload>)
+ break
+
+ case 'live-rtmp-hls-transcoding':
+ await new ProcessLiveRTMPHLSTranscoding(options as ProcessOptions<RunnerJobLiveRTMPHLSTranscodingPayload>).process()
+ break
+
+ case 'video-studio-transcoding':
+ await processStudioTranscoding(options as ProcessOptions<RunnerJobStudioTranscodingPayload>)
+ break
+
+ case 'video-transcription':
+ await processVideoTranscription(options as ProcessOptions<RunnerJobTranscriptionPayload>)
+ break
+
+ default:
+ logger.error(`Unknown job ${job.type} to process`)
+ return
}
logger.info(`[${server.url}] Finished processing job of type ${job.type}: ${job.uuid}`)
diff --git a/apps/peertube-runner/src/server/process/shared/common.ts b/apps/peertube-runner/src/server/process/shared/common.ts
index 09241d93b4..cf76829910 100644
--- a/apps/peertube-runner/src/server/process/shared/common.ts
+++ b/apps/peertube-runner/src/server/process/shared/common.ts
@@ -5,7 +5,7 @@ import { RunnerJob, RunnerJobPayload } from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { PeerTubeServer } from '@peertube/peertube-server-commands'
import { ConfigManager, downloadFile, logger } from '../../../shared/index.js'
-import { getTranscodingLogger } from './transcoding-logger.js'
+import { getWinstonLogger } from './winston-logger.js'
export type JobWithToken <T extends RunnerJobPayload = RunnerJobPayload> = RunnerJob<T> & { jobToken: string }
@@ -101,6 +101,6 @@ function getCommonFFmpegOptions () {
available: getDefaultAvailableEncoders(),
encodersToTry: getDefaultEncodersToTry()
},
- logger: getTranscodingLogger()
+ logger: getWinstonLogger()
}
}
diff --git a/apps/peertube-runner/src/server/process/shared/index.ts b/apps/peertube-runner/src/server/process/shared/index.ts
index 638bf127f1..67d556f915 100644
--- a/apps/peertube-runner/src/server/process/shared/index.ts
+++ b/apps/peertube-runner/src/server/process/shared/index.ts
@@ -1,3 +1,3 @@
export * from './common.js'
export * from './process-vod.js'
-export * from './transcoding-logger.js'
+export * from './winston-logger.js'
diff --git a/apps/peertube-runner/src/server/process/shared/process-transcription.ts b/apps/peertube-runner/src/server/process/shared/process-transcription.ts
new file mode 100644
index 0000000000..715433f090
--- /dev/null
+++ b/apps/peertube-runner/src/server/process/shared/process-transcription.ts
@@ -0,0 +1,79 @@
+import { hasAudioStream } from '@peertube/peertube-ffmpeg'
+import { RunnerJobTranscriptionPayload, TranscriptionSuccess } from '@peertube/peertube-models'
+import { buildSUUID } from '@peertube/peertube-node-utils'
+import { TranscriptionModel, WhisperBuiltinModel, transcriberFactory } from '@peertube/peertube-transcription'
+import { remove } from 'fs-extra/esm'
+import { join } from 'path'
+import { ConfigManager } from '../../../shared/config-manager.js'
+import { logger } from '../../../shared/index.js'
+import { ProcessOptions, downloadInputFile, scheduleTranscodingProgress } from './common.js'
+import { getWinstonLogger } from './winston-logger.js'
+
+export async function processVideoTranscription (options: ProcessOptions<RunnerJobTranscriptionPayload>) {
+ const { server, job, runnerToken } = options
+
+ const config = ConfigManager.Instance.getConfig().transcription
+
+ const payload = job.payload
+
+ let inputPath: string
+
+ const updateProgressInterval = scheduleTranscodingProgress({
+ job,
+ server,
+ runnerToken,
+ progressGetter: () => undefined
+ })
+
+ const outputPath = join(ConfigManager.Instance.getTranscriptionDirectory(), buildSUUID())
+
+ const transcriber = transcriberFactory.createFromEngineName({
+ engineName: config.engine,
+ enginePath: config.enginePath,
+ logger: getWinstonLogger()
+ })
+
+ try {
+ logger.info(`Downloading input file ${payload.input.videoFileUrl} for transcription job ${job.jobToken}`)
+
+ inputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
+
+ logger.info(`Downloaded input file ${payload.input.videoFileUrl} for job ${job.jobToken}. Running transcription.`)
+
+ if (await hasAudioStream(inputPath) !== true) {
+ await server.runnerJobs.error({
+ jobToken: job.jobToken,
+ jobUUID: job.uuid,
+ runnerToken,
+ message: 'This input file does not contain audio'
+ })
+
+ return
+ }
+
+ const transcriptFile = await transcriber.transcribe({
+ mediaFilePath: inputPath,
+ model: config.modelPath
+ ? await TranscriptionModel.fromPath(config.modelPath)
+ : new WhisperBuiltinModel(config.model),
+ format: 'vtt',
+ transcriptDirectory: outputPath
+ })
+
+ const successBody: TranscriptionSuccess = {
+ inputLanguage: transcriptFile.language,
+ vttFile: transcriptFile.path
+ }
+
+ await server.runnerJobs.success({
+ jobToken: job.jobToken,
+ jobUUID: job.uuid,
+ runnerToken,
+ payload: successBody
+ })
+ } finally {
+ if (inputPath) await remove(inputPath)
+ if (outputPath) await remove(outputPath)
+ if (updateProgressInterval) clearInterval(updateProgressInterval)
+ }
+}
diff --git a/apps/peertube-runner/src/server/process/shared/transcoding-logger.ts b/apps/peertube-runner/src/server/process/shared/transcoding-logger.ts
deleted file mode 100644
index d0775e13b0..0000000000
--- a/apps/peertube-runner/src/server/process/shared/transcoding-logger.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { LogFn } from 'pino'
-import { logger } from '../../../shared/index.js'
-
-export function getTranscodingLogger () {
- return {
- info: buildWinstonLogger(logger.info.bind(logger)),
- debug: buildWinstonLogger(logger.debug.bind(logger)),
- warn: buildWinstonLogger(logger.warn.bind(logger)),
- error: buildWinstonLogger(logger.error.bind(logger))
- }
-}
-
-function buildWinstonLogger (log: LogFn) {
- return (arg1: string, arg2?: object) => {
- if (arg2) return log(arg2, arg1)
-
- return log(arg1)
- }
-}
diff --git a/apps/peertube-runner/src/server/process/shared/winston-logger.ts b/apps/peertube-runner/src/server/process/shared/winston-logger.ts
new file mode 100644
index 0000000000..d2958ea6a0
--- /dev/null
+++ b/apps/peertube-runner/src/server/process/shared/winston-logger.ts
@@ -0,0 +1,19 @@
+import { LogFn } from 'pino'
+import { logger } from '../../../shared/index.js'
+
+export function getWinstonLogger () {
+ return {
+ info: buildLogLevelFn(logger.info.bind(logger)),
+ debug: buildLogLevelFn(logger.debug.bind(logger)),
+ warn: buildLogLevelFn(logger.warn.bind(logger)),
+ error: buildLogLevelFn(logger.error.bind(logger))
+ }
+}
+
+function buildLogLevelFn (log: LogFn) {
+ return (arg1: string, arg2?: object) => {
+ if (arg2) return log(arg2, arg1)
+
+ return log(arg1)
+ }
+}
diff --git a/apps/peertube-runner/src/server/shared/supported-job.ts b/apps/peertube-runner/src/server/shared/supported-job.ts
index d905b5de27..38cd281405 100644
--- a/apps/peertube-runner/src/server/shared/supported-job.ts
+++ b/apps/peertube-runner/src/server/shared/supported-job.ts
@@ -1,15 +1,16 @@
import {
RunnerJobLiveRTMPHLSTranscodingPayload,
RunnerJobPayload,
- RunnerJobType,
RunnerJobStudioTranscodingPayload,
+ RunnerJobTranscriptionPayload,
+ RunnerJobType,
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODWebVideoTranscodingPayload,
VideoStudioTaskPayload
} from '@peertube/peertube-models'
-const supportedMatrix = {
+const supportedMatrix: { [ id in RunnerJobType ]: (payload: RunnerJobPayload) => boolean } = {
'vod-web-video-transcoding': (_payload: RunnerJobVODWebVideoTranscodingPayload) => {
return true
},
@@ -29,6 +30,9 @@ const supportedMatrix = {
if (!Array.isArray(tasks)) return false
return tasks.every(t => t && supported.has(t.name))
+ },
+ 'video-transcription': (_payload: RunnerJobTranscriptionPayload) => {
+ return true
}
}
diff --git a/apps/peertube-runner/src/shared/config-manager.ts b/apps/peertube-runner/src/shared/config-manager.ts
index 84a326a168..97a70204a5 100644
--- a/apps/peertube-runner/src/shared/config-manager.ts
+++ b/apps/peertube-runner/src/shared/config-manager.ts
@@ -1,4 +1,5 @@
import { parse, stringify } from '@iarna/toml'
+import { TranscriptionEngineName, WhisperBuiltinModelName } from '@peertube/peertube-transcription'
import envPaths from 'env-paths'
import { ensureDir, pathExists, remove } from 'fs-extra/esm'
import { readFile, writeFile } from 'fs/promises'
@@ -24,6 +25,13 @@ type Config = {
runnerName: string
runnerDescription?: string
}[]
+
+ transcription: {
+ engine: TranscriptionEngineName
+ enginePath: string | null
+ model: WhisperBuiltinModelName
+ modelPath: string | null
+ }
}
export class ConfigManager {
@@ -37,6 +45,12 @@ export class ConfigManager {
threads: 2,
nice: 20
},
+ transcription: {
+ engine: 'whisper-ctranslate2',
+ enginePath: null,
+ model: 'small',
+ modelPath: null
+ },
registeredInstances: []
}
@@ -98,6 +112,10 @@ export class ConfigManager {
return join(paths.cache, this.id, 'transcoding')
}
+ getTranscriptionDirectory () {
+ return join(paths.cache, this.id, 'transcription')
+ }
+
getSocketDirectory () {
return join(paths.data, this.id)
}
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
index 3de40666fc..ea8094d5fe 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
+++ b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.html
@@ -318,7 +318,7 @@
>
<ng-container ngProjectAs="description">
<span i18n [hidden]="isImportVideosHttpEnabled()">
- ⛔ You need to allow import with HTTP URL to be able to activate this feature.
+ ⛔ You need to allow import with HTTP URL to be able to activate this feature.
</span>
</ng-container>
</my-peertube-checkbox>
@@ -359,7 +359,6 @@
</ng-container>
<ng-container formGroupName="storyboards">
-
<div class="form-group">
<my-peertube-checkbox
inputName="storyboardsEnabled" formControlName="enabled"
@@ -370,7 +369,35 @@
</ng-container>
</my-peertube-checkbox>
</div>
+ </ng-container>
+ <ng-container formGroupName="videoTranscription">
+ <div class="form-group">
+ <my-peertube-checkbox
+ inputName="videoTranscriptionEnabled" formControlName="enabled"
+ i18n-labelText labelText="Enable video transcription"
+ >
+ <ng-container ngProjectAs="description">
+ <span i18n>Automatically create a subtitle file of uploaded/imported VOD videos</span>
+ </ng-container>
+
+ <ng-container ngProjectAs="extra">
+ <div class="form-group" formGroupName="remoteRunners" [ngClass]="getTranscriptionRunnerDisabledClass()">
+ <my-peertube-checkbox
+ inputName="videoTranscriptionRemoteRunnersEnabled" formControlName="enabled"
+ i18n-labelText labelText="Enable remote runners for transcription"
+ >
+ <ng-container ngProjectAs="description">
+ <span i18n>
+ Use <a routerLink="/admin/system/runners/runners-list">remote runners</a> to process transcription tasks.
+ Remote runners has to register on your instance first.
+ </span>
+ </ng-container>
+ </my-peertube-checkbox>
+ </div>
+ </ng-container>
+ </my-peertube-checkbox>
+ </div>
</ng-container>
</div>
</div>
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
index 9f1cbc758f..98510c7c34 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-basic-configuration.component.ts
@@ -137,6 +137,18 @@ export class EditBasicConfigurationComponent implements OnInit, OnChanges {
return { 'disabled-checkbox-extra': !this.isSearchIndexEnabled() }
}
+ // ---------------------------------------------------------------------------
+
+ isTranscriptionEnabled () {
+ return this.form.value['videoTranscription']['enabled'] === true
+ }
+
+ getTranscriptionRunnerDisabledClass () {
+ return { 'disabled-checkbox-extra': !this.isTranscriptionEnabled() }
+ }
+
+ // ---------------------------------------------------------------------------
+
isAutoFollowIndexEnabled () {
return this.form.value['followings']['instance']['autoFollowIndex']['enabled'] === true
}
diff --git a/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts b/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
index 6c14b5c557..a85b171652 100644
--- a/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
+++ b/client/src/app/+admin/config/edit-custom-config/edit-custom-config.component.ts
@@ -267,6 +267,12 @@ export class EditCustomConfigComponent extends FormReactive implements OnInit {
enabled: null
}
},
+ videoTranscription: {
+ enabled: null,
+ remoteRunners: {
+ enabled: null
+ }
+ },
videoFile: {
update: {
enabled: null
diff --git a/client/src/app/+admin/overview/videos/video-list.component.ts b/client/src/app/+admin/overview/videos/video-list.component.ts
index 3eb9323221..f7d88b752d 100644
--- a/client/src/app/+admin/overview/videos/video-list.component.ts
+++ b/client/src/app/+admin/overview/videos/video-list.component.ts
@@ -1,7 +1,7 @@
import { DatePipe, NgClass, NgFor, NgIf } from '@angular/common'
import { Component, OnInit, ViewChild } from '@angular/core'
import { ActivatedRoute, Router, RouterLink } from '@angular/router'
-import { AuthService, ConfirmService, Notifier, RestPagination, RestTable } from '@app/core'
+import { AuthService, ConfirmService, Notifier, RestPagination, RestTable, ServerService } from '@app/core'
import { formatICU, getAbsoluteAPIUrl } from '@app/helpers'
import { VideoDetails } from '@app/shared/shared-main/video/video-details.model'
import { VideoFileTokenService } from '@app/shared/shared-main/video/video-file-token.service'
@@ -30,6 +30,7 @@ import {
VideoActionsDropdownComponent
} from '../../../shared/shared-video-miniature/video-actions-dropdown.component'
import { VideoAdminService } from './video-admin.service'
+import { VideoCaptionService } from '@app/shared/shared-main/video-caption/video-caption.service'
@Component({
selector: 'my-video-list',
@@ -84,7 +85,8 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
removeFiles: true,
transcoding: true,
studio: true,
- stats: true
+ stats: true,
+ generateTranscription: true
}
loading = true
@@ -100,6 +102,8 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
private videoService: VideoService,
private videoAdminService: VideoAdminService,
private videoBlockService: VideoBlockService,
+ private videoCaptionService: VideoCaptionService,
+ private server: ServerService,
private videoFileTokenService: VideoFileTokenService
) {
super()
@@ -109,6 +113,10 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
return this.auth.getUser()
}
+ get serverConfig () {
+ return this.server.getHTMLConfig()
+ }
+
ngOnInit () {
this.initialize()
@@ -160,6 +168,14 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
isDisplayed: videos => videos.every(v => v.canRemoveFiles(this.authUser)),
iconName: 'delete'
}
+ ],
+ [
+ {
+ label: $localize`Generate caption`,
+ handler: videos => this.generateCaption(videos),
+ isDisplayed: videos => videos.every(v => v.canGenerateTranscription(this.authUser, this.serverConfig.videoTranscription.enabled)),
+ iconName: 'video-lang'
+ }
]
]
}
@@ -399,4 +415,15 @@ export class VideoListComponent extends RestTable <Video> implements OnInit {
error: err => this.notifier.error(err.message)
})
}
+
+ private generateCaption (videos: Video[]) {
+ this.videoCaptionService.generateCaption(videos.map(v => v.id))
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Transcription jobs created.`)
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
+ }
}
diff --git a/client/src/app/+admin/system/jobs/jobs.component.ts b/client/src/app/+admin/system/jobs/jobs.component.ts
index 2ff60f8e05..122fe274c8 100644
--- a/client/src/app/+admin/system/jobs/jobs.component.ts
+++ b/client/src/app/+admin/system/jobs/jobs.component.ts
@@ -69,6 +69,7 @@ export class JobsComponent extends RestTable implements OnInit {
'video-redundancy',
'video-studio-edition',
'video-transcoding',
+ 'video-transcription',
'videos-views-stats'
]
diff --git a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
index 69a1b08828..2a8e48e250 100644
--- a/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
+++ b/client/src/app/+my-account/my-account-settings/my-account-notification-preferences/my-account-notification-preferences.component.ts
@@ -49,7 +49,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {
abuseStateChange: $localize`One of your abuse reports has been accepted or rejected by moderators`,
newPeerTubeVersion: $localize`A new PeerTube version is available`,
newPluginVersion: $localize`One of your plugin/theme has a new available version`,
- myVideoStudioEditionFinished: $localize`Video studio edition has finished`
+ myVideoStudioEditionFinished: $localize`Video studio edition has finished`,
+ myVideoTranscriptionGenerated: $localize`The transcription of your video has been generated`
}
this.notificationSettingGroups = [
{
@@ -68,7 +69,8 @@ export class MyAccountNotificationPreferencesComponent implements OnInit {
'blacklistOnMyVideo',
'myVideoPublished',
'myVideoImportFinished',
- 'myVideoStudioEditionFinished'
+ 'myVideoStudioEditionFinished',
+ 'myVideoTranscriptionGenerated'
]
},
diff --git a/client/src/app/+videos/+video-edit/shared/video-edit.component.html b/client/src/app/+videos/+video-edit/shared/video-edit.component.html
index 9bc160bbfe..57dcd2b2e7 100644
--- a/client/src/app/+videos/+video-edit/shared/video-edit.component.html
+++ b/client/src/app/+videos/+video-edit/shared/video-edit.component.html
@@ -173,12 +173,8 @@
<ng-template ngbNavContent>
<div class="captions">
-
- <div class="captions-header">
- <button (click)="openAddCaptionModal()" class="peertube-create-button">
- <my-global-icon iconName="add" aria-hidden="true"></my-global-icon>
- <ng-container i18n>Add another caption</ng-container>
- </button>
+ <div class="alert pt-alert-primary" *ngIf="displayTranscriptionInfo && isTranscriptionEnabled()" i18n>
+ A subtitle will be automatically generated from your video.
</div>
<div class="form-group" *ngFor="let videoCaption of videoCaptions">
@@ -226,6 +222,13 @@
No captions for now.
</div>
+ <div class="mt-3 mb-3">
+ <button (click)="openAddCaptionModal()" class="peertube-create-button">
+ <my-global-icon iconName="add" aria-hidden="true"></my-global-icon>
+ <ng-container i18n>Add a caption</ng-container>
+ </button>
+ </div>
+
</div>
</ng-template>
</ng-container>
diff --git a/client/src/app/+videos/+video-edit/shared/video-edit.component.scss b/client/src/app/+videos/+video-edit/shared/video-edit.component.scss
index 944d21cafc..fbe9d78cf9 100644
--- a/client/src/app/+videos/+video-edit/shared/video-edit.component.scss
+++ b/client/src/app/+videos/+video-edit/shared/video-edit.component.scss
@@ -24,11 +24,6 @@ my-peertube-checkbox {
}
}
-.captions-header {
- text-align: end;
- margin-bottom: 1rem;
-}
-
.caption-entry {
display: flex;
height: 40px;
diff --git a/client/src/app/+videos/+video-edit/shared/video-edit.component.ts b/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
index a6aad39518..5469b7fa86 100644
--- a/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
+++ b/client/src/app/+videos/+video-edit/shared/video-edit.component.ts
@@ -1,5 +1,16 @@
import { DatePipe, NgClass, NgFor, NgIf, NgTemplateOutlet } from '@angular/common'
-import { ChangeDetectorRef, Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'
+import {
+ ChangeDetectorRef,
+ Component,
+ EventEmitter,
+ Input,
+ NgZone,
+ OnDestroy,
+ OnInit,
+ Output,
+ ViewChild,
+ booleanAttribute
+} from '@angular/core'
import { AbstractControl, FormArray, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'
import { HooksService, PluginService, ServerService } from '@app/core'
import { removeElementFromArray } from '@app/helpers'
@@ -63,10 +74,10 @@ import { HelpComponent } from '../../../shared/shared-main/misc/help.component'
import { EmbedComponent } from '../../../shared/shared-main/video/embed.component'
import { LiveDocumentationLinkComponent } from '../../../shared/shared-video-live/live-documentation-link.component'
import { I18nPrimengCalendarService } from './i18n-primeng-calendar.service'
+import { ThumbnailManagerComponent } from './thumbnail-manager/thumbnail-manager.component'
import { VideoCaptionAddModalComponent } from './video-caption-add-modal.component'
import { VideoCaptionEditModalContentComponent } from './video-caption-edit-modal-content/video-caption-edit-modal-content.component'
import { VideoEditType } from './video-edit.type'
-import { ThumbnailManagerComponent } from './thumbnail-manager/thumbnail-manager.component'
type VideoLanguages = VideoConstant<string> & { group?: string }
type PluginField = {
@@ -122,15 +133,17 @@ export class VideoEditComponent implements OnInit, OnDestroy {
@Input() publishedVideo: VideoDetails
@Input() userVideoChannels: SelectChannelItem[] = []
- @Input() forbidScheduledPublication = true
+
+ @Input({ transform: booleanAttribute }) forbidScheduledPublication = true
+ @Input({ transform: booleanAttribute }) displayTranscriptionInfo = true
@Input() videoCaptions: VideoCaptionWithPathEdit[] = []
@Input() videoSource: VideoSource
@Input() videoChapters: VideoChapter[] = []
- @Input() hideWaitTranscoding = false
- @Input() updateVideoFileEnabled = false
+ @Input({ transform: booleanAttribute }) hideWaitTranscoding = false
+ @Input({ transform: booleanAttribute }) updateVideoFileEnabled = false
@Input() type: VideoEditType
@Input() liveVideo: LiveVideo
@@ -405,6 +418,10 @@ export class VideoEditComponent implements OnInit, OnDestroy {
return !!this.form.value['originallyPublishedAt']
}
+ isTranscriptionEnabled () {
+ return this.serverConfig.videoTranscription.enabled
+ }
+
// ---------------------------------------------------------------------------
resetField (name: string) {
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.html b/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.html
index 4831b76801..dceae41293 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.html
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-go-live.component.html
@@ -53,8 +53,8 @@
<form [hidden]="!isInUpdateForm" novalidate [formGroup]="form">
<my-video-edit
[form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions"
- [forbidScheduledPublication]="true" [hideWaitTranscoding]="true"
[validationMessages]="validationMessages" [userVideoChannels]="userVideoChannels" [liveVideo]="liveVideo"
+ forbidScheduledPublication="true" hideWaitTranscoding="true" displayTranscriptionInfo="false"
type="go-live"
></my-video-edit>
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.html b/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.html
index af0580dc8d..5dc9dd013d 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.html
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-import-torrent.component.html
@@ -59,8 +59,9 @@
<!-- Hidden because we want to load the component -->
<form [hidden]="!hasImportedVideo" novalidate [formGroup]="form">
<my-video-edit
- [form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions" [forbidScheduledPublication]="true"
+ [form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions"
[validationMessages]="validationMessages" [userVideoChannels]="userVideoChannels"
+ forbidScheduledPublication="true"
type="import-torrent"
></my-video-edit>
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.html b/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.html
index 591573d854..e7991d3985 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.html
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-import-url.component.html
@@ -57,8 +57,9 @@
<form [hidden]="!hasImportedVideo" novalidate [formGroup]="form">
<my-video-edit
#videoEdit
- [form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions" [forbidScheduledPublication]="true"
+ [form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions"
[validationMessages]="validationMessages" [userVideoChannels]="userVideoChannels"
+ forbidScheduledPublication="true"
type="import-url"
></my-video-edit>
diff --git a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.html b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.html
index 165a3fba57..066cfb14e1 100644
--- a/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.html
+++ b/client/src/app/+videos/+video-edit/video-add-components/video-upload.component.html
@@ -67,7 +67,7 @@
<my-video-edit
[form]="form" [formErrors]="formErrors" [videoCaptions]="videoCaptions"
[validationMessages]="validationMessages" [userVideoChannels]="userVideoChannels"
- [forbidScheduledPublication]="false"
+ forbidScheduledPublication="false"
type="upload"
></my-video-edit>
diff --git a/client/src/app/+videos/+video-edit/video-update.component.html b/client/src/app/+videos/+video-edit/video-update.component.html
index 0761d4c09c..b04147deee 100644
--- a/client/src/app/+videos/+video-edit/video-update.component.html
+++ b/client/src/app/+videos/+video-edit/video-update.component.html
@@ -20,6 +20,7 @@
type="update" (pluginFieldsAdded)="hydratePluginFieldsFromVideo()"
[liveVideo]="liveVideo" [publishedVideo]="videoDetails"
[videoSource]="videoSource" [updateVideoFileEnabled]="isUpdateVideoFileEnabled()"
+ displayTranscriptionInfo="false"
(formBuilt)="onFormBuilt()"
>
diff --git a/client/src/app/shared/shared-instance/instance-features-table.component.html b/client/src/app/shared/shared-instance/instance-features-table.component.html
index 80b6776a69..4ea71ace42 100644
--- a/client/src/app/shared/shared-instance/instance-features-table.component.html
+++ b/client/src/app/shared/shared-instance/instance-features-table.component.html
@@ -34,6 +34,13 @@
</td>
</tr>
+ <tr>
+ <th i18n class="sub-label" scope="row">Automatic transcription</th>
+ <td>
+ <my-feature-boolean [value]="serverConfig.videoTranscription.enabled"></my-feature-boolean>
+ </td>
+ </tr>
+
<tr>
<th i18n class="sub-label" scope="row">Video uploads</th>
<td>
diff --git a/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss b/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss
index d39f7c0484..03a5a86ce8 100644
--- a/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss
+++ b/client/src/app/shared/shared-main/buttons/action-dropdown.component.scss
@@ -63,6 +63,10 @@
&.with-icon {
@include dropdown-with-icon-item;
+
+ .icon-video-lang {
+ top: 0;
+ }
}
a,
diff --git a/client/src/app/shared/shared-main/users/user-notification.model.ts b/client/src/app/shared/shared-main/users/user-notification.model.ts
index 8e59072553..6870fb8cf3 100644
--- a/client/src/app/shared/shared-main/users/user-notification.model.ts
+++ b/client/src/app/shared/shared-main/users/user-notification.model.ts
@@ -11,6 +11,7 @@ import {
UserNotificationType,
UserNotificationType_Type,
UserRight,
+ VideoConstant,
VideoInfo
} from '@peertube/peertube-models'
import { logger } from '@root-helpers/logger'
@@ -90,6 +91,12 @@ export class UserNotification implements UserNotificationServer {
username: string
}
+ videoCaption?: {
+ id: number
+ language: VideoConstant<string>
+ video: VideoInfo
+ }
+
createdAt: string
updatedAt: string
@@ -149,6 +156,8 @@ export class UserNotification implements UserNotificationServer {
this.peertube = hash.peertube
this.registration = hash.registration
+ this.videoCaption = hash.videoCaption
+
this.createdAt = hash.createdAt
this.updatedAt = hash.updatedAt
@@ -250,6 +259,10 @@ export class UserNotification implements UserNotificationServer {
this.pluginQueryParams.pluginType = this.plugin.type + ''
break
+ case UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED:
+ this.videoUrl = this.buildVideoUrl(this.videoCaption.video)
+ break
+
case UserNotificationType.MY_VIDEO_STUDIO_EDITION_FINISHED:
this.videoUrl = this.buildVideoUrl(this.video)
break
diff --git a/client/src/app/shared/shared-main/video-caption/video-caption.service.ts b/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
index 502b26f951..4cd3105acb 100644
--- a/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
+++ b/client/src/app/shared/shared-main/video-caption/video-caption.service.ts
@@ -1,15 +1,15 @@
-import { Observable, of } from 'rxjs'
-import { catchError, map, switchMap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { RestExtractor, ServerService } from '@app/core'
import { objectToFormData } from '@app/helpers'
import { peertubeTranslate, sortBy } from '@peertube/peertube-core-utils'
import { ResultList, VideoCaption } from '@peertube/peertube-models'
+import { Observable, from, of } from 'rxjs'
+import { catchError, concatMap, map, switchMap, toArray } from 'rxjs/operators'
import { environment } from '../../../../environments/environment'
-import { VideoCaptionEdit } from './video-caption-edit.model'
import { VideoPasswordService } from '../video/video-password.service'
import { VideoService } from '../video/video.service'
+import { VideoCaptionEdit } from './video-caption-edit.model'
@Injectable()
export class VideoCaptionService {
@@ -74,4 +74,13 @@ export class VideoCaptionService {
getCaptionContent ({ captionPath }: Pick<VideoCaption, 'captionPath'>) {
return this.authHttp.get(environment.originServerUrl + captionPath, { responseType: 'text' })
}
+
+ generateCaption (videoIds: (number | string)[]) {
+ return from(videoIds)
+ .pipe(
+ concatMap(videoId => this.authHttp.post(`${VideoService.BASE_VIDEO_URL}/${videoId}/captions/generate`, {})),
+ toArray(),
+ catchError(err => this.restExtractor.handleError(err))
+ )
+ }
}
diff --git a/client/src/app/shared/shared-main/video/video.model.ts b/client/src/app/shared/shared-main/video/video.model.ts
index cbfb58ce3e..3a9572ec29 100644
--- a/client/src/app/shared/shared-main/video/video.model.ts
+++ b/client/src/app/shared/shared-main/video/video.model.ts
@@ -244,6 +244,10 @@ export class Video implements VideoServerModel {
this.isUpdatableBy(user)
}
+ canGenerateTranscription (user: AuthUser, transcriptionEnabled: boolean) {
+ return transcriptionEnabled && this.isLocal && user.hasRight(UserRight.UPDATE_ANY_VIDEO)
+ }
+
// ---------------------------------------------------------------------------
isOwner (user: AuthUser) {
diff --git a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
index f06c2da57a..5fb84a9666 100644
--- a/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
+++ b/client/src/app/shared/shared-video-miniature/video-actions-dropdown.component.ts
@@ -11,6 +11,7 @@ import {
DropdownButtonSize,
DropdownDirection
} from '../shared-main/buttons/action-dropdown.component'
+import { VideoCaptionService } from '../shared-main/video-caption/video-caption.service'
import { RedundancyService } from '../shared-main/video/redundancy.service'
import { VideoDetails } from '../shared-main/video/video-details.model'
import { Video } from '../shared-main/video/video.model'
@@ -37,6 +38,7 @@ export type VideoActionsDisplayType = {
transcoding?: boolean
studio?: boolean
stats?: boolean
+ generateTranscription?: boolean
}
@Component({
@@ -115,6 +117,7 @@ export class VideoActionsDropdownComponent implements OnChanges {
private videoBlocklistService: VideoBlockService,
private screenService: ScreenService,
private videoService: VideoService,
+ private videoCaptionService: VideoCaptionService,
private redundancyService: RedundancyService,
private serverService: ServerService
) { }
@@ -206,6 +209,10 @@ export class VideoActionsDropdownComponent implements OnChanges {
return this.video.isLiveInfoAvailableBy(this.user)
}
+ canGenerateTranscription () {
+ return this.video.canGenerateTranscription(this.user, this.serverService.getHTMLConfig().videoTranscription.enabled)
+ }
+
isVideoDownloadableByAnonymous () {
return (
this.video &&
@@ -338,7 +345,7 @@ export class VideoActionsDropdownComponent implements OnChanges {
this.videoService.runTranscoding({ videos: [ video ], type, askForForceTranscodingIfNeeded: true })
.subscribe({
next: () => {
- this.notifier.success($localize`Transcoding jobs created for "${video.name}".`)
+ this.notifier.success($localize`Transcoding job created for "${video.name}".`)
this.transcodingCreated.emit()
},
@@ -346,6 +353,17 @@ export class VideoActionsDropdownComponent implements OnChanges {
})
}
+ generateCaption (video: Video) {
+ this.videoCaptionService.generateCaption([ video.id ])
+ .subscribe({
+ next: () => {
+ this.notifier.success($localize`Transcription job created for "${video.name}".`)
+ },
+
+ error: err => this.notifier.error(err.message)
+ })
+ }
+
onVideoBlocked () {
this.videoBlocked.emit()
}
@@ -466,6 +484,14 @@ export class VideoActionsDropdownComponent implements OnChanges {
iconName: 'delete'
}
],
+ [
+ {
+ label: $localize`Generate caption`,
+ handler: ({ video }) => this.generateCaption(video),
+ isDisplayed: () => this.displayOptions.generateTranscription && this.canGenerateTranscription(),
+ iconName: 'video-lang'
+ }
+ ],
[ // actions regarding the account/its server
{
label: $localize`Mute account`,
diff --git a/client/src/app/shared/standalone-notifications/user-notifications.component.html b/client/src/app/shared/standalone-notifications/user-notifications.component.html
index d3367ede9e..c0c8242210 100644
--- a/client/src/app/shared/standalone-notifications/user-notifications.component.html
+++ b/client/src/app/shared/standalone-notifications/user-notifications.component.html
@@ -239,6 +239,14 @@
}
</ng-container>
+ <ng-container *ngSwitchCase="22"> <!-- UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED -->
+ <my-global-icon iconName="video-lang" aria-hidden="true"></my-global-icon>
+
+ <div class="message" i18n>
+ <em>{{ notification.videoCaption.language.label }}</em> transcription of <a (click)="markAsRead(notification)" [routerLink]="notification.videoUrl">your video {{ notification.videoCaption.video.name }}</a> has been generated
+ </div>
+ </ng-container>
+
<ng-container *ngSwitchDefault>
<my-global-icon iconName="alert" aria-hidden="true"></my-global-icon>
diff --git a/config/default.yaml b/config/default.yaml
index f097588ffc..8920e0d37c 100644
--- a/config/default.yaml
+++ b/config/default.yaml
@@ -716,6 +716,34 @@ video_studio:
remote_runners:
enabled: false
+video_transcription:
+ # Enable automatic transcription of videos
+ enabled: false
+
+ # Choose engine for local transcription
+ # Supported: 'openai-whisper' or 'whisper-ctranslate2'
+ engine: 'whisper-ctranslate2'
+
+ # You can set a custom engine path for local transcription
+ # If not provided, PeerTube will try to automatically install it in the PeerTube bin directory
+ engine_path: null
+
+ # Choose engine model for local transcription
+ # Available for 'openai-whisper' and 'whisper-ctranslate2': 'tiny', 'base', 'small', 'medium' or 'large-v3'
+ model: 'small'
+
+ # Or specify the model path:
+ # * PyTorch model file path for 'openai-whisper'
+ # * CTranslate2 Whisper model directory path for 'whisper-ctranslate2'
+ # If not provided, PeerTube will automatically download the model
+ model_path: null
+
+ # Enable remote runners to transcribe videos
+ # If enabled, your instance won't transcribe the videos itself
+ # At least 1 remote runner must be configured to transcribe your videos
+ remote_runners:
+ enabled: false
+
video_file:
update:
# Add ability for users to replace the video file of an existing video
diff --git a/config/production.yaml.example b/config/production.yaml.example
index 0e8fd86ee1..0296b7e569 100644
--- a/config/production.yaml.example
+++ b/config/production.yaml.example
@@ -726,6 +726,34 @@ video_studio:
remote_runners:
enabled: false
+video_transcription:
+ # Enable automatic transcription of videos
+ enabled: false
+
+ # Choose engine for local transcription
+ # Supported: 'openai-whisper' or 'whisper-ctranslate2'
+ engine: 'whisper-ctranslate2'
+
+ # You can set a custom engine path for local transcription
+ # If not provided, PeerTube will try to automatically install it in the PeerTube bin directory
+ engine_path: null
+
+ # Choose engine model for local transcription
+ # Available for 'openai-whisper' and 'whisper-ctranslate2': 'tiny', 'base', 'small', 'medium' or 'large-v3'
+ model: 'small'
+
+ # Or specify the model path:
+ # * PyTorch model file path for 'openai-whisper'
+ # * CTranslate2 Whisper model directory path for 'whisper-ctranslate2'
+ # If not provided, PeerTube will automatically download the model
+ model_path: null
+
+ # Enable remote runners to transcribe videos
+ # If enabled, your instance won't transcribe the videos itself
+ # At least 1 remote runner must be configured to transcribe your videos
+ remote_runners:
+ enabled: false
+
video_file:
update:
# Add ability for users to replace the video file of an existing video
diff --git a/config/test.yaml b/config/test.yaml
index e3ac19cefd..4be2d25d96 100644
--- a/config/test.yaml
+++ b/config/test.yaml
@@ -166,3 +166,6 @@ open_telemetry:
search:
search_index:
url: 'https://search.joinpeertube.org/'
+
+video_transcription:
+ model: 'tiny'
diff --git a/packages/ffmpeg/src/ffmpeg-command-wrapper.ts b/packages/ffmpeg/src/ffmpeg-command-wrapper.ts
index 482d20320e..9dd867299c 100644
--- a/packages/ffmpeg/src/ffmpeg-command-wrapper.ts
+++ b/packages/ffmpeg/src/ffmpeg-command-wrapper.ts
@@ -1,14 +1,13 @@
import { pick, promisify0 } from '@peertube/peertube-core-utils'
-import { AvailableEncoders, EncoderOptionsBuilder, EncoderOptionsBuilderParams, EncoderProfile } from '@peertube/peertube-models'
+import {
+ AvailableEncoders,
+ EncoderOptionsBuilder,
+ EncoderOptionsBuilderParams,
+ EncoderProfile,
+ SimpleLogger
+} from '@peertube/peertube-models'
import ffmpeg, { FfmpegCommand } from 'fluent-ffmpeg'
-type FFmpegLogger = {
- info: (msg: string, obj?: object) => void
- debug: (msg: string, obj?: object) => void
- warn: (msg: string, obj?: object) => void
- error: (msg: string, obj?: object) => void
-}
-
export interface FFmpegCommandWrapperOptions {
availableEncoders?: AvailableEncoders
profile?: string
@@ -17,7 +16,7 @@ export interface FFmpegCommandWrapperOptions {
tmpDirectory: string
threads: number
- logger: FFmpegLogger
+ logger: SimpleLogger
lTags?: { tags: string[] }
updateJobProgress?: (progress?: number) => void
@@ -35,7 +34,7 @@ export class FFmpegCommandWrapper {
private readonly tmpDirectory: string
private readonly threads: number
- private readonly logger: FFmpegLogger
+ private readonly logger: SimpleLogger
private readonly lTags: { tags: string[] }
private readonly updateJobProgress: (progress?: number) => void
diff --git a/packages/jiwer/README.md b/packages/jiwer/README.md
deleted file mode 100644
index 663c399bfc..0000000000
--- a/packages/jiwer/README.md
+++ /dev/null
@@ -1,37 +0,0 @@
-JiWER
-=====
-__JiWER__ CLI NodeJs wrapper.
-
-> *JiWER is a python tool for computing the word-error-rate of ASR systems.*
-> https://jitsi.github.io/jiwer/cli/
-
-__JiWER__ serves as a reference implementation to calculate errors rates between 2 text files:
-- WER (Word Error Rate)
-- CER (Character Error Rate)
-
-Build
------
-
-```sh
-npm run build
-```
-
-Usage
------
-```typescript
-const jiwerCLI = new JiwerClI('./reference.txt', './hypothesis.txt')
-
-// WER as a percentage, ex: 0.03 -> 3%
-console.log(await jiwerCLI.wer())
-
-// CER as a percentage: 0.01 -> 1%
-console.log(await jiwerCLI.cer())
-
-// Detailed comparison report
-console.log(await jiwerCLI.alignment())
-```
-
-Resources
----------
-- https://jitsi.github.io/jiwer/
-- https://github.com/rapidfuzz/RapidFuzz
diff --git a/packages/jiwer/requirements.txt b/packages/jiwer/requirements.txt
deleted file mode 100644
index 53d9fb34b3..0000000000
--- a/packages/jiwer/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-jiwer==3.0.4
diff --git a/packages/jiwer/src/index.ts b/packages/jiwer/src/index.ts
deleted file mode 100644
index 586fd08439..0000000000
--- a/packages/jiwer/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './jiwer-cli.js'
diff --git a/packages/models/src/common/index.ts b/packages/models/src/common/index.ts
index 1f8ebdd94b..846164d8f4 100644
--- a/packages/models/src/common/index.ts
+++ b/packages/models/src/common/index.ts
@@ -1,2 +1,3 @@
export * from './file-storage.enum.js'
export * from './result-list.model.js'
+export * from './simple-logger.model.js'
diff --git a/packages/models/src/common/simple-logger.model.ts b/packages/models/src/common/simple-logger.model.ts
new file mode 100644
index 0000000000..7561ac4b66
--- /dev/null
+++ b/packages/models/src/common/simple-logger.model.ts
@@ -0,0 +1,6 @@
+export type SimpleLogger = {
+ info: (msg: string, obj?: object) => void
+ debug: (msg: string, obj?: object) => void
+ warn: (msg: string, obj?: object) => void
+ error: (msg: string, obj?: object) => void
+}
diff --git a/packages/models/src/runners/runner-job-payload.model.ts b/packages/models/src/runners/runner-job-payload.model.ts
index 19b9d649bb..605e216cf0 100644
--- a/packages/models/src/runners/runner-job-payload.model.ts
+++ b/packages/models/src/runners/runner-job-payload.model.ts
@@ -8,7 +8,8 @@ export type RunnerJobVODPayload =
export type RunnerJobPayload =
RunnerJobVODPayload |
RunnerJobLiveRTMPHLSTranscodingPayload |
- RunnerJobStudioTranscodingPayload
+ RunnerJobStudioTranscodingPayload |
+ RunnerJobTranscriptionPayload
// ---------------------------------------------------------------------------
@@ -54,6 +55,12 @@ export interface RunnerJobStudioTranscodingPayload {
tasks: VideoStudioTaskPayload[]
}
+export interface RunnerJobTranscriptionPayload {
+ input: {
+ videoFileUrl: string
+ }
+}
+
// ---------------------------------------------------------------------------
export function isAudioMergeTranscodingPayload (payload: RunnerJobPayload): payload is RunnerJobVODAudioMergeTranscodingPayload {
diff --git a/packages/models/src/runners/runner-job-private-payload.model.ts b/packages/models/src/runners/runner-job-private-payload.model.ts
index 3c9f08de6d..3a1398bc70 100644
--- a/packages/models/src/runners/runner-job-private-payload.model.ts
+++ b/packages/models/src/runners/runner-job-private-payload.model.ts
@@ -8,7 +8,8 @@ export type RunnerJobVODPrivatePayload =
export type RunnerJobPrivatePayload =
RunnerJobVODPrivatePayload |
RunnerJobLiveRTMPHLSTranscodingPrivatePayload |
- RunnerJobVideoStudioTranscodingPrivatePayload
+ RunnerJobVideoStudioTranscodingPrivatePayload |
+ RunnerJobTranscriptionPrivatePayload
// ---------------------------------------------------------------------------
@@ -45,3 +46,9 @@ export interface RunnerJobVideoStudioTranscodingPrivatePayload {
videoUUID: string
originalTasks: VideoStudioTaskPayload[]
}
+
+// ---------------------------------------------------------------------------
+
+export interface RunnerJobTranscriptionPrivatePayload {
+ videoUUID: string
+}
diff --git a/packages/models/src/runners/runner-job-success-body.model.ts b/packages/models/src/runners/runner-job-success-body.model.ts
index f45336b059..541f815ca3 100644
--- a/packages/models/src/runners/runner-job-success-body.model.ts
+++ b/packages/models/src/runners/runner-job-success-body.model.ts
@@ -12,7 +12,8 @@ export type RunnerJobSuccessPayload =
VODHLSTranscodingSuccess |
VODAudioMergeTranscodingSuccess |
LiveRTMPHLSTranscodingSuccess |
- VideoStudioTranscodingSuccess
+ VideoStudioTranscodingSuccess |
+ TranscriptionSuccess
export interface VODWebVideoTranscodingSuccess {
videoFile: Blob | string
@@ -35,6 +36,12 @@ export interface VideoStudioTranscodingSuccess {
videoFile: Blob | string
}
+export interface TranscriptionSuccess {
+ inputLanguage: string
+
+ vttFile: Blob | string
+}
+
export function isWebVideoOrAudioMergeTranscodingPayloadSuccess (
payload: RunnerJobSuccessPayload
): payload is VODHLSTranscodingSuccess | VODAudioMergeTranscodingSuccess {
@@ -44,3 +51,7 @@ export function isWebVideoOrAudioMergeTranscodingPayloadSuccess (
export function isHLSTranscodingPayloadSuccess (payload: RunnerJobSuccessPayload): payload is VODHLSTranscodingSuccess {
return !!(payload as VODHLSTranscodingSuccess)?.resolutionPlaylistFile
}
+
+export function isTranscriptionPayloadSuccess (payload: RunnerJobSuccessPayload): payload is TranscriptionSuccess {
+ return !!(payload as TranscriptionSuccess)?.vttFile
+}
diff --git a/packages/models/src/runners/runner-job-type.type.ts b/packages/models/src/runners/runner-job-type.type.ts
index 91b92a7294..0456e788cf 100644
--- a/packages/models/src/runners/runner-job-type.type.ts
+++ b/packages/models/src/runners/runner-job-type.type.ts
@@ -3,4 +3,5 @@ export type RunnerJobType =
'vod-hls-transcoding' |
'vod-audio-merge-transcoding' |
'live-rtmp-hls-transcoding' |
- 'video-studio-transcoding'
+ 'video-studio-transcoding' |
+ 'video-transcription'
diff --git a/packages/models/src/server/custom-config.model.ts b/packages/models/src/server/custom-config.model.ts
index a443525df2..f053dc6acd 100644
--- a/packages/models/src/server/custom-config.model.ts
+++ b/packages/models/src/server/custom-config.model.ts
@@ -179,6 +179,14 @@ export interface CustomConfig {
}
}
+ videoTranscription: {
+ enabled: boolean
+
+ remoteRunners: {
+ enabled: boolean
+ }
+ }
+
videoFile: {
update: {
enabled: boolean
diff --git a/packages/models/src/server/job.model.ts b/packages/models/src/server/job.model.ts
index 7713a9d3e7..8402f6cb4b 100644
--- a/packages/models/src/server/job.model.ts
+++ b/packages/models/src/server/job.model.ts
@@ -33,6 +33,7 @@ export type JobType =
| 'generate-video-storyboard'
| 'create-user-export'
| 'import-user-archive'
+ | 'video-transcription'
export interface Job {
id: number | string
@@ -101,11 +102,16 @@ export interface VideoImportYoutubeDLPayload {
type: VideoImportYoutubeDLPayloadType
videoImportId: number
+ generateTranscription: boolean
+
fileExt?: string
}
export interface VideoImportTorrentPayload {
type: VideoImportTorrentPayloadType
+
+ generateTranscription: boolean
+
videoImportId: number
}
@@ -316,3 +322,9 @@ export interface CreateUserExportPayload {
export interface ImportUserArchivePayload {
userImportId: number
}
+
+// ---------------------------------------------------------------------------
+
+export interface VideoTranscriptionPayload {
+ videoUUID: string
+}
diff --git a/packages/models/src/server/server-config.model.ts b/packages/models/src/server/server-config.model.ts
index 2e3626854f..3d26d2efbf 100644
--- a/packages/models/src/server/server-config.model.ts
+++ b/packages/models/src/server/server-config.model.ts
@@ -346,6 +346,10 @@ export interface ServerConfig {
storyboards: {
enabled: boolean
}
+
+ videoTranscription: {
+ enabled: boolean
+ }
}
export type HTMLServerConfig = Omit<ServerConfig, 'signup'>
diff --git a/packages/models/src/server/server-error-code.enum.ts b/packages/models/src/server/server-error-code.enum.ts
index 156525c795..53811d55cf 100644
--- a/packages/models/src/server/server-error-code.enum.ts
+++ b/packages/models/src/server/server-error-code.enum.ts
@@ -3,58 +3,59 @@ export const ServerErrorCode = {
* The simplest form of payload too large: when the file size is over the
* global file size limit
*/
- MAX_FILE_SIZE_REACHED:'max_file_size_reached',
+ MAX_FILE_SIZE_REACHED: 'max_file_size_reached',
/**
* The payload is too large for the user quota set
*/
- QUOTA_REACHED:'quota_reached',
+ QUOTA_REACHED: 'quota_reached',
/**
* Error yielded upon trying to access a video that is not federated, nor can
- * be. This may be due to: remote videos on instances that are not followed by
+ * be. This may be due to: remote videos on instances that are not followed by
* yours, and with your instance disallowing unknown instances being accessed.
*/
- DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS:'does_not_respect_follow_constraints',
+ DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS: 'does_not_respect_follow_constraints',
- LIVE_NOT_ENABLED:'live_not_enabled',
- LIVE_NOT_ALLOWING_REPLAY:'live_not_allowing_replay',
- LIVE_CONFLICTING_PERMANENT_AND_SAVE_REPLAY:'live_conflicting_permanent_and_save_replay',
+ LIVE_NOT_ENABLED: 'live_not_enabled',
+ LIVE_NOT_ALLOWING_REPLAY: 'live_not_allowing_replay',
+ LIVE_CONFLICTING_PERMANENT_AND_SAVE_REPLAY: 'live_conflicting_permanent_and_save_replay',
/**
- * Pretty self-explanatory: the set maximum number of simultaneous lives was
+ * Pretty self-explanatory: the set maximum number of simultaneous lives was
* reached, and this error is typically there to inform the user trying to
* broadcast one.
*/
- MAX_INSTANCE_LIVES_LIMIT_REACHED:'max_instance_lives_limit_reached',
+ MAX_INSTANCE_LIVES_LIMIT_REACHED: 'max_instance_lives_limit_reached',
/**
- * Pretty self-explanatory: the set maximum number of simultaneous lives FOR
+ * Pretty self-explanatory: the set maximum number of simultaneous lives FOR
* THIS USER was reached, and this error is typically there to inform the user
* trying to broadcast one.
*/
- MAX_USER_LIVES_LIMIT_REACHED:'max_user_lives_limit_reached',
+ MAX_USER_LIVES_LIMIT_REACHED: 'max_user_lives_limit_reached',
/**
* A torrent should have at most one correct video file. Any more and we will
* not be able to choose automatically.
*/
- INCORRECT_FILES_IN_TORRENT:'incorrect_files_in_torrent',
+ INCORRECT_FILES_IN_TORRENT: 'incorrect_files_in_torrent',
- COMMENT_NOT_ASSOCIATED_TO_VIDEO:'comment_not_associated_to_video',
+ COMMENT_NOT_ASSOCIATED_TO_VIDEO: 'comment_not_associated_to_video',
- MISSING_TWO_FACTOR:'missing_two_factor',
- INVALID_TWO_FACTOR:'invalid_two_factor',
+ MISSING_TWO_FACTOR: 'missing_two_factor',
+ INVALID_TWO_FACTOR: 'invalid_two_factor',
- ACCOUNT_WAITING_FOR_APPROVAL:'account_waiting_for_approval',
- ACCOUNT_APPROVAL_REJECTED:'account_approval_rejected',
+ ACCOUNT_WAITING_FOR_APPROVAL: 'account_waiting_for_approval',
+ ACCOUNT_APPROVAL_REJECTED: 'account_approval_rejected',
- RUNNER_JOB_NOT_IN_PROCESSING_STATE:'runner_job_not_in_processing_state',
- RUNNER_JOB_NOT_IN_PENDING_STATE:'runner_job_not_in_pending_state',
- UNKNOWN_RUNNER_TOKEN:'unknown_runner_token',
+ RUNNER_JOB_NOT_IN_PROCESSING_STATE: 'runner_job_not_in_processing_state',
+ RUNNER_JOB_NOT_IN_PENDING_STATE: 'runner_job_not_in_pending_state',
+ UNKNOWN_RUNNER_TOKEN: 'unknown_runner_token',
- VIDEO_REQUIRES_PASSWORD:'video_requires_password',
- INCORRECT_VIDEO_PASSWORD:'incorrect_video_password',
+ VIDEO_REQUIRES_PASSWORD: 'video_requires_password',
+ INCORRECT_VIDEO_PASSWORD: 'incorrect_video_password',
- VIDEO_ALREADY_BEING_TRANSCODED:'video_already_being_transcoded',
+ VIDEO_ALREADY_BEING_TRANSCODED: 'video_already_being_transcoded',
+ VIDEO_ALREADY_BEING_TRANSCRIBED: 'video_already_being_transcribed',
MAX_USER_VIDEO_QUOTA_EXCEEDED_FOR_USER_EXPORT: 'max_user_video_quota_exceeded_for_user_export'
} as const
diff --git a/packages/models/src/users/user-notification-setting.model.ts b/packages/models/src/users/user-notification-setting.model.ts
index fbd94994e5..64d8cfb2da 100644
--- a/packages/models/src/users/user-notification-setting.model.ts
+++ b/packages/models/src/users/user-notification-setting.model.ts
@@ -31,4 +31,6 @@ export interface UserNotificationSetting {
newPluginVersion: UserNotificationSettingValueType
myVideoStudioEditionFinished: UserNotificationSettingValueType
+
+ myVideoTranscriptionGenerated: UserNotificationSettingValueType
}
diff --git a/packages/models/src/users/user-notification.model.ts b/packages/models/src/users/user-notification.model.ts
index e8435f031a..362c080ec7 100644
--- a/packages/models/src/users/user-notification.model.ts
+++ b/packages/models/src/users/user-notification.model.ts
@@ -1,6 +1,7 @@
import { FollowState } from '../actors/index.js'
import { AbuseStateType } from '../moderation/index.js'
import { PluginType_Type } from '../plugins/index.js'
+import { VideoConstant } from '../videos/video-constant.model.js'
export const UserNotificationType = {
NEW_VIDEO_FROM_SUBSCRIPTION: 1,
@@ -36,7 +37,9 @@ export const UserNotificationType = {
NEW_USER_REGISTRATION_REQUEST: 20,
- NEW_LIVE_FROM_SUBSCRIPTION: 21
+ NEW_LIVE_FROM_SUBSCRIPTION: 21,
+
+ MY_VIDEO_TRANSCRIPTION_GENERATED: 22
} as const
export type UserNotificationType_Type = typeof UserNotificationType[keyof typeof UserNotificationType]
@@ -138,6 +141,12 @@ export interface UserNotification {
username: string
}
+ videoCaption?: {
+ id: number
+ language: VideoConstant<string>
+ video: VideoInfo
+ }
+
createdAt: string
updatedAt: string
}
diff --git a/packages/models/src/videos/caption/index.ts b/packages/models/src/videos/caption/index.ts
index a175768ce1..bd48c25546 100644
--- a/packages/models/src/videos/caption/index.ts
+++ b/packages/models/src/videos/caption/index.ts
@@ -1,2 +1,3 @@
-export * from './video-caption.model.js'
+export * from './video-caption-generate.model.js'
export * from './video-caption-update.model.js'
+export * from './video-caption.model.js'
diff --git a/packages/models/src/videos/caption/video-caption-generate.model.ts b/packages/models/src/videos/caption/video-caption-generate.model.ts
new file mode 100644
index 0000000000..996e622eca
--- /dev/null
+++ b/packages/models/src/videos/caption/video-caption-generate.model.ts
@@ -0,0 +1,3 @@
+export interface VideoCaptionGenerate {
+ forceTranscription?: boolean // Default false
+}
diff --git a/packages/models/src/videos/import/video-import-create.model.ts b/packages/models/src/videos/import/video-import-create.model.ts
index 3ec0d22f36..81618631a8 100644
--- a/packages/models/src/videos/import/video-import-create.model.ts
+++ b/packages/models/src/videos/import/video-import-create.model.ts
@@ -5,5 +5,8 @@ export interface VideoImportCreate extends VideoUpdate {
magnetUri?: string
torrentfile?: Blob
+ // Default is true if the feature is enabled by the instance admin
+ generateTranscription?: boolean
+
channelId: number // Required
}
diff --git a/packages/models/src/videos/video-create.model.ts b/packages/models/src/videos/video-create.model.ts
index 0eca383726..6fa72fde01 100644
--- a/packages/models/src/videos/video-create.model.ts
+++ b/packages/models/src/videos/video-create.model.ts
@@ -27,4 +27,7 @@ export interface VideoCreate {
thumbnailfile?: Blob | string
previewfile?: Blob | string
+
+ // Default is true if the feature is enabled by the instance admin
+ generateTranscription?: boolean
}
diff --git a/packages/server-commands/src/runners/runner-jobs-command.ts b/packages/server-commands/src/runners/runner-jobs-command.ts
index 4e702199f4..64bcc5655f 100644
--- a/packages/server-commands/src/runners/runner-jobs-command.ts
+++ b/packages/server-commands/src/runners/runner-jobs-command.ts
@@ -5,9 +5,6 @@ import {
AcceptRunnerJobResult,
ErrorRunnerJobBody,
HttpStatusCode,
- isHLSTranscodingPayloadSuccess,
- isLiveRTMPHLSTranscodingUpdatePayload,
- isWebVideoOrAudioMergeTranscodingPayloadSuccess,
ListRunnerJobsQuery,
RequestRunnerJobBody,
RequestRunnerJobResult,
@@ -22,8 +19,13 @@ import {
RunnerJobType,
RunnerJobUpdateBody,
RunnerJobVODPayload,
+ TranscriptionSuccess,
VODHLSTranscodingSuccess,
- VODWebVideoTranscodingSuccess
+ VODWebVideoTranscodingSuccess,
+ isHLSTranscodingPayloadSuccess,
+ isLiveRTMPHLSTranscodingUpdatePayload,
+ isTranscriptionPayloadSuccess,
+ isWebVideoOrAudioMergeTranscodingPayloadSuccess
} from '@peertube/peertube-models'
import { unwrapBody } from '../requests/index.js'
import { waitJobs } from '../server/jobs.js'
@@ -196,6 +198,12 @@ export class RunnerJobsCommand extends AbstractCommand {
payloadWithoutFiles = omit(payloadWithoutFiles as VODHLSTranscodingSuccess, [ 'resolutionPlaylistFile' ])
}
+ if (isTranscriptionPayloadSuccess(payload) && payload.vttFile) {
+ attaches[`payload[vttFile]`] = payload.vttFile
+
+ payloadWithoutFiles = omit(payloadWithoutFiles as TranscriptionSuccess, [ 'vttFile' ])
+ }
+
return this.postUploadRequest({
...options,
diff --git a/packages/server-commands/src/server/config-command.ts b/packages/server-commands/src/server/config-command.ts
index 874fb3c5a2..ed648818e7 100644
--- a/packages/server-commands/src/server/config-command.ts
+++ b/packages/server-commands/src/server/config-command.ts
@@ -355,6 +355,29 @@ export class ConfigCommand extends AbstractCommand {
// ---------------------------------------------------------------------------
+ enableTranscription ({ remote = false }: { remote?: boolean } = {}) {
+ return this.setTranscriptionEnabled(true, remote)
+ }
+
+ disableTranscription () {
+ return this.setTranscriptionEnabled(false, false)
+ }
+
+ private setTranscriptionEnabled (enabled: boolean, remoteEnabled: boolean) {
+ return this.updateExistingConfig({
+ newConfig: {
+ videoTranscription: {
+ enabled,
+ remoteRunners: {
+ enabled: remoteEnabled
+ }
+ }
+ }
+ })
+ }
+
+ // ---------------------------------------------------------------------------
+
getConfig (options: OverrideCommandOptions = {}) {
const path = '/api/v1/config'
diff --git a/packages/server-commands/src/shared/abstract-command.ts b/packages/server-commands/src/shared/abstract-command.ts
index 116b028473..665bf13f8e 100644
--- a/packages/server-commands/src/shared/abstract-command.ts
+++ b/packages/server-commands/src/shared/abstract-command.ts
@@ -1,7 +1,10 @@
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
-import { isAbsolute } from 'path'
+import { HttpStatusCode, HttpStatusCodeType } from '@peertube/peertube-models'
import { buildAbsoluteFixturePath, getFileSize } from '@peertube/peertube-node-utils'
+import { expect } from 'chai'
+import got, { Response as GotResponse } from 'got'
+import { isAbsolute } from 'path'
import {
makeDeleteRequest,
makeGetRequest,
@@ -11,12 +14,9 @@ import {
unwrapBody,
unwrapText
} from '../requests/requests.js'
-import { expect } from 'chai'
-import got, { Response as GotResponse } from 'got'
-import { HttpStatusCode, HttpStatusCodeType } from '@peertube/peertube-models'
-import type { PeerTubeServer } from '../server/server.js'
import { createReadStream } from 'fs'
+import type { PeerTubeServer } from '../server/server.js'
export interface OverrideCommandOptions {
token?: string
diff --git a/packages/server-commands/src/videos/captions-command.ts b/packages/server-commands/src/videos/captions-command.ts
index a8336aa278..3834b4dbb6 100644
--- a/packages/server-commands/src/videos/captions-command.ts
+++ b/packages/server-commands/src/videos/captions-command.ts
@@ -1,3 +1,4 @@
+import { pick } from '@peertube/peertube-core-utils'
import { HttpStatusCode, ResultList, VideoCaption } from '@peertube/peertube-models'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
@@ -32,6 +33,23 @@ export class CaptionsCommand extends AbstractCommand {
})
}
+ runGenerate (options: OverrideCommandOptions & {
+ videoId: string | number
+ forceTranscription?: boolean
+ }) {
+ const { videoId } = options
+ const path = '/api/v1/videos/' + videoId + '/captions/generate'
+
+ return this.postBodyRequest({
+ ...options,
+
+ path,
+ fields: pick(options, [ 'forceTranscription' ]),
+ implicitToken: true,
+ defaultExpectedStatus: HttpStatusCode.NO_CONTENT_204
+ })
+ }
+
list (options: OverrideCommandOptions & {
videoId: string | number
videoPassword?: string
diff --git a/packages/server-commands/src/videos/video-imports-command.ts b/packages/server-commands/src/videos/video-imports-command.ts
index c60d787c9b..b0c22d332c 100644
--- a/packages/server-commands/src/videos/video-imports-command.ts
+++ b/packages/server-commands/src/videos/video-imports-command.ts
@@ -4,12 +4,19 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared/index.js'
export class VideoImportsCommand extends AbstractCommand {
- importVideo (options: OverrideCommandOptions & {
- attributes: (VideoImportCreate | { torrentfile?: string, previewfile?: string, thumbnailfile?: string })
+ async importVideo (options: OverrideCommandOptions & {
+ attributes: (Partial<VideoImportCreate> | { torrentfile?: string, previewfile?: string, thumbnailfile?: string })
}) {
const { attributes } = options
const path = '/api/v1/videos/imports'
+ let defaultChannelId = 1
+
+ try {
+ const { videoChannels } = await this.server.users.getMyInfo({ token: options.token })
+ defaultChannelId = videoChannels[0].id
+ } catch (e) { /* empty */ }
+
let attaches: any = {}
if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile }
if (attributes.thumbnailfile) attaches = { thumbnailfile: attributes.thumbnailfile }
@@ -20,7 +27,11 @@ export class VideoImportsCommand extends AbstractCommand {
path,
attaches,
- fields: options.attributes,
+ fields: {
+ channelId: defaultChannelId,
+
+ ...options.attributes
+ },
implicitToken: true,
defaultExpectedStatus: HttpStatusCode.OK_200
}))
diff --git a/packages/tests/fixtures/transcription/videos/communiquer-lors-dune-classe-transplantee.mp4 b/packages/tests/fixtures/transcription/videos/communiquer-lors-dune-classe-transplantee.mp4
index 4ef5b6ee13..4f18cb0c19 100644
Binary files a/packages/tests/fixtures/transcription/videos/communiquer-lors-dune-classe-transplantee.mp4 and b/packages/tests/fixtures/transcription/videos/communiquer-lors-dune-classe-transplantee.mp4 differ
diff --git a/packages/tests/fixtures/transcription/videos/derive_sectaire.mp4 b/packages/tests/fixtures/transcription/videos/derive_sectaire.mp4
index f6969a62b3..6f4ebc7fd7 100644
Binary files a/packages/tests/fixtures/transcription/videos/derive_sectaire.mp4 and b/packages/tests/fixtures/transcription/videos/derive_sectaire.mp4 differ
diff --git a/packages/tests/package.json b/packages/tests/package.json
index 02882ebc72..566712bf2a 100644
--- a/packages/tests/package.json
+++ b/packages/tests/package.json
@@ -6,7 +6,8 @@
"devDependencies": {},
"scripts": {
"build": "tsc",
- "watch": "tsc -w"
+ "watch": "tsc -w",
+ "install-dependencies:transcription": "pip install -r ./requirements.txt ../transcription-devtools/requirements.txt"
},
"dependencies": {}
}
diff --git a/packages/tests/requirements.txt b/packages/tests/requirements.txt
new file mode 100644
index 0000000000..2efc72264b
--- /dev/null
+++ b/packages/tests/requirements.txt
@@ -0,0 +1,2 @@
+whisper-ctranslate2
+openai-whisper
diff --git a/packages/tests/src/api/check-params/index.ts b/packages/tests/src/api/check-params/index.ts
index d92210d346..17fc996c97 100644
--- a/packages/tests/src/api/check-params/index.ts
+++ b/packages/tests/src/api/check-params/index.ts
@@ -42,6 +42,7 @@ import './video-source.js'
import './video-storyboards.js'
import './video-studio.js'
import './video-token.js'
+import './video-transcription.js'
import './videos-common-filters.js'
import './videos-history.js'
import './videos-overviews.js'
diff --git a/packages/tests/src/api/check-params/user-notifications.ts b/packages/tests/src/api/check-params/user-notifications.ts
index cf20324a1f..cdbf09b626 100644
--- a/packages/tests/src/api/check-params/user-notifications.ts
+++ b/packages/tests/src/api/check-params/user-notifications.ts
@@ -171,6 +171,7 @@ describe('Test user notifications API validators', function () {
abuseStateChange: UserNotificationSettingValue.WEB,
newPeerTubeVersion: UserNotificationSettingValue.WEB,
myVideoStudioEditionFinished: UserNotificationSettingValue.WEB,
+ myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB,
newPluginVersion: UserNotificationSettingValue.WEB
}
diff --git a/packages/tests/src/api/check-params/video-transcription.ts b/packages/tests/src/api/check-params/video-transcription.ts
new file mode 100644
index 0000000000..fc28924a5e
--- /dev/null
+++ b/packages/tests/src/api/check-params/video-transcription.ts
@@ -0,0 +1,106 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { HttpStatusCode, UserRole } from '@peertube/peertube-models'
+import {
+ PeerTubeServer,
+ cleanupTests,
+ createMultipleServers,
+ doubleFollow,
+ setAccessTokensToServers,
+ waitJobs
+} from '@peertube/peertube-server-commands'
+
+describe('Test video transcription API validator', function () {
+ let servers: PeerTubeServer[]
+
+ let userToken: string
+ let anotherUserToken: string
+
+ let remoteId: string
+ let validId: string
+
+ // ---------------------------------------------------------------
+
+ before(async function () {
+ this.timeout(240000)
+
+ servers = await createMultipleServers(2)
+ await setAccessTokensToServers(servers)
+
+ await doubleFollow(servers[0], servers[1])
+
+ userToken = await servers[0].users.generateUserAndToken('user', UserRole.USER)
+ anotherUserToken = await servers[0].users.generateUserAndToken('user2', UserRole.USER)
+
+ {
+ const { uuid } = await servers[1].videos.quickUpload({ name: 'remote video' })
+ remoteId = uuid
+ }
+
+ {
+ const { uuid } = await servers[0].videos.quickUpload({ name: 'both 1', token: userToken })
+ validId = uuid
+ }
+
+ await waitJobs(servers)
+
+ await servers[0].config.enableTranscription()
+ })
+
+ it('Should not run transcription of an unknown video', async function () {
+ await servers[0].captions.runGenerate({ videoId: 404, expectedStatus: HttpStatusCode.NOT_FOUND_404 })
+ })
+
+ it('Should not run transcription of a remote video', async function () {
+ await servers[0].captions.runGenerate({ videoId: remoteId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+ })
+
+ it('Should not run transcription by a owner/moderator user', async function () {
+ await servers[0].captions.runGenerate({ videoId: validId, token: anotherUserToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })
+ })
+
+ it('Should not run transcription if a caption file already exists', async function () {
+ await servers[0].captions.add({
+ language: 'en',
+ videoId: validId,
+ fixture: 'subtitle-good1.vtt'
+ })
+
+ await servers[0].captions.runGenerate({ videoId: validId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+
+ await servers[0].captions.delete({ language: 'en', videoId: validId })
+ })
+
+ it('Should not run transcription if the instance disabled it', async function () {
+ await servers[0].config.disableTranscription()
+
+ await servers[0].captions.runGenerate({ videoId: validId, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })
+
+ await servers[0].config.enableTranscription()
+ })
+
+ it('Should succeed to run transcription', async function () {
+ await servers[0].captions.runGenerate({ videoId: validId, token: userToken })
+ })
+
+ it('Should fail to run transcription twice', async function () {
+ await servers[0].captions.runGenerate({ videoId: validId, token: userToken, expectedStatus: HttpStatusCode.CONFLICT_409 })
+ })
+
+ it('Should fail to run transcription twice with a non-admin user with the forceTranscription boolean', async function () {
+ await servers[0].captions.runGenerate({
+ videoId: validId,
+ token: userToken,
+ forceTranscription: true,
+ expectedStatus: HttpStatusCode.FORBIDDEN_403
+ })
+ })
+
+ it('Should succeed to run transcription twice with the forceTranscription boolean', async function () {
+ await servers[0].captions.runGenerate({ videoId: validId, forceTranscription: true })
+ })
+
+ after(async function () {
+ await cleanupTests(servers)
+ })
+})
diff --git a/packages/tests/src/api/notifications/caption-notifications.ts b/packages/tests/src/api/notifications/caption-notifications.ts
new file mode 100644
index 0000000000..4d584ec0b6
--- /dev/null
+++ b/packages/tests/src/api/notifications/caption-notifications.ts
@@ -0,0 +1,81 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { UserNotification } from '@peertube/peertube-models'
+import { PeerTubeServer, cleanupTests, waitJobs } from '@peertube/peertube-server-commands'
+import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'
+import {
+ CheckerBaseParams,
+ checkMyVideoTranscriptionGenerated,
+ prepareNotificationsTest
+} from '@tests/shared/notifications.js'
+import { join } from 'path'
+
+describe('Test caption notifications', function () {
+ let servers: PeerTubeServer[] = []
+
+ let userNotifications: UserNotification[] = []
+ let emails: object[] = []
+ let userAccessToken: string
+
+ before(async function () {
+ this.timeout(120000)
+
+ const res = await prepareNotificationsTest(1)
+ emails = res.emails
+ userAccessToken = res.userAccessToken
+ servers = res.servers
+ userNotifications = res.userNotifications
+ })
+
+ describe('Transcription of my video generated is published', function () {
+ const language = { id: 'en', label: 'English' }
+ let baseParams: CheckerBaseParams
+
+ before(() => {
+ baseParams = {
+ server: servers[0],
+ emails,
+ socketNotifications: userNotifications,
+ token: userAccessToken
+ }
+ })
+
+ async function uploadAndWait () {
+ const { uuid } = await servers[0].videos.upload({
+ token: userAccessToken,
+ attributes: {
+ name: 'video',
+ fixture: join('transcription', 'videos', 'the_last_man_on_earth.mp4'),
+ language: undefined
+ }
+ })
+ await waitJobs(servers)
+
+ return servers[0].videos.get({ id: uuid })
+ }
+
+ it('Should not send a notification if transcription is not enabled', async function () {
+ this.timeout(50000)
+
+ const { name, shortUUID } = await uploadAndWait()
+
+ await checkMyVideoTranscriptionGenerated({ ...baseParams, videoName: name, shortUUID, language, checkType: 'absence' })
+ })
+
+ it('Should send a notification transcription is enabled', async function () {
+ this.timeout(240000)
+
+ await servers[0].config.enableTranscription()
+
+ const { name, shortUUID } = await uploadAndWait()
+
+ await checkMyVideoTranscriptionGenerated({ ...baseParams, videoName: name, shortUUID, language, checkType: 'presence' })
+ })
+ })
+
+ after(async function () {
+ MockSmtpServer.Instance.kill()
+
+ await cleanupTests(servers)
+ })
+})
diff --git a/packages/tests/src/api/notifications/index.ts b/packages/tests/src/api/notifications/index.ts
index d63d941828..977c4159fb 100644
--- a/packages/tests/src/api/notifications/index.ts
+++ b/packages/tests/src/api/notifications/index.ts
@@ -1,4 +1,5 @@
import './admin-notifications.js'
+import './captions-notifications.js'
import './comments-notifications.js'
import './moderation-notifications.js'
import './notifications-api.js'
diff --git a/packages/tests/src/api/runners/index.ts b/packages/tests/src/api/runners/index.ts
index 441ddc8746..ed82228920 100644
--- a/packages/tests/src/api/runners/index.ts
+++ b/packages/tests/src/api/runners/index.ts
@@ -2,4 +2,5 @@ export * from './runner-common.js'
export * from './runner-live-transcoding.js'
export * from './runner-socket.js'
export * from './runner-studio-transcoding.js'
+export * from './runner-transcription.js'
export * from './runner-vod-transcoding.js'
diff --git a/packages/tests/src/api/runners/runner-transcription.ts b/packages/tests/src/api/runners/runner-transcription.ts
new file mode 100644
index 0000000000..cbd4b171fa
--- /dev/null
+++ b/packages/tests/src/api/runners/runner-transcription.ts
@@ -0,0 +1,109 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import {
+ RunnerJobTranscriptionPayload,
+ TranscriptionSuccess
+} from '@peertube/peertube-models'
+import {
+ PeerTubeServer,
+ cleanupTests,
+ createMultipleServers,
+ doubleFollow,
+ setAccessTokensToServers,
+ setDefaultVideoChannel,
+ waitJobs
+} from '@peertube/peertube-server-commands'
+import { checkPersistentTmpIsEmpty } from '@tests/shared/directories.js'
+import { expect } from 'chai'
+
+describe('Test runner transcription', function () {
+ let servers: PeerTubeServer[] = []
+ let runnerToken: string
+
+ before(async function () {
+ this.timeout(120_000)
+
+ servers = await createMultipleServers(2)
+
+ await setAccessTokensToServers(servers)
+ await setDefaultVideoChannel(servers)
+
+ await doubleFollow(servers[0], servers[1])
+
+ await servers[0].config.enableTranscription({ remote: true })
+ runnerToken = await servers[0].runners.autoRegisterRunner()
+ })
+
+ async function upload () {
+ const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video', language: undefined } })
+
+ const { availableJobs } = await servers[0].runnerJobs.request({ runnerToken })
+ expect(availableJobs).to.have.lengthOf(1)
+
+ const jobUUID = availableJobs[0].uuid
+
+ const { job } = await servers[0].runnerJobs.accept<RunnerJobTranscriptionPayload>({ runnerToken, jobUUID })
+ return { uuid, job }
+ }
+
+ it('Should execute a remote transcription job', async function () {
+ this.timeout(240_000)
+
+ const { uuid, job } = await upload()
+
+ expect(job.type === 'video-transcription')
+ expect(job.payload.input.videoFileUrl).to.exist
+
+ // Check video input file
+ {
+ await servers[0].runnerJobs.getJobFile({ url: job.payload.input.videoFileUrl, jobToken: job.jobToken, runnerToken })
+ }
+
+ const payload: TranscriptionSuccess = {
+ inputLanguage: 'ar',
+ vttFile: 'subtitle-good1.vtt'
+ }
+
+ await servers[0].runnerJobs.success({ runnerToken, jobUUID: job.uuid, jobToken: job.jobToken, payload })
+
+ await waitJobs(servers)
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: uuid })
+ expect(video.language.id).to.equal('ar')
+
+ const captions = await server.captions.list({ videoId: uuid })
+ expect(captions)
+ }
+
+ await checkPersistentTmpIsEmpty(servers[0])
+ })
+
+ it('Should not assign caption/language with an unknown inputLanguage', async function () {
+ this.timeout(240_000)
+
+ const { uuid, job } = await upload()
+
+ const payload: TranscriptionSuccess = {
+ inputLanguage: 'toto',
+ vttFile: 'subtitle-good1.vtt'
+ }
+
+ await servers[0].runnerJobs.success({ runnerToken, jobUUID: job.uuid, jobToken: job.jobToken, payload })
+
+ await waitJobs(servers)
+
+ for (const server of servers) {
+ const video = await server.videos.get({ id: uuid })
+ expect(video.language.id).to.be.null
+
+ const { total, data } = await server.captions.list({ videoId: uuid })
+ expect(total).to.equal(0)
+ expect(data).to.have.lengthOf(0)
+ }
+ })
+
+ after(async function () {
+ await cleanupTests(servers)
+ })
+})
diff --git a/packages/tests/src/api/server/config.ts b/packages/tests/src/api/server/config.ts
index 179dc4b883..78728893b5 100644
--- a/packages/tests/src/api/server/config.ts
+++ b/packages/tests/src/api/server/config.ts
@@ -108,6 +108,9 @@ function checkInitialConfig (server: PeerTubeServer, data: CustomConfig) {
expect(data.videoStudio.enabled).to.be.false
expect(data.videoStudio.remoteRunners.enabled).to.be.false
+ expect(data.videoTranscription.enabled).to.be.false
+ expect(data.videoTranscription.remoteRunners.enabled).to.be.false
+
expect(data.videoFile.update.enabled).to.be.false
expect(data.import.videos.concurrency).to.equal(2)
@@ -292,6 +295,12 @@ function buildNewCustomConfig (server: PeerTubeServer): CustomConfig {
enabled: true
}
},
+ videoTranscription: {
+ enabled: true,
+ remoteRunners: {
+ enabled: true
+ }
+ },
videoFile: {
update: {
enabled: true
diff --git a/packages/tests/src/api/videos/index.ts b/packages/tests/src/api/videos/index.ts
index a4bcd9741d..358fbfaff1 100644
--- a/packages/tests/src/api/videos/index.ts
+++ b/packages/tests/src/api/videos/index.ts
@@ -1,24 +1,25 @@
+import './channel-import-videos.js'
import './multiple-servers.js'
import './resumable-upload.js'
import './single-server.js'
import './video-captions.js'
import './video-change-ownership.js'
+import './video-channel-syncs.js'
import './video-channels.js'
import './video-chapters.js'
-import './channel-import-videos.js'
-import './video-channel-syncs.js'
import './video-comments.js'
import './video-description.js'
import './video-files.js'
import './video-imports.js'
import './video-nsfw.js'
-import './video-playlists.js'
import './video-playlist-thumbnails.js'
-import './video-source.js'
+import './video-playlists.js'
import './video-privacy.js'
import './video-schedule-update.js'
+import './video-source.js'
+import './video-static-file-privacy.js'
+import './video-storyboard.js'
+import './video-transcription.js'
import './videos-common-filters.js'
import './videos-history.js'
import './videos-overview.js'
-import './video-static-file-privacy.js'
-import './video-storyboard.js'
diff --git a/packages/tests/src/api/videos/video-transcription.ts b/packages/tests/src/api/videos/video-transcription.ts
new file mode 100644
index 0000000000..6548cd9efc
--- /dev/null
+++ b/packages/tests/src/api/videos/video-transcription.ts
@@ -0,0 +1,145 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { VideoPrivacy } from '@peertube/peertube-models'
+import {
+ PeerTubeServer,
+ cleanupTests,
+ createMultipleServers,
+ doubleFollow,
+ sendRTMPStream,
+ setAccessTokensToServers,
+ setDefaultVideoChannel,
+ stopFfmpeg,
+ waitJobs
+} from '@peertube/peertube-server-commands'
+import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'
+import { checkCaption, checkLanguage, checkNoCaption, uploadForTranscription } from '@tests/shared/transcription.js'
+
+describe('Test video transcription', function () {
+ let servers: PeerTubeServer[]
+
+ before(async function () {
+ this.timeout(60000)
+
+ servers = await createMultipleServers(2)
+
+ await setAccessTokensToServers(servers)
+ await setDefaultVideoChannel(servers)
+ await doubleFollow(servers[0], servers[1])
+
+ await waitJobs(servers)
+ await waitJobs(servers)
+ })
+
+ // ---------------------------------------------------------------------------
+
+ it('Should generate a transcription on request', async function () {
+ this.timeout(360000)
+
+ await servers[0].config.disableTranscription()
+
+ const uuid = await uploadForTranscription(servers[0])
+ await waitJobs(servers)
+ await checkLanguage(servers, uuid, null)
+
+ await servers[0].config.enableTranscription()
+
+ await servers[0].captions.runGenerate({ videoId: uuid })
+ await waitJobs(servers)
+ await checkLanguage(servers, uuid, 'en')
+
+ await checkCaption(servers, uuid)
+ })
+
+ it('Should run transcription on upload by default', async function () {
+ this.timeout(360000)
+
+ const uuid = await uploadForTranscription(servers[0])
+
+ await waitJobs(servers)
+ await checkCaption(servers, uuid)
+ await checkLanguage(servers, uuid, 'en')
+ })
+
+ it('Should run transcription on import by default', async function () {
+ this.timeout(360000)
+
+ const { video } = await servers[0].videoImports.importVideo({
+ attributes: {
+ privacy: VideoPrivacy.PUBLIC,
+ targetUrl: FIXTURE_URLS.transcriptionVideo,
+ language: undefined
+ }
+ })
+
+ await waitJobs(servers)
+ await checkCaption(servers, video.uuid)
+ await checkLanguage(servers, video.uuid, 'en')
+ })
+
+ it('Should run transcription when live ended', async function () {
+ this.timeout(360000)
+
+ await servers[0].config.enableMinimumTranscoding()
+ await servers[0].config.enableLive({ allowReplay: true, transcoding: true, resolutions: 'min' })
+
+ const { live, video } = await servers[0].live.quickCreate({
+ saveReplay: true,
+ permanentLive: false,
+ privacy: VideoPrivacy.PUBLIC
+ })
+
+ const ffmpegCommand = sendRTMPStream({ rtmpBaseUrl: live.rtmpUrl, streamKey: live.streamKey })
+ await servers[0].live.waitUntilPublished({ videoId: video.id })
+
+ await stopFfmpeg(ffmpegCommand)
+
+ await servers[0].live.waitUntilReplacedByReplay({ videoId: video.id })
+ await waitJobs(servers)
+ await checkCaption(servers, video.uuid, 'WEBVTT\n\n00:')
+ await checkLanguage(servers, video.uuid, 'en')
+
+ await servers[0].config.enableLive({ allowReplay: false })
+ await servers[0].config.disableTranscoding()
+ })
+
+ it('Should not run transcription if disabled by user', async function () {
+ this.timeout(120000)
+
+ {
+ const uuid = await uploadForTranscription(servers[0], { generateTranscription: false })
+
+ await waitJobs(servers)
+ await checkNoCaption(servers, uuid)
+ await checkLanguage(servers, uuid, null)
+ }
+
+ {
+ const { video } = await servers[0].videoImports.importVideo({
+ attributes: {
+ privacy: VideoPrivacy.PUBLIC,
+ targetUrl: FIXTURE_URLS.transcriptionVideo,
+ generateTranscription: false
+ }
+ })
+
+ await waitJobs(servers)
+ await checkNoCaption(servers, video.uuid)
+ await checkLanguage(servers, video.uuid, null)
+ }
+ })
+
+ it('Should not run a transcription if the video does not contain audio', async function () {
+ this.timeout(120000)
+
+ const uuid = await uploadForTranscription(servers[0], { generateTranscription: false })
+
+ await waitJobs(servers)
+ await checkNoCaption(servers, uuid)
+ await checkLanguage(servers, uuid, null)
+ })
+
+ after(async function () {
+ await cleanupTests(servers)
+ })
+})
diff --git a/packages/tests/src/jiwer/jiwer-cli.spec.ts b/packages/tests/src/jiwer/jiwer-cli.spec.ts
index ccc2ab26bc..06645f35ae 100644
--- a/packages/tests/src/jiwer/jiwer-cli.spec.ts
+++ b/packages/tests/src/jiwer/jiwer-cli.spec.ts
@@ -3,7 +3,7 @@ import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import { join } from 'path'
import { mkdir, rm, writeFile } from 'node:fs/promises'
import { expect } from 'chai'
-import { JiwerClI } from '@peertube/peertube-jiwer'
+import { JiwerClI } from '@peertube/peertube-transcription-devtools'
describe('Jiwer CLI', function () {
const transcriptDirectory = buildAbsoluteFixturePath('transcription/transcript-evaluator')
diff --git a/packages/tests/src/peertube-runner/index.ts b/packages/tests/src/peertube-runner/index.ts
index f02611046b..7807f8479c 100644
--- a/packages/tests/src/peertube-runner/index.ts
+++ b/packages/tests/src/peertube-runner/index.ts
@@ -2,4 +2,5 @@ export * from './client-cli.js'
export * from './live-transcoding.js'
export * from './replace-file.js'
export * from './studio-transcoding.js'
+export * from './video-transcription.js'
export * from './vod-transcoding.js'
diff --git a/packages/tests/src/peertube-runner/live-transcoding.ts b/packages/tests/src/peertube-runner/live-transcoding.ts
index 85eac4ce9c..69d44b531a 100644
--- a/packages/tests/src/peertube-runner/live-transcoding.ts
+++ b/packages/tests/src/peertube-runner/live-transcoding.ts
@@ -194,7 +194,7 @@ describe('Test Live transcoding in peertube-runner program', function () {
describe('Check cleanup', function () {
it('Should have an empty cache directory', async function () {
- await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner)
+ await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner, 'transcoding')
})
})
diff --git a/packages/tests/src/peertube-runner/studio-transcoding.ts b/packages/tests/src/peertube-runner/studio-transcoding.ts
index e044b2fcfc..6ce390f10e 100644
--- a/packages/tests/src/peertube-runner/studio-transcoding.ts
+++ b/packages/tests/src/peertube-runner/studio-transcoding.ts
@@ -111,7 +111,7 @@ describe('Test studio transcoding in peertube-runner program', function () {
describe('Check cleanup', function () {
it('Should have an empty cache directory', async function () {
- await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner)
+ await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner, 'transcoding')
})
})
diff --git a/packages/tests/src/peertube-runner/video-transcription.ts b/packages/tests/src/peertube-runner/video-transcription.ts
new file mode 100644
index 0000000000..a810524f58
--- /dev/null
+++ b/packages/tests/src/peertube-runner/video-transcription.ts
@@ -0,0 +1,89 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { wait } from '@peertube/peertube-core-utils'
+import { RunnerJobState } from '@peertube/peertube-models'
+import {
+ PeerTubeServer,
+ cleanupTests,
+ createMultipleServers,
+ doubleFollow,
+ setAccessTokensToServers,
+ setDefaultVideoChannel,
+ waitJobs
+} from '@peertube/peertube-server-commands'
+import { checkPeerTubeRunnerCacheIsEmpty } from '@tests/shared/directories.js'
+import { PeerTubeRunnerProcess } from '@tests/shared/peertube-runner-process.js'
+import { checkCaption, checkLanguage, checkNoCaption, uploadForTranscription } from '@tests/shared/transcription.js'
+
+describe('Test transcription in peertube-runner program', function () {
+ let servers: PeerTubeServer[] = []
+ let peertubeRunner: PeerTubeRunnerProcess
+
+ before(async function () {
+ this.timeout(120_000)
+
+ servers = await createMultipleServers(2)
+
+ await setAccessTokensToServers(servers)
+ await setDefaultVideoChannel(servers)
+
+ await doubleFollow(servers[0], servers[1])
+
+ await servers[0].config.enableTranscription({ remote: true })
+
+ const registrationToken = await servers[0].runnerRegistrationTokens.getFirstRegistrationToken()
+
+ peertubeRunner = new PeerTubeRunnerProcess(servers[0])
+ await peertubeRunner.runServer()
+ await peertubeRunner.registerPeerTubeInstance({ registrationToken, runnerName: 'runner' })
+ })
+
+ describe('Running transcription', function () {
+
+ it('Should run transcription on classic file', async function () {
+ this.timeout(360000)
+
+ const uuid = await uploadForTranscription(servers[0])
+ await waitJobs(servers, { runnerJobs: true })
+
+ await checkCaption(servers, uuid)
+ await checkLanguage(servers, uuid, 'en')
+ })
+
+ it('Should not run transcription on video without audio stream', async function () {
+ this.timeout(360000)
+
+ const uuid = await uploadForTranscription(servers[0], { fixture: 'video_short_no_audio.mp4' })
+
+ await waitJobs(servers)
+
+ let continueWhile = true
+ while (continueWhile) {
+ await wait(500)
+
+ const { data } = await servers[0].runnerJobs.list({ stateOneOf: [ RunnerJobState.ERRORED ] })
+
+ continueWhile = !data.some(j => j.type === 'video-transcription')
+ }
+
+ await checkNoCaption(servers, uuid)
+ await checkLanguage(servers, uuid, null)
+ })
+ })
+
+ describe('Check cleanup', function () {
+
+ it('Should have an empty cache directory', async function () {
+ await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner, 'transcription')
+ })
+ })
+
+ after(async function () {
+ if (peertubeRunner) {
+ await peertubeRunner.unregisterPeerTubeInstance({ runnerName: 'runner' })
+ peertubeRunner.kill()
+ }
+
+ await cleanupTests(servers)
+ })
+})
diff --git a/packages/tests/src/peertube-runner/vod-transcoding.ts b/packages/tests/src/peertube-runner/vod-transcoding.ts
index da0f26079e..a7397820aa 100644
--- a/packages/tests/src/peertube-runner/vod-transcoding.ts
+++ b/packages/tests/src/peertube-runner/vod-transcoding.ts
@@ -373,7 +373,7 @@ describe('Test VOD transcoding in peertube-runner program', function () {
describe('Check cleanup', function () {
it('Should have an empty cache directory', async function () {
- await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner)
+ await checkPeerTubeRunnerCacheIsEmpty(peertubeRunner, 'transcoding')
})
})
diff --git a/packages/tests/src/shared/directories.ts b/packages/tests/src/shared/directories.ts
index f21e7b7c64..e9be0c77d6 100644
--- a/packages/tests/src/shared/directories.ts
+++ b/packages/tests/src/shared/directories.ts
@@ -32,13 +32,13 @@ export async function checkDirectoryIsEmpty (server: PeerTubeServer, directory:
expect(filtered).to.have.lengthOf(0)
}
-export async function checkPeerTubeRunnerCacheIsEmpty (runner: PeerTubeRunnerProcess) {
- const directoryPath = join(homedir(), '.cache', 'peertube-runner-nodejs', runner.getId(), 'transcoding')
+export async function checkPeerTubeRunnerCacheIsEmpty (runner: PeerTubeRunnerProcess, subDir: 'transcoding' | 'transcription') {
+ const directoryPath = join(homedir(), '.cache', 'peertube-runner-nodejs', runner.getId(), subDir)
const directoryExists = await pathExists(directoryPath)
expect(directoryExists).to.be.true
const files = await readdir(directoryPath)
- expect(files, 'Directory content: ' + files.join(', ')).to.have.lengthOf(0)
+ expect(files, `Sub-directory ${subDir} content: ${files.join(', ')}`).to.have.lengthOf(0)
}
diff --git a/packages/tests/src/shared/fixture-urls.ts b/packages/tests/src/shared/fixture-urls.ts
index b4c659e76b..daade2d83d 100644
--- a/packages/tests/src/shared/fixture-urls.ts
+++ b/packages/tests/src/shared/fixture-urls.ts
@@ -26,6 +26,7 @@ export const FIXTURE_URLS = {
badVideo: 'https://download.cpy.re/peertube/bad_video.mp4',
goodVideo: 'https://download.cpy.re/peertube/good_video.mp4',
goodVideo720: 'https://download.cpy.re/peertube/good_video_720.mp4',
+ transcriptionVideo: 'https://download.cpy.re/peertube/the_last_man_on_earth.mp4',
chatersVideo: 'https://download.cpy.re/peertube/video_chapters.mp4',
diff --git a/packages/tests/src/shared/notifications.ts b/packages/tests/src/shared/notifications.ts
index 5f4b240f91..eb9ef3e358 100644
--- a/packages/tests/src/shared/notifications.ts
+++ b/packages/tests/src/shared/notifications.ts
@@ -54,6 +54,7 @@ function getAllNotificationsSettings (): UserNotificationSetting {
autoInstanceFollowing: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
myVideoStudioEditionFinished: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
+ myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newPluginVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL
}
}
@@ -758,6 +759,40 @@ async function checkNewPluginVersion (options: CheckerBaseParams & {
await checkNotification({ ...options, notificationChecker, emailNotificationFinder })
}
+async function checkMyVideoTranscriptionGenerated (options: CheckerBaseParams & {
+ videoName: string
+ shortUUID: string
+ language: {
+ id: string
+ label: string
+ }
+ checkType: CheckerType
+}) {
+ const { videoName, shortUUID, language } = options
+ const notificationType = UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED
+
+ function notificationChecker (notification: UserNotification, checkType: CheckerType) {
+ if (checkType === 'presence') {
+ expect(notification).to.not.be.undefined
+ expect(notification.type).to.equal(notificationType)
+
+ expect(notification.videoCaption).to.exist
+ expect(notification.videoCaption.language.id).to.equal(language.id)
+ expect(notification.videoCaption.language.label).to.equal(language.label)
+ checkVideo(notification.videoCaption.video, videoName, shortUUID)
+ } else {
+ expect(notification.videoCaption).to.satisfy(c => c === undefined || c.Video.shortUUID !== shortUUID)
+ }
+ }
+
+ function emailNotificationFinder (email: object) {
+ const text: string = email['text']
+ return text.includes(shortUUID) && text.includes('Transcription in ' + language.label)
+ }
+
+ await checkNotification({ ...options, notificationChecker, emailNotificationFinder })
+}
+
async function prepareNotificationsTest (serversCount = 3, overrideConfigArg: any = {}) {
const userNotifications: UserNotification[] = []
const adminNotifications: UserNotification[] = []
@@ -863,7 +898,8 @@ export {
checkNewPeerTubeVersion,
checkNewPluginVersion,
checkVideoStudioEditionIsFinished,
- checkRegistrationRequest
+ checkRegistrationRequest,
+ checkMyVideoTranscriptionGenerated
}
// ---------------------------------------------------------------------------
diff --git a/packages/tests/src/shared/transcription.ts b/packages/tests/src/shared/transcription.ts
new file mode 100644
index 0000000000..9deb153f0a
--- /dev/null
+++ b/packages/tests/src/shared/transcription.ts
@@ -0,0 +1,81 @@
+/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
+
+import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
+import { PeerTubeServer, VideoEdit } from '@peertube/peertube-server-commands'
+import { downloadFile, unzip } from '@peertube/peertube-transcription-devtools'
+import { expect } from 'chai'
+import { ensureDir, pathExists } from 'fs-extra/esm'
+import { join } from 'path'
+import { testCaptionFile } from './captions.js'
+import { FIXTURE_URLS } from './fixture-urls.js'
+
+type CustomModelName = 'tiny.pt' | 'faster-whisper-tiny'
+
+export async function downloadCustomModelsIfNeeded (modelName: CustomModelName) {
+ if (await pathExists(getCustomModelPath(modelName))) return
+
+ await ensureDir(getCustomModelDirectory())
+ await unzip(await downloadFile(FIXTURE_URLS.transcriptionModels, getCustomModelDirectory()))
+}
+
+export function getCustomModelDirectory () {
+ return buildAbsoluteFixturePath(join('transcription', 'models-v1'))
+}
+
+export function getCustomModelPath (modelName: CustomModelName) {
+ return join(getCustomModelDirectory(), 'models', modelName)
+}
+
+// ---------------------------------------------------------------------------
+
+export async function checkCaption (servers: PeerTubeServer[], uuid: string, captionContains = 'WEBVTT\n\n00:00.000 --> 00:') {
+ for (const server of servers) {
+ const body = await server.captions.list({ videoId: uuid })
+ expect(body.total).to.equal(1)
+ expect(body.data).to.have.lengthOf(1)
+
+ const caption = body.data[0]
+ expect(caption.language.id).to.equal('en')
+ expect(caption.language.label).to.equal('English')
+
+ {
+ await testCaptionFile(server.url, caption.captionPath, captionContains)
+ }
+ }
+}
+
+export async function checkNoCaption (servers: PeerTubeServer[], uuid: string) {
+ for (const server of servers) {
+ const body = await server.captions.list({ videoId: uuid })
+ expect(body.total).to.equal(0)
+ expect(body.data).to.have.lengthOf(0)
+ }
+}
+
+// ---------------------------------------------------------------------------
+
+export async function checkLanguage (servers: PeerTubeServer[], uuid: string, expected: string | null) {
+ for (const server of servers) {
+ const video = await server.videos.get({ id: uuid })
+
+ if (expected) {
+ expect(video.language.id).to.equal(expected)
+ } else {
+ expect(video.language.id).to.be.null
+ }
+ }
+}
+
+export async function uploadForTranscription (server: PeerTubeServer, body: Partial<VideoEdit> = {}) {
+ const { uuid } = await server.videos.upload({
+ attributes: {
+ name: 'video',
+ fixture: join('transcription', 'videos', 'the_last_man_on_earth.mp4'),
+ language: undefined,
+
+ ...body
+ }
+ })
+
+ return uuid
+}
diff --git a/packages/tests/src/transcription/levenshtein-distance.spec.ts b/packages/tests/src/transcription/levenshtein-distance.spec.ts
index d4c502a02c..63a2c71f21 100644
--- a/packages/tests/src/transcription/levenshtein-distance.spec.ts
+++ b/packages/tests/src/transcription/levenshtein-distance.spec.ts
@@ -1,5 +1,5 @@
+import { levenshteinDistance } from '@peertube/peertube-transcription-devtools'
import { expect } from 'chai'
-import { levenshteinDistance } from '@peertube/peertube-transcription'
describe('Levenshtein distance', function () {
it(`equals 1 when there is only one character difference`, function () {
diff --git a/packages/tests/src/transcription/transcriber-factory.spec.ts b/packages/tests/src/transcription/transcriber-factory.spec.ts
index cd9d9f29f9..139b557f81 100644
--- a/packages/tests/src/transcription/transcriber-factory.spec.ts
+++ b/packages/tests/src/transcription/transcriber-factory.spec.ts
@@ -1,17 +1,16 @@
-import { transcriberFactory } from '@peertube/peertube-transcription'
+import { TranscriptionEngineName, transcriberFactory } from '@peertube/peertube-transcription'
+import { createLogger } from 'winston'
describe('Transcriber factory', function () {
- const transcribers = [
- 'openai-whisper',
- 'whisper-ctranslate2',
- 'whisper-timestamped'
- ]
+ const transcribers: TranscriptionEngineName[] = [ 'openai-whisper', 'whisper-ctranslate2' ]
describe('Should be able to create a transcriber for each available transcription engine', function () {
- transcribers.forEach(function (transcriberName) {
+
+ for (const transcriberName of transcribers) {
it(`Should be able to create a(n) ${transcriberName} transcriber`, function () {
- transcriberFactory.createFromEngineName(transcriberName)
+ transcriberFactory.createFromEngineName({ engineName: transcriberName, logger: createLogger() })
})
- })
+ }
+
})
})
diff --git a/packages/tests/src/transcription/transcript/transcript-file-evaluator.spec.ts b/packages/tests/src/transcription/transcript/transcript-file-evaluator.spec.ts
index 93df638dbc..0ee2fba2f7 100644
--- a/packages/tests/src/transcription/transcript/transcript-file-evaluator.spec.ts
+++ b/packages/tests/src/transcription/transcript/transcript-file-evaluator.spec.ts
@@ -1,17 +1,18 @@
/* eslint-disable @typescript-eslint/no-unused-expressions, no-new, max-len */
-import { TranscriptFile, TranscriptFileEvaluator } from '@peertube/peertube-transcription'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
-import { join } from 'node:path'
-import { mkdir, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
+import { TranscriptFile } from '@peertube/peertube-transcription'
+import { TranscriptFileEvaluator } from '@peertube/peertube-transcription-devtools'
import { expect } from 'chai'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
describe('Transcript File Evaluator', function () {
const transcriptDirectory = join(tmpdir(), 'peertube-transcription', 'transcript-file-evaluator')
const referenceTranscriptFilePath = buildAbsoluteFixturePath('transcription/videos/communiquer-lors-dune-classe-transplantee.txt')
before(async function () {
- await mkdir(transcriptDirectory, { recursive: true })
+ await ensureDir(transcriptDirectory)
})
it(`may not compare files in another format than txt`, async function () {
@@ -62,6 +63,6 @@ Ensuite, il pourront lire et commenter ce de leurs camarades ou répondre aux co
})
after(async function () {
- await rm(transcriptDirectory, { recursive: true, force: true })
+ await remove(transcriptDirectory)
})
})
diff --git a/packages/tests/src/transcription/transcript/transcript-file.spec.ts b/packages/tests/src/transcription/transcript/transcript-file.spec.ts
index 112c246b34..e2e3c194a2 100644
--- a/packages/tests/src/transcription/transcript/transcript-file.spec.ts
+++ b/packages/tests/src/transcription/transcript/transcript-file.spec.ts
@@ -1,15 +1,16 @@
/* eslint-disable @typescript-eslint/no-unused-expressions */
-import { expect } from 'chai'
-import { join } from 'node:path'
-import { mkdir, rm } from 'node:fs/promises'
+import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import { TranscriptFile } from '@peertube/peertube-transcription'
+import { expect } from 'chai'
+import { ensureDir, remove } from 'fs-extra/esm'
import { tmpdir } from 'node:os'
-import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
+import { join } from 'node:path'
describe('Transcript File', function () {
const transcriptFileDirectory = join(tmpdir(), 'peertube-transcription', 'transcript-file')
+
before(async function () {
- await mkdir(transcriptFileDirectory, { recursive: true })
+ await ensureDir(transcriptFileDirectory)
})
it(`may creates a new transcript file from scratch`, async function () {
@@ -33,12 +34,11 @@ describe('Transcript File', function () {
})
it(`fails when loading a file which is obviously not a transcript`, function () {
-
expect(() => TranscriptFile.fromPath(buildAbsoluteFixturePath('transcription/videos/the_last_man_on_earth.mp4'), 'en'))
.to.throw(`Couldn't guess transcript format from extension "mp4". Valid formats are: txt, vtt, srt.`)
})
after(async function () {
- await rm(transcriptFileDirectory, { recursive: true, force: true })
+ await remove(transcriptFileDirectory)
})
})
diff --git a/packages/tests/src/transcription/transcription-run.spec.ts b/packages/tests/src/transcription/transcription-run.spec.ts
deleted file mode 100644
index d877fbded2..0000000000
--- a/packages/tests/src/transcription/transcription-run.spec.ts
+++ /dev/null
@@ -1 +0,0 @@
-describe('Transcription run', function () {})
diff --git a/packages/tests/src/transcription/utils.spec.ts b/packages/tests/src/transcription/utils.spec.ts
index 487b9aeda3..1498169f81 100644
--- a/packages/tests/src/transcription/utils.spec.ts
+++ b/packages/tests/src/transcription/utils.spec.ts
@@ -1,14 +1,16 @@
-import { cp, lstat, mkdir, rm } from 'node:fs/promises'
-import { join } from 'node:path'
-import { tmpdir } from 'node:os'
-import { expect } from 'chai'
-import { downloadFile, unzip } from '@peertube/peertube-transcription'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
+import { downloadFile, unzip } from '@peertube/peertube-transcription-devtools'
+import { expect } from 'chai'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { cp, lstat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
describe('downloadFile', function () {
const testDirectory = join(tmpdir(), 'peertube-transcription', 'utils')
+
before(async function () {
- await mkdir(testDirectory, { recursive: true })
+ await ensureDir(testDirectory)
})
it(`Downloads a file and write it to the disk `, async function () {
@@ -18,7 +20,7 @@ describe('downloadFile', function () {
})
after(async function () {
- await rm(testDirectory, { recursive: true, force: true })
+ await remove(testDirectory)
})
})
@@ -26,8 +28,9 @@ describe('unzip', function () {
const zipFixtureFileName = 'hello_world.zip'
const zipFixtureFilePath = buildAbsoluteFixturePath(`transcription/${zipFixtureFileName}`)
const testDirectory = join(tmpdir(), 'peertube-transcription', 'utils')
+
before(async function () {
- await mkdir(testDirectory, { recursive: true })
+ await ensureDir(testDirectory)
})
it(`Extract zip archive to directory`, async function () {
@@ -39,6 +42,6 @@ describe('unzip', function () {
})
after(async function () {
- await rm(testDirectory, { recursive: true, force: true })
+ await remove(testDirectory)
})
})
diff --git a/packages/tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts b/packages/tests/src/transcription/whisper/openai-transcriber.spec.ts
similarity index 70%
rename from packages/tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts
rename to packages/tests/src/transcription/whisper/openai-transcriber.spec.ts
index d3f3f9ca7c..20b2b56d59 100644
--- a/packages/tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts
+++ b/packages/tests/src/transcription/whisper/openai-transcriber.spec.ts
@@ -1,57 +1,59 @@
/* eslint-disable @typescript-eslint/no-unused-expressions, max-len */
-import { expect, config } from 'chai'
-import { createLogger } from 'winston'
-import { join } from 'node:path'
-import { mkdir, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import {
- downloadFile,
- levenshteinDistance,
OpenaiTranscriber,
TranscriptFile,
- TranscriptFileEvaluator,
TranscriptionModel,
- unzip,
WhisperBuiltinModel
} from '@peertube/peertube-transcription'
-import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'
+import { TranscriptFileEvaluator, levenshteinDistance } from '@peertube/peertube-transcription-devtools'
+import { downloadCustomModelsIfNeeded, getCustomModelPath } from '@tests/shared/transcription.js'
+import { config, expect } from 'chai'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { createLogger } from 'winston'
config.truncateThreshold = 0
describe('Open AI Whisper transcriber', function () {
const tmpDirectory = join(tmpdir(), 'peertube-transcription')
const transcriptDirectory = join(tmpDirectory, 'transcriber', 'openai')
- const modelsDirectory = join(tmpDirectory, 'models')
+
const shortVideoPath = buildAbsoluteFixturePath('transcription/videos/the_last_man_on_earth.mp4')
const frVideoPath = buildAbsoluteFixturePath('transcription/videos/derive_sectaire.mp4')
+
const referenceTranscriptFile = new TranscriptFile({
path: buildAbsoluteFixturePath('transcription/videos/derive_sectaire.txt'),
language: 'fr',
format: 'txt'
})
- const transcriber = new OpenaiTranscriber(
- {
+
+ const transcriber = new OpenaiTranscriber({
+ engine: {
name: 'openai-whisper',
- requirements: [],
type: 'binary',
- binary: 'whisper',
+ command: 'whisper',
supportedModelFormats: [ 'PyTorch' ],
- languageDetection: true
+ languageDetection: true,
+ version: ''
},
- createLogger(),
- transcriptDirectory
- )
+ logger: createLogger()
+ })
+ const model = new TranscriptionModel('tiny')
before(async function () {
- this.timeout(1 * 1000 * 60)
- await mkdir(transcriptDirectory, { recursive: true })
- await unzip(await downloadFile(FIXTURE_URLS.transcriptionModels, tmpDirectory))
+ this.timeout(120000)
+
+ await ensureDir(transcriptDirectory)
+
+ await downloadCustomModelsIfNeeded('tiny.pt')
})
- it('Should transcribe a media file and provide a valid path to a transcript file in `vtt` format by default', async function () {
+ it('Should transcribe a media file and provide a valid path to a transcript file in `vtt` format', async function () {
this.timeout(3 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en' })
+
+ const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'vtt', model, transcriptDirectory })
expect(transcript.format).to.equals('vtt')
expect(transcript.language).to.equals('en')
@@ -59,7 +61,7 @@ describe('Open AI Whisper transcriber', function () {
})
it('May produce a transcript file in the `srt` format', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'srt' })
+ const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'srt', model, transcriptDirectory })
expect(transcript.format).to.equals('srt')
expect(transcript.language).to.equals('en')
@@ -67,7 +69,7 @@ describe('Open AI Whisper transcriber', function () {
})
it('May produce a transcript file in the `txt` format', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'txt' })
+ const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'txt', model, transcriptDirectory })
expect(transcript.format).to.equals('txt')
expect(transcript.language).to.equals('en')
@@ -80,16 +82,20 @@ describe('Open AI Whisper transcriber', function () {
it('May transcribe a media file using a local PyTorch model', async function () {
this.timeout(2 * 1000 * 60)
+
await transcriber.transcribe({
mediaFilePath: shortVideoPath,
- model: await TranscriptionModel.fromPath(join(modelsDirectory, 'tiny.pt')),
- language: 'en'
+ model: await TranscriptionModel.fromPath(getCustomModelPath('tiny.pt')),
+ language: 'en',
+ format: 'vtt',
+ transcriptDirectory
})
})
it('May transcribe a media file in french', async function () {
this.timeout(3 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath, language: 'fr', format: 'txt' })
+
+ const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath, language: 'fr', format: 'txt', model, transcriptDirectory })
expect(transcript.format).to.equals('txt')
expect(transcript.language).to.equals('fr')
@@ -98,18 +104,21 @@ describe('Open AI Whisper transcriber', function () {
it('Guesses the video language if not provided', async function () {
this.timeout(3 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath })
+
+ const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath, model, format: 'vtt', transcriptDirectory })
expect(transcript.language).to.equals('fr')
})
- it('May transcribe a media file in french with small model', async function () {
+ it('May transcribe a media file in french with small model (can be long)', async function () {
this.timeout(6 * 1000 * 60)
+
const transcript = await transcriber.transcribe({
mediaFilePath: frVideoPath,
language: 'fr',
format: 'txt',
- model: new WhisperBuiltinModel('small')
+ model: new WhisperBuiltinModel('small'),
+ transcriptDirectory
})
expect(transcript.language).to.equals('fr')
@@ -120,6 +129,6 @@ describe('Open AI Whisper transcriber', function () {
})
after(async function () {
- await rm(transcriptDirectory, { recursive: true, force: true })
+ await remove(transcriptDirectory)
})
})
diff --git a/packages/tests/src/transcription/whisper/transcriber/timestamped-transcriber.spec.ts b/packages/tests/src/transcription/whisper/transcriber/timestamped-transcriber.spec.ts
deleted file mode 100644
index bf4adee9e4..0000000000
--- a/packages/tests/src/transcription/whisper/transcriber/timestamped-transcriber.spec.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/* eslint-disable @typescript-eslint/no-unused-expressions, max-len */
-import { expect, config } from 'chai'
-import { createLogger } from 'winston'
-import { join } from 'node:path'
-import { mkdir, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
-import {
- OpenaiTranscriber,
- WhisperTimestampedTranscriber,
- TranscriptFileEvaluator,
- TranscriptionModel,
- WhisperTranscribeArgs,
- levenshteinDistance, downloadFile, unzip
-} from '@peertube/peertube-transcription'
-import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'
-
-config.truncateThreshold = 0
-
-describe('Linto timestamped Whisper transcriber', function () {
- const tmpDirectory = join(tmpdir(), 'peertube-transcription')
- const transcriptDirectory = join(tmpDirectory, 'transcriber', 'timestamped')
- const modelsDirectory = join(tmpDirectory, 'models')
- const shortVideoPath = buildAbsoluteFixturePath('transcription/videos/the_last_man_on_earth.mp4')
- const frVideoPath = buildAbsoluteFixturePath('transcription/videos/derive_sectaire.mp4')
- const transcriber = new WhisperTimestampedTranscriber(
- {
- name: 'whisper-timestamped',
- requirements: [],
- type: 'binary',
- binary: 'whisper_timestamped',
- supportedModelFormats: [ 'PyTorch' ],
- languageDetection: true
- },
- createLogger(),
- transcriptDirectory
- )
-
- before(async function () {
- this.timeout(1 * 1000 * 60)
- await mkdir(transcriptDirectory, { recursive: true })
- await unzip(await downloadFile(FIXTURE_URLS.transcriptionModels, tmpDirectory))
- })
-
- it('Should transcribe a media file and provide a valid path to a transcript file in `vtt` format by default', async function () {
- this.timeout(1 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en' })
-
- expect(transcript.format).to.equals('vtt')
- expect(transcript.language).to.equals('en')
- expect(await transcript.read()).not.to.be.empty
- })
-
- it('May produce a transcript file in the `srt` format with a ms precision', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'srt' })
-
- expect(transcript.format).to.equals('srt')
- expect(transcript.language).to.equals('en')
- expect(await transcript.read()).not.to.be.empty
- })
-
- it('May produce a transcript file in `txt` format', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'txt' })
-
- expect(transcript.format).to.equals('txt')
- expect(transcript.language).to.equals('en')
- expect(await transcript.read()).not.to.be.empty
- expect(levenshteinDistance(
- (await transcript.read()).toString(),
- 'December 1965, is that all it has been since I inherited the world only three years, seems like a hundred million.'
- )).to.be.below(10)
- })
-
- it('May transcribe a media file using a local PyTorch model file', async function () {
- this.timeout(2 * 1000 * 60)
- await transcriber.transcribe({
- mediaFilePath: shortVideoPath,
- model: await TranscriptionModel.fromPath(join(modelsDirectory, 'tiny.pt')),
- language: 'en'
- })
- })
-
- it('May transcribe a media file in french', async function () {
- this.timeout(2 * 1000 * 60)
- const transcript = await transcriber.transcribe({
- mediaFilePath: frVideoPath,
- language: 'fr',
- format: 'txt'
- })
-
- expect(transcript.format).to.equals('txt')
- expect(transcript.language).to.equals('fr')
- expect(await transcript.read()).not.to.be.empty
- })
-
- it('Guesses the video language if not provided', async function () {
- this.timeout(2 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath })
- expect(transcript.language).to.equals('fr')
- })
-
- it('Should produce a text transcript similar to openai-whisper implementation', async function () {
- this.timeout(11 * 1000 * 60)
- const transcribeArgs: WhisperTranscribeArgs = {
- mediaFilePath: frVideoPath,
- model: await TranscriptionModel.fromPath(join(modelsDirectory, 'tiny.pt')),
- language: 'fr',
- format: 'txt'
- }
- const transcript = await transcriber.transcribe(transcribeArgs)
-
- const openaiTranscriber = new OpenaiTranscriber(
- {
- name: 'openai-whisper',
- requirements: [],
- type: 'binary',
- binary: 'whisper',
- supportedModelFormats: [ 'PyTorch' ]
- },
- createLogger(),
- join(transcriptDirectory, 'openai-whisper')
- )
- const openaiTranscript = await openaiTranscriber.transcribe(transcribeArgs)
-
- const transcriptFileEvaluator = new TranscriptFileEvaluator(openaiTranscript, transcript)
- expect(await transcriptFileEvaluator.wer()).to.be.below(25 / 100)
- expect(await transcriptFileEvaluator.cer()).to.be.below(15 / 100)
- })
-
- after(async function () {
- await rm(transcriptDirectory, { recursive: true, force: true })
- })
-})
diff --git a/packages/tests/src/transcription/whisper/transcriber/whisper-ctranslate2.spec.ts b/packages/tests/src/transcription/whisper/whisper-ctranslate2.spec.ts
similarity index 61%
rename from packages/tests/src/transcription/whisper/transcriber/whisper-ctranslate2.spec.ts
rename to packages/tests/src/transcription/whisper/whisper-ctranslate2.spec.ts
index 3a9984e87e..cd4f30a39e 100644
--- a/packages/tests/src/transcription/whisper/transcriber/whisper-ctranslate2.spec.ts
+++ b/packages/tests/src/transcription/whisper/whisper-ctranslate2.spec.ts
@@ -1,50 +1,58 @@
/* eslint-disable @typescript-eslint/no-unused-expressions, max-len */
-import { expect, config } from 'chai'
-import { createLogger } from 'winston'
-import { join } from 'node:path'
-import { mkdir, rm } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
import { buildAbsoluteFixturePath } from '@peertube/peertube-node-utils'
import {
- Ctranslate2Transcriber, downloadFile,
- levenshteinDistance,
+ Ctranslate2Transcriber,
OpenaiTranscriber,
TranscriptFile,
- TranscriptFileEvaluator,
- TranscriptionModel, unzip,
- WhisperTranscribeArgs
+ TranscriptionModel
} from '@peertube/peertube-transcription'
-import { FIXTURE_URLS } from '@tests/shared/fixture-urls.js'
+import { TranscriptFileEvaluator, levenshteinDistance } from '@peertube/peertube-transcription-devtools'
+import { downloadCustomModelsIfNeeded, getCustomModelPath } from '@tests/shared/transcription.js'
+import { config, expect } from 'chai'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { createLogger } from 'winston'
config.truncateThreshold = 0
describe('Whisper CTranslate2 transcriber', function () {
const tmpDirectory = join(tmpdir(), 'peertube-transcription')
const transcriptDirectory = join(tmpDirectory, 'transcriber', 'ctranslate2')
- const modelsDirectory = join(tmpDirectory, 'models')
+
const shortVideoPath = buildAbsoluteFixturePath('transcription/videos/the_last_man_on_earth.mp4')
const frVideoPath = buildAbsoluteFixturePath('transcription/videos/derive_sectaire.mp4')
- const transcriber = new Ctranslate2Transcriber(
- {
- name: 'anyNameShouldBeFineReally',
- requirements: [],
+
+ const transcriber = new Ctranslate2Transcriber({
+ engine: {
+ name: 'whisper-ctranslate2',
type: 'binary',
- binary: 'whisper-ctranslate2',
- supportedModelFormats: [],
- languageDetection: true
+ command: 'whisper-ctranslate2',
+ supportedModelFormats: [ 'CTranslate2' ],
+ languageDetection: true,
+ version: '0.4.4'
},
- createLogger(),
- transcriptDirectory
- )
+ logger: createLogger()
+ })
+
+ const model = new TranscriptionModel('tiny')
before(async function () {
- this.timeout(1 * 1000 * 60)
- await mkdir(transcriptDirectory, { recursive: true })
- await unzip(await downloadFile(FIXTURE_URLS.transcriptionModels, tmpDirectory))
+ this.timeout(120000)
+
+ await ensureDir(transcriptDirectory)
+
+ await downloadCustomModelsIfNeeded('faster-whisper-tiny')
})
- it('Should transcribe a media file and provide a valid path to a transcript file in `vtt` format by default', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en' })
+ it('Should transcribe a media file and provide a valid path to a transcript file in `vtt` format', async function () {
+ const transcript = await transcriber.transcribe({
+ mediaFilePath: shortVideoPath,
+ language: 'en',
+ format: 'vtt',
+ model,
+ transcriptDirectory
+ })
expect(transcript.format).to.equals('vtt')
expect(transcript.language).to.equals('en')
@@ -52,7 +60,13 @@ describe('Whisper CTranslate2 transcriber', function () {
})
it('May produce a transcript file in the `srt` format', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'srt' })
+ const transcript = await transcriber.transcribe({
+ mediaFilePath: shortVideoPath,
+ language: 'en',
+ format: 'srt',
+ model,
+ transcriptDirectory
+ })
expect(transcript.format).to.equals('srt')
expect(transcript.language).to.equals('en')
@@ -60,7 +74,13 @@ describe('Whisper CTranslate2 transcriber', function () {
})
it('May produce a transcript file in the `txt` format', async function () {
- const transcript = await transcriber.transcribe({ mediaFilePath: shortVideoPath, language: 'en', format: 'txt' })
+ const transcript = await transcriber.transcribe({
+ mediaFilePath: shortVideoPath,
+ language: 'en',
+ format: 'txt',
+ model,
+ transcriptDirectory
+ })
expect(await transcript.equals(new TranscriptFile({
path: join(transcriptDirectory, 'the_last_man_on_earth.txt'),
format: 'txt',
@@ -78,10 +98,12 @@ describe('Whisper CTranslate2 transcriber', function () {
it('May transcribe a media file using a local CTranslate2 model', async function () {
this.timeout(2 * 1000 * 60)
+
const transcript = await transcriber.transcribe({
mediaFilePath: shortVideoPath,
- model: await TranscriptionModel.fromPath(join(modelsDirectory, 'faster-whisper-tiny')),
+ model: await TranscriptionModel.fromPath(getCustomModelPath('faster-whisper-tiny')),
language: 'en',
+ transcriptDirectory,
format: 'txt'
})
@@ -92,7 +114,14 @@ describe('Whisper CTranslate2 transcriber', function () {
it('May transcribe a media file in french', async function () {
this.timeout(5 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath, language: 'fr', format: 'txt' })
+
+ const transcript = await transcriber.transcribe({
+ mediaFilePath: frVideoPath,
+ language: 'fr',
+ format: 'txt',
+ model,
+ transcriptDirectory
+ })
expect(transcript.format).to.equals('txt')
expect(transcript.language).to.equals('fr')
@@ -101,30 +130,39 @@ describe('Whisper CTranslate2 transcriber', function () {
it('Guesses the video language if not provided', async function () {
this.timeout(2 * 1000 * 60)
- const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath })
+
+ const transcript = await transcriber.transcribe({ mediaFilePath: frVideoPath, format: 'vtt', model, transcriptDirectory })
expect(transcript.language).to.equals('fr')
})
it('Should produce a text transcript similar to openai-whisper implementation', async function () {
this.timeout(10 * 1000 * 60)
- const transcribeArgs: WhisperTranscribeArgs = {
+
+ const transcribeArgs = {
mediaFilePath: frVideoPath,
language: 'fr',
- format: 'txt'
+ format: 'txt' as 'txt',
+ transcriptDirectory,
+ model
}
+
const transcript = await transcriber.transcribe(transcribeArgs)
- const openaiTranscriber = new OpenaiTranscriber(
- {
+
+ const openaiTranscriber = new OpenaiTranscriber({
+ engine: {
name: 'openai-whisper',
- requirements: [],
type: 'binary',
- binary: 'whisper',
- supportedModelFormats: [ 'PyTorch' ]
+ command: 'whisper',
+ supportedModelFormats: [ 'PyTorch' ],
+ version: '0.4.4'
},
- createLogger(),
- join(transcriptDirectory, 'openai-whisper')
- )
- const openaiTranscript = await openaiTranscriber.transcribe(transcribeArgs)
+ logger: createLogger()
+ })
+ const openaiTranscript = await openaiTranscriber.transcribe({
+ ...transcribeArgs,
+
+ transcriptDirectory: join(transcriptDirectory, 'openai-whisper')
+ })
const transcriptFileEvaluator = new TranscriptFileEvaluator(openaiTranscript, transcript)
expect(await transcriptFileEvaluator.wer()).to.be.below(20 / 100)
@@ -132,6 +170,6 @@ describe('Whisper CTranslate2 transcriber', function () {
})
after(async function () {
- await rm(transcriptDirectory, { recursive: true, force: true })
+ await remove(transcriptDirectory)
})
})
diff --git a/packages/tests/tsconfig.json b/packages/tests/tsconfig.json
index 5b8e2a6c4e..642b973933 100644
--- a/packages/tests/tsconfig.json
+++ b/packages/tests/tsconfig.json
@@ -8,13 +8,13 @@
"@tests/*": [ "./src/*" ],
"@server/*": [ "../../server/core/*" ],
"@peertube/peertube-transcription": [ "../transcription" ],
- "@peertube/peertube-jiwer": [ "../jiwer" ],
+ "@peertube/peertube-transcription-devtools": [ "../transcription-devtools" ],
}
},
"references": [
{ "path": "../core-utils" },
{ "path": "../ffmpeg" },
- { "path": "../jiwer" },
+ { "path": "../transcription-devtools" },
{ "path": "../models" },
{ "path": "../node-utils" },
{ "path": "../typescript-utils" },
diff --git a/packages/transcription-devtools/README.md b/packages/transcription-devtools/README.md
new file mode 100644
index 0000000000..9e9799ccfa
--- /dev/null
+++ b/packages/transcription-devtools/README.md
@@ -0,0 +1,63 @@
+# Transcription DevTools
+
+Includes:
+ * __JiWER__ CLI NodeJS wrapper
+ * Benchmark tool to test multiple transcription engines
+ * TypeScript classes to evaluate word-error-rate of files generated by the transcription
+
+## Build
+
+```sh
+npm run build
+```
+
+## Benchmark
+
+A benchmark of available __transcribers__ might be run with:
+```sh
+npm run benchmark
+```
+```
+┌────────────────────────┬───────────────────────┬───────────────────────┬──────────┬────────┬───────────────────────┐
+│ (index) │ WER │ CER │ duration │ model │ engine │
+├────────────────────────┼───────────────────────┼───────────────────────┼──────────┼────────┼───────────────────────┤
+│ 5yZGBYqojXe7nuhq1TuHvz │ '28.39506172839506%' │ '9.62457337883959%' │ '41s' │ 'tiny' │ 'openai-whisper' │
+│ x6qREJ2AkTU4e5YmvfivQN │ '29.75206611570248%' │ '10.46195652173913%' │ '15s' │ 'tiny' │ 'whisper-ctranslate2' │
+└────────────────────────┴───────────────────────┴───────────────────────┴──────────┴────────┴───────────────────────┘
+```
+
+The benchmark may be run with multiple model builtin sizes:
+
+```sh
+MODELS=tiny,small,large npm run benchmark
+```
+
+## Jiwer
+
+> *JiWER is a python tool for computing the word-error-rate of ASR systems.*
+> https://jitsi.github.io/jiwer/cli/
+
+__JiWER__ serves as a reference implementation to calculate errors rates between 2 text files:
+- WER (Word Error Rate)
+- CER (Character Error Rate)
+
+
+### Usage
+
+```typescript
+const jiwerCLI = new JiwerClI('./reference.txt', './hypothesis.txt')
+
+// WER as a percentage, ex: 0.03 -> 3%
+console.log(await jiwerCLI.wer())
+
+// CER as a percentage: 0.01 -> 1%
+console.log(await jiwerCLI.cer())
+
+// Detailed comparison report
+console.log(await jiwerCLI.alignment())
+```
+
+## Resources
+
+- https://jitsi.github.io/jiwer/
+- https://github.com/rapidfuzz/RapidFuzz
diff --git a/packages/jiwer/package.json b/packages/transcription-devtools/package.json
similarity index 65%
rename from packages/jiwer/package.json
rename to packages/transcription-devtools/package.json
index b014769567..8856fb7829 100644
--- a/packages/jiwer/package.json
+++ b/packages/transcription-devtools/package.json
@@ -1,5 +1,5 @@
{
- "name": "@peertube/peertube-jiwer",
+ "name": "@peertube/peertube-transcription-devtools",
"private": true,
"version": "0.0.0",
"main": "dist/index.js",
@@ -12,9 +12,9 @@
"type": "module",
"devDependencies": {},
"scripts": {
- "preinstall": "pip install -r requirements.txt",
"build": "tsc",
- "watch": "tsc -w"
+ "watch": "tsc -w",
+ "benchmark": "tsx --conditions=peertube:tsx --tsconfig ./tsconfig.json ./src/benchmark.ts"
},
"dependencies": {}
}
diff --git a/packages/transcription-devtools/requirements.txt b/packages/transcription-devtools/requirements.txt
new file mode 100644
index 0000000000..68a1e7c5bc
--- /dev/null
+++ b/packages/transcription-devtools/requirements.txt
@@ -0,0 +1 @@
+jiwer
diff --git a/packages/transcription/src/benchmark.ts b/packages/transcription-devtools/src/benchmark.ts
similarity index 82%
rename from packages/transcription/src/benchmark.ts
rename to packages/transcription-devtools/src/benchmark.ts
index 4cac164493..884af03c08 100644
--- a/packages/transcription/src/benchmark.ts
+++ b/packages/transcription-devtools/src/benchmark.ts
@@ -1,17 +1,18 @@
-import { createLogger, transports, format } from 'winston'
-import { join } from 'node:path'
-import { performance, PerformanceObserver } from 'node:perf_hooks'
-import { tmpdir } from 'node:os'
-import { rm, mkdir } from 'node:fs/promises'
-import { buildAbsoluteFixturePath, buildSUUID, SUUID } from '@peertube/peertube-node-utils'
+import { millisecondsToTime } from '@peertube/peertube-core-utils'
+import { SUUID, buildAbsoluteFixturePath, buildSUUID } from '@peertube/peertube-node-utils'
import {
- transcriberFactory,
TranscriptFile,
- TranscriptFileEvaluator,
TranscriptionEngine,
- TranscriptionModel
+ TranscriptionEngineName,
+ TranscriptionModel,
+ transcriberFactory
} from '@peertube/peertube-transcription'
-import { millisecondsToTime } from '@peertube/peertube-core-utils'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PerformanceObserver, performance } from 'node:perf_hooks'
+import { createLogger, format, transports } from 'winston'
+import { TranscriptFileEvaluator } from './transcript-file-evaluator.js'
interface BenchmarkResult {
uuid: SUUID
@@ -59,16 +60,15 @@ const formatBenchmarkResult = ({ WER, CER, duration, engine, model }: Partial<Be
void (async () => {
const logger = createLogger()
logger.add(new transports.Console({ format: format.printf(log => log.message) }))
- const transcribers = [
- 'openai-whisper',
- 'whisper-ctranslate2',
- 'whisper-timestamped'
- ]
+
+ const transcribers: TranscriptionEngineName[] = [ 'openai-whisper', 'whisper-ctranslate2' ]
const models = process.env.MODELS
? process.env.MODELS.trim().split(',').map(modelName => modelName.trim()).filter(modelName => modelName)
: [ 'tiny' ]
const transcriptDirectory = join(tmpdir(), 'peertube-transcription', 'benchmark')
+ const pipDirectory = join(tmpdir(), 'peertube-transcription', 'pip')
+
const mediaFilePath = buildAbsoluteFixturePath('transcription/videos/derive_sectaire.mp4')
const referenceTranscriptFile = new TranscriptFile({
path: buildAbsoluteFixturePath('transcription/videos/derive_sectaire.txt'),
@@ -79,7 +79,7 @@ void (async () => {
let benchmarkResults: Record<string, BenchmarkResult> = {}
// before
- await mkdir(transcriptDirectory, { recursive: true })
+ await ensureDir(transcriptDirectory)
const performanceObserver = new PerformanceObserver((items) => {
items
.getEntries()
@@ -97,11 +97,13 @@ void (async () => {
for (const transcriberName of transcribers) {
logger.info(`Create "${transcriberName}" transcriber for the benchmark...`)
- const transcriber = transcriberFactory.createFromEngineName(
- transcriberName,
- createLogger(),
- transcriptDirectory
- )
+ const transcriber = transcriberFactory.createFromEngineName({
+ engineName: transcriberName,
+ logger: createLogger(),
+ binDirectory: join(pipDirectory, 'bin')
+ })
+
+ await transcriber.install(pipDirectory)
for (const modelName of models) {
logger.info(`Run benchmark with "${modelName}" model:`)
@@ -110,6 +112,7 @@ void (async () => {
const transcriptFile = await transcriber.transcribe({
mediaFilePath,
model,
+ transcriptDirectory,
language: 'fr',
format: 'txt',
runId: uuid
@@ -134,6 +137,6 @@ void (async () => {
Object.values(benchmarkResultsGroupedByModel).forEach(benchmark => console.table(benchmark))
// after
- await rm(transcriptDirectory, { recursive: true, force: true })
+ await remove(transcriptDirectory)
performance.clearMarks()
})()
diff --git a/packages/transcription-devtools/src/index.ts b/packages/transcription-devtools/src/index.ts
new file mode 100644
index 0000000000..fd7f80b9bb
--- /dev/null
+++ b/packages/transcription-devtools/src/index.ts
@@ -0,0 +1,5 @@
+export * from './jiwer-cli.js'
+export * from './levenshtein.js'
+export * from './transcript-file-evaluator-interface.js'
+export * from './transcript-file-evaluator.js'
+export * from './utils.js'
diff --git a/packages/jiwer/src/jiwer-cli.ts b/packages/transcription-devtools/src/jiwer-cli.ts
similarity index 100%
rename from packages/jiwer/src/jiwer-cli.ts
rename to packages/transcription-devtools/src/jiwer-cli.ts
diff --git a/packages/transcription/src/levenshtein.ts b/packages/transcription-devtools/src/levenshtein.ts
similarity index 100%
rename from packages/transcription/src/levenshtein.ts
rename to packages/transcription-devtools/src/levenshtein.ts
diff --git a/packages/transcription/src/transcript/transcript-file-evaluator-interface.ts b/packages/transcription-devtools/src/transcript-file-evaluator-interface.ts
similarity index 100%
rename from packages/transcription/src/transcript/transcript-file-evaluator-interface.ts
rename to packages/transcription-devtools/src/transcript-file-evaluator-interface.ts
diff --git a/packages/transcription/src/transcript/transcript-file-evaluator.ts b/packages/transcription-devtools/src/transcript-file-evaluator.ts
similarity index 75%
rename from packages/transcription/src/transcript/transcript-file-evaluator.ts
rename to packages/transcription-devtools/src/transcript-file-evaluator.ts
index 7ae411ee44..faf696e753 100644
--- a/packages/transcription/src/transcript/transcript-file-evaluator.ts
+++ b/packages/transcription-devtools/src/transcript-file-evaluator.ts
@@ -1,14 +1,14 @@
import assert from 'node:assert'
-import { JiwerClI } from '@peertube/peertube-jiwer'
import { TranscriptFileEvaluatorInterface } from './transcript-file-evaluator-interface.js'
-import { TranscriptFileInterface } from './index.js'
+import { TranscriptFile } from '@peertube/peertube-transcription'
+import { JiwerClI } from './jiwer-cli.js'
export class TranscriptFileEvaluator implements TranscriptFileEvaluatorInterface {
- referenceTranscriptFile: TranscriptFileInterface
- hypothesisTranscriptFile: TranscriptFileInterface
+ referenceTranscriptFile: TranscriptFile
+ hypothesisTranscriptFile: TranscriptFile
jiwerCLI: JiwerClI
- constructor (referenceTranscriptFile: TranscriptFileInterface, hypothesisTranscriptFile: TranscriptFileInterface) {
+ constructor (referenceTranscriptFile: TranscriptFile, hypothesisTranscriptFile: TranscriptFile) {
assert(referenceTranscriptFile.format === 'txt', 'Can only evaluate txt transcript file')
assert(hypothesisTranscriptFile.format === 'txt', 'Can only evaluate txt transcript file')
diff --git a/packages/transcription/src/utils.ts b/packages/transcription-devtools/src/utils.ts
similarity index 100%
rename from packages/transcription/src/utils.ts
rename to packages/transcription-devtools/src/utils.ts
diff --git a/packages/jiwer/tsconfig.json b/packages/transcription-devtools/tsconfig.json
similarity index 51%
rename from packages/jiwer/tsconfig.json
rename to packages/transcription-devtools/tsconfig.json
index 58fa2330ba..39f9bd4b6d 100644
--- a/packages/jiwer/tsconfig.json
+++ b/packages/transcription-devtools/tsconfig.json
@@ -3,6 +3,9 @@
"compilerOptions": {
"outDir": "./dist",
"rootDir": "src",
- "tsBuildInfoFile": "./dist/.tsbuildinfo"
- }
+ "tsBuildInfoFile": "./dist/.tsbuildinfo",
+ },
+ "references": [
+ { "path": "../transcription" }
+ ]
}
diff --git a/packages/transcription/README.md b/packages/transcription/README.md
index b16ff75d4d..7036f54b64 100644
--- a/packages/transcription/README.md
+++ b/packages/transcription/README.md
@@ -1,45 +1,50 @@
# Transcription
Video **transcription** consists in transcribing the audio content of a video to a text.
+
> This process might be called __Automatic Speech Recognition__ or __Speech to Text__ in more general context.
-Provide a common API to many transcription backend, currently :
-- `openai-whisper` CLI
-- `faster-whisper` (*via* `whisper-ctranslate2` CLI)
-- `whisper-timestamped`
+Provide a common API to many transcription backend, currently:
+ - `openai-whisper` CLI
+ - `faster-whisper` (*via* `whisper-ctranslate2` CLI)
> Potential candidates could be: whisper-cpp, vosk, ...
## Requirements
-- Python
-- PIP
+ - Python 3
+ - PIP
And at least one of the following transcription backend:
-- Python :
- - `openai-whisper`
- - `whisper-ctranslate2>=0.4.3`
- - `whisper-timestamped>=1.15.4`
-
-And to run the transcript evaluation tests :
-- Python
- - `jiwer>=3.04`
+ - Python:
+ - `openai-whisper`
+ - `whisper-ctranslate2>=0.4.3`
## Usage
-Create a transcriber manually :
+Create a transcriber manually:
+
```typescript
import { OpenaiTranscriber } from '@peertube/peertube-transcription'
(async () => {
- // create a transcriber powered by OpeanAI Whisper CLI
+ // Optional if you want to use a local installation of transcribe engines
+ const binDirectory = 'local/pip/path/bin'
+
+ // Create a transcriber powered by OpenAI Whisper CLI
const transcriber = new OpenaiTranscriber({
name: 'openai-whisper',
- binary: 'whisper',
- languageDetection: true
+ command: 'whisper',
+ languageDetection: true,
+ binDirectory
});
+ // If not installed globally, install the transcriber engine (use pip under the hood)
+ await transcriber.install('local/pip/path')
+
+ // Transcribe
const transcriptFile = await transcriber.transcribe({
mediaFilePath: './myVideo.mp4',
+ model: 'tiny',
format: 'txt'
});
@@ -55,38 +60,24 @@ import { WhisperBuiltinModel } from '@peertube/peertube-transcription/dist'
const transcriptFile = await transcriber.transcribe({
mediaFilePath: './myVideo.mp4',
- model: WhisperBuiltinModel.fromPath('./models/large.pt'),
+ model: await WhisperBuiltinModel.fromPath('./models/large.pt'),
format: 'txt'
});
```
You may use the builtin Factory if you're happy with the default configuration:
+
```Typescript
import { transcriberFactory } from '@peertube/peertube-transcription'
-transcriberFactory.createFromEngineName('openai-whisper')
-```
-> For further usage [../tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts](../tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts)
-
-## Benchmark
-A benchmark of available __transcribers__ might be run with:
-```sh
-npm run benchmark
-```
-```
-┌────────────────────────┬───────────────────────┬───────────────────────┬──────────┬────────┬───────────────────────┐
-│ (index) │ WER │ CER │ duration │ model │ engine │
-├────────────────────────┼───────────────────────┼───────────────────────┼──────────┼────────┼───────────────────────┤
-│ 5yZGBYqojXe7nuhq1TuHvz │ '28.39506172839506%' │ '9.62457337883959%' │ '41s' │ 'tiny' │ 'openai-whisper' │
-│ x6qREJ2AkTU4e5YmvfivQN │ '29.75206611570248%' │ '10.46195652173913%' │ '15s' │ 'tiny' │ 'whisper-ctranslate2' │
-│ qbt6BekKMVzxq4KCSLCzt3 │ '31.020408163265305%' │ '10.784982935153584%' │ '20s' │ 'tiny' │ 'whisper-timestamped' │
-└────────────────────────┴───────────────────────┴───────────────────────┴──────────┴────────┴───────────────────────┘
+transcriberFactory.createFromEngineName({
+ engineName: transcriberName,
+ logger: compatibleWinstonLogger,
+ transcriptDirectory: '/tmp/transcription'
+})
```
+> For further usage [../tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts](../tests/src/transcription/whisper/transcriber/openai-transcriber.spec.ts)
-The benchmark may be run with multiple model builtin sizes:
-```sh
-MODELS=tiny,small,large npm run benchmark
-```
## Lexicon
- ONNX: Open Neural Network eXchange. A specification, the ONNX Runtime run these models.
diff --git a/packages/transcription/package.json b/packages/transcription/package.json
index 9138de4dc8..366a086869 100644
--- a/packages/transcription/package.json
+++ b/packages/transcription/package.json
@@ -12,10 +12,8 @@
"type": "module",
"devDependencies": {},
"scripts": {
- "preinstall": "pip install -r requirements.txt",
"build": "tsc",
- "watch": "tsc -w",
- "benchmark": "tsx --conditions=peertube:tsx --tsconfig ./tsconfig.json ./src/benchmark.ts"
+ "watch": "tsc -w"
},
"dependencies": {}
}
diff --git a/packages/transcription/requirements.txt b/packages/transcription/requirements.txt
deleted file mode 100644
index bc457025cd..0000000000
--- a/packages/transcription/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-openai-whisper==20231117
-whisper-ctranslate2==0.4.4
-whisper-timestamped==1.15.4
diff --git a/packages/transcription/src/abstract-transcriber.ts b/packages/transcription/src/abstract-transcriber.ts
index b9a0f66e55..b3d998b729 100644
--- a/packages/transcription/src/abstract-transcriber.ts
+++ b/packages/transcription/src/abstract-transcriber.ts
@@ -1,38 +1,47 @@
-import { createLogger, Logger } from 'winston'
-import { join } from 'node:path'
+import { SimpleLogger } from '@peertube/peertube-models'
+import { buildSUUID, SUUID } from '@peertube/peertube-node-utils'
import { PerformanceObserver } from 'node:perf_hooks'
-import { buildSUUID, SUUID, root } from '@peertube/peertube-node-utils'
+import { join } from 'path'
+import { TranscriptFile, TranscriptFormat } from './transcript-file.js'
import { TranscriptionEngine } from './transcription-engine.js'
import { TranscriptionModel } from './transcription-model.js'
import { TranscriptionRun } from './transcription-run.js'
-import { TranscriptFile, TranscriptFormat } from './transcript/index.js'
export interface TranscribeArgs {
mediaFilePath: string
model: TranscriptionModel
+ format: TranscriptFormat
+ transcriptDirectory: string
+
language?: string
- format?: TranscriptFormat
runId?: SUUID
}
export abstract class AbstractTranscriber {
- public static DEFAULT_TRANSCRIPT_DIRECTORY = join(root(), 'dist', 'transcripts')
-
engine: TranscriptionEngine
- logger: Logger
- transcriptDirectory: string
- performanceObserver?: PerformanceObserver
- run?: TranscriptionRun
- constructor (
- engine: TranscriptionEngine,
- logger: Logger = createLogger(),
- transcriptDirectory: string = AbstractTranscriber.DEFAULT_TRANSCRIPT_DIRECTORY,
+ protected binDirectory: string
+ protected enginePath: string
+
+ protected logger: SimpleLogger
+
+ protected performanceObserver?: PerformanceObserver
+ protected run?: TranscriptionRun
+
+ constructor (options: {
+ engine: TranscriptionEngine
+ binDirectory?: string
+ enginePath?: string
+
+ logger: SimpleLogger
performanceObserver?: PerformanceObserver
- ) {
+ }) {
+ const { engine, logger, enginePath, binDirectory, performanceObserver } = options
+
this.engine = engine
+ this.enginePath = enginePath
this.logger = logger
- this.transcriptDirectory = transcriptDirectory
+ this.binDirectory = binDirectory
this.performanceObserver = performanceObserver
}
@@ -59,11 +68,14 @@ export abstract class AbstractTranscriber {
return model.format === 'PyTorch'
}
- abstract transcribe ({
- mediaFilePath,
- model,
- language,
- format = 'vtt',
- runId = buildSUUID()
- }: TranscribeArgs): Promise<TranscriptFile>
+ protected getEngineBinary () {
+ if (this.enginePath) return this.enginePath
+ if (this.binDirectory) return join(this.binDirectory, this.engine.command)
+
+ return this.engine.command
+ }
+
+ abstract transcribe (options: TranscribeArgs): Promise<TranscriptFile>
+
+ abstract install (path: string): Promise<void>
}
diff --git a/packages/transcription/src/index.ts b/packages/transcription/src/index.ts
index 44eaa07990..9ae289181b 100644
--- a/packages/transcription/src/index.ts
+++ b/packages/transcription/src/index.ts
@@ -1,13 +1,12 @@
import { TranscriberFactory } from './transcriber-factory.js'
import { engines } from './whisper/index.js'
-export * from './transcript/index.js'
-export * from './levenshtein.js'
+export * from './abstract-transcriber.js'
+export * from './transcript-file.js'
export * from './subtitle.js'
export * from './transcription-engine.js'
export * from './transcription-model.js'
export * from './transcription-run.js'
-export * from './utils.js'
export * from './whisper/index.js'
export const transcriberFactory = new TranscriberFactory(engines)
diff --git a/packages/transcription/src/transcriber-factory.ts b/packages/transcription/src/transcriber-factory.ts
index cb22d617c9..c682052bc3 100644
--- a/packages/transcription/src/transcriber-factory.ts
+++ b/packages/transcription/src/transcriber-factory.ts
@@ -1,10 +1,6 @@
-import { Logger, createLogger } from 'winston'
-import { TranscriptionEngine } from './transcription-engine.js'
-import {
- Ctranslate2Transcriber,
- OpenaiTranscriber, WhisperTimestampedTranscriber
-} from './whisper/index.js'
-import { AbstractTranscriber } from './abstract-transcriber.js'
+import { SimpleLogger } from '@peertube/peertube-models'
+import { TranscriptionEngine, TranscriptionEngineName } from './transcription-engine.js'
+import { Ctranslate2Transcriber, OpenaiTranscriber } from './whisper/index.js'
export class TranscriberFactory {
engines: TranscriptionEngine[]
@@ -13,26 +9,28 @@ export class TranscriberFactory {
this.engines = engines
}
- createFromEngineName (
- engineName: string,
- logger: Logger = createLogger(),
- transcriptDirectory: string = AbstractTranscriber.DEFAULT_TRANSCRIPT_DIRECTORY
- ) {
- const engine = this.getEngineByName(engineName)
+ createFromEngineName (options: {
+ engineName: TranscriptionEngineName
+ enginePath?: string
+ binDirectory?: string
- const transcriberArgs: ConstructorParameters<typeof AbstractTranscriber> = [
- engine,
- logger,
- transcriptDirectory
- ]
+ logger: SimpleLogger
+ }) {
+ const { engineName } = options
+
+ const transcriberArgs = {
+ ...options,
+
+ engine: this.getEngineByName(engineName)
+ }
switch (engineName) {
case 'openai-whisper':
- return new OpenaiTranscriber(...transcriberArgs)
+ return new OpenaiTranscriber(transcriberArgs)
+
case 'whisper-ctranslate2':
- return new Ctranslate2Transcriber(...transcriberArgs)
- case 'whisper-timestamped':
- return new WhisperTimestampedTranscriber(...transcriberArgs)
+ return new Ctranslate2Transcriber(transcriberArgs)
+
default:
throw new Error(`Unimplemented engine ${engineName}`)
}
diff --git a/packages/transcription/src/transcript/transcript-file.ts b/packages/transcription/src/transcript-file.ts
similarity index 69%
rename from packages/transcription/src/transcript/transcript-file.ts
rename to packages/transcription/src/transcript-file.ts
index 36af9fa8fc..b2c17e0b6d 100644
--- a/packages/transcription/src/transcript/transcript-file.ts
+++ b/packages/transcription/src/transcript-file.ts
@@ -1,20 +1,16 @@
-import { statSync } from 'node:fs'
+import assert from 'node:assert'
import { readFile, writeFile } from 'node:fs/promises'
import { extname } from 'node:path'
-import assert from 'node:assert'
-import { TranscriptFileInterface, TranscriptFormat } from './transcript-file-interface.js'
-import { TranscriptFileEvaluator } from './transcript-file-evaluator.js'
-import { srtToTxt } from '../subtitle.js'
-import { levenshteinDistance } from '../levenshtein.js'
+import { srtToTxt } from './subtitle.js'
+
+export type TranscriptFormat = 'txt' | 'vtt' | 'srt' | 'json'
-export class TranscriptFile implements TranscriptFileInterface {
+export class TranscriptFile {
path: string
language: string
format: TranscriptFormat = 'vtt'
constructor ({ path, language, format = 'vtt' }: { path: string, language: string, format?: TranscriptFormat }) {
- statSync(path)
-
this.path = path
this.language = language
this.format = format
@@ -25,7 +21,7 @@ export class TranscriptFile implements TranscriptFileInterface {
* @see https://nodejs.org/docs/latest-v18.x/api/fs.html#filehandlereadfileoptions for options
*/
async read (options: Parameters<typeof readFile>[1] = 'utf8') {
- return await readFile(this.path, options)
+ return readFile(this.path, options)
}
static fromPath (path: string, language = 'en') {
@@ -68,21 +64,7 @@ export class TranscriptFile implements TranscriptFileInterface {
return content === transcriptContent
}
- cer (transcript: TranscriptFile) {
- return (new TranscriptFileEvaluator(this, transcript)).cer()
- }
-
- async evaluate (transcript: TranscriptFile) {
- const evaluator = new TranscriptFileEvaluator(this, transcript)
-
- return evaluator.evaluate()
- }
-
async readAsTxt () {
return srtToTxt(String(await this.read()))
}
-
- async distance (transcript: TranscriptFile) {
- return levenshteinDistance(await this.readAsTxt(), await transcript.readAsTxt())
- }
}
diff --git a/packages/transcription/src/transcript/index.ts b/packages/transcription/src/transcript/index.ts
deleted file mode 100644
index bd76d1a863..0000000000
--- a/packages/transcription/src/transcript/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from './transcript-file.js'
-export * from './transcript-file-evaluator.js'
-export * from './transcript-file-interface.js'
diff --git a/packages/transcription/src/transcript/transcript-file-interface.ts b/packages/transcription/src/transcript/transcript-file-interface.ts
deleted file mode 100644
index d30b6913fc..0000000000
--- a/packages/transcription/src/transcript/transcript-file-interface.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type TranscriptFormat = 'txt' | 'vtt' | 'srt' | 'json'
-
-export type TranscriptFileInterface = { path: string, language?: string, format: TranscriptFormat }
diff --git a/packages/transcription/src/transcription-engine.ts b/packages/transcription/src/transcription-engine.ts
index 3174e39808..ebe81ddfe9 100644
--- a/packages/transcription/src/transcription-engine.ts
+++ b/packages/transcription/src/transcription-engine.ts
@@ -1,23 +1,16 @@
import { ModelFormat } from './transcription-model.js'
-/**
- * The engine, or framework.
- */
-export class TranscriptionEngine {
- name: string
+export type TranscriptionEngineName = 'openai-whisper' | 'whisper-ctranslate2'
+
+export interface TranscriptionEngine {
+ name: TranscriptionEngineName
description?: string
language?: string
- requirements: string[]
- type: 'binary' | 'bindings' | 'ws'
- binary: string
+ type: 'binary'
+ command: string
+ version: string
license?: string
forgeURL?: string
supportedModelFormats: ModelFormat[]
languageDetection?: true
- // There could be a default models.
- // There could be a list of default models
-
- constructor (parameters: TranscriptionEngine) {
- Object.assign(this, parameters)
- }
}
diff --git a/packages/transcription/src/transcription-run.ts b/packages/transcription/src/transcription-run.ts
index 608afbb6ad..570027a93e 100644
--- a/packages/transcription/src/transcription-run.ts
+++ b/packages/transcription/src/transcription-run.ts
@@ -1,11 +1,12 @@
+import { SimpleLogger } from '@peertube/peertube-models'
import { buildSUUID, SUUID } from '@peertube/peertube-node-utils'
-import { createLogger, Logger } from 'winston'
+import { createLogger } from 'winston'
export class TranscriptionRun {
uuid: SUUID
- logger: Logger
+ logger: SimpleLogger
- constructor (logger = createLogger(), uuid: SUUID = buildSUUID()) {
+ constructor (logger: SimpleLogger = createLogger(), uuid: SUUID = buildSUUID()) {
this.uuid = uuid
this.logger = logger
}
@@ -26,8 +27,8 @@ export class TranscriptionRun {
this.getStartPerformanceMarkName(),
this.getEndPerformanceMarkName()
)
- } catch (e) {
- this.logger.log({ level: 'error', message: e })
+ } catch (err) {
+ this.logger.error(err.message, { err })
}
}
diff --git a/packages/transcription/src/whisper/README.md b/packages/transcription/src/whisper/README.md
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/packages/transcription/src/whisper/engines.ts b/packages/transcription/src/whisper/engines.ts
index 711b098b73..ac4ce0babc 100644
--- a/packages/transcription/src/whisper/engines.ts
+++ b/packages/transcription/src/whisper/engines.ts
@@ -1,51 +1,28 @@
import { TranscriptionEngine } from '../transcription-engine.js'
export const engines: TranscriptionEngine[] = [
- {
- name : 'whisper-cpp',
- description : 'High-performance inference of OpenAI\'s Whisper automatic speech recognition model',
- type: 'binary',
- binary: 'main',
- language : 'cpp',
- requirements : [],
- forgeURL : 'https://github.com/ggerganov/whisper.cpp',
- license : 'MIT',
- supportedModelFormats: [ 'ONNX' ]
- },
{
name: 'openai-whisper',
description: 'High-performance inference of OpenAI\'s Whisper automatic speech recognition model',
- requirements: [ 'python', 'pyTorch', 'ffmpeg' ],
language: 'python',
type: 'binary',
- binary: 'whisper',
+ command: 'whisper',
forgeURL: 'https://github.com/openai/whisper',
license: 'MIT',
supportedModelFormats: [ 'PyTorch' ],
- languageDetection: true
+ languageDetection: true,
+ version: '20231117'
},
{
name: 'whisper-ctranslate2',
- description: '',
- requirements: [ 'python' ],
+ description: 'Whisper command line client compatible with original OpenAI client based on CTranslate2.',
language: 'python',
type: 'binary',
- binary: 'whisper-ctranslate2',
- forgeURL: 'https://github.com/openai/whisper',
- license: 'MIT',
- supportedModelFormats: [ 'CTranslate2' ],
- languageDetection: true
- },
- {
- name: 'whisper-timestamped',
- description: '',
- requirements: [ 'python' ],
- language: 'python',
- type: 'binary',
- binary: 'whisper_timestamped',
- forgeURL: 'https://github.com/openai/whisper',
+ command: 'whisper-ctranslate2',
+ forgeURL: 'https://github.com/Softcatala/whisper-ctranslate2',
license: 'MIT',
supportedModelFormats: [ 'CTranslate2' ],
- languageDetection: true
+ languageDetection: true,
+ version: '0.4.4'
}
]
diff --git a/packages/transcription/src/whisper/transcriber/ctranslate2-transcriber.ts b/packages/transcription/src/whisper/transcriber/ctranslate2-transcriber.ts
index 01b9739a33..260488123a 100644
--- a/packages/transcription/src/whisper/transcriber/ctranslate2-transcriber.ts
+++ b/packages/transcription/src/whisper/transcriber/ctranslate2-transcriber.ts
@@ -1,22 +1,26 @@
-import { $ } from 'execa'
import { buildSUUID } from '@peertube/peertube-node-utils'
+import { $ } from 'execa'
+import assert from 'node:assert'
import { lstat } from 'node:fs/promises'
-import { OpenaiTranscriber, WhisperTranscribeArgs } from './openai-transcriber.js'
-import { TranscriptFile } from '../../transcript/index.js'
+import { TranscribeArgs } from '../../abstract-transcriber.js'
+import { TranscriptFile } from '../../transcript-file.js'
+import { TranscriptionModel } from '../../transcription-model.js'
import { WhisperBuiltinModel } from '../whisper-builtin-model.js'
-import assert from 'node:assert'
+import { OpenaiTranscriber } from './openai-transcriber.js'
export class Ctranslate2Transcriber extends OpenaiTranscriber {
+
async transcribe ({
mediaFilePath,
model = new WhisperBuiltinModel('tiny'),
language,
- format = 'vtt',
+ format,
+ transcriptDirectory,
runId = buildSUUID()
- }: WhisperTranscribeArgs): Promise<TranscriptFile> {
+ }: TranscribeArgs): Promise<TranscriptFile> {
this.assertLanguageDetectionAvailable(language)
- const $$ = $({ verbose: process.env.NODE_ENV !== 'production' })
+ const $$ = $({ verbose: process.env.NODE_ENV !== 'production', env: this.getExecEnv() })
if (model.path) {
assert(await lstat(model.path).then(stats => stats.isDirectory()), 'Model path must be a path to a directory.')
@@ -27,7 +31,7 @@ export class Ctranslate2Transcriber extends OpenaiTranscriber {
this.createRun(runId)
this.startRun()
- await $$`${this.engine.binary} ${[
+ await $$`${this.getEngineBinary()} ${[
mediaFilePath,
...modelArgs,
'--word_timestamps',
@@ -35,15 +39,25 @@ export class Ctranslate2Transcriber extends OpenaiTranscriber {
'--output_format',
'all',
'--output_dir',
- this.transcriptDirectory,
+ transcriptDirectory,
...languageArgs
]}`
this.stopRun()
return new TranscriptFile({
- language: language || await this.getDetectedLanguage(mediaFilePath),
- path: this.getTranscriptFilePath(mediaFilePath, format),
+ language: language || await this.getDetectedLanguage(transcriptDirectory, mediaFilePath),
+ path: this.getTranscriptFilePath(transcriptDirectory, mediaFilePath, format),
format
})
}
+
+ supports (model: TranscriptionModel) {
+ return model.format === 'CTranslate2'
+ }
+
+ async install (directory: string) {
+ const $$ = $({ verbose: true })
+
+ await $$`pip3 install -U -t ${directory} whisper-ctranslate2==${this.engine.version}`
+ }
}
diff --git a/packages/transcription/src/whisper/transcriber/index.ts b/packages/transcription/src/whisper/transcriber/index.ts
index 950c39b073..3b9a2a7454 100644
--- a/packages/transcription/src/whisper/transcriber/index.ts
+++ b/packages/transcription/src/whisper/transcriber/index.ts
@@ -1,3 +1,2 @@
export * from './ctranslate2-transcriber.js'
export * from './openai-transcriber.js'
-export * from './timestamped-transcriber.js'
diff --git a/packages/transcription/src/whisper/transcriber/openai-transcriber.ts b/packages/transcription/src/whisper/transcriber/openai-transcriber.ts
index 5d9a7ce856..20f07b6152 100644
--- a/packages/transcription/src/whisper/transcriber/openai-transcriber.ts
+++ b/packages/transcription/src/whisper/transcriber/openai-transcriber.ts
@@ -1,31 +1,30 @@
-import { join } from 'path'
-import { $ } from 'execa'
import { buildSUUID } from '@peertube/peertube-node-utils'
-import { TranscriptFile, TranscriptFormat } from '../../transcript/index.js'
-import { AbstractTranscriber, TranscribeArgs } from '../../abstract-transcriber.js'
-import { WhisperBuiltinModel } from '../whisper-builtin-model.js'
-import { TranscriptionModel } from '../../transcription-model.js'
-import { readFile } from 'node:fs/promises'
+import { $ } from 'execa'
+import { readJSON } from 'fs-extra/esm'
import { parse } from 'node:path'
-
-export type WhisperTranscribeArgs = Omit<TranscribeArgs, 'model'> & { model?: TranscriptionModel }
+import { join, resolve } from 'path'
+import { AbstractTranscriber, TranscribeArgs } from '../../abstract-transcriber.js'
+import { TranscriptFile, TranscriptFormat } from '../../transcript-file.js'
export class OpenaiTranscriber extends AbstractTranscriber {
+
async transcribe ({
mediaFilePath,
- model = new WhisperBuiltinModel('tiny'),
+ model,
language,
- format = 'vtt',
+ format,
+ transcriptDirectory,
runId = buildSUUID()
- }: WhisperTranscribeArgs): Promise<TranscriptFile> {
+ }: TranscribeArgs): Promise<TranscriptFile> {
this.assertLanguageDetectionAvailable(language)
- const $$ = $({ verbose: process.env.NODE_ENV !== 'production' })
+ const $$ = $({ verbose: process.env.NODE_ENV !== 'production', env: this.getExecEnv() })
const languageArgs = language ? [ '--language', language ] : []
this.createRun(runId)
this.startRun()
- await $$`${this.engine.binary} ${[
+
+ await $$`${this.getEngineBinary()} ${[
mediaFilePath,
'--word_timestamps',
'True',
@@ -34,29 +33,45 @@ export class OpenaiTranscriber extends AbstractTranscriber {
'--output_format',
'all',
'--output_dir',
- this.transcriptDirectory,
+ transcriptDirectory,
...languageArgs
]}`
this.stopRun()
return new TranscriptFile({
- language: language || await this.getDetectedLanguage(mediaFilePath),
- path: this.getTranscriptFilePath(mediaFilePath, format),
+ language: language || await this.getDetectedLanguage(transcriptDirectory, mediaFilePath),
+ path: this.getTranscriptFilePath(transcriptDirectory, mediaFilePath, format),
format
})
}
- async getDetectedLanguage (mediaFilePath: string) {
- const { language } = await this.readJsonTranscriptFile(mediaFilePath)
+ // ---------------------------------------------------------------------------
+
+ protected async getDetectedLanguage (transcriptDirectory: string, mediaFilePath: string) {
+ const { language } = await this.readJsonTranscriptFile(transcriptDirectory, mediaFilePath)
return language
}
- async readJsonTranscriptFile (mediaFilePath: string) {
- return JSON.parse(await readFile(this.getTranscriptFilePath(mediaFilePath, 'json'), 'utf8'))
+ protected async readJsonTranscriptFile (transcriptDirectory: string, mediaFilePath: string) {
+ return readJSON(this.getTranscriptFilePath(transcriptDirectory, mediaFilePath, 'json'), 'utf8')
}
- getTranscriptFilePath (mediaFilePath: string, format: TranscriptFormat) {
- return join(this.transcriptDirectory, `${parse(mediaFilePath).name}.${format}`)
+ protected getTranscriptFilePath (transcriptDirectory: string, mediaFilePath: string, format: TranscriptFormat) {
+ return join(transcriptDirectory, `${parse(mediaFilePath).name}.${format}`)
+ }
+
+ // ---------------------------------------------------------------------------
+
+ async install (directory: string) {
+ const $$ = $({ verbose: true })
+
+ await $$`pip3 install -U -t ${[ directory ]} openai-whisper==${this.engine.version}`
+ }
+
+ protected getExecEnv () {
+ if (!this.binDirectory) return undefined
+
+ return { PYTHONPATH: resolve(this.binDirectory, '../') }
}
}
diff --git a/packages/transcription/src/whisper/transcriber/timestamped-transcriber.ts b/packages/transcription/src/whisper/transcriber/timestamped-transcriber.ts
deleted file mode 100644
index fcdd33eb1a..0000000000
--- a/packages/transcription/src/whisper/transcriber/timestamped-transcriber.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { $ } from 'execa'
-import { buildSUUID } from '@peertube/peertube-node-utils'
-import assert from 'node:assert'
-import { join, parse } from 'node:path'
-import { existsSync } from 'node:fs'
-import { rename } from 'node:fs/promises'
-import { TranscriptFile, TranscriptFormat } from '../../transcript/index.js'
-import { OpenaiTranscriber, WhisperTranscribeArgs } from './openai-transcriber.js'
-import { WhisperBuiltinModel } from '../whisper-builtin-model.js'
-
-export class WhisperTimestampedTranscriber extends OpenaiTranscriber {
- async transcribe ({
- mediaFilePath,
- model = new WhisperBuiltinModel('tiny'),
- language,
- format = 'vtt',
- runId = buildSUUID()
- }: WhisperTranscribeArgs): Promise<TranscriptFile> {
- this.assertLanguageDetectionAvailable(language)
-
- const $$ = $({ verbose: process.env.NODE_ENV !== 'production' })
- const languageArgs = language ? [ '--language', language ] : []
-
- this.createRun(runId)
- this.startRun()
- await $$`${this.engine.binary} ${[
- mediaFilePath,
- '--model',
- model?.path || model.name,
- '--output_format',
- 'all',
- '--output_dir',
- this.transcriptDirectory,
- ...languageArgs
- ]}`
- this.stopRun()
-
- const internalTranscriptPath = this.getTranscriptFilePath(mediaFilePath, format, false)
- const transcriptPath = join(this.transcriptDirectory, `${parse(mediaFilePath).name}.${format}`)
- // Whisper timestamped output files with the video file extension by defaults, ex: video.mp4.vtt
- // @see https://github.com/linto-ai/whisper-timestamped/issues/189
- assert(existsSync(internalTranscriptPath), `${internalTranscriptPath} file doesn't exist.`)
- await rename(internalTranscriptPath, transcriptPath)
- // communiquer-lors-dune-classe-transplantee.mp4.words.json
- return new TranscriptFile({
- language: language || await this.getDetectedLanguage(mediaFilePath),
- path: transcriptPath,
- format
- })
- }
-
- getTranscriptFilePath (mediaFilePath: string, format: TranscriptFormat, words = true) {
- return join(this.transcriptDirectory, `${parse(mediaFilePath).base}${words ? '.words' : ''}.${format}`)
- }
-}
diff --git a/packages/transcription/tsconfig.json b/packages/transcription/tsconfig.json
index 94971d65aa..c390b2ae91 100644
--- a/packages/transcription/tsconfig.json
+++ b/packages/transcription/tsconfig.json
@@ -9,7 +9,6 @@
{ "path": "../models" },
{ "path": "../core-utils" },
{ "path": "../node-utils" },
- { "path": "../jiwer" },
{ "path": "../server-commands" }
]
}
diff --git a/scripts/ci.sh b/scripts/ci.sh
index 8d483b42c8..88ae5d6899 100755
--- a/scripts/ci.sh
+++ b/scripts/ci.sh
@@ -131,6 +131,8 @@ elif [ "$1" = "api-5" ]; then
MOCHA_PARALLEL=true runJSTest "$1" $((2*$speedFactor)) $transcodingFiles $runnersFiles
elif [ "$1" = "external-plugins" ]; then
+ npm run install-dependencies:transcription --workspace=@peertube/tests
+
npm run build:server
npm run build:tests
npm run build:peertube-runner
@@ -147,12 +149,13 @@ elif [ "$1" = "lint" ]; then
( cd client && npm run lint )
elif [ "$1" = "transcription" ]; then
- npm run preinstall --workspace=@peertube/peertube-transcription --workspace=@peertube/peertube-jiwer
+ npm run install-dependencies:transcription --workspace=@peertube/tests
+
npm run build:server
npm run build:tests
transcriptionFiles=$(findTestFiles ./packages/tests/dist/transcription)
- jiwerFiles=$(findTestFiles ./packages/tests/dist/jiwer)
+ transcriptionDevToolsFiles=$(findTestFiles ./packages/tests/dist/transcription-devtools)
- MOCHA_PARALLEL=true runJSTest "$1" $((3*$speedFactor)) $transcriptionFiles $jiwerFiles
+ MOCHA_PARALLEL=true runJSTest "$1" $((3*$speedFactor)) $transcriptionFiles $transcriptionDevToolsFiles
fi
diff --git a/server/core/controllers/api/config.ts b/server/core/controllers/api/config.ts
index 9f44e4a891..7937104e67 100644
--- a/server/core/controllers/api/config.ts
+++ b/server/core/controllers/api/config.ts
@@ -1,10 +1,16 @@
+import { About, ActorImageType, ActorImageType_Type, CustomConfig, HttpStatusCode, UserRight } from '@peertube/peertube-models'
+import { createReqFiles } from '@server/helpers/express-utils.js'
+import { MIMETYPES } from '@server/initializers/constants.js'
+import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '@server/lib/local-actor.js'
+import { ServerConfigManager } from '@server/lib/server-config-manager.js'
+import { ActorImageModel } from '@server/models/actor/actor-image.js'
+import { getServerActor } from '@server/models/application/application.js'
+import { ModelCache } from '@server/models/shared/model-cache.js'
import express from 'express'
import { remove, writeJSON } from 'fs-extra/esm'
import snakeCase from 'lodash-es/snakeCase.js'
import validator from 'validator'
-import { ServerConfigManager } from '@server/lib/server-config-manager.js'
-import { About, ActorImageType, ActorImageType_Type, CustomConfig, HttpStatusCode, UserRight } from '@peertube/peertube-models'
-import { auditLoggerFactory, CustomConfigAuditView, getAuditIdFromRes } from '../../helpers/audit-logger.js'
+import { CustomConfigAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../helpers/audit-logger.js'
import { objectConverter } from '../../helpers/core-utils.js'
import { CONFIG, reloadConfig } from '../../initializers/config.js'
import { ClientHtml } from '../../lib/html/client-html.js'
@@ -18,12 +24,6 @@ import {
updateBannerValidator
} from '../../middlewares/index.js'
import { customConfigUpdateValidator, ensureConfigIsEditable } from '../../middlewares/validators/config.js'
-import { createReqFiles } from '@server/helpers/express-utils.js'
-import { MIMETYPES } from '@server/initializers/constants.js'
-import { deleteLocalActorImageFile, updateLocalActorImageFiles } from '@server/lib/local-actor.js'
-import { getServerActor } from '@server/models/application/application.js'
-import { ActorImageModel } from '@server/models/actor/actor-image.js'
-import { ModelCache } from '@server/models/shared/model-cache.js'
const configRouter = express.Router()
@@ -385,6 +385,12 @@ function customConfig (): CustomConfig {
enabled: CONFIG.VIDEO_STUDIO.REMOTE_RUNNERS.ENABLED
}
},
+ videoTranscription: {
+ enabled: CONFIG.VIDEO_TRANSCRIPTION.ENABLED,
+ remoteRunners: {
+ enabled: CONFIG.VIDEO_TRANSCRIPTION.REMOTE_RUNNERS.ENABLED
+ }
+ },
videoFile: {
update: {
enabled: CONFIG.VIDEO_FILE.UPDATE.ENABLED
diff --git a/server/core/controllers/api/runners/jobs.ts b/server/core/controllers/api/runners/jobs.ts
index c7aada7c24..5b81062d82 100644
--- a/server/core/controllers/api/runners/jobs.ts
+++ b/server/core/controllers/api/runners/jobs.ts
@@ -1,4 +1,25 @@
-import express, { UploadFiles } from 'express'
+import {
+ AbortRunnerJobBody,
+ AcceptRunnerJobResult,
+ ErrorRunnerJobBody,
+ HttpStatusCode,
+ ListRunnerJobsQuery,
+ LiveRTMPHLSTranscodingUpdatePayload,
+ RequestRunnerJobResult,
+ RunnerJobState,
+ RunnerJobSuccessBody,
+ RunnerJobSuccessPayload,
+ RunnerJobType,
+ RunnerJobUpdateBody,
+ RunnerJobUpdatePayload,
+ ServerErrorCode,
+ TranscriptionSuccess,
+ UserRight,
+ VODAudioMergeTranscodingSuccess,
+ VODHLSTranscodingSuccess,
+ VODWebVideoTranscodingSuccess,
+ VideoStudioTranscodingSuccess
+} from '@peertube/peertube-models'
import { retryTransactionWrapper } from '@server/helpers/database-utils.js'
import { createReqFiles } from '@server/helpers/express-utils.js'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
@@ -28,33 +49,13 @@ import {
successRunnerJobValidator,
updateRunnerJobValidator
} from '@server/middlewares/validators/runners/index.js'
-import { RunnerModel } from '@server/models/runner/runner.js'
import { RunnerJobModel } from '@server/models/runner/runner-job.js'
-import {
- AbortRunnerJobBody,
- AcceptRunnerJobResult,
- ErrorRunnerJobBody,
- HttpStatusCode,
- ListRunnerJobsQuery,
- LiveRTMPHLSTranscodingUpdatePayload,
- RequestRunnerJobResult,
- RunnerJobState,
- RunnerJobSuccessBody,
- RunnerJobSuccessPayload,
- RunnerJobType,
- RunnerJobUpdateBody,
- RunnerJobUpdatePayload,
- ServerErrorCode,
- UserRight,
- VideoStudioTranscodingSuccess,
- VODAudioMergeTranscodingSuccess,
- VODHLSTranscodingSuccess,
- VODWebVideoTranscodingSuccess
-} from '@peertube/peertube-models'
+import { RunnerModel } from '@server/models/runner/runner.js'
+import express, { UploadFiles } from 'express'
const postRunnerJobSuccessVideoFiles = createReqFiles(
- [ 'payload[videoFile]', 'payload[resolutionPlaylistFile]' ],
- { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT }
+ [ 'payload[videoFile]', 'payload[resolutionPlaylistFile]', 'payload[vttFile]' ],
+ { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT, ...MIMETYPES.VIDEO_CAPTIONS.MIMETYPE_EXT }
)
const runnerJobUpdateVideoFiles = createReqFiles(
@@ -345,7 +346,15 @@ const jobSuccessPayloadBuilders: {
}
},
- 'live-rtmp-hls-transcoding': () => ({})
+ 'live-rtmp-hls-transcoding': () => ({}),
+
+ 'video-transcription': (payload: TranscriptionSuccess, files) => {
+ return {
+ ...payload,
+
+ vttFile: files['payload[vttFile]'][0].path
+ }
+ }
}
async function postRunnerJobSuccess (req: express.Request, res: express.Response) {
diff --git a/server/core/controllers/api/users/my-notifications.ts b/server/core/controllers/api/users/my-notifications.ts
index 3266dd811d..cd37eeb005 100644
--- a/server/core/controllers/api/users/my-notifications.ts
+++ b/server/core/controllers/api/users/my-notifications.ts
@@ -76,6 +76,7 @@ async function updateNotificationSettings (req: express.Request, res: express.Re
abuseStateChange: body.abuseStateChange,
newPeerTubeVersion: body.newPeerTubeVersion,
newPluginVersion: body.newPluginVersion,
+ myVideoTranscriptionGenerated: body.myVideoTranscriptionGenerated,
myVideoStudioEditionFinished: body.myVideoStudioEditionFinished
}
diff --git a/server/core/controllers/api/videos/captions.ts b/server/core/controllers/api/videos/captions.ts
index 9c3db2f90f..7703eed0f6 100644
--- a/server/core/controllers/api/videos/captions.ts
+++ b/server/core/controllers/api/videos/captions.ts
@@ -1,31 +1,47 @@
-import express from 'express'
-import { HttpStatusCode } from '@peertube/peertube-models'
+import { HttpStatusCode, VideoCaptionGenerate } from '@peertube/peertube-models'
import { Hooks } from '@server/lib/plugins/hooks.js'
+import { createLocalCaption, createTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import express from 'express'
import { createReqFiles } from '../../../helpers/express-utils.js'
-import { logger } from '../../../helpers/logger.js'
+import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { MIMETYPES } from '../../../initializers/constants.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import { federateVideoIfNeeded } from '../../../lib/activitypub/videos/index.js'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares/index.js'
-import { addVideoCaptionValidator, deleteVideoCaptionValidator, listVideoCaptionsValidator } from '../../../middlewares/validators/index.js'
+import {
+ addVideoCaptionValidator,
+ deleteVideoCaptionValidator,
+ generateVideoCaptionValidator,
+ listVideoCaptionsValidator
+} from '../../../middlewares/validators/index.js'
import { VideoCaptionModel } from '../../../models/video/video-caption.js'
-import { createLocalCaption } from '@server/lib/video-captions.js'
+
+const lTags = loggerTagsFactory('api', 'video-caption')
const reqVideoCaptionAdd = createReqFiles([ 'captionfile' ], MIMETYPES.VIDEO_CAPTIONS.MIMETYPE_EXT)
const videoCaptionsRouter = express.Router()
+videoCaptionsRouter.post('/:videoId/captions/generate',
+ authenticate,
+ asyncMiddleware(generateVideoCaptionValidator),
+ asyncMiddleware(createGenerateVideoCaption)
+)
+
videoCaptionsRouter.get('/:videoId/captions',
asyncMiddleware(listVideoCaptionsValidator),
asyncMiddleware(listVideoCaptions)
)
+
videoCaptionsRouter.put('/:videoId/captions/:captionLanguage',
authenticate,
reqVideoCaptionAdd,
asyncMiddleware(addVideoCaptionValidator),
asyncRetryTransactionMiddleware(createVideoCaption)
)
+
videoCaptionsRouter.delete('/:videoId/captions/:captionLanguage',
authenticate,
asyncMiddleware(deleteVideoCaptionValidator),
@@ -40,6 +56,19 @@ export {
// ---------------------------------------------------------------------------
+async function createGenerateVideoCaption (req: express.Request, res: express.Response) {
+ const video = res.locals.videoAll
+
+ const body = req.body as VideoCaptionGenerate
+ if (body.forceTranscription === true) {
+ await VideoJobInfoModel.abortAllTasks(video.uuid, 'pendingTranscription')
+ }
+
+ await createTranscriptionTaskIfNeeded(video)
+
+ return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
+}
+
async function listVideoCaptions (req: express.Request, res: express.Response) {
const data = await VideoCaptionModel.listVideoCaptions(res.locals.onlyVideo.id)
@@ -74,7 +103,7 @@ async function deleteVideoCaption (req: express.Request, res: express.Response)
await federateVideoIfNeeded(video, false, t)
})
- logger.info('Video caption %s of video %s deleted.', videoCaption.language, video.uuid)
+ logger.info('Video caption %s of video %s deleted.', videoCaption.language, video.uuid, lTags(video.uuid))
Hooks.runAction('action:api.video-caption.deleted', { caption: videoCaption, req, res })
diff --git a/server/core/controllers/api/videos/import.ts b/server/core/controllers/api/videos/import.ts
index 5e6694899f..69dc368bde 100644
--- a/server/core/controllers/api/videos/import.ts
+++ b/server/core/controllers/api/videos/import.ts
@@ -142,7 +142,8 @@ async function handleTorrentImport (req: express.Request, res: express.Response,
? 'torrent-file'
: 'magnet-uri',
videoImportId: videoImport.id,
- preventException: false
+ preventException: false,
+ generateTranscription: body.generateTranscription
}
await JobQueue.Instance.createJob({ type: 'video-import', payload })
diff --git a/server/core/helpers/custom-validators/runners/jobs.ts b/server/core/helpers/custom-validators/runners/jobs.ts
index 78c6c2e1e0..ec0238b77b 100644
--- a/server/core/helpers/custom-validators/runners/jobs.ts
+++ b/server/core/helpers/custom-validators/runners/jobs.ts
@@ -1,83 +1,74 @@
-import { UploadFilesForCheck } from 'express'
-import validator from 'validator'
-import { CONSTRAINTS_FIELDS, RUNNER_JOB_STATES } from '@server/initializers/constants.js'
import {
LiveRTMPHLSTranscodingSuccess,
RunnerJobSuccessPayload,
RunnerJobType,
RunnerJobUpdatePayload,
- VideoStudioTranscodingSuccess,
+ TranscriptionSuccess,
VODAudioMergeTranscodingSuccess,
VODHLSTranscodingSuccess,
- VODWebVideoTranscodingSuccess
+ VODWebVideoTranscodingSuccess,
+ VideoStudioTranscodingSuccess
} from '@peertube/peertube-models'
+import { CONSTRAINTS_FIELDS, RUNNER_JOB_STATES } from '@server/initializers/constants.js'
+import { UploadFilesForCheck } from 'express'
+import validator from 'validator'
import { exists, isArray, isFileValid, isSafeFilename } from '../misc.js'
const RUNNER_JOBS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.RUNNER_JOBS
const runnerJobTypes = new Set([ 'vod-hls-transcoding', 'vod-web-video-transcoding', 'vod-audio-merge-transcoding' ])
-function isRunnerJobTypeValid (value: RunnerJobType) {
+export function isRunnerJobTypeValid (value: RunnerJobType) {
return runnerJobTypes.has(value)
}
-function isRunnerJobSuccessPayloadValid (value: RunnerJobSuccessPayload, type: RunnerJobType, files: UploadFilesForCheck) {
+export function isRunnerJobSuccessPayloadValid (value: RunnerJobSuccessPayload, type: RunnerJobType, files: UploadFilesForCheck) {
return isRunnerJobVODWebVideoResultPayloadValid(value as VODWebVideoTranscodingSuccess, type, files) ||
isRunnerJobVODHLSResultPayloadValid(value as VODHLSTranscodingSuccess, type, files) ||
isRunnerJobVODAudioMergeResultPayloadValid(value as VODHLSTranscodingSuccess, type, files) ||
isRunnerJobLiveRTMPHLSResultPayloadValid(value as LiveRTMPHLSTranscodingSuccess, type) ||
- isRunnerJobVideoStudioResultPayloadValid(value as VideoStudioTranscodingSuccess, type, files)
+ isRunnerJobVideoStudioResultPayloadValid(value as VideoStudioTranscodingSuccess, type, files) ||
+ isRunnerJobTranscriptionResultPayloadValid(value as TranscriptionSuccess, type, files)
}
// ---------------------------------------------------------------------------
-function isRunnerJobProgressValid (value: string) {
+export function isRunnerJobProgressValid (value: string) {
return validator.default.isInt(value + '', RUNNER_JOBS_CONSTRAINTS_FIELDS.PROGRESS)
}
-function isRunnerJobUpdatePayloadValid (value: RunnerJobUpdatePayload, type: RunnerJobType, files: UploadFilesForCheck) {
+export function isRunnerJobUpdatePayloadValid (value: RunnerJobUpdatePayload, type: RunnerJobType, files: UploadFilesForCheck) {
return isRunnerJobVODWebVideoUpdatePayloadValid(value, type, files) ||
isRunnerJobVODHLSUpdatePayloadValid(value, type, files) ||
isRunnerJobVideoStudioUpdatePayloadValid(value, type, files) ||
isRunnerJobVODAudioMergeUpdatePayloadValid(value, type, files) ||
- isRunnerJobLiveRTMPHLSUpdatePayloadValid(value, type, files)
+ isRunnerJobLiveRTMPHLSUpdatePayloadValid(value, type, files) ||
+ isRunnerJobTranscriptionUpdatePayloadValid(value, type, files)
}
// ---------------------------------------------------------------------------
-function isRunnerJobTokenValid (value: string) {
+export function isRunnerJobTokenValid (value: string) {
return exists(value) && validator.default.isLength(value, RUNNER_JOBS_CONSTRAINTS_FIELDS.TOKEN)
}
-function isRunnerJobAbortReasonValid (value: string) {
+export function isRunnerJobAbortReasonValid (value: string) {
return validator.default.isLength(value, RUNNER_JOBS_CONSTRAINTS_FIELDS.REASON)
}
-function isRunnerJobErrorMessageValid (value: string) {
+export function isRunnerJobErrorMessageValid (value: string) {
return validator.default.isLength(value, RUNNER_JOBS_CONSTRAINTS_FIELDS.ERROR_MESSAGE)
}
-function isRunnerJobStateValid (value: any) {
+export function isRunnerJobStateValid (value: any) {
return exists(value) && RUNNER_JOB_STATES[value] !== undefined
}
-function isRunnerJobArrayOfStateValid (value: any) {
+export function isRunnerJobArrayOfStateValid (value: any) {
return isArray(value) && value.every(v => isRunnerJobStateValid(v))
}
// ---------------------------------------------------------------------------
-
-export {
- isRunnerJobTypeValid,
- isRunnerJobSuccessPayloadValid,
- isRunnerJobUpdatePayloadValid,
- isRunnerJobTokenValid,
- isRunnerJobErrorMessageValid,
- isRunnerJobProgressValid,
- isRunnerJobAbortReasonValid,
- isRunnerJobArrayOfStateValid,
- isRunnerJobStateValid
-}
-
+// Private
// ---------------------------------------------------------------------------
function isRunnerJobVODWebVideoResultPayloadValid (
@@ -124,6 +115,15 @@ function isRunnerJobVideoStudioResultPayloadValid (
isFileValid({ files, field: 'payload[videoFile]', mimeTypeRegex: null, maxSize: null })
}
+function isRunnerJobTranscriptionResultPayloadValid (
+ value: TranscriptionSuccess,
+ type: RunnerJobType,
+ files: UploadFilesForCheck
+) {
+ return type === 'video-transcription' &&
+ isFileValid({ files, field: 'payload[vttFile]', mimeTypeRegex: null, maxSize: null })
+}
+
// ---------------------------------------------------------------------------
function isRunnerJobVODWebVideoUpdatePayloadValid (
@@ -153,6 +153,15 @@ function isRunnerJobVODAudioMergeUpdatePayloadValid (
(!value || (typeof value === 'object' && Object.keys(value).length === 0))
}
+function isRunnerJobTranscriptionUpdatePayloadValid (
+ value: RunnerJobUpdatePayload,
+ type: RunnerJobType,
+ _files: UploadFilesForCheck
+) {
+ return type === 'video-transcription' &&
+ (!value || (typeof value === 'object' && Object.keys(value).length === 0))
+}
+
function isRunnerJobLiveRTMPHLSUpdatePayloadValid (
value: RunnerJobUpdatePayload,
type: RunnerJobType,
diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.ts
index 5fe0f8376f..2ecffcb368 100644
--- a/server/core/initializers/config.ts
+++ b/server/core/initializers/config.ts
@@ -13,6 +13,7 @@ import {
import { decacheModule } from '@server/helpers/decache.js'
import { buildPath, root } from '@peertube/peertube-node-utils'
import { parseBytes, parseDurationToMs } from '../helpers/core-utils.js'
+import { TranscriptionEngineName, WhisperBuiltinModelName } from '@peertube/peertube-transcription'
const require = createRequire(import.meta.url)
let config: IConfig = require('config')
@@ -515,6 +516,16 @@ const CONFIG = {
get ENABLED () { return config.get<boolean>('video_file.update.enabled') }
}
},
+ VIDEO_TRANSCRIPTION: {
+ get ENABLED () { return config.get<boolean>('video_transcription.enabled') },
+ get ENGINE () { return config.get<TranscriptionEngineName>('video_transcription.engine') },
+ get ENGINE_PATH () { return config.get<string>('video_transcription.engine_path') },
+ get MODEL () { return config.get<WhisperBuiltinModelName>('video_transcription.model') },
+ get MODEL_PATH () { return config.get<string>('video_transcription.model_path') },
+ REMOTE_RUNNERS: {
+ get ENABLED () { return config.get<boolean>('video_transcription.remote_runners.enabled') }
+ }
+ },
IMPORT: {
VIDEOS: {
get CONCURRENCY () { return config.get<number>('import.videos.concurrency') },
diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.ts
index ebb205a33f..faf9442494 100644
--- a/server/core/initializers/constants.ts
+++ b/server/core/initializers/constants.ts
@@ -47,7 +47,7 @@ import { cpus } from 'os'
// ---------------------------------------------------------------------------
-const LAST_MIGRATION_VERSION = 850
+const LAST_MIGRATION_VERSION = 855
// ---------------------------------------------------------------------------
@@ -213,7 +213,8 @@ const JOB_ATTEMPTS: { [id in JobType]: number } = {
'notify': 1,
'federate-video': 1,
'create-user-export': 1,
- 'import-user-archive': 1
+ 'import-user-archive': 1,
+ 'video-transcription': 1
}
// Excluded keys are jobs that can be configured by admins
const JOB_CONCURRENCY: { [id in Exclude<JobType, 'video-transcoding' | 'video-import'>]: number } = {
@@ -241,7 +242,8 @@ const JOB_CONCURRENCY: { [id in Exclude<JobType, 'video-transcoding' | 'video-im
'notify': 5,
'federate-video': 3,
'create-user-export': 1,
- 'import-user-archive': 1
+ 'import-user-archive': 1,
+ 'video-transcription': 1
}
const JOB_TTL: { [id in JobType]: number } = {
'activitypub-http-broadcast': 60000 * 10, // 10 minutes
@@ -270,7 +272,8 @@ const JOB_TTL: { [id in JobType]: number } = {
'notify': 60000 * 5, // 5 minutes
'federate-video': 60000 * 5, // 5 minutes,
'create-user-export': 60000 * 60 * 24, // 24 hours
- 'import-user-archive': 60000 * 60 * 24 // 24 hours
+ 'import-user-archive': 60000 * 60 * 24, // 24 hours
+ 'video-transcription': 1000 * 3600 * 6 // 6 hours
}
const REPEAT_JOBS: { [ id in JobType ]?: RepeatOptions } = {
'videos-views-stats': {
@@ -282,7 +285,8 @@ const REPEAT_JOBS: { [ id in JobType ]?: RepeatOptions } = {
}
const JOB_PRIORITY = {
TRANSCODING: 100,
- VIDEO_STUDIO: 150
+ VIDEO_STUDIO: 150,
+ TRANSCRIPTION: 200
}
const JOB_REMOVAL_OPTIONS = {
@@ -1013,7 +1017,9 @@ const DIRECTORIES = {
ORIGINAL_VIDEOS: CONFIG.STORAGE.ORIGINAL_VIDEO_FILES_DIR,
- HLS_REDUNDANCY: join(CONFIG.STORAGE.REDUNDANCY_DIR, 'hls')
+ HLS_REDUNDANCY: join(CONFIG.STORAGE.REDUNDANCY_DIR, 'hls'),
+
+ LOCAL_PIP_DIRECTORY: join(CONFIG.STORAGE.BIN_DIR, 'pip')
}
const RESUMABLE_UPLOAD_SESSION_LIFETIME = SCHEDULER_INTERVALS_MS.REMOVE_DANGLING_RESUMABLE_UPLOADS
diff --git a/server/core/initializers/migrations/0855-transcription.ts b/server/core/initializers/migrations/0855-transcription.ts
new file mode 100644
index 0000000000..330e67e700
--- /dev/null
+++ b/server/core/initializers/migrations/0855-transcription.ts
@@ -0,0 +1,67 @@
+import * as Sequelize from 'sequelize'
+
+async function up (utils: {
+ transaction: Sequelize.Transaction
+ queryInterface: Sequelize.QueryInterface
+ sequelize: Sequelize.Sequelize
+}): Promise<void> {
+ const { transaction } = utils
+
+ // Notification
+ {
+ await utils.queryInterface.addColumn('userNotification', 'videoCaptionId', {
+ type: Sequelize.INTEGER,
+ defaultValue: null,
+ allowNull: true,
+ references: {
+ model: 'videoCaption',
+ key: 'id'
+ },
+ onUpdate: 'CASCADE',
+ onDelete: 'CASCADE'
+ }, { transaction })
+ }
+
+ // Notification settings
+ {
+ {
+ const data = {
+ type: Sequelize.INTEGER,
+ defaultValue: null,
+ allowNull: true
+ }
+ await utils.queryInterface.addColumn('userNotificationSetting', 'myVideoTranscriptionGenerated', data, { transaction })
+ }
+
+ {
+ const query = 'UPDATE "userNotificationSetting" SET "myVideoTranscriptionGenerated" = 1'
+ await utils.sequelize.query(query, { transaction })
+ }
+
+ {
+ const data = {
+ type: Sequelize.INTEGER,
+ defaultValue: null,
+ allowNull: false
+ }
+ await utils.queryInterface.changeColumn('userNotificationSetting', 'myVideoTranscriptionGenerated', data, { transaction })
+ }
+ }
+
+ // Video job info
+ {
+ await utils.queryInterface.addColumn('videoJobInfo', 'pendingTranscription', {
+ type: Sequelize.INTEGER,
+ allowNull: false,
+ defaultValue: 0
+ }, { transaction })
+ }
+}
+
+function down (options) {
+ throw new Error('Not implemented.')
+}
+
+export {
+ down, up
+}
diff --git a/server/core/lib/job-queue/handlers/video-import.ts b/server/core/lib/job-queue/handlers/video-import.ts
index c791a402b5..14337a85e4 100644
--- a/server/core/lib/job-queue/handlers/video-import.ts
+++ b/server/core/lib/job-queue/handlers/video-import.ts
@@ -24,11 +24,13 @@ import { Hooks } from '@server/lib/plugins/hooks.js'
import { ServerConfigManager } from '@server/lib/server-config-manager.js'
import { createOptimizeOrMergeAudioJobs } from '@server/lib/transcoding/create-transcoding-job.js'
import { isUserQuotaValid } from '@server/lib/user.js'
+import { createTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
import { replaceChaptersIfNotExist } from '@server/lib/video-chapters.js'
import { buildNewFile } from '@server/lib/video-file.js'
import { buildMoveJob, buildStoryboardJobIfNeeded } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
import { buildNextVideoState } from '@server/lib/video-state.js'
+import { VideoCaptionModel } from '@server/models/video/video-caption.js'
import { MUserId, MVideoFile, MVideoFullLight } from '@server/types/models/index.js'
import { MVideoImport, MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import.js'
import { Job } from 'bullmq'
@@ -84,7 +86,7 @@ export {
async function processTorrentImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportTorrentPayload) {
logger.info('Processing torrent video import in job %s.', job.id)
- const options = { type: payload.type, videoImportId: payload.videoImportId }
+ const options = { type: payload.type, generateTranscription: payload.generateTranscription, videoImportId: payload.videoImportId }
const target = {
torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
@@ -96,7 +98,7 @@ async function processTorrentImport (job: Job, videoImport: MVideoImportDefault,
async function processYoutubeDLImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportYoutubeDLPayload) {
logger.info('Processing youtubeDL video import in job %s.', job.id)
- const options = { type: payload.type, videoImportId: videoImport.id }
+ const options = { type: payload.type, generateTranscription: payload.generateTranscription, videoImportId: videoImport.id }
const youtubeDL = new YoutubeDLWrapper(
videoImport.targetUrl,
@@ -122,6 +124,7 @@ async function getVideoImportOrDie (payload: VideoImportPayload) {
type ProcessFileOptions = {
type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
+ generateTranscription: boolean
videoImportId: number
}
async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
@@ -228,7 +231,14 @@ async function processFile (downloader: () => Promise<string>, videoImport: MVid
})
})
- await afterImportSuccess({ videoImport: videoImportUpdated, video, videoFile, user: videoImport.User, videoFileAlreadyLocked: true })
+ await afterImportSuccess({
+ videoImport: videoImportUpdated,
+ video,
+ videoFile,
+ user: videoImport.User,
+ generateTranscription: options.generateTranscription,
+ videoFileAlreadyLocked: true
+ })
} finally {
videoFileLockReleaser()
}
@@ -277,9 +287,12 @@ async function afterImportSuccess (options: {
video: MVideoFullLight
videoFile: MVideoFile
user: MUserId
+
videoFileAlreadyLocked: boolean
+
+ generateTranscription: boolean
}) {
- const { video, videoFile, videoImport, user, videoFileAlreadyLocked } = options
+ const { video, videoFile, videoImport, user, generateTranscription, videoFileAlreadyLocked } = options
Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: Object.assign(videoImport, { Video: video }), success: true })
@@ -294,6 +307,10 @@ async function afterImportSuccess (options: {
// Generate the storyboard in the job queue, and don't forget to federate an update after
await JobQueue.Instance.createJob(buildStoryboardJobIfNeeded({ video, federate: true }))
+ if (await VideoCaptionModel.hasVideoCaption(video.id) !== true && generateTranscription === true) {
+ await createTranscriptionTaskIfNeeded(video)
+ }
+
if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
await JobQueue.Instance.createJob(
await buildMoveJob({ video, previousVideoState: VideoState.TO_IMPORT, type: 'move-to-object-storage' })
diff --git a/server/core/lib/job-queue/handlers/video-live-ending.ts b/server/core/lib/job-queue/handlers/video-live-ending.ts
index 496367eda8..91ba79a631 100644
--- a/server/core/lib/job-queue/handlers/video-live-ending.ts
+++ b/server/core/lib/job-queue/handlers/video-live-ending.ts
@@ -1,9 +1,7 @@
-import { Job } from 'bullmq'
-import { remove } from 'fs-extra/esm'
-import { readdir } from 'fs/promises'
-import { join } from 'path'
+import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '@peertube/peertube-ffmpeg'
import { ThumbnailType, VideoLiveEndingPayload, VideoState } from '@peertube/peertube-models'
import { peertubeTruncate } from '@server/helpers/core-utils.js'
+import { CONFIG } from '@server/initializers/config.js'
import { CONSTRAINTS_FIELDS } from '@server/initializers/constants.js'
import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'
@@ -16,7 +14,10 @@ import {
} from '@server/lib/paths.js'
import { generateLocalVideoMiniature, regenerateMiniaturesIfNeeded } from '@server/lib/thumbnail.js'
import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/hls-transcoding.js'
+import { createTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
+import { buildStoryboardJobIfNeeded } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
+import { isVideoInPublicDirectory } from '@server/lib/video-privacy.js'
import { moveToNextState } from '@server/lib/video-state.js'
import { VideoBlacklistModel } from '@server/models/video/video-blacklist.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
@@ -26,11 +27,12 @@ import { VideoLiveModel } from '@server/models/video/video-live.js'
import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist.js'
import { VideoModel } from '@server/models/video/video.js'
import { MVideo, MVideoLive, MVideoLiveSession, MVideoWithAllFiles } from '@server/types/models/index.js'
-import { ffprobePromise, getAudioStream, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '@peertube/peertube-ffmpeg'
+import { Job } from 'bullmq'
+import { remove } from 'fs-extra/esm'
+import { readdir } from 'fs/promises'
+import { join } from 'path'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { JobQueue } from '../job-queue.js'
-import { isVideoInPublicDirectory } from '@server/lib/video-privacy.js'
-import { buildStoryboardJobIfNeeded } from '@server/lib/video-jobs.js'
const lTags = loggerTagsFactory('live', 'job')
@@ -174,9 +176,13 @@ async function saveReplayToExternalVideo (options: {
await replayVideo.addAndSaveThumbnail(thumbnail)
}
- await moveToNextState({ video: replayVideo, isNewVideo: true })
-
await createStoryboardJob(replayVideo)
+
+ if (CONFIG.VIDEO_TRANSCRIPTION.ENABLED === true) {
+ await createTranscriptionTaskIfNeeded(replayVideo)
+ }
+
+ await moveToNextState({ video: replayVideo, isNewVideo: true })
}
async function replaceLiveByReplay (options: {
@@ -245,6 +251,10 @@ async function replaceLiveByReplay (options: {
await moveToNextState({ video: videoWithFiles, isNewVideo: true })
await createStoryboardJob(videoWithFiles)
+
+ if (CONFIG.VIDEO_TRANSCRIPTION.ENABLED === true) {
+ await createTranscriptionTaskIfNeeded(videoWithFiles)
+ }
}
async function assignReplayFilesToVideo (options: {
diff --git a/server/core/lib/job-queue/handlers/video-transcription.ts b/server/core/lib/job-queue/handlers/video-transcription.ts
new file mode 100644
index 0000000000..47ae8e3374
--- /dev/null
+++ b/server/core/lib/job-queue/handlers/video-transcription.ts
@@ -0,0 +1,21 @@
+import { VideoTranscriptionPayload } from '@peertube/peertube-models'
+import { generateSubtitle } from '@server/lib/video-captions.js'
+import { Job } from 'bullmq'
+import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
+import { VideoModel } from '../../../models/video/video.js'
+
+const lTags = loggerTagsFactory('transcription')
+
+export async function processVideoTranscription (job: Job) {
+ const payload = job.data as VideoTranscriptionPayload
+
+ logger.info('Processing video transcription in job %s.', job.id)
+
+ const video = await VideoModel.load(payload.videoUUID)
+ if (!video) {
+ logger.info('Do not process transcription job %d, video does not exist.', job.id, lTags(payload.videoUUID))
+ return
+ }
+
+ return generateSubtitle({ video })
+}
diff --git a/server/core/lib/job-queue/job-queue.ts b/server/core/lib/job-queue/job-queue.ts
index 5559c8ea30..f3ecd952c8 100644
--- a/server/core/lib/job-queue/job-queue.ts
+++ b/server/core/lib/job-queue/job-queue.ts
@@ -1,15 +1,3 @@
-import {
- FlowJob,
- FlowProducer,
- Job,
- JobsOptions,
- Queue,
- QueueEvents,
- QueueEventsOptions,
- QueueOptions,
- Worker,
- WorkerOptions
-} from 'bullmq'
import { pick, timeoutPromise } from '@peertube/peertube-core-utils'
import {
ActivitypubFollowPayload,
@@ -37,12 +25,25 @@ import {
VideoLiveEndingPayload,
VideoRedundancyPayload,
VideoStudioEditionPayload,
- VideoTranscodingPayload
+ VideoTranscodingPayload,
+ VideoTranscriptionPayload
} from '@peertube/peertube-models'
import { parseDurationToMs } from '@server/helpers/core-utils.js'
import { jobStates } from '@server/helpers/custom-validators/jobs.js'
import { CONFIG } from '@server/initializers/config.js'
import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy.js'
+import {
+ FlowJob,
+ FlowProducer,
+ Job,
+ JobsOptions,
+ Queue,
+ QueueEvents,
+ QueueEventsOptions,
+ QueueOptions,
+ Worker,
+ WorkerOptions
+} from 'bullmq'
import { logger } from '../../helpers/logger.js'
import { JOB_ATTEMPTS, JOB_CONCURRENCY, JOB_REMOVAL_OPTIONS, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants.js'
import { Hooks } from '../plugins/hooks.js'
@@ -58,10 +59,13 @@ import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unica
import { refreshAPObject } from './handlers/activitypub-refresher.js'
import { processActorKeys } from './handlers/actor-keys.js'
import { processAfterVideoChannelImport } from './handlers/after-video-channel-import.js'
+import { processCreateUserExport } from './handlers/create-user-export.js'
import { processEmail } from './handlers/email.js'
import { processFederateVideo } from './handlers/federate-video.js'
import { processGenerateStoryboard } from './handlers/generate-storyboard.js'
+import { processImportUserArchive } from './handlers/import-user-archive.js'
import { processManageVideoTorrent } from './handlers/manage-video-torrent.js'
+import { onMoveToFileSystemFailure, processMoveToFileSystem } from './handlers/move-to-file-system.js'
import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage.js'
import { processNotify } from './handlers/notify.js'
import { processTranscodingJobBuilder } from './handlers/transcoding-job-builder.js'
@@ -71,10 +75,8 @@ import { processVideoImport } from './handlers/video-import.js'
import { processVideoLiveEnding } from './handlers/video-live-ending.js'
import { processVideoStudioEdition } from './handlers/video-studio-edition.js'
import { processVideoTranscoding } from './handlers/video-transcoding.js'
+import { processVideoTranscription } from './handlers/video-transcription.js'
import { processVideosViewsStats } from './handlers/video-views-stats.js'
-import { onMoveToFileSystemFailure, processMoveToFileSystem } from './handlers/move-to-file-system.js'
-import { processCreateUserExport } from './handlers/create-user-export.js'
-import { processImportUserArchive } from './handlers/import-user-archive.js'
export type CreateJobArgument =
{ type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
@@ -104,7 +106,8 @@ export type CreateJobArgument =
{ type: 'federate-video', payload: FederateVideoPayload } |
{ type: 'create-user-export', payload: CreateUserExportPayload } |
{ type: 'generate-video-storyboard', payload: GenerateStoryboardPayload } |
- { type: 'import-user-archive', payload: ImportUserArchivePayload }
+ { type: 'import-user-archive', payload: ImportUserArchivePayload } |
+ { type: 'video-transcription', payload: VideoTranscriptionPayload }
export type CreateJobOptions = {
delay?: number
@@ -139,7 +142,8 @@ const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
'videos-views-stats': processVideosViewsStats,
'generate-video-storyboard': processGenerateStoryboard,
'create-user-export': processCreateUserExport,
- 'import-user-archive': processImportUserArchive
+ 'import-user-archive': processImportUserArchive,
+ 'video-transcription': processVideoTranscription
}
const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
@@ -171,10 +175,11 @@ const jobTypes: JobType[] = [
'video-live-ending',
'video-redundancy',
'video-studio-edition',
- 'video-transcoding',
+ 'video-transcription',
'videos-views-stats',
'create-user-export',
- 'import-user-archive'
+ 'import-user-archive',
+ 'video-transcoding'
]
const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
@@ -561,6 +566,5 @@ class JobQueue {
// ---------------------------------------------------------------------------
export {
- jobTypes,
- JobQueue
+ JobQueue, jobTypes
}
diff --git a/server/core/lib/local-video-creator.ts b/server/core/lib/local-video-creator.ts
index 4414a52a83..1c4c574d13 100644
--- a/server/core/lib/local-video-creator.ts
+++ b/server/core/lib/local-video-creator.ts
@@ -107,6 +107,8 @@ export class LocalVideoCreator {
this.channel = options.channel
this.videoAttributeResultHook = options.videoAttributeResultHook
+
+ this.lTags = options.lTags
}
async create () {
@@ -201,8 +203,11 @@ export class LocalVideoCreator {
if (this.videoFile) {
transaction.afterCommit(() => {
- addVideoJobsAfterCreation({ video: this.video, videoFile: this.videoFile })
- .catch(err => logger.error('Cannot build new video jobs of %s.', this.video.uuid, { err, ...this.lTags(this.video.uuid) }))
+ addVideoJobsAfterCreation({
+ video: this.video,
+ videoFile: this.videoFile,
+ generateTranscription: this.videoAttributes.generateTranscription ?? true
+ }).catch(err => logger.error('Cannot build new video jobs of %s.', this.video.uuid, { err, ...this.lTags(this.video.uuid) }))
})
} else {
await federateVideoIfNeeded(this.video, true, transaction)
diff --git a/server/core/lib/notifier/notifier.ts b/server/core/lib/notifier/notifier.ts
index 277f0afb74..0048340d8b 100644
--- a/server/core/lib/notifier/notifier.ts
+++ b/server/core/lib/notifier/notifier.ts
@@ -11,6 +11,7 @@ import {
MCommentOwnerVideo,
MPlugin,
MVideoAccountLight,
+ MVideoCaptionVideo,
MVideoFullLight
} from '../../types/models/index.js'
import { JobQueue } from '../job-queue/index.js'
@@ -41,7 +42,8 @@ import {
OwnedPublicationAfterTranscoding,
RegistrationRequestForModerators,
StudioEditionFinishedForOwner,
- UnblacklistForOwner
+ UnblacklistForOwner,
+ VideoTranscriptionGeneratedForOwner
} from './shared/index.js'
const lTags = loggerTagsFactory('notifier')
@@ -69,7 +71,8 @@ class Notifier {
newAbuseMessage: [ NewAbuseMessageForReporter, NewAbuseMessageForModerators ],
newPeertubeVersion: [ NewPeerTubeVersionForAdmins ],
newPluginVersion: [ NewPluginVersionForAdmins ],
- videoStudioEditionFinished: [ StudioEditionFinishedForOwner ]
+ videoStudioEditionFinished: [ StudioEditionFinishedForOwner ],
+ videoTranscriptionGenerated: [ VideoTranscriptionGeneratedForOwner ]
}
private static instance: Notifier
@@ -275,6 +278,16 @@ class Notifier {
.catch(err => logger.error('Cannot notify on finished studio edition %s.', video.url, { err }))
}
+ notifyOfGeneratedVideoTranscription (caption: MVideoCaptionVideo) {
+ const models = this.notificationModels.videoTranscriptionGenerated
+ const video = caption.Video
+
+ logger.debug('Notify on generated video transcription', { language: caption.language, video: video.url, ...lTags() })
+
+ this.sendNotifications(models, caption)
+ .catch(err => logger.error('Cannot notify on generated video transcription %s of video %s.', caption.language, video.url, { err }))
+ }
+
private async notify <T> (object: AbstractNotification<T>) {
await object.prepare()
diff --git a/server/core/lib/notifier/shared/caption/index.ts b/server/core/lib/notifier/shared/caption/index.ts
new file mode 100644
index 0000000000..ec9db5564e
--- /dev/null
+++ b/server/core/lib/notifier/shared/caption/index.ts
@@ -0,0 +1 @@
+export * from './video-transcription-generated-for-owner.js'
diff --git a/server/core/lib/notifier/shared/caption/video-transcription-generated-for-owner.ts b/server/core/lib/notifier/shared/caption/video-transcription-generated-for-owner.ts
new file mode 100644
index 0000000000..a777407368
--- /dev/null
+++ b/server/core/lib/notifier/shared/caption/video-transcription-generated-for-owner.ts
@@ -0,0 +1,63 @@
+import { UserNotificationType } from '@peertube/peertube-models'
+import { logger } from '@server/helpers/logger.js'
+import { VIDEO_LANGUAGES, WEBSERVER } from '@server/initializers/constants.js'
+import { UserNotificationModel } from '@server/models/user/user-notification.js'
+import { UserModel } from '@server/models/user/user.js'
+import { MUserDefault, MUserWithNotificationSetting, MVideoCaptionVideo, UserNotificationModelForApi } from '@server/types/models/index.js'
+import { AbstractNotification } from '../common/abstract-notification.js'
+
+export class VideoTranscriptionGeneratedForOwner extends AbstractNotification <MVideoCaptionVideo> {
+ private user: MUserDefault
+
+ async prepare () {
+ this.user = await UserModel.loadByVideoId(this.payload.videoId)
+ }
+
+ log () {
+ logger.info(
+ 'Notifying user %s the transcription %s of video %s is generated.',
+ this.user.username, this.payload.language, this.payload.Video.url
+ )
+ }
+
+ getSetting (user: MUserWithNotificationSetting) {
+ return user.NotificationSetting.myVideoTranscriptionGenerated
+ }
+
+ getTargetUsers () {
+ if (!this.user) return []
+
+ return [ this.user ]
+ }
+
+ createNotification (user: MUserWithNotificationSetting) {
+ const notification = UserNotificationModel.build<UserNotificationModelForApi>({
+ type: UserNotificationType.MY_VIDEO_TRANSCRIPTION_GENERATED,
+ userId: user.id,
+ videoCaptionId: this.payload.id
+ })
+ notification.VideoCaption = this.payload
+
+ return notification
+ }
+
+ createEmail (to: string) {
+ const video = this.payload.Video
+ const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
+
+ const language = VIDEO_LANGUAGES[this.payload.language]
+
+ return {
+ to,
+ subject: `Transcription in ${language} of your video ${video.name} has been generated`,
+ text: `Transcription in ${language} of your video ${video.name} has been generated.`,
+ locals: {
+ title: 'Transcription has been generated',
+ action: {
+ text: 'View video',
+ url: videoUrl
+ }
+ }
+ }
+ }
+}
diff --git a/server/core/lib/notifier/shared/index.ts b/server/core/lib/notifier/shared/index.ts
index f4f165c401..5ae060db72 100644
--- a/server/core/lib/notifier/shared/index.ts
+++ b/server/core/lib/notifier/shared/index.ts
@@ -1,5 +1,6 @@
export * from './abuse/index.js'
export * from './blacklist/index.js'
+export * from './caption/index.js'
export * from './comment/index.js'
export * from './common/index.js'
export * from './follow/index.js'
diff --git a/server/core/lib/runners/job-handlers/abstract-job-handler.ts b/server/core/lib/runners/job-handlers/abstract-job-handler.ts
index d31effee63..55f7cd74ad 100644
--- a/server/core/lib/runners/job-handlers/abstract-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/abstract-job-handler.ts
@@ -6,6 +6,8 @@ import {
RunnerJobStateType,
RunnerJobStudioTranscodingPayload,
RunnerJobSuccessPayload,
+ RunnerJobTranscriptionPayload,
+ RunnerJobTranscriptionPrivatePayload,
RunnerJobType,
RunnerJobUpdatePayload,
RunnerJobVODAudioMergeTranscodingPayload,
@@ -51,6 +53,11 @@ type CreateRunnerJobArg =
type: Extract<RunnerJobType, 'video-studio-transcoding'>
payload: RunnerJobStudioTranscodingPayload
privatePayload: RunnerJobVideoStudioTranscodingPrivatePayload
+ } |
+ {
+ type: Extract<RunnerJobType, 'video-transcription'>
+ payload: RunnerJobTranscriptionPayload
+ privatePayload: RunnerJobTranscriptionPrivatePayload
}
export abstract class AbstractJobHandler <C, U extends RunnerJobUpdatePayload, S extends RunnerJobSuccessPayload> {
diff --git a/server/core/lib/runners/job-handlers/abstract-vod-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/abstract-vod-transcoding-job-handler.ts
index d05a66ccfc..20c0a62bb1 100644
--- a/server/core/lib/runners/job-handlers/abstract-vod-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/abstract-vod-transcoding-job-handler.ts
@@ -11,7 +11,7 @@ import { moveToFailedTranscodingState, moveToNextState } from '@server/lib/video
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import { MRunnerJob } from '@server/types/models/runners/index.js'
import { AbstractJobHandler } from './abstract-job-handler.js'
-import { loadTranscodingRunnerVideo } from './shared/index.js'
+import { loadRunnerVideo } from './shared/utils.js'
// eslint-disable-next-line max-len
export abstract class AbstractVODTranscodingJobHandler <C, U extends RunnerJobUpdatePayload, S extends RunnerJobSuccessPayload> extends AbstractJobHandler<C, U, S> {
@@ -38,7 +38,7 @@ export abstract class AbstractVODTranscodingJobHandler <C, U extends RunnerJobUp
}) {
if (options.nextState !== RunnerJobState.ERRORED) return
- const video = await loadTranscodingRunnerVideo(options.runnerJob, this.lTags)
+ const video = await loadRunnerVideo(options.runnerJob, this.lTags)
if (!video) return
await moveToFailedTranscodingState(video)
@@ -51,7 +51,7 @@ export abstract class AbstractVODTranscodingJobHandler <C, U extends RunnerJobUp
}) {
const { runnerJob } = options
- const video = await loadTranscodingRunnerVideo(options.runnerJob, this.lTags)
+ const video = await loadRunnerVideo(options.runnerJob, this.lTags)
if (!video) return
const pending = await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode')
diff --git a/server/core/lib/runners/job-handlers/index.ts b/server/core/lib/runners/job-handlers/index.ts
index c3205fae39..a9fb79160a 100644
--- a/server/core/lib/runners/job-handlers/index.ts
+++ b/server/core/lib/runners/job-handlers/index.ts
@@ -1,6 +1,7 @@
export * from './abstract-job-handler.js'
export * from './live-rtmp-hls-transcoding-job-handler.js'
export * from './runner-job-handlers.js'
+export * from './transcription-job-handler.js'
export * from './video-studio-transcoding-job-handler.js'
export * from './vod-audio-merge-transcoding-job-handler.js'
export * from './vod-hls-transcoding-job-handler.js'
diff --git a/server/core/lib/runners/job-handlers/runner-job-handlers.ts b/server/core/lib/runners/job-handlers/runner-job-handlers.ts
index f8a672e649..771bf9d6ac 100644
--- a/server/core/lib/runners/job-handlers/runner-job-handlers.ts
+++ b/server/core/lib/runners/job-handlers/runner-job-handlers.ts
@@ -1,7 +1,8 @@
-import { MRunnerJob } from '@server/types/models/runners/index.js'
import { RunnerJobSuccessPayload, RunnerJobType, RunnerJobUpdatePayload } from '@peertube/peertube-models'
+import { MRunnerJob } from '@server/types/models/runners/index.js'
import { AbstractJobHandler } from './abstract-job-handler.js'
import { LiveRTMPHLSTranscodingJobHandler } from './live-rtmp-hls-transcoding-job-handler.js'
+import { TranscriptionJobHandler } from './transcription-job-handler.js'
import { VideoStudioTranscodingJobHandler } from './video-studio-transcoding-job-handler.js'
import { VODAudioMergeTranscodingJobHandler } from './vod-audio-merge-transcoding-job-handler.js'
import { VODHLSTranscodingJobHandler } from './vod-hls-transcoding-job-handler.js'
@@ -12,7 +13,8 @@ const processors: Record<RunnerJobType, new() => AbstractJobHandler<unknown, Run
'vod-hls-transcoding': VODHLSTranscodingJobHandler,
'vod-audio-merge-transcoding': VODAudioMergeTranscodingJobHandler,
'live-rtmp-hls-transcoding': LiveRTMPHLSTranscodingJobHandler,
- 'video-studio-transcoding': VideoStudioTranscodingJobHandler
+ 'video-studio-transcoding': VideoStudioTranscodingJobHandler,
+ 'video-transcription': TranscriptionJobHandler
}
export function getRunnerJobHandlerClass (job: MRunnerJob) {
diff --git a/server/core/lib/runners/job-handlers/shared/index.ts b/server/core/lib/runners/job-handlers/shared/index.ts
deleted file mode 100644
index bec61e3a08..0000000000
--- a/server/core/lib/runners/job-handlers/shared/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './vod-helpers.js'
diff --git a/server/core/lib/runners/job-handlers/shared/vod-helpers.ts b/server/core/lib/runners/job-handlers/shared/utils.ts
similarity index 87%
rename from server/core/lib/runners/job-handlers/shared/vod-helpers.ts
rename to server/core/lib/runners/job-handlers/shared/utils.ts
index 3c63206bc3..e78d05235b 100644
--- a/server/core/lib/runners/job-handlers/shared/vod-helpers.ts
+++ b/server/core/lib/runners/job-handlers/shared/utils.ts
@@ -23,12 +23,12 @@ export async function onVODWebVideoOrAudioMergeTranscodingJob (options: {
await onTranscodingEnded({ isNewVideo: privatePayload.isNewVideo, moveVideoToNextState: true, video })
}
-export async function loadTranscodingRunnerVideo (runnerJob: MRunnerJob, lTags: LoggerTagsFn) {
+export async function loadRunnerVideo (runnerJob: MRunnerJob, lTags: LoggerTagsFn) {
const videoUUID = runnerJob.privatePayload.videoUUID
const video = await VideoModel.loadFull(videoUUID)
if (!video) {
- logger.info('Video %s does not exist anymore after transcoding runner job.', videoUUID, lTags(videoUUID))
+ logger.info('Video %s does not exist anymore after runner job.', videoUUID, lTags(videoUUID))
return undefined
}
diff --git a/server/core/lib/runners/job-handlers/transcription-job-handler.ts b/server/core/lib/runners/job-handlers/transcription-job-handler.ts
new file mode 100644
index 0000000000..077f1afc24
--- /dev/null
+++ b/server/core/lib/runners/job-handlers/transcription-job-handler.ts
@@ -0,0 +1,101 @@
+import {
+ RunnerJobState,
+ RunnerJobStateType,
+ RunnerJobTranscriptionPayload,
+ RunnerJobTranscriptionPrivatePayload,
+ RunnerJobUpdatePayload,
+ TranscriptionSuccess
+} from '@peertube/peertube-models'
+import { buildUUID } from '@peertube/peertube-node-utils'
+import { JOB_PRIORITY } from '@server/initializers/constants.js'
+import { onTranscriptionEnded } from '@server/lib/video-captions.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import { MVideoUUID } from '@server/types/models/index.js'
+import { MRunnerJob } from '@server/types/models/runners/index.js'
+import { generateRunnerTranscodingVideoInputFileUrl } from '../runner-urls.js'
+import { AbstractJobHandler } from './abstract-job-handler.js'
+import { loadRunnerVideo } from './shared/utils.js'
+
+type CreateOptions = {
+ video: MVideoUUID
+}
+
+export class TranscriptionJobHandler extends AbstractJobHandler<CreateOptions, RunnerJobUpdatePayload, TranscriptionSuccess> {
+
+ protected isAbortSupported () {
+ return true
+ }
+
+ protected specificUpdate (_options: {
+ runnerJob: MRunnerJob
+ }) {
+ // empty
+ }
+
+ protected specificAbort (_options: {
+ runnerJob: MRunnerJob
+ }) {
+ // empty
+ }
+
+ protected async specificError (options: {
+ runnerJob: MRunnerJob
+ nextState: RunnerJobStateType
+ }) {
+ if (options.nextState !== RunnerJobState.ERRORED) return
+
+ await VideoJobInfoModel.decrease(options.runnerJob.privatePayload.videoUUID, 'pendingTranscription')
+ }
+
+ protected async specificCancel (options: {
+ runnerJob: MRunnerJob
+ }) {
+ await VideoJobInfoModel.decrease(options.runnerJob.privatePayload.videoUUID, 'pendingTranscription')
+ }
+
+ async create (options: CreateOptions) {
+ const { video } = options
+
+ const jobUUID = buildUUID()
+ const payload: RunnerJobTranscriptionPayload = {
+ input: {
+ videoFileUrl: generateRunnerTranscodingVideoInputFileUrl(jobUUID, video.uuid)
+ }
+ }
+
+ const privatePayload: RunnerJobTranscriptionPrivatePayload = {
+ videoUUID: video.uuid
+ }
+
+ const job = await this.createRunnerJob({
+ type: 'video-transcription',
+ jobUUID,
+ payload,
+ privatePayload,
+ priority: JOB_PRIORITY.TRANSCODING
+ })
+
+ await VideoJobInfoModel.increaseOrCreate(video.uuid, 'pendingTranscription')
+
+ return job
+ }
+
+ // ---------------------------------------------------------------------------
+
+ protected async specificComplete (options: {
+ runnerJob: MRunnerJob
+ resultPayload: TranscriptionSuccess
+ }) {
+ const { runnerJob, resultPayload } = options
+
+ const video = await loadRunnerVideo(runnerJob, this.lTags)
+ if (!video) return
+
+ await onTranscriptionEnded({
+ video,
+ language: resultPayload.inputLanguage,
+ vttPath: resultPayload.vttFile as string,
+ lTags: this.lTags().tags
+ })
+ }
+}
diff --git a/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts
index d958d447fb..a244cddfff 100644
--- a/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts
@@ -19,7 +19,7 @@ import { MRunnerJob } from '@server/types/models/runners/index.js'
import { basename } from 'path'
import { generateRunnerEditionTranscodingVideoInputFileUrl, generateRunnerTranscodingVideoInputFileUrl } from '../runner-urls.js'
import { AbstractJobHandler } from './abstract-job-handler.js'
-import { loadTranscodingRunnerVideo } from './shared/index.js'
+import { loadRunnerVideo } from './shared/utils.js'
type CreateOptions = {
video: MVideo
@@ -108,7 +108,7 @@ export class VideoStudioTranscodingJobHandler extends AbstractJobHandler<CreateO
const { runnerJob, resultPayload } = options
const privatePayload = runnerJob.privatePayload as RunnerJobVideoStudioTranscodingPrivatePayload
- const video = await loadTranscodingRunnerVideo(runnerJob, this.lTags)
+ const video = await loadRunnerVideo(runnerJob, this.lTags)
if (!video) {
await safeCleanupStudioTMPFiles(privatePayload.originalTasks)
@@ -149,7 +149,7 @@ export class VideoStudioTranscodingJobHandler extends AbstractJobHandler<CreateO
const payload = runnerJob.privatePayload as RunnerJobVideoStudioTranscodingPrivatePayload
await safeCleanupStudioTMPFiles(payload.originalTasks)
- const video = await loadTranscodingRunnerVideo(options.runnerJob, this.lTags)
+ const video = await loadRunnerVideo(options.runnerJob, this.lTags)
if (!video) return
return video.setNewState(VideoState.PUBLISHED, false, undefined)
diff --git a/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
index b93ab37a4d..5933501f51 100644
--- a/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/vod-audio-merge-transcoding-job-handler.ts
@@ -1,18 +1,18 @@
-import { logger } from '@server/helpers/logger.js'
-import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
-import { MVideo } from '@server/types/models/index.js'
-import { MRunnerJob } from '@server/types/models/runners/index.js'
import { pick } from '@peertube/peertube-core-utils'
-import { buildUUID } from '@peertube/peertube-node-utils'
import {
RunnerJobUpdatePayload,
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODWebVideoTranscodingPrivatePayload,
VODAudioMergeTranscodingSuccess
} from '@peertube/peertube-models'
+import { buildUUID } from '@peertube/peertube-node-utils'
+import { logger } from '@server/helpers/logger.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import { MVideo } from '@server/types/models/index.js'
+import { MRunnerJob } from '@server/types/models/runners/index.js'
import { generateRunnerTranscodingVideoInputFileUrl, generateRunnerTranscodingVideoPreviewFileUrl } from '../runner-urls.js'
import { AbstractVODTranscodingJobHandler } from './abstract-vod-transcoding-job-handler.js'
-import { loadTranscodingRunnerVideo, onVODWebVideoOrAudioMergeTranscodingJob } from './shared/index.js'
+import { loadRunnerVideo, onVODWebVideoOrAudioMergeTranscodingJob } from './shared/utils.js'
type CreateOptions = {
video: MVideo
@@ -71,7 +71,7 @@ export class VODAudioMergeTranscodingJobHandler extends AbstractVODTranscodingJo
const { runnerJob, resultPayload } = options
const privatePayload = runnerJob.privatePayload as RunnerJobVODWebVideoTranscodingPrivatePayload
- const video = await loadTranscodingRunnerVideo(runnerJob, this.lTags)
+ const video = await loadRunnerVideo(runnerJob, this.lTags)
if (!video) return
const videoFilePath = resultPayload.videoFile as string
diff --git a/server/core/lib/runners/job-handlers/vod-hls-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/vod-hls-transcoding-job-handler.ts
index 0cb011d95a..283ca7c309 100644
--- a/server/core/lib/runners/job-handlers/vod-hls-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/vod-hls-transcoding-job-handler.ts
@@ -1,21 +1,21 @@
-import { logger } from '@server/helpers/logger.js'
-import { onTranscodingEnded } from '@server/lib/transcoding/ended-transcoding.js'
-import { onHLSVideoFileTranscoding } from '@server/lib/transcoding/hls-transcoding.js'
-import { removeAllWebVideoFiles } from '@server/lib/video-file.js'
-import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
-import { MVideo } from '@server/types/models/index.js'
-import { MRunnerJob } from '@server/types/models/runners/index.js'
import { pick } from '@peertube/peertube-core-utils'
-import { buildUUID } from '@peertube/peertube-node-utils'
import {
RunnerJobUpdatePayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODHLSTranscodingPrivatePayload,
VODHLSTranscodingSuccess
} from '@peertube/peertube-models'
+import { buildUUID } from '@peertube/peertube-node-utils'
+import { logger } from '@server/helpers/logger.js'
+import { onTranscodingEnded } from '@server/lib/transcoding/ended-transcoding.js'
+import { onHLSVideoFileTranscoding } from '@server/lib/transcoding/hls-transcoding.js'
+import { removeAllWebVideoFiles } from '@server/lib/video-file.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import { MVideo } from '@server/types/models/index.js'
+import { MRunnerJob } from '@server/types/models/runners/index.js'
import { generateRunnerTranscodingVideoInputFileUrl } from '../runner-urls.js'
import { AbstractVODTranscodingJobHandler } from './abstract-vod-transcoding-job-handler.js'
-import { loadTranscodingRunnerVideo } from './shared/index.js'
+import { loadRunnerVideo } from './shared/utils.js'
type CreateOptions = {
video: MVideo
@@ -74,7 +74,7 @@ export class VODHLSTranscodingJobHandler extends AbstractVODTranscodingJobHandle
const { runnerJob, resultPayload } = options
const privatePayload = runnerJob.privatePayload as RunnerJobVODHLSTranscodingPrivatePayload
- const video = await loadTranscodingRunnerVideo(runnerJob, this.lTags)
+ const video = await loadRunnerVideo(runnerJob, this.lTags)
if (!video) return
const videoFilePath = resultPayload.videoFile as string
diff --git a/server/core/lib/runners/job-handlers/vod-web-video-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/vod-web-video-transcoding-job-handler.ts
index 12a846985e..081995a48d 100644
--- a/server/core/lib/runners/job-handlers/vod-web-video-transcoding-job-handler.ts
+++ b/server/core/lib/runners/job-handlers/vod-web-video-transcoding-job-handler.ts
@@ -1,18 +1,18 @@
-import { logger } from '@server/helpers/logger.js'
-import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
-import { MVideo } from '@server/types/models/index.js'
-import { MRunnerJob } from '@server/types/models/runners/index.js'
import { pick } from '@peertube/peertube-core-utils'
-import { buildUUID } from '@peertube/peertube-node-utils'
import {
RunnerJobUpdatePayload,
RunnerJobVODWebVideoTranscodingPayload,
RunnerJobVODWebVideoTranscodingPrivatePayload,
VODWebVideoTranscodingSuccess
} from '@peertube/peertube-models'
+import { buildUUID } from '@peertube/peertube-node-utils'
+import { logger } from '@server/helpers/logger.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import { MVideo } from '@server/types/models/index.js'
+import { MRunnerJob } from '@server/types/models/runners/index.js'
import { generateRunnerTranscodingVideoInputFileUrl } from '../runner-urls.js'
import { AbstractVODTranscodingJobHandler } from './abstract-vod-transcoding-job-handler.js'
-import { loadTranscodingRunnerVideo, onVODWebVideoOrAudioMergeTranscodingJob } from './shared/index.js'
+import { loadRunnerVideo, onVODWebVideoOrAudioMergeTranscodingJob } from './shared/utils.js'
type CreateOptions = {
video: MVideo
@@ -70,7 +70,7 @@ export class VODWebVideoTranscodingJobHandler extends AbstractVODTranscodingJobH
const { runnerJob, resultPayload } = options
const privatePayload = runnerJob.privatePayload as RunnerJobVODWebVideoTranscodingPrivatePayload
- const video = await loadTranscodingRunnerVideo(runnerJob, this.lTags)
+ const video = await loadRunnerVideo(runnerJob, this.lTags)
if (!video) return
const videoFilePath = resultPayload.videoFile as string
diff --git a/server/core/lib/server-config-manager.ts b/server/core/lib/server-config-manager.ts
index 523c2e554c..72e4ac24fa 100644
--- a/server/core/lib/server-config-manager.ts
+++ b/server/core/lib/server-config-manager.ts
@@ -192,6 +192,9 @@ class ServerConfigManager {
enabled: CONFIG.VIDEO_FILE.UPDATE.ENABLED
}
},
+ videoTranscription: {
+ enabled: CONFIG.VIDEO_TRANSCRIPTION.ENABLED
+ },
import: {
videos: {
http: {
diff --git a/server/core/lib/user-import-export/importers/user-settings-importer.ts b/server/core/lib/user-import-export/importers/user-settings-importer.ts
index 738f812370..fd72a46ee8 100644
--- a/server/core/lib/user-import-export/importers/user-settings-importer.ts
+++ b/server/core/lib/user-import-export/importers/user-settings-importer.ts
@@ -93,7 +93,8 @@ export class UserSettingsImporter extends AbstractUserImporter <UserSettingsExpo
autoInstanceFollowing: settingsImportData.autoInstanceFollowing,
newPeerTubeVersion: settingsImportData.newPeerTubeVersion,
newPluginVersion: settingsImportData.newPluginVersion,
- myVideoStudioEditionFinished: settingsImportData.myVideoStudioEditionFinished
+ myVideoStudioEditionFinished: settingsImportData.myVideoStudioEditionFinished,
+ myVideoTranscriptionGenerated: settingsImportData.myVideoTranscriptionGenerated
}
await UserNotificationSettingModel.updateUserSettings(values, this.user.id)
diff --git a/server/core/lib/user.ts b/server/core/lib/user.ts
index 3c3b0de0f4..39ec281a6e 100644
--- a/server/core/lib/user.ts
+++ b/server/core/lib/user.ts
@@ -274,7 +274,8 @@ function createDefaultUserNotificationSettings (user: MUserId, t: Transaction |
autoInstanceFollowing: UserNotificationSettingValue.WEB,
newPeerTubeVersion: UserNotificationSettingValue.WEB | UserNotificationSettingValue.EMAIL,
newPluginVersion: UserNotificationSettingValue.WEB,
- myVideoStudioEditionFinished: UserNotificationSettingValue.WEB
+ myVideoStudioEditionFinished: UserNotificationSettingValue.WEB,
+ myVideoTranscriptionGenerated: UserNotificationSettingValue.WEB
}
return UserNotificationSettingModel.create(values, { transaction: t })
diff --git a/server/core/lib/video-captions.ts b/server/core/lib/video-captions.ts
index 8b363274fb..ddd1418dc1 100644
--- a/server/core/lib/video-captions.ts
+++ b/server/core/lib/video-captions.ts
@@ -1,7 +1,25 @@
+import { hasAudioStream } from '@peertube/peertube-ffmpeg'
+import { buildSUUID } from '@peertube/peertube-node-utils'
+import { AbstractTranscriber, TranscriptionModel, WhisperBuiltinModel, transcriberFactory } from '@peertube/peertube-transcription'
import { moveAndProcessCaptionFile } from '@server/helpers/captions-utils.js'
+import { isVideoCaptionLanguageValid } from '@server/helpers/custom-validators/video-captions.js'
+import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
+import { CONFIG } from '@server/initializers/config.js'
+import { DIRECTORIES } from '@server/initializers/constants.js'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
-import { MVideo, MVideoCaption } from '@server/types/models/index.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
+import { VideoModel } from '@server/models/video/video.js'
+import { MVideo, MVideoCaption, MVideoFullLight, MVideoUUID, MVideoUrl } from '@server/types/models/index.js'
+import { ensureDir, remove } from 'fs-extra/esm'
+import { join } from 'path'
+import { federateVideoIfNeeded } from './activitypub/videos/federate.js'
+import { JobQueue } from './job-queue/job-queue.js'
+import { Notifier } from './notifier/notifier.js'
+import { TranscriptionJobHandler } from './runners/index.js'
+import { VideoPathManager } from './video-path-manager.js'
+
+const lTags = loggerTagsFactory('video-caption')
export async function createLocalCaption (options: {
video: MVideo
@@ -22,5 +40,122 @@ export async function createLocalCaption (options: {
await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t)
})
- return videoCaption
+ return Object.assign(videoCaption, { Video: video })
+}
+
+export async function createTranscriptionTaskIfNeeded (video: MVideoUUID & MVideoUrl) {
+ if (CONFIG.VIDEO_TRANSCRIPTION.ENABLED !== true) return
+
+ logger.info(`Creating transcription job for ${video.url}`, lTags(video.uuid))
+
+ if (CONFIG.VIDEO_TRANSCRIPTION.REMOTE_RUNNERS.ENABLED === true) {
+ await new TranscriptionJobHandler().create({ video })
+ } else {
+ await JobQueue.Instance.createJob({ type: 'video-transcription', payload: { videoUUID: video.uuid } })
+ }
+
+ await VideoJobInfoModel.increaseOrCreate(video.uuid, 'pendingTranscription')
+}
+
+// ---------------------------------------------------------------------------
+// Transcription task
+// ---------------------------------------------------------------------------
+
+let transcriber: AbstractTranscriber
+
+export async function generateSubtitle (options: {
+ video: MVideoUUID
+}) {
+ const inputFileMutexReleaser = await VideoPathManager.Instance.lockFiles(options.video.uuid)
+
+ const outputPath = join(CONFIG.STORAGE.TMP_DIR, 'transcription', buildSUUID())
+ await ensureDir(outputPath)
+
+ const binDirectory = join(DIRECTORIES.LOCAL_PIP_DIRECTORY, 'bin')
+
+ try {
+ // Lazy load the transcriber
+ if (!transcriber) {
+ transcriber = transcriberFactory.createFromEngineName({
+ engineName: CONFIG.VIDEO_TRANSCRIPTION.ENGINE,
+ enginePath: CONFIG.VIDEO_TRANSCRIPTION.ENGINE_PATH,
+ logger,
+ binDirectory
+ })
+
+ if (!CONFIG.VIDEO_TRANSCRIPTION.ENGINE_PATH) {
+ logger.info(`Installing transcriber ${transcriber.engine.name} to generate subtitles`, lTags())
+ await transcriber.install(DIRECTORIES.LOCAL_PIP_DIRECTORY)
+ }
+ }
+
+ const video = await VideoModel.loadFull(options.video.uuid)
+ const file = video.getMaxQualityFile().withVideoOrPlaylist(video)
+
+ await VideoPathManager.Instance.makeAvailableVideoFile(file, async videoInputPath => {
+ if (await hasAudioStream(videoInputPath) !== true) {
+ logger.info(
+ `Do not run transcription for ${video.uuid} in ${outputPath} because it does not contain an audio stream`,
+ lTags(video.uuid)
+ )
+
+ return
+ }
+
+ logger.info(`Running transcription for ${video.uuid} in ${outputPath}`, lTags(video.uuid))
+
+ const transcriptFile = await transcriber.transcribe({
+ mediaFilePath: videoInputPath,
+
+ model: CONFIG.VIDEO_TRANSCRIPTION.MODEL_PATH
+ ? await TranscriptionModel.fromPath(CONFIG.VIDEO_TRANSCRIPTION.MODEL_PATH)
+ : new WhisperBuiltinModel(CONFIG.VIDEO_TRANSCRIPTION.MODEL),
+
+ transcriptDirectory: outputPath,
+
+ format: 'vtt'
+ })
+
+ await onTranscriptionEnded({ video, language: transcriptFile.language, vttPath: transcriptFile.path })
+ })
+ } finally {
+ if (outputPath) await remove(outputPath)
+
+ inputFileMutexReleaser()
+ }
+}
+
+export async function onTranscriptionEnded (options: {
+ video: MVideoFullLight
+ language: string
+ vttPath: string
+ lTags?: (string | number)[]
+}) {
+ const { video, language, vttPath, lTags: customLTags = [] } = options
+
+ await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscription')
+
+ if (!isVideoCaptionLanguageValid(language)) {
+ logger.warn(`Invalid transcription language for video ${video.uuid}`, this.lTags(video.uuid))
+ return
+ }
+
+ if (!video.language) {
+ video.language = language
+ await video.save()
+ }
+
+ const caption = await createLocalCaption({
+ video,
+ language,
+ path: vttPath
+ })
+
+ await sequelizeTypescript.transaction(async t => {
+ await federateVideoIfNeeded(video, false, t)
+ })
+
+ Notifier.Instance.notifyOfGeneratedVideoTranscription(caption)
+
+ logger.info(`Transcription ended for ${video.uuid}`, lTags(video.uuid, ...customLTags))
}
diff --git a/server/core/lib/video-file.ts b/server/core/lib/video-file.ts
index 5134f76c9a..b43176fb16 100644
--- a/server/core/lib/video-file.ts
+++ b/server/core/lib/video-file.ts
@@ -8,7 +8,7 @@ import { VideoFileModel } from '@server/models/video/video-file.js'
import { VideoSourceModel } from '@server/models/video/video-source.js'
import { MVideo, MVideoFile, MVideoId, MVideoWithAllFiles } from '@server/types/models/index.js'
import { FfprobeData } from 'fluent-ffmpeg'
-import { move, remove } from 'fs-extra'
+import { move, remove } from 'fs-extra/esm'
import { lTags } from './object-storage/shared/index.js'
import { storeOriginalVideoFile } from './object-storage/videos.js'
import { generateHLSVideoFilename, generateWebVideoFilename } from './paths.js'
diff --git a/server/core/lib/video-jobs.ts b/server/core/lib/video-jobs.ts
index d69cda8a3b..9ad05a4c40 100644
--- a/server/core/lib/video-jobs.ts
+++ b/server/core/lib/video-jobs.ts
@@ -3,6 +3,7 @@ import { CONFIG } from '@server/initializers/config.js'
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import { MVideo, MVideoFile, MVideoFullLight, MVideoUUID } from '@server/types/models/index.js'
import { CreateJobArgument, CreateJobOptions, JobQueue } from './job-queue/job-queue.js'
+import { createTranscriptionTaskIfNeeded } from './video-captions.js'
import { moveFilesIfPrivacyChanged } from './video-privacy.js'
export async function buildMoveJob (options: {
@@ -57,8 +58,9 @@ export function buildStoryboardJobIfNeeded (options: {
export async function addVideoJobsAfterCreation (options: {
video: MVideo
videoFile: MVideoFile
+ generateTranscription: boolean
}) {
- const { video, videoFile } = options
+ const { video, videoFile, generateTranscription } = options
const jobs: (CreateJobArgument & CreateJobOptions)[] = [
{
@@ -105,7 +107,11 @@ export async function addVideoJobsAfterCreation (options: {
})
}
- return JobQueue.Instance.createSequentialJobFlow(...jobs)
+ await JobQueue.Instance.createSequentialJobFlow(...jobs)
+
+ if (generateTranscription === true && CONFIG.VIDEO_TRANSCRIPTION.ENABLED === true) {
+ await createTranscriptionTaskIfNeeded(video)
+ }
}
export async function addVideoJobsAfterUpdate (options: {
diff --git a/server/core/lib/video-pre-import.ts b/server/core/lib/video-pre-import.ts
index ceca6580ba..fbb94edacd 100644
--- a/server/core/lib/video-pre-import.ts
+++ b/server/core/lib/video-pre-import.ts
@@ -259,6 +259,7 @@ async function buildYoutubeDLImport (options: {
type: 'youtube-dl' as 'youtube-dl',
videoImportId: videoImport.id,
fileExt,
+ generateTranscription: importDataOverride.generateTranscription ?? true,
// If part of a sync process, there is a parent job that will aggregate children results
preventException: !!channelSync
}
diff --git a/server/core/middlewares/validators/videos/video-captions.ts b/server/core/middlewares/validators/videos/video-captions.ts
index d6407502be..74ad1e8aa7 100644
--- a/server/core/middlewares/validators/videos/video-captions.ts
+++ b/server/core/middlewares/validators/videos/video-captions.ts
@@ -1,6 +1,10 @@
+import { HttpStatusCode, ServerErrorCode, UserRight, VideoCaptionGenerate } from '@peertube/peertube-models'
+import { isBooleanValid, toBooleanOrNull } from '@server/helpers/custom-validators/misc.js'
+import { CONFIG } from '@server/initializers/config.js'
+import { VideoCaptionModel } from '@server/models/video/video-caption.js'
+import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import express from 'express'
import { body, param } from 'express-validator'
-import { UserRight } from '@peertube/peertube-models'
import { isVideoCaptionFile, isVideoCaptionLanguageValid } from '../../../helpers/custom-validators/video-captions.js'
import { cleanUpReqFiles } from '../../../helpers/express-utils.js'
import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../../initializers/constants.js'
@@ -14,7 +18,7 @@ import {
isValidVideoPasswordHeader
} from '../shared/index.js'
-const addVideoCaptionValidator = [
+export const addVideoCaptionValidator = [
isValidVideoIdParam('videoId'),
param('captionLanguage')
@@ -41,7 +45,75 @@ const addVideoCaptionValidator = [
}
]
-const deleteVideoCaptionValidator = [
+export const generateVideoCaptionValidator = [
+ isValidVideoIdParam('videoId'),
+
+ body('forceTranscription')
+ .optional()
+ .customSanitizer(toBooleanOrNull)
+ .custom(isBooleanValid),
+
+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+ if (areValidationErrors(req, res)) return
+
+ if (CONFIG.VIDEO_TRANSCRIPTION.ENABLED !== true) {
+ return res.fail({
+ status: HttpStatusCode.BAD_REQUEST_400,
+ message: 'Video transcription is disabled on this instance'
+ })
+ }
+
+ if (!await doesVideoExist(req.params.videoId, res)) return
+
+ const video = res.locals.videoAll
+
+ if (video.remote) {
+ return res.fail({
+ status: HttpStatusCode.BAD_REQUEST_400,
+ message: 'Cannot run transcription job on a remote video'
+ })
+ }
+
+ // Check if the user who did the request is able to update the video
+ const user = res.locals.oauth.token.User
+ if (!checkUserCanManageVideo(user, video, UserRight.UPDATE_ANY_VIDEO, res)) return
+
+ // Check the video has not already a caption
+ const captions = await VideoCaptionModel.listVideoCaptions(video.id)
+ if (captions.length !== 0) {
+ return res.fail({
+ status: HttpStatusCode.BAD_REQUEST_400,
+ message: 'This video already has captions'
+ })
+ }
+
+ // Bypass "video is already transcribed" check
+ const body = req.body as VideoCaptionGenerate
+ if (body.forceTranscription === true) {
+ if (user.hasRight(UserRight.UPDATE_ANY_VIDEO) !== true) {
+ return res.fail({
+ status: HttpStatusCode.FORBIDDEN_403,
+ message: 'Only admins can force transcription'
+ })
+ }
+
+ return next()
+ }
+
+ const info = await VideoJobInfoModel.load(video.id)
+ if (info && info.pendingTranscription > 0) {
+ return res.fail({
+ status: HttpStatusCode.CONFLICT_409,
+ type: ServerErrorCode.VIDEO_ALREADY_BEING_TRANSCRIBED,
+ message: 'This video is already being transcribed'
+ })
+ }
+
+ return next()
+ }
+]
+
+export const deleteVideoCaptionValidator = [
isValidVideoIdParam('videoId'),
param('captionLanguage')
@@ -60,7 +132,7 @@ const deleteVideoCaptionValidator = [
}
]
-const listVideoCaptionsValidator = [
+export const listVideoCaptionsValidator = [
isValidVideoIdParam('videoId'),
isValidVideoPasswordHeader(),
@@ -75,9 +147,3 @@ const listVideoCaptionsValidator = [
return next()
}
]
-
-export {
- addVideoCaptionValidator,
- listVideoCaptionsValidator,
- deleteVideoCaptionValidator
-}
diff --git a/server/core/models/user/sql/user-notitication-list-query-builder.ts b/server/core/models/user/sql/user-notitication-list-query-builder.ts
index 32f5ba73e6..fe0720e76b 100644
--- a/server/core/models/user/sql/user-notitication-list-query-builder.ts
+++ b/server/core/models/user/sql/user-notitication-list-query-builder.ts
@@ -183,7 +183,12 @@ export class UserNotificationListQueryBuilder extends AbstractRunQuery {
"Account->Actor->Server"."id" AS "Account.Actor.Server.id",
"Account->Actor->Server"."host" AS "Account.Actor.Server.host",
"UserRegistration"."id" AS "UserRegistration.id",
- "UserRegistration"."username" AS "UserRegistration.username"`
+ "UserRegistration"."username" AS "UserRegistration.username",
+ "VideoCaption"."id" AS "VideoCaption.id",
+ "VideoCaption"."language" AS "VideoCaption.language",
+ "VideoCaption->Video"."id" AS "VideoCaption.Video.id",
+ "VideoCaption->Video"."uuid" AS "VideoCaption.Video.uuid",
+ "VideoCaption->Video"."name" AS "VideoCaption.Video.name"`
}
private getJoins () {
@@ -269,6 +274,11 @@ export class UserNotificationListQueryBuilder extends AbstractRunQuery {
LEFT JOIN "server" AS "Account->Actor->Server" ON "Account->Actor"."serverId" = "Account->Actor->Server"."id"
) ON "UserNotificationModel"."accountId" = "Account"."id"
- LEFT JOIN "userRegistration" as "UserRegistration" ON "UserNotificationModel"."userRegistrationId" = "UserRegistration"."id"`
+ LEFT JOIN "userRegistration" as "UserRegistration" ON "UserNotificationModel"."userRegistrationId" = "UserRegistration"."id"
+
+ LEFT JOIN (
+ "videoCaption" AS "VideoCaption"
+ INNER JOIN "video" AS "VideoCaption->Video" ON "VideoCaption"."videoId" = "VideoCaption->Video"."id"
+ ) ON "UserNotificationModel"."videoCaptionId" = "VideoCaption"."id"`
}
}
diff --git a/server/core/models/user/user-notification-setting.ts b/server/core/models/user/user-notification-setting.ts
index 2ad3ddfa9d..dc48ca55de 100644
--- a/server/core/models/user/user-notification-setting.ts
+++ b/server/core/models/user/user-notification-setting.ts
@@ -181,6 +181,15 @@ export class UserNotificationSettingModel extends SequelizeModel<UserNotificatio
@Column
myVideoStudioEditionFinished: UserNotificationSettingValueType
+ @AllowNull(false)
+ @Default(null)
+ @Is(
+ 'UserNotificationSettingTranscriptionGeneratedForOwner',
+ value => throwIfNotValid(value, isUserNotificationSettingValid, 'myVideoTranscriptionGenerated')
+ )
+ @Column
+ myVideoTranscriptionGenerated: UserNotificationSettingValueType
+
@ForeignKey(() => UserModel)
@Column
userId: number
@@ -233,6 +242,7 @@ export class UserNotificationSettingModel extends SequelizeModel<UserNotificatio
abuseStateChange: this.abuseStateChange,
newPeerTubeVersion: this.newPeerTubeVersion,
myVideoStudioEditionFinished: this.myVideoStudioEditionFinished,
+ myVideoTranscriptionGenerated: this.myVideoTranscriptionGenerated,
newPluginVersion: this.newPluginVersion
}
}
diff --git a/server/core/models/user/user-notification.ts b/server/core/models/user/user-notification.ts
index 0b41bf6762..d1cd9c1231 100644
--- a/server/core/models/user/user-notification.ts
+++ b/server/core/models/user/user-notification.ts
@@ -13,6 +13,7 @@ import { ApplicationModel } from '../application/application.js'
import { PluginModel } from '../server/plugin.js'
import { SequelizeModel, throwIfNotValid } from '../shared/index.js'
import { VideoBlacklistModel } from '../video/video-blacklist.js'
+import { VideoCaptionModel } from '../video/video-caption.js'
import { VideoCommentModel } from '../video/video-comment.js'
import { VideoImportModel } from '../video/video-import.js'
import { VideoModel } from '../video/video.js'
@@ -260,6 +261,18 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>
})
UserRegistration: Awaited<UserRegistrationModel>
+ @ForeignKey(() => VideoCaptionModel)
+ @Column
+ videoCaptionId: number
+
+ @BelongsTo(() => VideoCaptionModel, {
+ foreignKey: {
+ allowNull: true
+ },
+ onDelete: 'cascade'
+ })
+ VideoCaption: Awaited<VideoCaptionModel>
+
static listForApi (userId: number, start: number, count: number, sort: string, unread?: boolean) {
const where = { userId }
@@ -441,6 +454,17 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>
? { id: this.UserRegistration.id, username: this.UserRegistration.username }
: undefined
+ const videoCaption = this.VideoCaption
+ ? {
+ id: this.VideoCaption.id,
+ language: {
+ id: this.VideoCaption.language,
+ label: VideoCaptionModel.getLanguageLabel(this.VideoCaption.language)
+ },
+ video: this.formatVideo(this.VideoCaption.Video)
+ }
+ : undefined
+
return {
id: this.id,
type: this.type,
@@ -455,6 +479,7 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>
plugin,
peertube,
registration,
+ videoCaption,
createdAt: this.createdAt.toISOString(),
updatedAt: this.updatedAt.toISOString()
}
@@ -531,4 +556,11 @@ export class UserNotificationModel extends SequelizeModel<UserNotificationModel>
width: a.width
}
}
+
+ formatVideoCaption (a: UserNotificationIncludes.ActorImageInclude) {
+ return {
+ path: a.getStaticPath(),
+ width: a.width
+ }
+ }
}
diff --git a/server/core/models/video/video-caption.ts b/server/core/models/video/video-caption.ts
index e707e868f8..df2124b86f 100644
--- a/server/core/models/video/video-caption.ts
+++ b/server/core/models/video/video-caption.ts
@@ -112,10 +112,21 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return undefined
}
+ static async insertOrReplaceLanguage (caption: MVideoCaption, transaction: Transaction) {
+ const existing = await VideoCaptionModel.loadByVideoIdAndLanguage(caption.videoId, caption.language, transaction)
+
+ // Delete existing file
+ if (existing) await existing.destroy({ transaction })
+
+ return caption.save({ transaction })
+ }
+
+ // ---------------------------------------------------------------------------
+
static loadByVideoIdAndLanguage (videoId: string | number, language: string, transaction?: Transaction): Promise<MVideoCaptionVideo> {
const videoInclude = {
model: VideoModel.unscoped(),
- attributes: [ 'id', 'remote', 'uuid' ],
+ attributes: [ 'id', 'name', 'remote', 'uuid', 'url' ],
where: buildWhereIdOrUUID(videoId)
}
@@ -148,13 +159,18 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return VideoCaptionModel.findOne(query)
}
- static async insertOrReplaceLanguage (caption: MVideoCaption, transaction: Transaction) {
- const existing = await VideoCaptionModel.loadByVideoIdAndLanguage(caption.videoId, caption.language, transaction)
+ // ---------------------------------------------------------------------------
- // Delete existing file
- if (existing) await existing.destroy({ transaction })
+ static async hasVideoCaption (videoId: number) {
+ const query = {
+ where: {
+ videoId
+ }
+ }
- return caption.save({ transaction })
+ const result = await VideoCaptionModel.unscoped().findOne(query)
+
+ return !!result
}
static listVideoCaptions (videoId: number, transaction?: Transaction): Promise<MVideoCaptionVideo[]> {
@@ -194,29 +210,16 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
return result
}
+ // ---------------------------------------------------------------------------
+
static getLanguageLabel (language: string) {
return VIDEO_LANGUAGES[language] || 'Unknown'
}
- static deleteAllCaptionsOfRemoteVideo (videoId: number, transaction: Transaction) {
- const query = {
- where: {
- videoId
- },
- transaction
- }
-
- return VideoCaptionModel.destroy(query)
- }
-
static generateCaptionName (language: string) {
return `${buildUUID()}-${language}.vtt`
}
- isOwned () {
- return this.Video.remote === false
- }
-
// ---------------------------------------------------------------------------
toFormattedJSON (this: MVideoCaptionFormattable): VideoCaption {
@@ -240,6 +243,10 @@ export class VideoCaptionModel extends SequelizeModel<VideoCaptionModel> {
// ---------------------------------------------------------------------------
+ isOwned () {
+ return this.Video.remote === false
+ }
+
getCaptionStaticPath (this: MVideoCaptionLanguageUrl) {
return join(LAZY_STATIC_PATHS.VIDEO_CAPTIONS, this.filename)
}
diff --git a/server/core/models/video/video-job-info.ts b/server/core/models/video/video-job-info.ts
index a1e55948b6..3a54ca2c71 100644
--- a/server/core/models/video/video-job-info.ts
+++ b/server/core/models/video/video-job-info.ts
@@ -1,10 +1,10 @@
+import { forceNumber } from '@peertube/peertube-core-utils'
import { Op, QueryTypes, Transaction } from 'sequelize'
import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, IsInt, Table, Unique, UpdatedAt } from 'sequelize-typescript'
-import { forceNumber } from '@peertube/peertube-core-utils'
-import { VideoModel } from './video.js'
import { SequelizeModel } from '../shared/sequelize-type.js'
+import { VideoModel } from './video.js'
-export type VideoJobInfoColumnType = 'pendingMove' | 'pendingTranscode'
+export type VideoJobInfoColumnType = 'pendingMove' | 'pendingTranscode' | 'pendingTranscription'
@Table({
tableName: 'videoJobInfo',
@@ -39,6 +39,12 @@ export class VideoJobInfoModel extends SequelizeModel<VideoJobInfoModel> {
@Column
pendingTranscode: number
+ @AllowNull(false)
+ @Default(0)
+ @IsInt
+ @Column
+ pendingTranscription: number
+
@ForeignKey(() => VideoModel)
@Unique
@Column
diff --git a/server/core/types/models/user/user-notification.ts b/server/core/types/models/user/user-notification.ts
index ca19f8f092..83411d3fd2 100644
--- a/server/core/types/models/user/user-notification.ts
+++ b/server/core/types/models/user/user-notification.ts
@@ -16,6 +16,7 @@ import { VideoBlacklistModel } from '../../../models/video/video-blacklist.js'
import { VideoChannelModel } from '../../../models/video/video-channel.js'
import { VideoCommentModel } from '../../../models/video/video-comment.js'
import { VideoImportModel } from '../../../models/video/video-import.js'
+import { VideoCaptionModel } from '@server/models/video/video-caption.js'
type Use<K extends keyof UserNotificationModel, M> = PickWith<UserNotificationModel, K, M>
@@ -98,13 +99,17 @@ export module UserNotificationIncludes {
export type UserRegistrationInclude =
Pick<UserRegistrationModel, 'id' | 'username'>
+
+ export type VideoCaptionInclude =
+ Pick<VideoCaptionModel, 'id' | 'language'> &
+ PickWith<VideoCaptionModel, 'Video', VideoInclude>
}
// ############################################################################
export type MUserNotification =
Omit<UserNotificationModel, 'User' | 'Video' | 'VideoComment' | 'Abuse' | 'VideoBlacklist' |
- 'VideoImport' | 'Account' | 'ActorFollow' | 'Plugin' | 'Application' | 'UserRegistration'>
+ 'VideoImport' | 'Account' | 'ActorFollow' | 'Plugin' | 'Application' | 'UserRegistration' | 'VideoCaption'>
// ############################################################################
@@ -119,4 +124,5 @@ export type UserNotificationModelForApi =
Use<'Plugin', UserNotificationIncludes.PluginInclude> &
Use<'Application', UserNotificationIncludes.ApplicationInclude> &
Use<'Account', UserNotificationIncludes.AccountIncludeActor> &
- Use<'UserRegistration', UserNotificationIncludes.UserRegistrationInclude>
+ Use<'UserRegistration', UserNotificationIncludes.UserRegistrationInclude> &
+ Use<'VideoCaption', UserNotificationIncludes.VideoCaptionInclude>
diff --git a/server/core/types/models/video/video-caption.ts b/server/core/types/models/video/video-caption.ts
index c00226ba5a..3472742a92 100644
--- a/server/core/types/models/video/video-caption.ts
+++ b/server/core/types/models/video/video-caption.ts
@@ -16,7 +16,7 @@ export type MVideoCaptionLanguageUrl =
export type MVideoCaptionVideo =
MVideoCaption &
- Use<'Video', Pick<MVideo, 'id' | 'remote' | 'uuid'>>
+ Use<'Video', Pick<MVideo, 'id' | 'name' | 'remote' | 'uuid' | 'url' | 'getWatchStaticPath'>>
// ############################################################################
diff --git a/server/tsconfig.types.json b/server/tsconfig.types.json
index 696fe7059c..444f9b0a13 100644
--- a/server/tsconfig.types.json
+++ b/server/tsconfig.types.json
@@ -13,7 +13,8 @@
{ "path": "../packages/models" },
{ "path": "../packages/node-utils" },
{ "path": "../packages/server-commands" },
- { "path": "../packages/typescript-utils" }
+ { "path": "../packages/typescript-utils" },
+ { "path": "../packages/transcription" }
],
"exclude": [
"tests/"
diff --git a/support/doc/api/openapi.yaml b/support/doc/api/openapi.yaml
index ff7312867f..62104f7fd9 100644
--- a/support/doc/api/openapi.yaml
+++ b/support/doc/api/openapi.yaml
@@ -4127,7 +4127,7 @@ paths:
/api/v1/videos/{id}/storyboards:
get:
summary: List storyboards of a video
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
operationId: listVideoStoryboards
tags:
- Video
@@ -4171,6 +4171,32 @@ paths:
items:
$ref: '#/components/schemas/VideoCaption'
+ /api/v1/videos/{id}/captions/generate:
+ post:
+ summary: Generate a video caption
+ operationId: generateVideoCaption
+ description: "**PeerTube >= 6.2** This feature has to be enabled by the administrator"
+ security:
+ - OAuth2:
+ - user
+ tags:
+ - Video Captions
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ forceTranscription:
+ type: boolean
+ default: false
+ responses:
+ '204':
+ description: successful operation
+ '404':
+ description: video not found
+
+
/api/v1/videos/{id}/captions/{captionLanguage}:
put:
summary: Add or replace a video caption
@@ -4221,7 +4247,7 @@ paths:
/api/v1/videos/{id}/chapters:
get:
summary: Get chapters of a video
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
operationId: getVideoChapters
tags:
- Video Chapters
@@ -4237,7 +4263,7 @@ paths:
$ref: '#/components/schemas/VideoChapters'
put:
summary: Replace video chapters
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
operationId: replaceVideoChapters
security:
- OAuth2:
@@ -4270,7 +4296,7 @@ paths:
/api/v1/videos/{id}/passwords:
get:
summary: List video passwords
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
security:
- OAuth2:
- user
@@ -4292,7 +4318,7 @@ paths:
description: video is not password protected
put:
summary: Update video passwords
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
security:
- OAuth2:
- user
@@ -4317,7 +4343,7 @@ paths:
/api/v1/videos/{id}/passwords/{videoPasswordId}:
delete:
summary: Delete a video password
- description: "**PeerTube** >= 6.0"
+ description: "**PeerTube >= 6.0**"
security:
- OAuth2:
- user
@@ -8315,7 +8341,7 @@ components:
nullable: true
example: |
"**[Want to help to translate this video?](https://weblate.framasoft.org/projects/what-is-peertube-video/)**\r\n\r\n
- **Take back the control of your videos! [#JoinPeertube](https://joinpeertube.org)**\r\n*A decentralized video hosting network,
+ **Take back the control of your videos! [#JoinPeertube](https://joinpeertube.org)**\r\n*A decentralized video hosting network,
based on free/libre software!*\r\n\r\n**Animation Produced by:** [LILA](https://libreart.info) - [ZeMarmot Team](https://film.zemarmot.net)\r\n
*Directed by* Aryeom\r\n*Assistant* Jehan\r\n**Licence**: [CC-By-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)\r\n\r\n
**Sponsored by** [Framasoft](https://framasoft.org)\r\n\r\n**Music**: [Red Step Forward](http://play.dogmazic.net/song.php?song_id=52491) - CC-By Ken Bushima\r\n\r\n
@@ -9683,6 +9709,9 @@ components:
waitTranscoding:
description: Whether or not we wait transcoding before publish the video
type: boolean
+ generateTranscription:
+ description: "**PeerTube >= 6.2** If enabled by the admin, automatically generate a subtitle of the video"
+ type: boolean
support:
description: A text tell the audience how to support the video creator
example: Please support our work on https://soutenir.framasoft.org/en/ <3
diff --git a/support/doc/dependencies.md b/support/doc/dependencies.md
index c6d745607d..158766c8df 100644
--- a/support/doc/dependencies.md
+++ b/support/doc/dependencies.md
@@ -2,13 +2,15 @@
:warning: **Warning**: dependencies guide is maintained by the community. Some parts may be outdated! :warning:
-Main dependencies version supported by PeerTube:
+Main dependencies supported by PeerTube:
* `node` >=18.x
* `yarn` 1.x (**must not be >=2.x**)
* `postgres` >=10.x
* `redis-server` >=6.x
* `ffmpeg` >=4.3 (using a ffmpeg static build [is not recommended](https://github.com/Chocobozzz/PeerTube/issues/6308))
+ * `python` >=3.x
+ * `pip`
_note_: only **LTS** versions of external dependencies are supported. If no LTS version matching the version constraint is available, only **release** versions are supported.
@@ -48,20 +50,12 @@ _note_: only **LTS** versions of external dependencies are supported. If no LTS
5. Install Python:
-On Ubuntu <= bionic (18.04 LTS) or Debian <= Buster:
-
-```
-sudo apt update
-sudo apt install python-dev
-python --version # Should be >= 2.x or >= 3.x
-```
-
On Ubuntu >= focal (20.04 LTS) or Debian >= Bullseye:
```
sudo apt update
-sudo apt install python3-dev python-is-python3 # python-is-python2 should also work
-python --version # Should be >= 2.x or >= 3.x
+sudo apt install python3-dev python3-pip python-is-python3
+python --version # Should be >= 3.x
```
6. Install common dependencies:
@@ -85,7 +79,7 @@ sudo systemctl start redis postgresql
1. Run:
```
-sudo pacman -S nodejs-lts-fermium yarn ffmpeg postgresql openssl redis git wget unzip python base-devel npm nginx
+sudo pacman -S nodejs-lts-fermium yarn ffmpeg postgresql openssl redis git wget unzip python python-pip base-devel npm nginx
```
Now that dependencies are installed, before running PeerTube you should start PostgreSQL and Redis:
@@ -214,7 +208,7 @@ sudo dnf update -y
5. Install PostgreSQL and Python3 and other stuff:
```
-sudo dnf install -y nginx postgresql postgresql-server postgresql-contrib openssl gcc-c++ make wget redis git python3
+sudo dnf install -y nginx postgresql postgresql-server postgresql-contrib openssl gcc-c++ make wget redis git python3 python3-pip
sudo ln -s /usr/bin/python3 /usr/bin/python
sudo PGSETUP_INITDB_OPTIONS='--auth-host=md5' postgresql-setup --initdb --unit postgresql
sudo systemctl enable --now redis
diff --git a/support/doc/development/tests.md b/support/doc/development/tests.md
index 2e4c6ff6a7..544b2ba2d5 100644
--- a/support/doc/development/tests.md
+++ b/support/doc/development/tests.md
@@ -36,11 +36,17 @@ Ensure you also have these commands:
```bash
exiftool --help
parallel --help
+
+# For transcription tests
+whisper --help
+whisper-ctranslate2 --help
+jiwer --help
```
Otherwise, install the packages. On Debian-based systems (like Debian, Ubuntu or Mint):
```bash
sudo apt-get install parallel libimage-exiftool-perl
+sudo pip install -r packages/tests/requirements.txt -r packages/transcription-devtools/requirements.txt
```
### Test
diff --git a/tsconfig.eslint.json b/tsconfig.eslint.json
index 61542e14e3..9ef5a40b7f 100644
--- a/tsconfig.eslint.json
+++ b/tsconfig.eslint.json
@@ -24,7 +24,7 @@
{ "path": "./apps/peertube-cli" },
{ "path": "./packages/core-utils" },
{ "path": "./packages/ffmpeg" },
- { "path": "./packages/jiwer" },
+ { "path": "./packages/transcription-devtools" },
{ "path": "./packages/models" },
{ "path": "./packages/node-utils" },
{ "path": "./packages/server-commands" },