
**********************************************
* Verbio dialplan applications for Asterisk. *
* Look further down for the English version  *
**********************************************


	-----------------------------------
	Aplicaciones Verbio sobre Asterisk.
	-----------------------------------

ndice
------

1. Fichero de configuracin 'verbio.conf'.
2. Descripcin de las diferentes aplicaciones.
 2.1.VerbioLoadVcb 
 2.2.VerbioUnloadVcb 
 2.3.VerbioRec 
 2.4.VerbioPrompt 
 2.5.VerbioPromptAndRec
 2.6.VerbioStreamAndRec
 2.7.VerbioLastErr
 2.8.VerbioInfo
 2.9.VerbioFreeChannel
3.Ejemplo de uso de las aplicaciones Verbio en Asterisk.
4.Carga y descarga de las aplicaciones Verbio en Asterisk.

------

Nota: si todava no ha realizado la instalacin de las aplicaciones Verbio,
es recomendable que se lea el documento INSTALL.


------------------------------------------
1 - Fichero de configuracin 'verbio.conf'
------------------------------------------

Este fichero reside en: '/etc/asterisk'

Las opciones ms importantes a configurar son:

Nota: Las opciones marcadas con '(X)', dependern de los paquetes Verbio 
instalados en la mquina donde corre el servidor de sntesis y/o reconocimiento. 

Seccin [general]
- primary_vox_server : ip de la mquina donde corre verbiod.

Seccin [tts]
- default_language   : Lenguaje por defecto del sintetizador de voz.(X) 
- default_speaker    : Locutor por defecto del sintetizador de voz. (X)
- text_prompts_path  : Ruta (por defecto) de los prompts de texto.

Si no queremos iniciar el tts, deberemos dejar 'default_language' comentado.


Seccin [asr]
- default_config     : Configuracin por defecto del reconocimiento.(X)
- default_language   : Lenguaje por defecto del reconocimiento.     (X)
- grammar_path	     : Ruta por defecto de las gramticas.

Si no queremos iniciar el asr, deberemos dejar 'default_config' comentado.


Como ejemplo, el siguiente fichero de configuracin es vlido para una 
instalacin la cual disponga, al menos, de los siguientes paquetes Verbio
instalados:

* verbio-engines  (Motores de sntesis y reconocimiento)
* verbio-clients  (Libreras de desarrollo)
* verbio-asr-es   (Reconocimiento espaol)
* verbio-tts-esao (Locutora espaola Laura)

;;;;;;;;;;;;;; verbio.conf ;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Verbio ASR and TTS engines Configuration
;
;;;;;;;;;;;;;;;;;;;;;;
;  General options   ;
;;;;;;;;;;;;;;;;;;;;;;
[general]
;
; Primary Voxserver (default: 127.0.0.1)
;
primary_vox_server 	= 127.0.0.1

;
; Backup voxserver
;
backup_vox_server 	= 127.0.0.1

;
; Network Timeout (seconds)
; default 5
;
net_timeout 		= 5

;;;;;;;;;;;;;;;;;;;;;;
; TTS Engine Options ;
;;;;;;;;;;;;;;;;;;;;;;
[tts]
;
; Default TTS language (depends on your verbio setup)
; If you do not want to load TTS, comment this option.
;
default_language 	= es ; check Verbio sdk documentation for available languages.

;
; Default TTS speaker (depends on your verbio setup)
;
default_speaker 	= laura

;
; Default path to promt files (text files that you want to be readed by Verbio TTS)
;
text_prompts_path 	=/var/lib/asterisk/verbio/text

;
; Misc options
; Delays in ms
;
init_delay		= 300
end_delay		= 20

;;;;;;;;;;;;;;;;;;;;;;
; ASR Engine Options ;
;;;;;;;;;;;;;;;;;;;;;;
[asr]
;
; Default ASR config (depends on your verbio setup)
; If you do not want to load ASR, comment this option.
;
default_config		= es ; check Verbio sdk documentation for available configs.

;
; Default ASR lang (depends on your verbio setup)
;
default_language	= es

;
; Default path to grammar files
;
grammar_path		= /var/lib/asterisk/verbio/gram

;
; Max duration of initial silence 10ms units.(300 -> 3 seconds)
; default: 300
;
init_sil		= 300

;
; Max duration of final silence 10ms units.(200 -> 2 seconds)
; default: 200
;
max_sil			= 200

;
; VAD (Voice Activity Detection) options
; min_ref: 5 (to be used in quiet rooms) - 190 (to be used in noisy rooms) 
; default: 5
;
min_ref		= 5

;
; Absolute timeout (max recognition time)
; default 30 (seconds)
;
;absolute_timeout	= 30

;;;;;;;;;;;;;;;;;;;;;;
;    Debug options   ;
;;;;;;;;;;;;;;;;;;;;;;
[debug]
;
; Global verbose mode
; Comment it to disable glogal verbose mode.
;
; Enable verbose on all Verbio applications, even if
; application's 'v' option is not set.
;
; If you are using 'res_speech_verbio', you can also set/unset
; verbosity (in your dialplan) using 'Set(SPEECH_ENGINE(verbose)=1)'
; or 'Set(SPEECH_ENGINE(verbose)=0)' 
;
;verbose		= 1

;
; Extended verbosity (verbose mode must be set)
; Comment it to disable extended verbosity
;
;extended_verbose	= 1

;
; save recorded files 
; default: 0
;
;keep_recorded_files	= 1 

;
; Path to recorded files 
; default /var/lib/asterisk/verbio/audio
;recorded_files_path	= /var/lib/asterisk/verbio/audio 

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


-----------------------------------------------
2 - Descripcin de las diferentes aplicaciones.
-----------------------------------------------

Nota: Si los parmetros marcados como opcionales se omiten, estos tomarn
los valores del fichero '/etc/asterisk/verbio.conf'.

2.1 - VerbioLoadVcb(gram_file|gram_type[|config][|lang][|options])

Descripcin:

Esta funcin carga una gramtica (sobre un puerto verbio asociado al canal 
Asterisk).

