Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 <files..> Transcribe the speech of audio and
video files
cloudconvert ai/tts [files..] Speak a text or text files to audio
files
cloudconvert ai/redact <files..> Remove personal data from PDF, TXT
and MD files
cloudconvert credits Print the remaining conversion credits of
your account
cloudconvert parameters <operation> List available task parameters for an
Expand Down
4 changes: 4 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -52,6 +53,9 @@ export function createCli(args: string[], partialDependencies: Partial<CliDepend
.command(createWatermarkCommand(dependencies.runJob))
.command(createCommandCommand(dependencies.runJob))
.command(createAgentCommand(dependencies.runJob))
.command(createSpeechToTextCommand(dependencies.runJob))
.command(createTextToSpeechCommand(dependencies.runJob))
.command(createRedactCommand(dependencies.runJob))
.demandCommand()
.option('api-key', {
alias: 'apikey',
Expand Down
109 changes: 109 additions & 0 deletions src/commands/ai.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import type { Argv, CommandModule } from 'yargs';

import type { CliArguments } from '../types.js';
import { createFileJobCommand } from './file-job.js';
import { addTaskParameterMiddleware, collectTaskParameters } from './task-parameters.js';
import type { JobRunner } from './types.js';

interface TextToSpeechArguments extends CliArguments {
text?: string;
}

export function createSpeechToTextCommand(runJob: JobRunner): CommandModule<object, object> {
return {
...createFileJobCommand(
{
command: 'ai/stt <files..>',
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<object, object> {
return {
...createFileJobCommand(
{
command: 'ai/redact <files..>',
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<object, object> {
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<object>): Argv<object> {
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');
}
2 changes: 1 addition & 1 deletion src/commands/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function createParametersCommand(): CommandModule<object, object> {
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', {
Expand Down
8 changes: 6 additions & 2 deletions src/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -525,11 +526,14 @@ async function fetchParameterOptions(
cloudconvert: CloudConvertClient,
taskData: TaskData
): Promise<Map<string, CloudConvertOperationOption>> {
// 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
})
Expand Down
120 changes: 120 additions & 0 deletions test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ describe('CLI compatibility', () => {
expect(help).toContain('cloudconvert pdf/rotate-pages <files..>');
expect(help).toContain('cloudconvert command <files..>');
expect(help).toContain('cloudconvert ai/agent [files..]');
expect(help).toContain('cloudconvert ai/stt <files..>');
expect(help).toContain('cloudconvert ai/tts [files..]');
expect(help).toContain('cloudconvert ai/redact <files..>');
expect(help).toContain('cloudconvert credits');
expect(help).toContain('cloudconvert parameters <operation>');
expect(help).toContain('--api-key');
Expand Down Expand Up @@ -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(
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading