natural-language-api-google/controllers/naturalLanguageController.js

76 lines
2.4 KiB
JavaScript

const { StatusCodes } = require("http-status-codes")
const { sentiment, convertTextToSpeech, listVoice } = require("../utils")
const language = require('@google-cloud/language').v2
const CustomError = require('../errors')
const voiceConfigList = require('../mockData/voice.json')
const getSentiment = async (req, res) => {
const { text, } = req.body
const status = await sentiment(text)
res.status(StatusCodes.OK).json({ status })
}
const getAudioFromText = async (req, res) => {
const { text, voice_name, voice_gender, languageCode } = req.query
if ((voice_name || voice_gender || languageCode) && languageCode == 'pt-BR') {
const config = { voice_name, voice_gender, languageCode }
for (const key in config) {
if (config.hasOwnProperty(key) && config[key] === undefined) {
throw new CustomError.BadRequestError(`The key ${key} is required when setted one of the three configuration parameters: voice_name, voice_gender and languageCode`)
}
}
const voice = voiceConfigList.find(({ name, ssmlGender, languageCode }) => {
if (name == config.voice_name && ssmlGender == config.voice_gender && languageCode == config.languageCode) return { name, ssmlGender, languageCode }
})
if (!voice)
throw new CustomError.BadRequestError(`Wrong config voice combination! Check the endpoint(http://localhost:6001/api/v1/nl/voice-config) to display the available configurations to a language`)
}
const audioBuffer = await convertTextToSpeech(text, voice_name, voice_gender, languageCode)
if (voice_name && voice_gender && languageCode){
filename = `${voice_name}_${voice_gender}_${languageCode}.mp3`
}
else{
filename = `pt-BR-Standard-B_MALE_pt-BR.mp3`
}
// Set the Content-Disposition header
// res.set("Content-Disposition", `attachment; filename="${filename}"`);
res.set("Content-Disposition", `inline; filename="${filename}"`);
res.contentType('audio/mpeg')
res.status(StatusCodes.OK).send(audioBuffer)
}
const getVoiceConfig = async (req, res) => {
const { languageCode } = req.query
console.log(languageCode)
const configs = await listVoice(languageCode)
res.status(StatusCodes.OK).json({ configs })
}
module.exports = {
getSentiment,
getAudioFromText,
getVoiceConfig
}