Parmetros:

gram_file	: fichero de gramtica.
gram_type   	: tipo de gramtica ((ISOLATED, CONNECTED, ABNF o BUILTIN)).
config   	: configuracin de reconocimiento (opcional).
lang   		: lenguaje a utilizar (opcional).
options   	: opciones. Las opciones disponibles son:
		- v (verbose)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)

Una vez cargada la gramtica, se establecer una variable de canal (VVCB_HANDLE)
la cual contiene el identificador de la gramtica cargada.


2.2 - VerbioUnloadVcb(vcb_handle[|config][|lang][|options])

Descripcin:

Descarga una gramtica.

Parmetros:

vcb_handle	: identificador de gramtica (-1 para descargar todas)
config   	: configuracin de reconocimiento (opcional).
lang   		: lenguaje a utilizar (opcional).
options		: opciones. Las opciones disponibles son:
		- v (verbose)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)


2.3 - VerbioRec([|config][|lang][|initsil][|maxsil][|abs_timeout][|options])

Descripcin:

Lanza el reconocimiento. Antes de hacer cualquier llamada a esta aplicacin,
deberemos haber cargado alguna gramtica con la funcin 'VerbioLoadVcb'.

Parmetros:

config   	: configuracin de reconocimiento (opcional).
lang   		: lenguaje a utilizar (opcional).
initsil		: mxima duracin de silencio de inicio (unidades de 10ms)
maxsil 		: mxima duracin de silencio final (unidades de 10ms)
abs_timeout 	: timeout absoluto de reconocimiento (segundos) (opcional)
options   	: opciones. Las opciones disponibles son:
		- b (beep antes de lanzar el reconocimiento)
		- v (verbose)
		- a (descolgar el canal)
		- d (habilitar la deteccin de dtmf)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)

Para acceder al resultado del reconocimiento, podemos consultar (desde el dialplan de Asterisk) 
las siguientes variables de canal:
 - VASR_WORDS   : Nmero de palabras reconocidas (n).
 - VASR_INDEXn  : ndice (dentro de la gramtica) de la palabra-n reconocida.
 - VASR_RESULTn : Resultado-n del reconocimiento.
 - VASR_SCOREn  : Score-n (confianza) del reconocimiento.
 - VASR_UTTERANCEn  : Utterance el resultado n.
 - VASR_WEIGHTn : Peso del resultado n dentro de la gramtica.
 - VASR_RULEn   : Regla a la que pertenece el resultado n.

Para compatibilidad con anteriores versiones:
 - VASR_INDEX  = VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

Si la deteccin de dtmf (opcin 'd') est habilitada, podemos consultar su estado con las siguientes
variables de canal:
 - VDTMF_DETECTED :TRUE (se ha detectado un tono) o FALSE (no se ha detectado tono)
 - VDTMF_RESULT   :si VDTMF_DETECTED = TRUE, VDTMF_RESULT contiene el valor de la 
					tecla pulsada -0,1,2,3,4,5,6,7,8,9,*,#...-.

	Se puede configurar el nmero mximo de dtmf a detectar y el dtmf de terminacin, 
	configurando (set) las siguientes variables del dialplan:
 
		- VERBIO_DTMF_MAXLEN
		- VERBIO_DTMF_TERMINATOR

Nota: si la opcin 'keep_recorded_files' est activada en 'verbio.conf', podemos consultar el nombre
del fichero generado (una vez la aplicacin de reconocimiento ha terminado), mediante la siguiente 
variable del dialplan: VASR_REC_FILE.


2.4 - VerbioPrompt(text_or_file[|lang][|speaker][|options])

Descripcin:

Sintetiza un texto o fichero de texto.

Parmetros:

text_or_file	: texto (o fichero - ver opciones -) a sintetizar.
lang   		: lenguaje a utilizar (opcional).
speaker   	: locutor a utilizar (opcional).
options   	: opciones. Las opciones disponibles son:
		- f (tratar el parmetro fichero_o_texto como si fuera un fichero)
		- v (verbose)
		- p (habilitar pausa/reproduccin mediante dtmf -tecla por defecto '#'.Para especificar una tecla: p0,p1,..,p*,p#. p. para qualquier tecla-)
		- s (habilitar parada del prompt mediante dtmf -tecla por defecto '#'. Para especificar una tecla: s0,s1,..,s*,s#. s. para qualquier tecla-)
		- a (descolgar el canal)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)

Si la opcin de parar el prompt ('s') est habilitada, podemos consultar su estado con las siguientes variables de canal:
 - VDTMF_DETECTED (TRUE -si el usuario ha pulsado la tecla de parada del prompt- or FALSE)
 - VDTMF_RESULT (si VDTMF_DETECTED = TRUE, contiene el valor de la tecla pulsada)


Al trabajar con la opcin 'f', los ficheros de texto a sintetizar, se buscarn en la ruta 
definida por el parmetro 'text_prompts_path', del fichero de configuracin ('/etc/asterisk/verbio.conf').
Si queremos sintetizar un fichero de texto que se encuentre en una ubicacin distinta, deberemos introducir
el path completo al fichero.

No olvidarse de escapar las comas (',') del texto que queremos sintetizar (ejemplo: "Hola\, buenas tardes.").
(Si usamos un fichero de texto -opcin 'f'- esto ltimo no aplica).


2.5 - VerbioPromptAndRec(text_or_file[|initsil][|maxsil][|tts_lang][|tts_spkr][|asr_conf][|asr_lang][|abs_timeout][|options])

Descripcin:

Lanza (al mismo tiempo) una sntesis y un reconocimiento. Dicha aplicacin permite, si la opcin
bargein est activada, que el usuario interrumpa la mquina (si durante la locucin el reconocedor
detecta que el usuario ha dicho algo, se parar la sntesis y la aplicacin terminar.
Permitindonos, as, consultar el resultado del reconocimiento efectuado)

Parmetros:

text_or_file	: texto (o fichero - ver opciones -) a sintetizar.
initsil        	: mxima duracin de silencio de inicio (unidades de 10ms) (opcional)
maxsil         	: mxima duracin de silencio final (unidades de 10ms) (opcional)
tts_lang       	: lenguaje (del sintetizador) a utilizar (opcional).
tts_spkr       	: locutor (del sintetizador) a utilizar (opcional).
asr_conf       	: configuracin de reconocimiento (opcional).
asr_lang       	: lenguaje (del reconocedor) a utilizar (opcional).
abs_timeout 	: timeout absoluto de reconocimiento (segundos) (opcional)
options		: opciones. Las opciones disponibles son:
	   	- f (tratar el parmetro fichero_o_texto como si fuera un fichero)
	   	- v (verbose)
       		- a (descolgar el canal)
		- b (beep antes de reconocer)
		- g (activar bargein. Permitir al usuario interrumpir a la mquina. Esta opcin desactivar 'b'.)
		- i (interrumpir de manera inmediata el prompt al detectar voz. Esta opcin activar 'g'.)
		- d (habilitar la deteccin de dtmf)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)

