Skip to content

Commit

Permalink
feat: simplify STTService request handling by refining SDK usage and …
Browse files Browse the repository at this point in the history
…improving error logging
  • Loading branch information
berry-13 committed Dec 4, 2024
1 parent ffa5f6f commit daacfce
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions api/server/services/Files/Audio/STTService.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class STTService {
'Content-Type': 'multipart/form-data',
...(apiKey && { Authorization: `Bearer ${apiKey}` }),
};
[headers].forEach(this.removeUndefined);
this.removeUndefined(headers);

return [url, data, headers];
}
Expand Down Expand Up @@ -234,34 +234,33 @@ class STTService {
* @throws {Error} If the provider is invalid, the response status is not 200, or the response data is missing.
*/
async sttRequest(provider, sttSchema, { audioBuffer, audioFile }) {
const useSDK = this.shouldUseSDK(provider, sttSchema);
const useSDK = this.shouldUseSDK(provider);
const strategy = useSDK ? this.sdkStrategies[provider] : this.apiStrategies[provider];

if (!strategy) {
throw new Error('Invalid provider or implementation');
}

const audioReadStream = Readable.from(audioBuffer);
audioReadStream.path = 'audio.wav';

if (useSDK) {
return strategy.call(this, sttSchema, audioReadStream, audioFile);
} else {
const [url, data, headers] = strategy.call(this, sttSchema, audioReadStream, audioFile);
}

try {
const response = await axios.post(url, data, { headers });
if (response.status !== 200) {
throw new Error('Invalid response from the STT API');
}
if (!response.data || !response.data.text) {
throw new Error('Missing data in response from the STT API');
}
return response.data.text.trim();
} catch (error) {
logger.error(`STT request failed for provider ${provider}:`, error);
throw error;
const [url, data, headers] = strategy.call(this, sttSchema, audioReadStream);

try {
const response = await axios.post(url, data, { headers });
if (response.status !== 200) {
throw new Error('Invalid response from the STT API');
}
if (!response.data || !response.data.text) {
throw new Error('Missing data in response from the STT API');
}
return response.data.text.trim();
} catch (error) {
logger.error(`STT request failed for provider ${provider}:`, error);
throw error;
}
}

Expand Down Expand Up @@ -294,9 +293,9 @@ class STTService {
} finally {
try {
await fs.unlink(req.file.path);
logger.debug('[/speech/stt] Temp. audio upload file deleted');
logger.debug('[/speech/stt] Temporary audio upload file deleted');
} catch (error) {
logger.debug('[/speech/stt] Temp. audio upload file already deleted');
logger.debug('[/speech/stt] Temporary audio upload file already deleted');
}
}
}
Expand Down

0 comments on commit daacfce

Please sign in to comment.