Skip to content

Commit

Permalink
Inclui exemplo de uso de templates
Browse files Browse the repository at this point in the history
  • Loading branch information
vanessagraciela committed Dec 16, 2021
1 parent abc79a9 commit bce9389
Show file tree
Hide file tree
Showing 7 changed files with 264 additions and 25 deletions.
26 changes: 16 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

O [CPQD Texto Fala](https://www.cpqd.com.br/cpqd-texto-fala/) é um *framework* que permite converter texto genérico, como notícias ou diálogos, em fala natural. É possível integrar o CPQD Texto Fala nas mais variadas aplicações, desde aplicativos móveis até sistemas de diálogo para telefonia.

Este repositório possui dois programas de exemplo implementados em C++. O programa ``example_tts`` demonstra o uso do básico do CPQD Texto Fala, utilizando síntese síncrona (bloqueia a *thread* até a síntese ser concluída). Já o programa ``example_tts_streaming`` demonstra o uso de síntese via streaming, que possibilita a entrega do áudio na medida em que a fala é sintetizada.
Este repositório possui três programas de exemplo implementados em C++. O programa ``example_tts`` demonstra o uso do básico do CPQD Texto Fala, utilizando síntese síncrona (bloqueia a *thread* até a síntese ser concluída). Já o programa ``example_tts_streaming`` demonstra o uso de síntese via streaming, que possibilita a entrega do áudio na medida em que a fala é sintetizada. E por fim o programa ``exemple_tts_template`` demostra o uso de templates do CPQD Texto Fala.


## Releases
Expand All @@ -17,7 +17,7 @@ Sempre prefira utilizar uma [versão estável](https://github.com/CPqD/tts-examp
Baixe o conteúdo do repositório em seu computador e crie um *branch* local apontando para a *tag* **v4.7-V1**:

# git clone https://github.com/CPqD/tts-examples-c.git
# git checkout -B v4.7-V1 tags/v4.7-V1
# git checkout -B v4.8-V1 tags/v4.8-V1

Para facilitar a criação dos projetos, o programa [CMake](https://cmake.org/) pode ser utilizado via interface gráfica.

Expand All @@ -31,23 +31,26 @@ Para criar os projetos:
- **Build the binaries**: caminho onde serão gerados os arquivos de build. Normalmente acrescentamos o diretório build no caminho do source code. Exemplo:/source/build
4. Clique em **Configure** e escolha o compilador Visual Studio versão 64 bits;
5. Clique em **Generate** para que as configurações sejam setadas no compilador;
6. A solution ``examples.sln`` e os projetos ``example_tts`` e ``example_tts_streaming`` estarão disponíveis na pasta build.
6. A solution ``examples.sln`` e os projetos ``example_tts``, ``example_tts_streaming`` e ``example_tts_template`` estarão disponíveis na pasta build.


Para compilar o projeto criado:
1. Abra solution ``examples.sln``;
2. Altere a configuração para Release;
3. Clique com o botão direito no projeto ``example_tts`` na opção **Build**;
4. Clique com o botão direito no projeto ``example_tts_streaming`` na opção **Build**;
5. Os executáveis (**example_tts.exe** e **example_tts_streaming.exe**) foram gerados na pasta Release.
4. Clique com o botão direito no projeto ``example_tts_template`` na opção **Build**;
5. Os executáveis (**example_tts.exe**, **example_tts_streaming.exe** e **example_tts_template**) foram gerados na pasta Release.


Com os exectutáveis ``example_tts.exe`` e ``example_tts_streaming.exe`` gerados, você pode testar o funcionamento da biblioteca do **CPQD Texto Fala** da seguinte maneira:
Com os exectutáveis ``example_tts.exe``, ``example_tts_streaming.exe`` e ``example_tts_template gerados``, você pode testar o funcionamento da biblioteca do **CPQD Texto Fala** da seguinte maneira:
1. Rode o programa exemplo informando o caminho da instalação da biblioteca do CPQD Texto Fala:

# example_tts.exe <caminho da instalação do CPQD Texto Fala>
# example_tts_streaming.exe <caminho da instalação do CPQD Texto Fala>
2. Ambos os exemplos irão gerar um arquivo example.wav contendo o texto sintetizado;
# example_tts_template.exe <caminho da instalação do CPQD Texto Fala> <caminho do arquivo do template> <caminho do arquivo de mensagem>
2. Os exemplos example_tts.exe e example_tts_streaming.exe irão gerar um arquivo example.wav contendo o texto sintetizado.
O exemplo example_tts_template.exe irá gerar um arquivo contendo o texto processado pelo template;
3. Opcionalmente o texto a ser sintetizado pode ser informado via arquivo (example.txt). Caso o arquivo não seja encontrado, um texto padrão será sintetizado.

Maiores dúvidas, veja a documentação de [instalação.](https://speechweb.cpqd.com.br/tts/docs/latest/InstallationGuide/Install.html)
Expand All @@ -59,7 +62,7 @@ Maiores dúvidas, veja a documentação de [instalação.](https://speechweb.cpq
Baixe o conteúdo do repositório em seu computador e crie um *branch* local apontando para a *tag* **v4.7-V1**:

# git clone https://github.com/CPqD/tts-examples-c.git
# git checkout -B v4.7-V1 tags/v4.7-V1
# git checkout -B v4.8-V1 tags/v4.8-V1

Para facilitar a criação dos projetos, o programa [CMake](https://cmake.org/) pode ser utilizado via linha de comando.

Expand All @@ -82,16 +85,19 @@ Para compilar o projeto criado:

# make example_tts
# make example_tts_streaming
# make example_tts_template

3. Os executáveis (**example_tts** e **example_tts_streaming**) foram gerados na pasta build.
3. Os executáveis (**example_tts**, **example_tts_streaming** e **example_tts_template**) foram gerados na pasta build.


Com os exectutáveis ``example_tts`` e ``example_tts_streaming`` gerados, você pode testar o funcionamento da biblioteca do **CPqD Texto Fala** da seguinte maneira:
Com os exectutáveis ``example_tts``, ``example_tts_streaming`` e ``example_tts_template`` gerados, você pode testar o funcionamento da biblioteca do **CPqD Texto Fala** da seguinte maneira:
1. Rode o programa exemplo informando o caminho da instalação da biblioteca do CPqD Texto Fala:

# ./example_tts <caminho da instalação do CPqD Texto Fala>
# ./example_tts_streaming <caminho da instalação do CPqD Texto Fala>
2. Ambos os exemplos irão gerar um arquivo example.wav contendo o texto sintetizado;
# ./example_tts_template <caminho da instalação do CPQD Texto Fala> <caminho do arquivo do template> <caminho do arquivo de mensagem>
2. Os exemplos example_tts.exe e example_tts_streaming.exe irão gerar um arquivo example.wav contendo o texto sintetizado.
O exemplo example_tts_template.exe irá gerar um arquivo contendo o texto processado pelo template;
3. Opcionalmente o texto a ser sintetizado pode ser informado via arquivo (example.txt). Caso o arquivo não seja encontrado, um texto padrão será sintetizado.

Maiores dúvidas, veja a documentação de [instalação.](https://speechweb.cpqd.com.br/tts/docs/latest/InstallationGuide/Installation/Install.html)
Expand Down
21 changes: 21 additions & 0 deletions source/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,24 @@ set_target_properties(example_tts_streaming PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" )


################################################################################
## template ##
################################################################################

file(GLOB EXAMPLE_TTS_TEMPLATE_SOURCES "template.cc"
"loader.cc")

file(GLOB EXAMPLE_TTS_TEMPLATE_HEADERS "loader.hh"
"tts.h")
source_group("Header Files" FILES ${EXAMPLE_TTS_TEMPLATE_HEADERS})


add_executable(example_tts_template ${EXAMPLE_TTS_TEMPLATE_SOURCES} ${EXAMPLE_TTS_TEMPLATE_HEADERS})
target_link_libraries(example_tts_template ${TTS_LINK_LIBRARIES})
set_target_properties(example_tts_template PROPERTIES
OUTPUT_NAME "example_tts_template"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" )
13 changes: 12 additions & 1 deletion source/loader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ TTS_LOADPLUGIN TTS_LoadPlugin;
TTS_UNLOADPLUGIN TTS_UnloadPlugin;
TTS_ENUMERATEVOICE TTS_EnumerateVoices;
TTS_ENUMERATEENCODER TTS_EnumerateEncoders;
TTS_VALIDATESSML TTS_ValidateSSML;
TTS_PROCESSMESSAGE TTS_ProcessMessage;
TTS_REGISTERINTERPRETATION TTS_RegisterInterpretation;
TTS_UNLOADTEMPLATE TTS_UnloadTemplate;
TTS_LOADTEMPLATE TTS_LoadTemplate;
TTS_LOADTEMPLATEFROMSTRING TTS_LoadTemplateFromString;


TTS_RETURN tts_loadLibrary(
Expand Down Expand Up @@ -75,7 +81,12 @@ TTS_RETURN tts_loadLibrary(
dynlib_symbol(library, "TTS_LoadPlugin", TTS_LoadPlugin, TTS_LOADPLUGIN);
dynlib_symbol(library, "TTS_UnloadPlugin", TTS_UnloadPlugin, TTS_UNLOADPLUGIN);
dynlib_symbol(library, "TTS_EnumerateVoices", TTS_EnumerateVoices, TTS_ENUMERATEVOICE);
dynlib_symbol(library, "TTS_EnumerateEncoders", TTS_EnumerateEncoders, TTS_ENUMERATEENCODER);
dynlib_symbol(library, "TTS_ValidateSSML", TTS_ValidateSSML, TTS_VALIDATESSML);
dynlib_symbol(library, "TTS_ProcessMessage", TTS_ProcessMessage, TTS_PROCESSMESSAGE);
dynlib_symbol(library, "TTS_RegisterInterpretation", TTS_RegisterInterpretation, TTS_REGISTERINTERPRETATION);
dynlib_symbol(library, "TTS_UnloadTemplate", TTS_UnloadTemplate, TTS_UNLOADTEMPLATE);
dynlib_symbol(library, "TTS_LoadTemplate", TTS_LoadTemplate, TTS_LOADTEMPLATE);
dynlib_symbol(library, "TTS_LoadTemplateFromString", TTS_LoadTemplateFromString, TTS_LOADTEMPLATEFROMSTRING);

ESCAPE:
if (result != 0)
Expand Down
6 changes: 6 additions & 0 deletions source/loader.hh
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ extern TTS_LOADPLUGIN TTS_LoadPlugin;
extern TTS_UNLOADPLUGIN TTS_UnloadPlugin;
extern TTS_ENUMERATEVOICE TTS_EnumerateVoices;
extern TTS_ENUMERATEENCODER TTS_EnumerateEncoders;
extern TTS_VALIDATESSML TTS_ValidateSSML;
extern TTS_PROCESSMESSAGE TTS_ProcessMessage;
extern TTS_REGISTERINTERPRETATION TTS_RegisterInterpretation;
extern TTS_UNLOADTEMPLATE TTS_UnloadTemplate;
extern TTS_LOADTEMPLATE TTS_LoadTemplate;
extern TTS_LOADTEMPLATEFROMSTRING TTS_LoadTemplateFromString;


#ifdef __cplusplus
Expand Down
2 changes: 0 additions & 2 deletions source/simpleSynthesis.cc
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "loader.hh"

#include <iostream>
#include <fstream>
#include <iomanip>
Expand Down
197 changes: 197 additions & 0 deletions source/template.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "loader.hh"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <list>
#include <sstream>


#if defined(WIN32) || defined(WIN64)
#include <fcntl.h>
#include <io.h>
char DIRECTORY_SEPARATOR = '\\';
#else
char DIRECTORY_SEPARATOR = '/';
#endif


using namespace std;


static void main_printError(
const char *function )
{
const TTS_ERROR_INFO *info = NULL;
const char *message = "(null)";
TTS_RETURN code = 0;
int subCode = 0;

TTS_RETURN result = TTS_GetLastError(&info);
if (result == TTS_OK && info->Message != NULL)
{
message = info->Message;
code = info->Code;
subCode = info->SubCode;
}

std::cerr << "Error at " << function << ": " << message << " (0x"
<< std::hex << std::setw(4) << std::setfill('0')
<< code << ":0x"
<< std::hex << std::setw(4) << std::setfill('0')
<< subCode << ')' << std::endl;

if (info != NULL) TTS_Free(info);
}


static void main_usage()
{
std::cerr << "Usage: tool_template <TTS path> <template> <message>" << std::endl;
std::cerr << std::endl;
std::cerr << " <TTS path> Path to the TTS installation directory." << std::endl;
std::cerr << " <template> Path to a file containing template text." << std::endl;
std::cerr << " <message> Path to a file containing message text." << std::endl;
exit(EXIT_FAILURE);
}



string main_loadInputFile(
const std::string &fileName)
{
string text;
ifstream input(fileName.c_str());
if (!input.good())
{
std::cout << "No '" << fileName << "' present." << std::endl;
return "";
}
else
{
string line;
while (getline(input, line))
{
text += line;
text += "\n";
}
input.close();
}

return text;
}


static void userCallback( void* context, const char *input, TTS_INTERPRET_OUTPUT_CALLBACK *output, void *data )
{
string out = input;
out += " esse texto";
output(context, out.c_str());
}


int main( int argc, char **argv )
{
TTS_RETURN result;
char *output = NULL;

if (argc < 4)
main_usage();

// very simple way to generate the CPqD Texto Fala library file name
string productPath(argv[1]);
#if defined(WIN32) || defined(WIN64)
string libraryFile = productPath + DIRECTORY_SEPARATOR + "libcpqdtts.dll";
#else
string libraryFile = productPath + DIRECTORY_SEPARATOR + "libcpqdtts.so";
#endif


result = tts_loadLibrary(libraryFile.c_str());
if (result != TTS_OK)
{
std::cerr << "Unable to load library '" << libraryFile << "'" << std::endl;
return 1;
}

// initialize the TTS
result = TTS_Initialize(productPath.c_str(), productPath.c_str());
if (result != TTS_OK)
{
main_printError("TTS_Initialize");
exit(EXIT_FAILURE);
}

//register user callback
result = TTS_RegisterInterpretation("teste", userCallback, NULL, true);
if (result != TTS_OK)
{
main_printError("TTS_RegisterInterpretation");
exit(EXIT_FAILURE);
}

//load template
result = TTS_LoadTemplate(argv[2]);
if (result != TTS_OK)
{
main_printError("TTS_LoadTemplate");
exit(EXIT_FAILURE);
}

//load message
string message = main_loadInputFile(argv[3]);
result = TTS_ProcessMessage(message.c_str(), TEMPLATE_MESSAGE_DONT_CHECK, &output);
if (result != TTS_OK)
{
main_printError("TTS_ProcessMessage");
exit(EXIT_FAILURE);
}

stringstream fileName;
fileName << "output.txt";
std::ofstream outputFile(fileName.str().c_str());
if (outputFile.is_open())
{
outputFile << output;
outputFile.close();
}
else
{
main_printError("Error save output file");
exit(EXIT_FAILURE);
}

result = TTS_ValidateSSML(output);
if (result != TTS_OK)
{
main_printError("TTS_ValidateSSML");
exit(EXIT_FAILURE);
}

result = TTS_UnloadTemplate(argv[2]);
if (result != TTS_OK)
{
main_printError("TTS_UnloadTemplate");
exit(EXIT_FAILURE);
}

result = TTS_Free(output);
if (result != TTS_OK)
{
main_printError("TTS_Free");
exit(EXIT_FAILURE);
}

result = TTS_Terminate();
if (result != TTS_OK)
{
main_printError("TTS_Terminate");
exit(EXIT_FAILURE);
}

tts_unloadLibrary();

return 0;
}
Loading

0 comments on commit bce9389

Please sign in to comment.