Al trabajar con la opcin 'f', los ficheros de texto a sintetizar, se buscarn en la ruta 
definida por el parmetro 'text_prompts_path' del fichero de configuracin ('/etc/asterisk/verbio.conf').
Si queremos sintetizar un fichero de texto que se encuentre en una ubicacin distinta, deberemos introducir
el path completo al fichero.

No olvidarse de escapar las comas (',') del texto que queremos sintetizar (ejemplo: "Hola\, buenas tardes.").
(Si usamos un fichero de texto -opcin 'f'- esto ltimo no aplica).

Cuando usemos bargein, hay que tener mucho cuidado al seleccionar los 
parmetros 'initsil', 'maxsil' y 'abs_timeout'.Si, por ejemplo, seleccionamos un 'initsil' 
o 'abs_timeout' demasiado pequeo, no le daremos suficiente tiempo de escucha al usuario, y 
nuestro mensaje (prompt) se ver interrumpido. 
Si no indicamos un valor para 'initsil', 'maxsil' o 'abs_timeout', se utilizarn
los valores indicados en el fichero de configuracin (verbio.conf)

Para acceder al resultado del reconocimiento, podemos consultar (desde el dialplan de Asterisk) 
las siguientes variables de canal (una vez la aplicacin 'VerbioPromptAndRec' haya terminado):
 - VASR_WORDS   : Nmero de palabras reconocidas (n).
 - VASR_INDEXn  : ndice (dentro de la gramtica) de la palabra-n reconocida.
 - VASR_RESULTn : Resultado-n del reconocimiento.
 - VASR_SCOREn  : Score-n (confianza) del reconocimiento.
 - VASR_UTTERANCEn  : Utterance el resultado n.
 - VASR_WEIGHTn : Peso del resultado n dentro de la gramtica.
 - VASR_RULEn   : Regla a la que pertenece el resultado n.

Para compatibilidad con anteriores versiones:
 - VASR_INDEX  = VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

Si la deteccin de dtmf (opcin 'd') est habilitada, podemos consultar su estado con las siguientes
variables de canal:
 - VDTMF_DETECTED :TRUE (se ha detectado un tono) o FALSE (no se ha detectado tono)
 - VDTMF_RESULT   :si VDTMF_DETECTED = TRUE, VDTMF_RESULT contiene el valor de la 
					tecla pulsada -0,1,2,3,4,5,6,7,8,9,*,#...-.

	Se puede configurar el nmero mximo de dtmf a detectar y el dtmf de terminacin, 
	configurando (set) las siguientes variables del dialplan:
 
		- VERBIO_DTMF_MAXLEN
		- VERBIO_DTMF_TERMINATOR

Nota: si la opcin 'keep_recorded_files' est activada en 'verbio.conf', podemos consultar el nombre
del fichero generado (una vez la aplicacin de reconocimiento ha terminado), mediante la siguiente 
variable del dialplan: VASR_REC_FILE.


2.6 - VerbioStreamAndRec(audio_file[|initsil][|maxsil][|asr_conf][|asr_lang][|abs_timeout][|options])

Descripcin:

Lanza (al mismo tiempo) la reproduccin de un fichero de sonido y un reconocimiento. 
Esta aplicacin, igual que la anterior, nos permite realizar 'bargein'. 

Parmetros:

audio_file  	: fichero a reproducir.
initsil     	: mxima duracin de silencio de inicio (unidades de 10ms) (opcional)
maxsil      	: mxima duracin de silencio final (unidades de 10ms) (opcional)
asr_conf    	: configuracin de reconocimiento (opcional).
asr_lang    	: lenguaje (del reconocedor) a utilizar (opcional).
abs_timeout 	: timeout absoluto de reconocimiento (segundos) (opcional)
options        	: opciones.Las opciones disponibles son:
		- v (verbose)
       		- a (descolgar el canal)
       		- b (beep antes de reconocer)
       		- g (activar bargein. Permitir al usuario interrumpir a la mquina. Esta opcin desactivar 'b'.)
		- i (interrumpir de manera inmediata el stream al detectar voz. Esta opcin activar 'g'.)
		- d (habilitar la deteccin de dtmf)
		- n (no ejecutar colgado cuando se produzca un error referente a Verbio)

Cuando usemos bargein, hay que tener mucho cuidado al seleccionar los 
parmetros 'initsil', 'maxsil' y 'abs_timeout'.Si, por ejemplo, seleccionamos un 'initsil' 
o 'abs_timeout' demasiado pequeo, no le daremos suficiente tiempo de escucha al usuario, y 
nuestro fichero a reproducir se ver interrumpido. 
Si no indicamos un valor para 'initsil', 'maxsil' o 'abs_timeout', se utilizarn
los valores indicados en el fichero de configuracin (verbio.conf)

