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
8 changes: 5 additions & 3 deletions src/apis/audio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { SpeechCreateParams } from 'openai/resources/audio/speech';
import { Stream } from '../streaming';
import { AUDIO_FILE_DURATION_HEADER } from '../constants';
import getAudioFileDuration from '../getAudioDuration';
import { isRunningInBrowser } from '../core';
import { isFsModuleAvailable } from '../core';

export class Audio extends ApiResource {
transcriptions: transcriptions;
Expand Down Expand Up @@ -78,7 +78,8 @@ export class transcriptions extends ApiResource {
> {
// @ts-ignore
const path = body.file?.path;
if (path && this.client.calculateAudioDuration && !isRunningInBrowser()) {

if (path && this.client.calculateAudioDuration && isFsModuleAvailable()) {
const duration = await getAudioFileDuration(path);
if (duration) {
params = {
Expand Down Expand Up @@ -110,7 +111,8 @@ export class translations extends ApiResource {
): Promise<any> {
const body: any = _body;
const path = body.file?.path;
if (path && this.client.calculateAudioDuration && !isRunningInBrowser()) {

if (path && this.client.calculateAudioDuration && isFsModuleAvailable()) {
const duration = await getAudioFileDuration(path);
if (duration) {
params = {
Expand Down
9 changes: 9 additions & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,12 @@ export const isRunningInBrowser = () => {
typeof navigator !== 'undefined'
);
};

export const isFsModuleAvailable = () => {
try {
require('fs');
return true;
} catch (e) {
return false;
}
};
10 changes: 6 additions & 4 deletions src/getAudioDuration.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { isRunningInBrowser } from './core';
import { isFsModuleAvailable } from './core';

const isBrowser = isRunningInBrowser();
const fsAvailable = isFsModuleAvailable();

let fs: any;
let open: any;
let read: any;
let stat: any;
let close: any;

if (!isBrowser) {
// Check if we're in Node.js AND fs module is available
if (fsAvailable) {
try {
fs = require('fs');
const { promisify } = require('util');
Expand All @@ -27,7 +28,8 @@ if (!isBrowser) {
* Uses optimized file reading to avoid loading entire files into memory
*/
async function getAudioFileDuration(filePath: string): Promise<string | null> {
if (isBrowser || !fs) {
// Only proceed if we're in Node.js, fs is available, and fs module loaded successfully
if (!fsAvailable || !fs) {
return null;
}

Expand Down
Loading