diff --git a/README.md b/README.md index f7c7fb6..f28a36b 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,39 @@ $ cloudconvert ai/agent --prompt="Convert https://example.com/report.docx to PDF ``` Use `--engine` to choose the AI model. You can list the available models using `cloudconvert parameters ai/agent --alternatives`. The `ai/agent` task itself does not consume credits; the tasks created by the agent consume credits as usual. See CloudConvert's [AI documentation](https://cloudconvert.com/docs/operations/ai) for details. + +#### Speech to Text + +Transcribe the speech of audio and video files to plain text (`txt`, the default), subtitles (`srt`, `vtt`) or `json` with the segments and their timestamps: + +``` +$ cloudconvert ai/stt interview.mp3 +$ cloudconvert ai/stt -f srt --language=en video.mp4 +$ cloudconvert ai/stt -f vtt --translate video.mp4 +``` + +#### Text to Speech + +Speak a text, or UTF-8 text files, to `mp3` (the default), `wav`, `flac` or `ogg`: + +``` +$ cloudconvert ai/tts --text="Welcome to CloudConvert. Your file is ready for download." --voice=ryan +$ cloudconvert ai/tts -f wav --instruct="Calm and slow, like a bedtime story." story.txt +``` + +#### Redact Personal Data + +Remove personal data from PDF, TXT and MD files. The output file has the format of the input file: + +``` +$ cloudconvert ai/redact contract.pdf +$ cloudconvert ai/redact --preset=strict --replacement=mask notes.txt +$ cloudconvert ai/redact --ocr=true --ocr_language.0=eng --ocr_language.1=deu scan.pdf +``` + +AI models make mistakes: some personal data may be missed. Check the result where it matters. + +`ai/stt`, `ai/tts` and `ai/redact` run on CloudConvert's own servers and consume credits like conversions. List their parameters, such as the voices, presets and languages, with `cloudconvert parameters ai/stt`, `ai/tts` or `ai/redact`. ## All Options @@ -162,6 +195,12 @@ Commands: graphicsmagick commands cloudconvert ai/agent [files..] Let an AI agent process files as described in a prompt (beta) + cloudconvert ai/stt Transcribe the speech of audio and + video files + cloudconvert ai/tts [files..] Speak a text or text files to audio + files + cloudconvert ai/redact Remove personal data from PDF, TXT + and MD files cloudconvert credits Print the remaining conversion credits of your account cloudconvert parameters List available task parameters for an diff --git a/src/app.ts b/src/app.ts index 5c8b44a..c658f0c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -4,6 +4,7 @@ import yargs from 'yargs/yargs'; import type { Argv } from 'yargs'; import { createAgentCommand } from './commands/agent.js'; +import { createRedactCommand, createSpeechToTextCommand, createTextToSpeechCommand } from './commands/ai.js'; import { createCaptureWebsiteCommand } from './commands/capture-website.js'; import { createCommandCommand } from './commands/command.js'; import { createConvertCommand } from './commands/convert.js'; @@ -52,6 +53,9 @@ export function createCli(args: string[], partialDependencies: Partial { + return { + ...createFileJobCommand( + { + command: 'ai/stt ', + describe: 'Transcribe the speech of audio and video files', + fileDescription: 'Path(s) to audio or video file(s) to transcribe', + operation: 'ai/stt', + format: { + alias: 'f', + describe: 'Format of the transcript: txt, srt, vtt or json. Defaults to txt' + }, + examples: [ + 'cloudconvert ai/stt input.mp3', + 'cloudconvert ai/stt -f srt --language=en input.mp4', + 'cloudconvert ai/stt -f vtt --translate input.mp4' + ] + }, + runJob + ), + aliases: ['ai-stt', 'stt'] + }; +} + +export function createRedactCommand(runJob: JobRunner): CommandModule { + return { + ...createFileJobCommand( + { + command: 'ai/redact ', + describe: 'Remove personal data from PDF, TXT and MD files', + fileDescription: 'Path(s) to PDF, TXT or MD file(s) to redact', + operation: 'ai/redact', + examples: [ + 'cloudconvert ai/redact input.pdf', + 'cloudconvert ai/redact --preset=strict --replacement=mask input.txt', + 'cloudconvert ai/redact --ocr=true --ocr_language.0=eng --ocr_language.1=deu input.pdf' + ] + }, + runJob + ), + aliases: ['ai-redact', 'redact', 'pdf/redact', 'pdf-redact'] + }; +} + +export function createTextToSpeechCommand(runJob: JobRunner): CommandModule { + return { + command: 'ai/tts [files..]', + aliases: ['ai-tts', 'tts'], + describe: 'Speak a text or text files to audio files', + builder: yargs => buildTextToSpeechOptions(yargs), + handler: async rawArgv => { + const argv = rawArgv as unknown as TextToSpeechArguments; + const hasText = argv.text !== undefined && argv.text !== ''; + + if ((argv.filePatterns ?? []).length > 0 && (argv.files ?? []).length < 1) { + throw new Error(`No files found: ${(argv.filePatterns ?? []).join(', ')}`); + } + + if (hasText && (argv.files ?? []).length > 0) { + throw new Error('Set either --text or text files, not both!'); + } + + if (!hasText && (argv.files ?? []).length < 1) { + throw new Error('You need to provide --text or at least one text file!'); + } + + await runJob(argv, { + operation: 'ai/tts', + ...(hasText ? { text: argv.text } : {}), + ...(argv.format ? { output_format: argv.format } : {}), + ...collectTaskParameters(argv) + }); + } + }; +} + +function buildTextToSpeechOptions(argv: Argv): Argv { + return addTaskParameterMiddleware( + argv + .positional('files', { + description: 'Path(s) to UTF-8 text file(s) to speak, instead of --text' + }) + .option('text', { + describe: 'The text to speak, up to 10,000 characters', + type: 'string' + }) + .option('output-format', { + alias: ['f', 'format'], + describe: 'Format of the audio file: mp3, wav, flac or ogg. Defaults to mp3', + type: 'string' + }) + .example('cloudconvert ai/tts --text="Welcome to CloudConvert." --voice=ryan', '') + .example('cloudconvert ai/tts -f wav --instruct="Calm and slow, like a bedtime story." story.txt', '') + ) + .help() + .hide('version') + .epilogue('Find possible task parameters with: cloudconvert parameters ai/tts'); +} diff --git a/src/commands/parameters.ts b/src/commands/parameters.ts index 87d8df9..44e409f 100644 --- a/src/commands/parameters.ts +++ b/src/commands/parameters.ts @@ -22,7 +22,7 @@ export function createParametersCommand(): CommandModule { yargs .positional('operation', { description: - 'Operation to inspect, for example: convert, optimize, thumbnail, watermark, capture-website or ai/agent', + 'Operation to inspect, for example: convert, optimize, thumbnail, watermark, capture-website, ai/agent or ai/stt', type: 'string' }) .option('input-format', { diff --git a/src/job.ts b/src/job.ts index ff1db45..fa285c9 100644 --- a/src/job.ts +++ b/src/job.ts @@ -38,6 +38,7 @@ const JOB_STATUS_POLL_INTERVAL_MS = 30_000; const JOB_CANCELLED_MESSAGE = 'Job cancelled.'; const AGENT_OPERATION = 'ai/agent'; const AGENT_NO_OUTPUT_CODE = 'AGENT_NO_OUTPUT'; +const FORMAT_OPTION_OPERATIONS = new Set(['ai/stt', 'ai/tts']); export interface RunJobDependencies { spinner: Spinner; @@ -525,11 +526,14 @@ async function fetchParameterOptions( cloudconvert: CloudConvertClient, taskData: TaskData ): Promise> { + // The operations API lists no operations of ai/stt and ai/tts when filtering by their output_format option + const filterByFormat = !FORMAT_OPTION_OPERATIONS.has(taskData.operation); + return collectOperationOptions( await fetchOperations(cloudconvert, { operation: taskData.operation, - inputFormat: typeof taskData.input_format === 'string' ? taskData.input_format : undefined, - outputFormat: typeof taskData.output_format === 'string' ? taskData.output_format : undefined, + inputFormat: filterByFormat && typeof taskData.input_format === 'string' ? taskData.input_format : undefined, + outputFormat: filterByFormat && typeof taskData.output_format === 'string' ? taskData.output_format : undefined, engine: typeof taskData.engine === 'string' ? taskData.engine : undefined, engineVersion: typeof taskData.engine_version === 'string' ? taskData.engine_version : undefined }) diff --git a/test/cli.test.ts b/test/cli.test.ts index 093c8f0..41e78e9 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -35,6 +35,9 @@ describe('CLI compatibility', () => { expect(help).toContain('cloudconvert pdf/rotate-pages '); expect(help).toContain('cloudconvert command '); expect(help).toContain('cloudconvert ai/agent [files..]'); + expect(help).toContain('cloudconvert ai/stt '); + expect(help).toContain('cloudconvert ai/tts [files..]'); + expect(help).toContain('cloudconvert ai/redact '); expect(help).toContain('cloudconvert credits'); expect(help).toContain('cloudconvert parameters '); expect(help).toContain('--api-key'); @@ -78,6 +81,9 @@ describe('CLI compatibility', () => { const commandHelp = await createCli(['command', '--help'], dependencies).getHelp(); const pdfOcrHelp = await createCli(['pdf/ocr', '--help'], dependencies).getHelp(); const agentHelp = await createCli(['ai/agent', '--help'], dependencies).getHelp(); + const sttHelp = await createCli(['ai/stt', '--help'], dependencies).getHelp(); + const ttsHelp = await createCli(['ai/tts', '--help'], dependencies).getHelp(); + const redactHelp = await createCli(['ai/redact', '--help'], dependencies).getHelp(); expect(convertHelp).toContain('Find possible task parameters with: cloudconvert parameters convert'); expect(captureWebsiteHelp).toContain( @@ -86,6 +92,9 @@ describe('CLI compatibility', () => { expect(commandHelp).toContain('Find possible task parameters with: cloudconvert parameters command'); expect(pdfOcrHelp).toContain('Find possible task parameters with: cloudconvert parameters pdf/ocr'); expect(agentHelp).toContain('Find possible task parameters with: cloudconvert parameters ai/agent'); + expect(sttHelp).toContain('Find possible task parameters with: cloudconvert parameters ai/stt'); + expect(ttsHelp).toContain('Find possible task parameters with: cloudconvert parameters ai/tts'); + expect(redactHelp).toContain('Find possible task parameters with: cloudconvert parameters ai/redact'); }); it('parses convert with -f and dotted -p parameters', async () => { @@ -328,6 +337,117 @@ describe('CLI compatibility', () => { await expect(parseJobCommand(['ai/agent', files[0]])).rejects.toThrow('Missing required argument: prompt'); }); + it('parses ai/stt with output format and dynamic parameters', async () => { + const { files, cleanup } = await createTempFiles(['interview.mp3']); + cleanups.push(cleanup); + const calls = await parseJobCommand([ + 'ai/stt', + '-f', + 'srt', + '--language=en', + '--translate', + '--max_line_length=42', + files[0] + ]); + + expect(calls[0].argv.files).toEqual([files[0]]); + expect(calls[0].taskData).toEqual({ + operation: 'ai/stt', + output_format: 'srt', + language: 'en', + translate: true, + max_line_length: 42 + }); + }); + + it('leaves the ai/stt output format to the API default', async () => { + const { files, cleanup } = await createTempFiles(['interview.mp3']); + cleanups.push(cleanup); + const calls = await parseJobCommand(['stt', files[0]]); + + expect(JSON.parse(JSON.stringify(calls[0].taskData))).toEqual({ operation: 'ai/stt' }); + }); + + it('requires files for ai/stt', async () => { + await expect(parseJobCommand(['ai/stt', 'missing.mp3'])).rejects.toThrow('You need to provide at least one file!'); + }); + + it('parses ai/tts with text and without files', async () => { + const calls = await parseJobCommand([ + 'ai/tts', + '-f', + 'mp3', + '--text=Welcome to CloudConvert. Your file is ready for download.', + '--voice=ryan' + ]); + + expect(calls[0].argv.files).toEqual([]); + expect(calls[0].taskData).toEqual({ + operation: 'ai/tts', + text: 'Welcome to CloudConvert. Your file is ready for download.', + output_format: 'mp3', + voice: 'ryan' + }); + }); + + it('keeps numeric ai/tts text as string', async () => { + const calls = await parseJobCommand(['tts', '--text=123']); + + expect(calls[0].taskData).toEqual({ operation: 'ai/tts', text: '123' }); + }); + + it('parses ai/tts with text files', async () => { + const { files, cleanup } = await createTempFiles(['story.txt']); + cleanups.push(cleanup); + const calls = await parseJobCommand(['ai-tts', '--instruct=Calm and slow.', files[0]]); + + expect(calls[0].argv.files).toEqual([files[0]]); + expect(calls[0].taskData).toEqual({ operation: 'ai/tts', instruct: 'Calm and slow.' }); + }); + + it('requires either text or text files for ai/tts', async () => { + const { files, cleanup } = await createTempFiles(['story.txt']); + cleanups.push(cleanup); + + await expect(parseJobCommand(['ai/tts'])).rejects.toThrow('You need to provide --text or at least one text file!'); + await expect(parseJobCommand(['ai/tts', '--text=Hello', files[0]])).rejects.toThrow( + 'Set either --text or text files, not both!' + ); + await expect(parseJobCommand(['ai/tts', 'missing.txt'])).rejects.toThrow('No files found: missing.txt'); + }); + + it('parses ai/redact with dynamic parameters', async () => { + const { files, cleanup } = await createTempFiles(['contract.pdf']); + cleanups.push(cleanup); + const calls = await parseJobCommand([ + 'ai/redact', + '--preset=standard', + '--ocr=true', + '--ocr_language.0=eng', + '--ocr_language.1=deu', + files[0] + ]); + + expect(calls[0].argv.files).toEqual([files[0]]); + expect(calls[0].taskData).toEqual({ + operation: 'ai/redact', + preset: 'standard', + ocr: 'true', + ocr_language: { 0: 'eng', 1: 'deu' } + }); + }); + + it('keeps ai-redact, redact, pdf/redact and pdf-redact as aliases for ai/redact', async () => { + const { files, cleanup } = await createTempFiles(['notes.txt']); + cleanups.push(cleanup); + + for (const alias of ['ai-redact', 'redact', 'pdf/redact', 'pdf-redact']) { + const calls = await parseJobCommand([alias, '--entities=person', '--entities=email', files[0]]); + + expect(calls[0].taskData).toEqual({ operation: 'ai/redact', entities: ['person', 'email'] }); + } + }); + it('passes --api-url to the client without sending it as task parameter', async () => { const { files, cleanup } = await createTempFiles(['input.pdf']); cleanups.push(cleanup); diff --git a/test/job.test.ts b/test/job.test.ts index e2d5647..66b82fe 100644 --- a/test/job.test.ts +++ b/test/job.test.ts @@ -424,6 +424,82 @@ describe('job services', () => { ); }); + it.each([ + { + operation: 'ai/stt', + options: [ + { name: 'output_format', type: 'enum' }, + { name: 'translate', type: 'boolean' }, + { name: 'max_line_length', type: 'integer' } + ], + taskData: { output_format: 'srt', translate: 'true', max_line_length: '42' }, + expected: { output_format: 'srt', translate: true, max_line_length: 42 }, + expectedFilters: { 'filter[operation]': 'ai/stt', include: 'options' } + }, + { + operation: 'ai/tts', + options: [ + { name: 'output_format', type: 'enum' }, + { name: 'instruct', type: 'string' } + ], + taskData: { output_format: 'wav', text: 'Hello', instruct: 123 }, + expected: { output_format: 'wav', text: 'Hello', instruct: '123' }, + expectedFilters: { 'filter[operation]': 'ai/tts', include: 'options' } + }, + { + operation: 'ai/redact', + options: [ + { name: 'ocr', type: 'boolean' }, + { name: 'threshold', type: 'float' } + ], + taskData: { ocr: 'true', threshold: '0.4' }, + expected: { ocr: true, threshold: 0.4 }, + expectedFilters: { 'filter[operation]': 'ai/redact', include: 'options' } + } + ])('casts $operation parameters, without filtering the operations by format', async ({ + operation, + options, + taskData, + expected, + expectedFilters + }) => { + const { files, cleanup } = await createTempFiles(['input']); + cleanups.push(cleanup); + const client = createFakeCloudConvertClient() as CloudConvertClient; + let finishedCallback: ((event: JobEvent) => void) | undefined; + + vi.mocked(client.call).mockResolvedValue({ data: [{ operation, options }] }); + vi.mocked(client.jobs.create).mockResolvedValue(createUploadJob()); + vi.mocked(client.jobs.subscribeEvent).mockImplementation((_id, event, callback) => { + if (event === 'finished') { + finishedCallback = callback; + } + }); + vi.mocked(client.tasks.upload).mockResolvedValue(undefined); + + const jobPromise = runJob(createArgv(client, files), { operation, ...taskData }, { + spinner: createSpinner(), + logger: createSilentLogger(), + downloadFile: vi.fn(async () => 'downloaded' as const) + }); + + await vi.waitFor(() => expect(client.tasks.upload).toHaveBeenCalledOnce()); + finishedCallback?.({ job: createFinishedJob() }); + await jobPromise; + + expect(client.call).toHaveBeenCalledWith('GET', 'operations', expectedFilters); + expect(client.jobs.create).toHaveBeenCalledWith(buildJobTemplate({ operation, ...expected }, files)); + }); + + it('builds ai/tts jobs with text and without input files', () => { + expect(buildJobTemplate({ operation: 'ai/tts', text: 'Hello' }, [])).toEqual({ + tasks: { + process: { operation: 'ai/tts', text: 'Hello' }, + export: { operation: 'export/url', input: 'process' } + } + }); + }); + it('rejects when the job fails and keeps the old failure text', async () => { const client = createFakeCloudConvertClient() as CloudConvertClient; const spinner = createSpinner();