Para acceder al resultado del reconocimiento, podemos consultar (desde el dialplan de Asterisk) 
las siguientes variables de canal (una vez la aplicacin 'VerbioPromptAndRec' haya terminado):
 - VASR_WORDS   : Nmero de palabras reconocidas (n).
 - VASR_INDEXn  : ndice (dentro de la gramtica) de la palabra-n reconocida.
 - VASR_RESULTn : Resultado-n del reconocimiento.
 - VASR_SCOREn  : Score-n (confianza) del reconocimiento.
 - VASR_UTTERANCEn  : Utterance el resultado n.
 - VASR_WEIGHTn : Peso del resultado n dentro de la gramtica.
 - VASR_RULEn   : Regla a la que pertenece el resultado n.

Para compatibilidad con anteriores versiones:
 - VASR_INDEX  = VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

Si la deteccin de dtmf (opcin 'd') est habilitada, podemos consultar su estado con las siguientes
variables de canal:
 - VDTMF_DETECTED :TRUE (se ha detectado un tono) o FALSE (no se ha detectado tono)
 - VDTMF_RESULT   :si VDTMF_DETECTED = TRUE, VDTMF_RESULT contiene el valor de la 
					tecla pulsada -0,1,2,3,4,5,6,7,8,9,*,#...-.

	Se puede configurar el nmero mximo de dtmf a detectar y el dtmf de terminacin, 
	configurando (set) las siguientes variables del dialplan:
 
		- VERBIO_DTMF_MAXLEN
		- VERBIO_DTMF_TERMINATOR

Nota: si la opcin 'keep_recorded_files' est activada en 'verbio.conf', podemos consultar el nombre
del fichero generado (una vez la aplicacin de reconocimiento ha terminado), mediante la siguiente 
variable del dialplan: VASR_REC_FILE.


2.7 - VerbioLastErr(var)

Descripcin:

Esta aplicacin permite consultar el ltimo mensaje de error referente a las 
funciones Verbio.

Parmetros

var: variable de canal donde guardaremos el mensaje de error.

Las aplicaciones Verbio debern ser ejecutadas con la opcin 'n' (para evitar,
cuando se produzca un error por parte de las funciones de Verbio, el cuelgue de la llamada).

Cdigos de error:

EVX_NOERROR	NO ERROR 
EVX_INVSETUP	Vox ERROR (Files may be corrupted. Check disk and repeat Vox Setup) 
EVX_NOMEM	OUT OF MEMORY. (Check memory leakages) 
EVX_VCBFILE	THE VOCABULARY FILE NAME IS NOT VALID. (Check the vocabulary file name and path writing permission) 
EVX_INVWORD	THE VOCABULARY CONTAINS AN INVALID WORD. (Check and correct invalid words) 
EVX_NOLICFILE	NO LICENSE FILE WAS FOUND. (Use Setup and CheckOut to obtain the Vox directory structure and the license file) 
EVX_INVLIC	THE LICENSE FILE IS NOT VALID. (Use CheckOut to obtain a valid license file) 
EVX_SYSTEM	SYSTEM ERROR (Check errno) 
EVX_NOLIBINIT	VOXLIB WAS NOT SUCCESSFULLY LOADED. (Call vox_libinit() before using any Vox function) 
EVX_NOLIC	NO LICENSE 
EVX_NOSETVCB	NO ACTIVE VOCABULARY. (Use vox_setvcb() to set the active vocabulary) 
EVX_NORECSTR	NO RECOGNITION. (Use vox_recstr() to init recognition) 
EVX_NOLINE	NO MORE LINES ARE AVAILABLE FOR THE SPECIFIED CHANNEL DEVICE 
EVX_BADPARM	INVALID PARAMETER IN FUNCTION CALL 
EVX_NOTIMP	NOT IMPLEMENTED 
EVX_NORECIND	NO RECIND OR NBEST. (Call vox_recind() before calling ATVOX_NIND()) 
EVX_INVFILE	INVALID FILENAME 
EVX_NETWORK	NETWORK ERROR 
EVX_DICFILE	THE DICTIONARY FILE NAME IS NOT VALID 
EVX_PARSER	ABNF PARSER ERROR 
EVX_INVVER 	THE VOXSERVER VERSION DOES NOT MATCH THE CLIENT VERSION 
EVX_UNKNOWN	Unknown error


2.8 - VerbioInfo()

Descripcin:

Esta aplicacin imprimir informacin diversa sobre la configuracin de Verbio (locutores instalados,
configuraciones de reconocimiento instaladas, versiones, licencias, etc...).

Esta aplicacin crear las siguientes variables de canal:
	- VTTS_SPEAKERS	: locutores disponibles (formato: 'id1:name1:gender1:age1:lang1;id2:name2:gender2:age2:lang2;')
	- VASR_CONFIGS 	: configuraciones de reconocimiento disponibles.



2.9.VerbioFreeChannel

Descripcin:

Esta aplicacin liberar los recursos (licencias y memoria) del servidor Verbio para el canal actual.
Esta aplicacin deber ser ejecutada SIEMPRE, antes de terminar una llamada que haga uso de las aplicaciones
Verbio.
Esta aplicacin es equivalente a ejecutar VerbioUnloadVcb con el parmetro vcb_handle a -1.


----------------------------------------------------------
3 - Ejemplo de uso de las aplicaciones Verbio en Asterisk.
----------------------------------------------------------

Consideraciones previas:

- Previamente a la ejecucin del ejemplo, deberemos copiar el fichero de 
  gramtica 'vdemo.txt' a la carpeta '/var/lib/asterisk/verbio/gram'.

- Este ejemplo supone un fichero de configuracin verbio.conf, tal como
  el mostrado en el punto 1.

- Ntese,tambin, que los parmetros marcados como 'opcional' (en los puntos 2.x)
  se han obviado a la hora de realizar las llamadas a las aplicaciones Verbio.

    Ejemplo (con todos los parmetros):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,es,es,v)

    Ejemplo (solo con los parmetros 'obligatorios'):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated)

    Ejemplo (algunos parmetros 'obviados'):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,,,v)

-------

Ejemplo:


;[...]
exten => 802,1,Goto(VERBIO_TEST,s,1)
;[...]

