66 lines
2.4 KiB
C++
66 lines
2.4 KiB
C++
#include "google/text_to_speech.h"
|
|||
|
|
|
||
|
|
#include "google/caps.h"
|
||
|
|
#include "google/endpoints.h"
|
||
|
|
#include "security/crypto/Base64.h"
|
||
|
|
|
||
|
|
namespace molo::google {
|
||
|
|
|
||
|
|
using clients::body::Json;
|
||
|
|
|
||
|
|
TextToSpeech::TextToSpeech(std::shared_ptr<GoogleClient> client)
|
||
|
|
: Service(std::move(client), endpoints::text_to_speech()) {}
|
||
|
|
|
||
|
|
Audio TextToSpeech::synthesize(const SynthesisRequest& request) const {
|
||
|
|
if (request.text.empty()) throw GoogleError::invalid("text is empty");
|
||
|
|
if (request.text.size() > Caps::kMaxTtsChars)
|
||
|
|
throw GoogleError::invalid("text over " +
|
||
|
|
std::to_string(Caps::kMaxTtsChars) + " characters");
|
||
|
|
if (request.speaking_rate < 0.25 || request.speaking_rate > 4.0)
|
||
|
|
throw GoogleError::invalid("speaking_rate outside 0.25..4.0");
|
||
|
|
|
||
|
|
Json input = Json::object();
|
||
|
|
input.set(request.ssml ? "ssml" : "text", Json(request.text));
|
||
|
|
Json voice = Json::object();
|
||
|
|
voice.set("languageCode", Json(request.language));
|
||
|
|
if (!request.voice.empty()) voice.set("name", Json(request.voice));
|
||
|
|
Json audio_config = Json::object();
|
||
|
|
audio_config.set("audioEncoding", Json(audio_encoding_name(request.encoding)));
|
||
|
|
audio_config.set("speakingRate", Json(request.speaking_rate));
|
||
|
|
Json body = Json::object();
|
||
|
|
body.set("input", input);
|
||
|
|
body.set("voice", voice);
|
||
|
|
body.set("audioConfig", audio_config);
|
||
|
|
|
||
|
|
Json reply = call("/text:synthesize", body);
|
||
|
|
Audio out;
|
||
|
|
out.mime = audio_encoding_mime(request.encoding);
|
||
|
|
if (!security::crypto::Base64::decode(string_at(reply, "audioContent"),
|
||
|
|
out.bytes) ||
|
||
|
|
out.bytes.empty())
|
||
|
|
throw GoogleError(502, "BAD_RESPONSE", "missing or invalid audioContent",
|
||
|
|
endpoint_.name);
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
std::vector<Voice> TextToSpeech::voices(const std::string& language) const {
|
||
|
|
Json reply = fetch(language.empty() ? "/voices"
|
||
|
|
: "/voices?languageCode=" + language);
|
||
|
|
std::vector<Voice> out;
|
||
|
|
const Json* list = reply.find("voices");
|
||
|
|
if (!list || !list->is_array()) return out;
|
||
|
|
for (const Json& v : list->as_array()) {
|
||
|
|
Voice voice;
|
||
|
|
voice.name = string_at(v, "name");
|
||
|
|
voice.gender = string_at(v, "ssmlGender");
|
||
|
|
if (const Json* codes = v.find("languageCodes");
|
||
|
|
codes && codes->is_array())
|
||
|
|
for (const Json& c : codes->as_array())
|
||
|
|
if (c.is_string()) voice.languages.push_back(c.as_string());
|
||
|
|
out.push_back(std::move(voice));
|
||
|
|
}
|
||
|
|
return out;
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace molo::google
|