Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(cli): support remote audio URLs in `generate asr` (#15987)

Arvin Xu2fdebb9f4ea4
diff --git a/apps/cli/src/commands/generate.test.ts b/apps/cli/src/commands/generate.test.ts
index 59778549366..478c2272902 100644
--- a/apps/cli/src/commands/generate.test.ts
+++ b/apps/cli/src/commands/generate.test.ts
@@ -369,6 +369,59 @@ describe('generate command', () => {
expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
expect(exitSpy).toHaveBeenCalledWith(1);
});
+
+ it('should download and transcribe an audio URL', async () => {
+ const fetchMock = vi
+ .fn()
+ // first call: download the remote audio
+ .mockResolvedValueOnce({
+ blob: vi.fn().mockResolvedValue(new Blob(['audio-bytes'])),
+ ok: true,
+ })
+ // second call: STT endpoint
+ .mockResolvedValueOnce({
+ json: vi.fn().mockResolvedValue({ text: 'hello world' }),
+ ok: true,
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'asr',
+ 'https://example.com/audio/sample.mp3',
+ ]);
+
+ expect(fetchMock).toHaveBeenNthCalledWith(1, 'https://example.com/audio/sample.mp3');
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 2,
+ 'https://app.lobehub.com/webapi/stt/openai',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(stdoutSpy).toHaveBeenCalledWith('hello world');
+ expect(exitSpy).not.toHaveBeenCalled();
+ });
+
+ it('should exit when audio URL download fails', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({ ok: false, status: 404, statusText: 'Not Found' }),
+ );
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'generate',
+ 'asr',
+ 'https://example.com/missing.mp3',
+ ]);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Failed to download audio'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
});
describe('delete', () => {
diff --git a/apps/cli/src/commands/generate/asr.ts b/apps/cli/src/commands/generate/asr.ts
index 9f407d4baa5..ad66b7e20ea 100644
--- a/apps/cli/src/commands/generate/asr.ts
+++ b/apps/cli/src/commands/generate/asr.ts
@@ -9,7 +9,9 @@ import { log } from '../../utils/logger';
export function registerAsrCommand(parent: Command) {
parent
.command('asr <audio-file>')
- .description('Convert speech to text (automatic speech recognition)')
+ .description(
+ 'Convert speech to text (automatic speech recognition). Accepts a local path or a URL',
+ )
.option('--model <model>', 'STT model', 'whisper-1')
.option('--language <lang>', 'Language code (e.g. en, zh)')
.option('--json', 'Output raw JSON')
@@ -22,7 +24,9 @@ export function registerAsrCommand(parent: Command) {
model: string;
},
) => {
- if (!existsSync(audioFile)) {
+ const isUrl = audioFile.startsWith('http://') || audioFile.startsWith('https://');
+
+ if (!isUrl && !existsSync(audioFile)) {
log.error(`File not found: ${audioFile}`);
process.exit(1);
return;
@@ -33,9 +37,23 @@ export function registerAsrCommand(parent: Command) {
const sttOptions: Record<string, any> = { model: options.model };
if (options.language) sttOptions.language = options.language;
+ let fileBuffer: Blob;
+ let fileName: string;
+ try {
+ if (isUrl) {
+ ({ blob: fileBuffer, name: fileName } = await fetchAudioFromUrl(audioFile));
+ } else {
+ fileBuffer = await readFileAsBlob(audioFile);
+ fileName = path.basename(audioFile);
+ }
+ } catch (error) {
+ log.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ return;
+ }
+
const formData = new FormData();
- const fileBuffer = await readFileAsBlob(audioFile);
- formData.append('speech', fileBuffer, path.basename(audioFile));
+ formData.append('speech', fileBuffer, fileName);
formData.append('options', JSON.stringify(sttOptions));
// Remove Content-Type for multipart/form-data (let fetch set it with boundary)
@@ -75,3 +93,24 @@ async function readFileAsBlob(filePath: string): Promise<Blob> {
}
return new Blob(chunks);
}
+
+async function fetchAudioFromUrl(url: string): Promise<{ blob: Blob; name: string }> {
+ const res = await fetch(url);
+ if (!res.ok) {
+ throw new Error(`Failed to download audio: ${res.status} ${res.statusText}`);
+ }
+
+ const blob = await res.blob();
+
+ // Derive a file name from the URL path, falling back to a generic name.
+ const pathname = (() => {
+ try {
+ return new URL(url).pathname;
+ } catch {
+ return '';
+ }
+ })();
+ const name = path.basename(pathname) || 'audio';
+
+ return { blob, name };
+}