;;;;;;;;;;;;;;;;;;;;;;;;
; VERBIO TEST  Context ;
;;;;;;;;;;;;;;;;;;;;;;;;
;
[VERBIO_TEST]
;
; (1) Cargar el vocabulario (vdemo.txt)
;
exten => s,1,Answer()
exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,,,v)
exten => s,n,VerbioPrompt(Establecido vocabulario ${VVCB_HANDLE}.)
; 
; Guardar el ltimo posible error de Verbio (opcional)
;
exten => s,n,VerbioLastErr(VERROR)
exten => s,n,NoOp(${VERROR})
;
; (2) Ejemplo de reconocimiento y prompt
;
exten => s,n,VerbioPromptAndRec(Hola\,indcame una entrada de la gramtica. Recuerda que\,si la opcin baryin est activada\, esta aplicacin te permite interrumpirme en cualquier momento.Gracias por llamar.,1500,100,,,,,,vg)
exten => s,n,VerbioPrompt("Palabras ${VASR_WORDS}. Resultado: ${VASR_RESULT0}. Score: ${VASR_SCORE0}",,,v)
;
; (3) Ejemplo de prompt
;
;exten => s,n,VerbioPrompt(/var/lib/asterisk/verbio/text/test.txt,,,fv)
exten => s,n,VerbioPrompt(Hola\,indcame una entrada de la gramtica.,,,v)
;
; (4) Ejemplo de reconocimiento
;
exten => s,n,VerbioRec(,,,,,vb)
exten => s,n,VerbioPrompt("Palabras ${VASR_WORDS}. Resultado: ${VASR_RESULT}. Score: ${VASR_SCORE}",,,v)
;
; (5) Descargar vocabulario establecido previamente
;
exten => s,n,VerbioUnloadVcb(${VVCB_HANDLE},,,v)
;
; (6) Liberar recursos (tanto licencias como memoria) 
;     (ATENCIN: NO OLVIDARSE DE EJECUTAR ESTA APLICACIN, SIEMPRE QUE TERMINE LA LLAMADA -HANGUP-.)
;
exten => h,1,VerbioFreeChannel()

----


------------------------------------------------------------
4 - Carga y descarga de las aplicaciones Verbio en Asterisk.
------------------------------------------------------------

Las aplicaciones Verbio se cargan y descargan automticamente al 
iniciar o parar Asterisk. Si, desde el CLI de Asterisk, queremos
cargar las aplicaciones Verbio pedemos ejecutar:

*CLI> load app_verbio_speech.so

Para la descarga de las aplicaciones Verbio podemos ejecutar:

*CLI> unload app_verbio_speech.so

Si hay algn error de configuracin/conexin se nos reportar por pantalla.

Nota: al cargar las aplicaciones Verbio (bien cuando arranca Asterisk o bien 
cuando cargamos manualmente con '(module) load app_verbio_speech.so'). Se intentar 
establecer la conexin con el servidor Verbio por lo cual, es muy importante
que tengamos el servidor de sntesis/reconocimiento arrancado.
La conexin con el servidor Verbio se mantiene abierta hasta que paremos 
Asterisk o ejecutemos '(module) unload app_verbio_speech.so'.

_______________________________________________________________________________
_______________________________________________________________________________

	----------------------------
	Verbio Asterisk applications
	----------------------------

Index
------

1. Configuration file ('verbio.conf').
2. Applications.
 2.1.VerbioLoadVcb 
 2.2.VerbioUnloadVcb 
 2.3.VerbioRec 
 2.4.VerbioPrompt 
 2.5.VerbioPromptAndRec
 2.6.VerbioStreamAndRec
 2.7.VerbioLastErr
 2.8.VerbioInfo
 2.9.VerbioFreeChannel
3.Dialplan example.
4.Loading and unloading Verbio applications

------

Note: If you have not installed Verbio applications on your Asterisk server,
you may want to read the 'INSTALL' document.


--------------------------------------
1 - Configuration file ('verbio.conf')
--------------------------------------

File location: '/etc/asterisk'

Most important options that you need to configure:

Note: Value of options marked with an '(X)', will depend on your 
Verbio voxserver's configuration.

Section [general]
- primary_vox_server : voxserver ip

Section [tts]
- default_language   : Default TTS language when executing Verbio apps.(X) 
- default_speaker    : Default TTS speaker when executing Verbio apps. (X)
- text_prompts_path  : Text prompts path (files from where to read prompts).

If we do not want to start TTS applications, we need to comment 
'default_language' option.


Seccin [asr]
- default_config     : Default recognition configuration.(X)
- default_language   : Default recognition language.     (X)
- grammar_path	     : Grammar path (grammar files storage folder).

If we do not want to start ASR applications, we need to comment
'default_config' option.

As an example, config file below matches an installation
with the following packages installed:

* verbio-engines  (ASR/TTS engines)
* verbio-clients  (Development package)
* verbio-asr-es   (Spanish ASR)
* verbio-tts-esao (Spanish speaker -Laura-)

;;;;;;;;;;;;;; verbio.conf ;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Verbio ASR and TTS engines Configuration
;
;;;;;;;;;;;;;;;;;;;;;;
;  General options   ;
;;;;;;;;;;;;;;;;;;;;;;
[general]
;
; Primary Voxserver (default: 127.0.0.1)
;
primary_vox_server 	= 127.0.0.1

;
; Backup voxserver
;
backup_vox_server 	= 127.0.0.1

;
; Network Timeout (seconds)
; default 5
;
net_timeout 		= 5

;;;;;;;;;;;;;;;;;;;;;;
; TTS Engine Options ;
;;;;;;;;;;;;;;;;;;;;;;
[tts]
;
; Default TTS language (depends on your verbio setup)
; If you do not want to load TTS, comment this option.
;
default_language 	= es ; check Verbio sdk documentation for available languages.

;
; Default TTS speaker (depends on your verbio setup)
;
default_speaker 	= laura

;
; Default path to promt files (text files that you want to be readed by Verbio TTS)
;
text_prompts_path 	=/var/lib/asterisk/verbio/text

;
; Misc options
; Delays in ms
;
init_delay		= 300
end_delay		= 20

;;;;;;;;;;;;;;;;;;;;;;
; ASR Engine Options ;
;;;;;;;;;;;;;;;;;;;;;;
[asr]
;
; Default ASR config (depends on your verbio setup)
; If you do not want to load ASR, comment this option.
;
default_config		= es ; check Verbio sdk documentation for available configs.

;
; Default ASR lang (depends on your verbio setup)
;
default_language	= es

;
; Default path to grammar files
;
grammar_path		= /var/lib/asterisk/verbio/gram

;
; Max duration of initial silence 10ms units.(300 -> 3 seconds)
; default: 300
;
init_sil		= 300

;
; Max duration of final silence 10ms units.(200 -> 2 seconds)
; default: 200
;
max_sil			= 200

;
; VAD (Voice Activity Detection) options
; min_ref: 5 (to be used in quiet rooms) - 190 (to be used in noisy rooms) 
; default: 5
;
min_ref		= 5

;
; Absolute timeout (max recognition time)
; default 30 (seconds)
;
;absolute_timeout	= 30

;;;;;;;;;;;;;;;;;;;;;;
;    Debug options   ;
;;;;;;;;;;;;;;;;;;;;;;
[debug]
;
; Global verbose mode
; Comment it to disable glogal verbose mode.
;
; Enable verbose on all Verbio applications, even if
; application's 'v' option is not set.
;
; If you are using 'res_speech_verbio', you can also set/unset
; verbosity (in your dialplan) using 'Set(SPEECH_ENGINE(verbose)=1)'
; or 'Set(SPEECH_ENGINE(verbose)=0)' 
;
;verbose		= 1

;
; Extended verbosity (verbose mode must be set)
; Comment it to disable extended verbosity
;
;extended_verbose	= 1

;
; save recorded files 
; default: 0
;
;keep_recorded_files	= 1 

;
; Path to recorded files 
; default /var/lib/asterisk/verbio/audio
;recorded_files_path	= /var/lib/asterisk/verbio/audio 

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


-----------------
2 - Applications
-----------------

Note: If optional parameters are omitted, '/etc/asterisk/verbio.conf' configured
values will be used.

2.1 - VerbioLoadVcb(gram_file|gram_type[|config][|lang][|options])

Description:

Loads a vocabulary.

Parameters:

- gram_file : grammar file
- gram_type : grammar type (ISOLATED, CONNECTED, ABNF or BUILTIN)
- config    : ASR config
- lang      : ASR language
- options   : v (verbosity on)
               n (do not hangup on Verbio error)

This function will set a channel var (VVCB_HANDLE) containing the id (vcb_handle)
of the loaded vocabulary (see VerbioUnloadVcb to see why we need this handle).


2.2 - VerbioUnloadVcb(vcb_handle[|config][|lang][|options])

Description:

Unloads a vocabulary.

Parameters:

- vcb_handle: vocabulary id to unload (-1 to unload all)
- config    : ASR config
- lang      : ASR language
- options   : v (verbosity on)
               n (do not hangup on Verbio error)

Please do not forget to execute this app on hangup...otherwise you may run out of licences.


2.3 - VerbioRec([|config][|lang][|initsil][|maxsil][|abs_timeout][|options])

Description:

Launch a recognition. Prior to run this application, we need to load a 
vocabulary (see 'VerbioLoadVcb' application).

Parameters:

- config    : ASR config
- lang      : ASR language
- initsil   : Initial silence (max duration of initial silence 10ms units)
- maxsil    : Max silence (max duration of final silence 10ms units)
- abs_timeout    : Absolute timeout (seconds)
- options   : v (verbosity on)
              b (beep before recognition)
              d (enable dtmf detection)
               n (do not hangup on Verbio error)


You /must/ execute VerbioLoadVcb app prior to Launch any recognition.

In order to check the recognition result, you need to check (once VerbioRec has finished)
the following channel vars:
 - VASR_WORDS   : Number of recognized words (n).
 - VASR_INDEXn  : Index (in grammar) of the n-word recognized.
 - VASR_RESULTn : n-Result of recognition.
 - VASR_SCOREn  : n-Score (confidence) of recognition.
 - VASR_UTTERANCEn: n-Utterance.
 - VASR_WEIGHTn : Weight of the n-result.
 - VASR_RULEn   : Rule of the n-result.

For backward compatibility:
 - VASR_INDEX  =  VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

If dtmf detection ('d' option) is enabled, the following channel vars will be set:
 - VDTMF_DETECTED (TRUE or FALSE)
 - VDTMF_RESULT (if VDTMF_DETECTED = TRUE, will contain the pressed key -0,1,2,3,4,5,6,7,8,9,*,#...-)

	You are also allowed to set DTMF max length and DTMF terminator via the following dialplan variables:
		- VERBIO_DTMF_MAXLEN"
		- VERBIO_DTMF_TERMINATOR"

Note: If 'keep_recorded_files' is enabled in 'verbio.conf', you can check the recorded file name via
      VASR_REC_FILE dialplan variable (once the recognition application has finished).



2.4 - VerbioPrompt(text_or_file[|lang][|speaker][|options])

Description:

Text to speech application (synthetises a text or a text file).

Parameters:

- text_or_file: text or file (see options) to synth
- lang        : tts language
- speaker     : tts speaker
- options     : v (verbosity on)
                f (tread text_or_file parameter as a text file to read from)
		p (enable pause/resume on dtmf -default key '#'. Use: p0,p1,..,p#,p* to specify a key, p. will enable all keys)
                s (enable stop prompt on dtmf -default key '#'. Use: s0,s1,..,s#,s* to specify a key, s. will enable all keys)
                n (do not hangup on Verbio error)

If stop prompt ('s' option) is enabled, the following channel vars will be set:
 - VDTMF_DETECTED (TRUE -if user has pressed stop key- or FALSE)
 - VDTMF_RESULT (if VDTMF_DETECTED = TRUE, will contain the pressed key)

When using option 'f', text files will be searched in 'text_prompts_path' ( defined in 
'/etc/asterisk/verbio.conf'). If we want to synth a text file placed in a different 
location, we need to specify the full path.

Remember to escape commas ',' (using a backslash - i.e "Hello\, how are you?"-) in the text that 
you want to synth. (This does not apply if you use a text file -option 'f'-)


2.5 - VerbioPromptAndRec(text_or_file[|initsil][|maxsil][|tts_lang][|tts_spkr][|asr_conf][|asr_lang][|abs_timeout][|options])

Description:

Launch synthesis and recognition (implements bargein).

Parameters:

- text_or_file: text or file (see options) to synth
- initsil     : Initial silence (max duration of initial silence 10ms units)
- maxsil      : Max silence (max duration of final silence 10ms units)
- tts_lang    : TTS language
- tts_spkr    : TTS speaker
- asr_conf    : ASR config
- asr_lang    : ASR language
- abs_timeout : Absolute timeout (seconds)
- options     : v (verbosity on)
                f (tread text_or_file parameter as a text file to read from)
                b (beep before rec -no sense when using bargein-)
                g (bargein activated, user can interrupt the system -will disable beep-)
                i (immediately stop prompt on voice detection -will enable bargein-)
                d (enable dtmf detection)
                n (do not hangup on Verbio error)

When using option 'f', text files will be searched in 'text_prompts_path' ( defined in 
'/etc/asterisk/verbio.conf'). If we want to synth a text file placed in a different 
location, we need to specify the full path.

Remember to escape commas ',' (using a backslash - i.e "Hello\, how are you?"-) in the text that 
you want to synth. (This does not apply if you use a text file -option 'f'-)

Please, when using bargein, be very carefull with initsil, maxsil and abs_timeout parameters. If you do not
properly set them you may run into problems like recognition stopping
(prior to finish) our prompt (if user does not speak).
initsil and abs_timeout must be high enough to allow the user listen our (full) prompt.

Also remember that you /must/ execute VerbioLoadVcb app prior to launch a recognition.

In order to check the recognition result, you need to check (once VerbioPromptAndRec has finished)
the following channel vars:
 - VASR_WORDS   : Number of recognized words (n).
 - VASR_INDEXn  : Index (in grammar) of the n-word recognized.
 - VASR_RESULTn : n-Result of recognition.
 - VASR_SCOREn  : n-Score (confidence) of recognition.
 - VASR_UTTERANCEn: n-Utterance.
 - VASR_WEIGHTn : Weight of the n-result.
 - VASR_RULEn   : Rule of the n-result.

For backward compatibility:
 - VASR_INDEX  =  VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

If dtmf detection ('d' option) is enabled, the following channel vars will be set:
 - VDTMF_DETECTED (TRUE or FALSE)
 - VDTMF_RESULT (if VDTMF_DETECTED = TRUE, will contain the pressed key -0,1,2,3,4,5,6,7,8,9,*,#...-)

	You are also allowed to set DTMF max length and DTMF terminator via the following dialplan variables:
		- VERBIO_DTMF_MAXLEN
		- VERBIO_DTMF_TERMINATOR

Note: If 'keep_recorded_files' is enabled in 'verbio.conf', you can check the recorded file name via
      VASR_REC_FILE dialplan variable (once the recognition application has finished).


2.6 - VerbioStreamAndRec(audio_file[|initsil][|maxsil][|asr_conf][|asr_lang][|abs_timeout][|options])

Description:

Stream (play audio file) and recognize application (implements bargein).

Parameters:

- audio_file  : Audio file to stream.
- initsil     : Initial silence (max duration of initial silence 10ms units)
- maxsil      : Max silence (max duration of final silence 10ms units)
- asr_conf    : ASR config
- asr_lang    : ASR language
- abs_timeout : Absolute timeout (seconds)
- options     : v (verbosity on)
                b (beep before rec -no sense when using bargein-)
                g (bargein activated, user can interrupt the system -will disable beep-)
                i (immediately stop stream on voice detection -will enable bargein-)
                d (enable dtmf detection)
                n (do not hangup on Verbio error)

Please, when using bargein, be very carefull with initsil, maxsil and abs_timeout parameters. If you do not
properly set them, you may run into problems like recognition stopping
(prior to finish) our audio file (if user does not speak).
initsil and abs_timeout must be high enough to allow the user to listen our (full) audio file.

Also remember that you /must/ execute VerbioLoadVcb app prior to launch a recognition.

In order to check the recognition result, you need to check (once VerbioPromptAndRec has finished)
the following channel vars:
 - VASR_WORDS   : Number of recognized words (n).
 - VASR_INDEXn  : Index (in grammar) of the n-word recognized.
 - VASR_RESULTn : n-Result of recognition.
 - VASR_SCOREn  : n-Score (confidence) of recognition.
 - VASR_UTTERANCEn: n-Utterance.
 - VASR_WEIGHTn : Weight of the n-result.
 - VASR_RULEn   : Rule of the n-result.

For backward compatibility:
 - VASR_INDEX  =  VASR_INDEX0
 - VASR_RESULT =  VASR_RESULT0
 - VASR_SCORE  =  VASR_SCORE0
 - VASR_UTTERANCE  =  VASR_UTTERANCE0
 - VASR_WEIGHT  =  VASR_WEIGHT0
 - VASR_RULE  =  VASR_RULE0

If dtmf detection ('d' option) is enabled, the following channel vars will be set:
 - VDTMF_DETECTED (TRUE or FALSE)
 - VDTMF_RESULT (if VDTMF_DETECTED = TRUE, will contain the pressed key -0,1,2,3,4,5,6,7,8,9,*,#...-)

	You are also allowed to set DTMF max length and DTMF terminator via the following dialplan variables:
		- VERBIO_DTMF_MAXLEN\n"
		- VERBIO_DTMF_TERMINATOR\n";

Note: If 'keep_recorded_files' is enabled in 'verbio.conf', you can check the recorded file name via
      VASR_REC_FILE dialplan variable (once the recognition application has finished).


2.7 - VerbioLastErr(var)

Description:

Get Verbio last error

Parameters:

- var: channel var where to store last error message.

You need to call Verbio apps using the 'n' option (in order to
disable hangup on app error).


Error codes:

EVX_NOERROR	NO ERROR 
EVX_INVSETUP	Vox ERROR (Files may be corrupted. Check disk and repeat Vox Setup) 
EVX_NOMEM	OUT OF MEMORY. (Check memory leakages) 
EVX_VCBFILE	THE VOCABULARY FILE NAME IS NOT VALID. (Check the vocabulary file name and path writing permission) 
EVX_INVWORD	THE VOCABULARY CONTAINS AN INVALID WORD. (Check and correct invalid words) 
EVX_NOLICFILE	NO LICENSE FILE WAS FOUND. (Use Setup and CheckOut to obtain the Vox directory structure and the license file) 
EVX_INVLIC	THE LICENSE FILE IS NOT VALID. (Use CheckOut to obtain a valid license file) 
EVX_SYSTEM	SYSTEM ERROR (Check errno) 
EVX_NOLIBINIT	VOXLIB WAS NOT SUCCESSFULLY LOADED. (Call vox_libinit() before using any Vox function) 
EVX_NOLIC	NO LICENSE 
EVX_NOSETVCB	NO ACTIVE VOCABULARY. (Use vox_setvcb() to set the active vocabulary) 
EVX_NORECSTR	NO RECOGNITION. (Use vox_recstr() to init recognition) 
EVX_NOLINE	NO MORE LINES ARE AVAILABLE FOR THE SPECIFIED CHANNEL DEVICE 
EVX_BADPARM	INVALID PARAMETER IN FUNCTION CALL 
EVX_NOTIMP	NOT IMPLEMENTED 
EVX_NORECIND	NO RECIND OR NBEST. (Call vox_recind() before calling ATVOX_NIND()) 
EVX_INVFILE	INVALID FILENAME 
EVX_NETWORK	NETWORK ERROR 
EVX_DICFILE	THE DICTIONARY FILE NAME IS NOT VALID 
EVX_PARSER	ABNF PARSER ERROR 
EVX_INVVER 	THE VOXSERVER VERSION DOES NOT MATCH THE CLIENT VERSION 
EVX_UNKNOWN	Unknown error


2.8 - VerbioInfo()

Description:

Print Verbio-related info.

Channel vars set by VerbioInfo:
	- VTTS_SPEAKERS	: available tts speakers (format: 'id1:name1:gender1:age1:lang1;id2:name2:gender2:age2:lang2;')
	- VASR_CONFIGS 	: available asr configurations.


2.9.VerbioFreeChannel

Description:

Free Verbio resources (memory and licences).
Please do not forget to run this application at the end of every call.

This application is equivalent to execute VerbioUnloadVcb whith vcb_handle set to -1.



--------------------
3 - Dialplan example
--------------------

Considerations:

- We need to copy 'vdemo.txt' grammar file to '/var/lib/asterisk/verbio/gram'.

- This example assumes a 'verbio.conf' like the one shown on section 1.

- Application parameters marked as [|optional] (sections 2.x) are omitted.

    Example (all parameters):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,es,es,v)

    Example (only mandatory params):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated)

    Example (some params omitted):
    exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,,,v)

-------

Example:


;[...]
exten => 802,1,Goto(VERBIO_TEST,s,1)
;[...]

;;;;;;;;;;;;;;;;;;;;;;;;
; VERBIO TEST  Context ;
;;;;;;;;;;;;;;;;;;;;;;;;
;
[VERBIO_TEST]
;
; (1) Load vocabulary
;
exten => s,1,Answer()
exten => s,n,VerbioLoadVcb(vdemo.txt,isolated,,,v)
exten => s,n,VerbioPrompt(Establecido vocabulario ${VVCB_HANDLE}.)
; 
; Get last error (optional)
;
exten => s,n,VerbioLastErr(VERROR)
exten => s,n,NoOp(${VERROR})
;
; (2) Prompt and recognize example
;
exten => s,n,VerbioPromptAndRec(Hola\,indcame una entrada de la gramtica. Recuerda que\,si la opcin baryin est activada\, esta aplicacin te permite interrumpirme en cualquier momento.Gracias por llamar.,1500,100,,,,,,vg)
exten => s,n,VerbioPrompt("Palabras ${VASR_WORDS}. Resultado: ${VASR_RESULT0}. Score: ${VASR_SCORE0}",,,v)
;
; (3) Prompt example
;
;exten => s,n,VerbioPrompt(/var/lib/asterisk/verbio/text/test.txt,,,fv)
exten => s,n,VerbioPrompt(Hola\,indcame una entrada de la gramtica.,,,v)
;
; (4) Recognize example
;
exten => s,n,VerbioRec(,,,,,vb)
exten => s,n,VerbioPrompt("Palabras ${VASR_WORDS}. Resultado: ${VASR_RESULT}. Score: ${VASR_SCORE}",,,v)
;
; (5) Unload vocabulary
;
exten => s,n,VerbioUnloadVcb(${VVCB_HANDLE},,,v)
;
; (6) Unload Vcb on hangup 
;     WARNING:DO NOT FORGET TO RUN THIS FUNCTION ON HANGUP (ON CALL TERMINATION).
;
exten => h,1,VerbioFreeChannel()

----


----------------------------------------------
4 - Loading and unloading Verbio applications.
----------------------------------------------

Verbio applications get automatically loaded on Asterisk startup.

If we want to manually load Verbio apps:

*CLI> load app_verbio_speech.so

Unload:

*CLI> unload app_verbio_speech.so

Errors will be reported to Asterisk's CLI.

Note: when loading Verbio apps (Asterisk startup / manual load) the connection
to configured voxserver ('primary_vox_server' option in 
'/etc/asterisk/verbio.conf') /must/ be available.

Voxserver connection remains opened until Verbio apps
get unloaded (keepalive messages are automatically send). 




