` | Adds a pause in speech for a specified duration. |
| `` | Indicates a paragraph break, resulting in a pause. |
| `` | Represents a sentence break, adding a pause. |
| `` | The root tag that defines the speech content. |
| `` | Specifies which voice to use for speech (e.g., male, female). |
### `speed`
The speech rate of the audio file. Allows values: from 0.5 (slowest speed rate) up to 1.5 (fastest speed rate). Note: By default, speed = 1 (normal speed).
**For Example**:
```bash cURL theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'REV-APPNAME: tts' \
--header 'speaker: hi_female' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": ["भारत मेरा देश है। मेरी कंपनी का नाम रेवेरी लैंग्वेज टेक्नोलॉजीज है।" ],
"speed": 1,
}'
```
````
### `pitch`
Speaking pitch, in the range Allows values: from -3 up tp 3. 3 indicates an increase of 3 semitones from the original pitch. -3 indicates a decrease of 3 semitones from the original pitch. Note: By default, the pitch = 0 (zero)
**For Example**:
```bash cURL
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'REV-APPNAME: tts' \
--header 'speaker: hi_female' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": ["भारत मेरा देश है। मेरी कंपनी का नाम रेवेरी लैंग्वेज टेक्नोलॉजीज है।" ],
"pitch": -3,
}'
````
### `sample_rate`
The sampling rate (in hertz) to synthesize the audio output. Refer to [Supporting Sampling Rate](/usage-guides/text-to-speech/supported-sampling-rates), to know the supporting audio sample rates. Note: By default, the sample\_rate = 22050 Hz (22.05kHz)
**For Example**:
```bash cURL theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'REV-APPNAME: tts' \
--header 'speaker: hi_female' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": ["भारत मेरा देश है। मेरी कंपनी का नाम रेवेरी लैंग्वेज टेक्नोलॉजीज है।" ],
"sample_rate": 22050,
}'
```
### `format`
The speech audio format to generate the audio file. Refer to [Supporting Audio Formats](/usage-guides/text-to-speech/supported-audio-formats), to know the supporting audio formats. Note: By default, the format = WAV
**For Example**:
```bash cURL theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'REV-APPNAME: tts' \
--header 'speaker: hi_female' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": ["भारत मेरा देश है। मेरी कंपनी का नाम रेवेरी लैंग्वेज टेक्नोलॉजीज है।" ],
"format": wav,
}'
```
# Sample Codes
Source: https://docs.reverieinc.com/usage-guides/text-to-speech/sample-code
Access Python SDK samples for generating lifelike speech using Reverie’s TTS API. Ideal for server-side TTS processing and automation.
{" "}
Explore JavaScript SDK examples to integrate real-time Text-to-Speech directly into web applications and browser-based experiences.
Find GoLang SDK samples to implement fast and scalable TTS solutions for backend systems and APIs.
# SSML Tags
Source: https://docs.reverieinc.com/usage-guides/text-to-speech/ssml-tags
## SSML Tags for Text-to-Speech Customization
SSML (Speech Synthesis Markup Language) tags allow you to customize how a text-to-speech engine generates audio.
SSML gives you precise control over speech characteristics like pauses, pitch, speed, and pronunciation, enabling natural and context-appropriate audio output.
Reverie’s TTS API supports SSML to structure text, switch voices, and customize pronunciation for various formats like dates, currencies, and units.
## Core SSML Tags
### `` and ``
The root element for any SSML document. Surround all text to be spoken with this tag.\
**Note**: The `` tag is mandatory.
Encapsulates text and other tags, specifying the voice to use via the `name` attribute. Supports multiple voices in a single request.
`` represents a Paragraph. Use the tag to add a pause between paragraphs in the text.
**Note**: By default, the API will separate the paragraphs by 800ms break.
` ` represents a Sentence. Use the tag to add a pause between lines or sentences in the text.
**Note**: By default, the API will separate the sentences within a paragraph by a 400ms break.
Recommend using the `` and `` tags to structure your requests, especially when using ``.
For `` Tag:
```xml theme={null}
This is a sentence
```
For `` Tag:
```xml theme={null}
This is an example.
यह एक उदाहरण है
```
### ``
It represents a pause in the speech. Set the length of the pause with the time attribute. Add pause of a specified duration, either in seconds or milliseconds.
`` is currently not supported within a sentence. It can only exist before or between sentences or paragraphs.
| Attribute | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------ |
| `strength` | (Optional) Strength of the pause inserted. Values: `none`, `x-weak`, `weak`, `medium`, `strong`, `x-strong`. |
| `time` | (Optional) Duration of the pause, e.g., `"1s"`, `"750ms"`. Unit must be specified. Default: `"400ms"`. |
```xml theme={null}
Fetching results
Found 3 items
```
### ``
Pronounce the specified word or phrase as a different word or phrase. Specify the pronunciation to substitute with the alias attribute.
| Attribute | Description |
| --------- | ------------------------------------------------------- |
| `alias` | The word or phrase to speak in place of the tagged text |
```xml theme={null}
www
```
### ``
The `` tag will allow you to provide instructions for how to speak a text file. The TTS engine will automatically detect many of these features, but the say-as command will enable you to mark them specifically.
Use the `` tag with the interpret-as attribute to tell the TTS how to speak certain characters, words, and numbers.
| Attribute | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `interpret-as` | Uses some available possibility values to speak the given text. In the below section, we provide you the values available interpret-as |
```xml theme={null}
www
```
#### `Cardinal`
Interprets the numerical text as a cardinal number, as in 1,2,3,4
By default, the API will understand and pronounce the numbers in Cardinal format.
**Example**: The API will interpret 1234 as One thousand two hundred and thirty-four.
```xml theme={null}
1234
```
#### `Ordinal`
This value will interpret and speak the ordinal value for the given digit within the enclosed tag.
| Value | Interpret Ordinal Value |
| ----- | ----------------------- |
| 44 | Forty-Fourth |
| 2 | Second |
```xml theme={null}
2
```
#### `Character`
This value will speak the characters in a given text within the enclosed tag.
| Value | Interpret Ordinal Value |
| ----- | -------------------------------------------- |
| HELLO | API will pronounce each character separately |
| 50WS | Five Zero W S |
```xml theme={null}
50WS
```
#### `Digits`
This value spells out the digits in a given number within the enclosed tag.
| Value | Interpret Digits |
| ----- | ------------------ |
| 44 | Four Four |
| 1234 | One Two Three Four |
```xml theme={null}
1234
```
#### `Units`
Interpret a value as a measurement. The value should be a number followed by a unit or just a unit. The units supported by the TTS API are:
| Units | Interpreted as |
| ------------------- | -------------- |
| kgs, kg | kilograms |
| gms, gm, g | grams |
| mgs, mg | milligrams |
| kms, km | kilometers |
| cms, cm | centimeters |
| mtr, m | meters |
| mm | millimeters |
| ltrs, ltr, lt, l, ℓ | liters |
| ft | feet |
| in | inches |
| lbs, lb | pounds |
| hrs, hr | hours |
| min | minutes |
| sec, s | seconds |
```xml theme={null}
5l of oil is added to your cart.
```
#### `Date`
This value will speak the enclosed tag’s date, using the format given in the associated format attribute. The format attribute is mandatory for use with the date value of interpret-as.
| | Denoted as | Digit Length |
| ----- | ---------- | ------------- |
| Date | d | 1 or 2 digits |
| Month | m | 1 or 2 digits |
| Year | y | 4 digits |
**Supported Date Formats:**
| Date Format | Interpret Date |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dmy` | **day-month-year**
Example: 10-02-1990 is read as Tenth February, Nineteen Ninety
Sample Code:
`10-2-1990` |
| `mdy` | **month-day-year**
Example: 02-10-1990 is read as Tenth February, Nineteen Ninety
Sample Code:
`2-10` |
| `dm` | **day-month**
Example: 10-2 is read as Tenth February
Sample Code:
`10-2` |
| `md` | **month-day**
Example: 02-10 is read as Tenth February
Sample Code:
`2-10` |
#### `Currency`
Use the currency parameter to control the synthesis of monetary quantities. The currency formats supported and spoken by the API is:
| Currency | Symbol | API Interpretation |
| --------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
| Rupee & Paisa | `₹, Rs., र` | Example: `₹`10.50 is read as Ten rupees fifty paise.
Sample Code: ``₹10.50`` |
| Dollars & Cents | `$` | Example: `$`10.50 is read as Ten dollars fifty cents.
Sample Code: ``\$10.50`` |
| Pounds & Pence | `£` | Example: `£`10.50 is read as Ten pounds fifty pence.
Sample Code: ``£10.50`` |
| Euros & Cents | `€` | Example: `€`10.50 is read as Ten euros fifty cents.
Sample Code: ``€10.50`` |
#### `URL`
This value is used to control the synthesis of the website address.
By default, the API will interpret the website address and speak in the right format.
The API will pronounce symbols as present in a web address.
**Example**: reverieinc.com is pronounced as reverieinc dot com
```xml theme={null}
reverieinc.com
```
### ``
The prosody element can be used to adjust the below-listed attributes for the text-to-speech output.
| Attribute | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pitch` | (optional) Changes the pitch (frequency) of the enclosed text overall.
Values:
Absolute or relative values in Hertz (Hz). e.g. 350Hz, +20Hz, -10Hz.
Relative values in semitones (st). e.g. +1st, -0.5st.
Absolute or relative values in percentage. e.g. 90%, +10%, -5%.
Labels: default, x-low, low, medium, high, x-high. |
| `rate` | (optional) Changes the rate of speaking of the enclosed text overall.
Values:
Number as a factor. 1.0 being default. e.g. 0.75, 1.2.
Absolute or relative values in percentage. e.g. 90%, +20%, -10%.
Labels: default, x-slow, slow, medium, fast, x-fast. |
| `duration` | (optional) Elapsed time of the enclosed text overall. overrides rate.
Values:
Number with unit (seconds or milliseconds). e.g. 2.5s, 3500ms. |
| `volume` | (optional) Changes the loudness of the enclosed text overall.
Values:
Absolute or relative number, 100 being default. e.g. 80, 120, +5, -10.
Absolute or relative values in percentage. e.g. 90%, +20%, -10%.
Relative values in decibels (dB). e.g. +6dB, -6dB.
Labels: default, silent, x-soft, soft, medium, loud, x-loud. |
| `contour` | (optional) Changes the pitch at various points as the utterance progresses.
Expressed as a space-separated array of parameter pairs. The first value denotes the location in text as a percentage. The second value denotes the desired pitch. See pitch attribute for possible value expressions.
e.g. ``
Note: This option is available for English and Hindi only. But the request will not fail if this option is used for other languages. It will just not have the intended effect. |
| `range` | (optional) Changes the range of pitch variation of the enclosed text. Range refers to the difference between min and max pitch. Refer pitch attribute for possible value expressions.
Note: This option is available for English and Hindi only. But the request will not fail if this option is used for other languages. It will just not have the intended effect. |
```xml theme={null}
```
# Supported Audio Formats
Source: https://docs.reverieinc.com/usage-guides/text-to-speech/supported-audio-formats
| Audio Format | Description |
| ------------ | -------------------- |
| **WAV** | Default audio format |
| **MP3** | |
| **FLAC** | |
| **OGG** | |
| **OPUS** | |
| **PCM** | |
# Supported Sampling Rates
Source: https://docs.reverieinc.com/usage-guides/text-to-speech/supported-sampling-rates
| Sample Rate (Hz) | Description |
| -------------------- | ------------------- |
| **8000 (8kHz)** | |
| **16000 (16kHz)** | |
| **22050 (22.05kHz)** | Default sample rate |
| **24000 (24kHz)** | |
| **44100 (44.1kHz)** | |
| **48000 (48kHz)** | |
# Speakers
Source: https://docs.reverieinc.com/usage-guides/text-to-speech/supported-speakers
| Language | Male Speaker | Female Speaker |
| -------------- | ----------------------------------------------- | ---------------------------------------- |
| Hindi | hi\_male, hi\_male\_2, hi\_male\_3, hi\_male\_4 | hi\_female, hi\_female\_2, hi\_female\_3 |
| Bengali | bn\_male, bn\_male\_2 | bn\_female, bn\_female\_2 |
| Kannada | kn\_male, kn\_male\_2 | kn\_female, kn\_female\_2 |
| Malayalam | ml\_male | ml\_female |
| Tamil | ta\_male | ta\_female |
| Telugu | te\_male, te\_male\_2 | te\_female, te\_female\_2 |
| Gujarati | gu\_male | gu\_female |
| Odia | or\_male | or\_female |
| Assamese | as\_male | as\_female |
| Marathi | mr\_male, mr\_male\_2, mr\_male\_3 | mr\_female, mr\_female\_2, mr\_female\_3 |
| Punjabi | pa\_male | pa\_female |
| Indian English | en\_male, en\_male\_2 | en\_female, en\_female\_2 |
# Getting Started
Source: https://docs.reverieinc.com/usage-guides/transliteration/getting-started
The Transliteration API is a REST API used to transliterate the content from English to Indic languages and vice-versa.
In this guide, you’ll learn how to automatically transcribe live streaming audio in real time using Reverie's SDKs, which are supported for use with the Reverie API.
Before you start, you'll need to follow the steps in the [Get your API
Credentials](/authentication) to obtain your API KEY & APP ID.
### Make your first Call
Make your first API Call using the cURL request. Add your own API Credentials where it says `` & ``
and then run the following example in a terminal or your favorite API client.
```bash theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'cnt_lang: en' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
}'
```
By default, The API will return the strings in the target language.
### SDKs
Reverie has several SDKs that can make it easier to use the API.
Follow these steps to use the SDK of your choice to make a Reverie Transliteration request.
### Install Dependencies
```bash JavaScript theme={null}
npm i @reverieit/reverie-client
```
```bash Python theme={null}
pip install reverie-sdk
```
### Transliterate Text to your preferred language
The following code shows how to convert the text to your preferred language.
```javascript JavaScript theme={null}
const ReverieClient = require("@reverieit/reverie-client");
const reverieClient = new ReverieClient({
apiKey: "YOUR-API-KEY",
appId: "YOUR-APP-ID",
});
async function transliterateText() {
const translation = await reverieClient.transliterate({
text: "Namaste",
src_lang: "en",
tgt_lang: "ta",
});
console.log(translation);
}
transliterateText();
```
```python Python theme={null}
from reverie_sdk import ReverieClient
client = ReverieClient(
api_key="MY_API_KEY",
app_id="MY_APP_ID",
)
res = client.t13n.transliteration(
data=[
"Reverie Language Technologies is located in Bengaluru ",
"The address is Jio Avana, Bellandur, Bengaluru -560102",
"The website address is www.reverieinc.com.",
],
src_lang="en",
cnt_lang="en",
tgt_lang="hi",
noOfSuggestions=2,
)
print(res)
```
```go Go theme={null}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
const (
apiURL = "https://revapi.reverieinc.com/"
apiKey = ""
appID = ""
)
type RequestBody struct {
Data []string `json:"data"`
IsBulk bool `json:"isBulk"`
IgnoreTaggedEntities bool `json:"ignoreTaggedEntities"`
}
type APIResponse struct {
ResponseList []struct {
APIStatus int `json:"apiStatus"`
InString string `json:"inString"`
OutString []string `json:"outString"`
} `json:"responseList"`
}
func main() {
text := "Reverie Language Technologies ltd website address is www.reverieinc.com"
requestBody := map[string]interface{}{
"data": []string{text},
"isBulk": false,
"ignoreTaggedEntities": false,
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatalf("Error marshaling JSON: %v", err)
}
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatalf("Error creating request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("REV-API-KEY", apiKey)
req.Header.Set("REV-APP-ID", appID)
req.Header.Set("src_lang", "en")
req.Header.Set("tgt_lang", "hi")
req.Header.Set("domain", "1")
req.Header.Set("cnt_lang", "en")
req.Header.Set("REV-APPNAME", "transliteration")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error making request: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading response body: %v", err)
}
var apiResponse APIResponse
err = json.Unmarshal(body, &apiResponse)
if err != nil {
log.Fatalf("Error unmarshaling response: %v", err)
}
if len(apiResponse.ResponseList) > 0 && len(apiResponse.ResponseList[0].OutString) > 0 {
fmt.Println("Transliterated text:", apiResponse.ResponseList[0].OutString[0])
} else {
fmt.Println("No response from API")
}
}
```
### Results
In order to see the results from Reverie, you must run the application. Run your application from the terminal. Your transcripts will appear in your shell.
```bash JavaScript theme={null}
# Run your application using the file you created in the previous step
# Example:
npm start
```
```python Python theme={null}
# Run your application using the file you created in the previous step
# Example:
python main.py
```
```go GoLang theme={null}
// Run your application using the file you created in the previous step
// Example:
go run main.go
```
### Analyzing the Response
The API returns a `responseList`, which is an array containing the transliterated content. Each item includes the `inString`, representing the original text in the source script, and the corresponding `outString`, which is the result of converting that text into the target script. Additionally, the response includes an `api_status` field, where a value of `2` indicates a successful transaction.
# Key Features
Source: https://docs.reverieinc.com/usage-guides/transliteration/key-features
### `domain`
The Domain refers to the universe in which you use the Transliteration API. Example- Health Care, Insurance, Legal, etc. Refer to [Supporting Domain](/usage-guides/transliteration/supported-domains) to see the available domains.
**For Example**:
```bash generic theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'cnt_lang: en' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
}'
```
```bash bfsi theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 6' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
}'
```
### `cnt_lang`
The language of the words in the input text. Example -“data”: “Singh Sahab aap Kahan the.” In the example above, the Hindi language words are written in the English language script (Roman Script). So cnt\_lang = “hi” This is an optional parameter. If no value is provided, by default the value is the same as src\_lang.
**For Example**:
```bash cnt_lang = en theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'cnt_lang: en' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
}'
```
### `isBulk`
Specify whether the API should initially search in the Exception DB to transliterate the input text. Note: By default, the isBulk= true and will not search in the Exception DB.
**For Example**:
```bash isBulk = true theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
"isBulk" :true,
}'
```
```bash isBulk = false theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Reverie Language Technologies ltd website address is www.reverieinc.com"],
"isBulk" :false,
}'
```
### `noOfSuggestions`
Mention the number of transliteration suggestions the API should return for the input text. Note: By default, the noOfSuggestions = 1, means the API will return only one transliteration suggestion for the input string.
**For Example**:
```bash noOfSuggestions = 1 theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Rama"],
"noOfSuggestions" :1,
}'
```
```bash noOfSuggestions = 2 theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Rama"],
"noOfSuggestions" :2,
}'
```
**Response**
```json noOfSuggestions = 1 theme={null}
{
"responseList": [
{
"inString": "Rama",
"outString": [
"रामा"
],
"status": 2
}
]
}
```
```json noOfSuggestions = 2 theme={null}
{
"responseList": [
{
"inString": "Rama",
"outString": [
"रामा",
"रमा"
],
"status": 2
}
]
}
```
### `abbreviate`
The abbreviate will Validate whether any Abbreviations/ Acronyms are passed in the input text and will transliterate it accurately. Note - By default, the abbreviate = true. Note - if the value is false, the API will consider the abbreviation as a word and transliterate it to the nearest available word. Note - In the input text, pass the abbreviations in upper case.
**For Example**:
```bash abbreviate = true theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Rama"],
"abbreviate" :true,
}'
```
```bash abbreviate = false theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Rama"],
"abbreviate" :false,
}'
```
### `convertNumber`
Specify whether to convert the numbers in the input text to the target language script based on the value type.
* Three types of values for this parameter:
* local: This value can convert the input number to the target language script.\
Example:
| Source String | Target String |
| ------------- | ------------- |
| 2020.04 | २०२०.०४ |
* words: This value can convert numbers into words with respect to the target language.\
Example:
| Source String | Target String |
| ------------- | ------------- |
| 505 | पांच सौ पांच |
* roman: This value can convert Roman numbers to English numbers.\
Example:
* If the user types `sector V` in English, the transliteration would be `सेक्टर 5` in Hindi.
* `Block II` will be transliterated as `ब्लॉक 2`.
**For Example**:
```bash convertNumber = local theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["2020.04"],
"convertNumber" : "local",
}'
```
```bash convertNumber = words theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["505"],
"convertNumber" : "words",
}'
```
```bash convertNumber = roman theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["sector V"],
"convertNumber" : "roman",
}'
```
**Response**
```json convertNumber = local theme={null}
{
"responseList": [
{
"inString": "2020.04",
"outString": [
"२०२०.०४"
],
"status": 2
}
]
}
```
```json convertNumber = words theme={null}
{
"responseList": [
{
"inString": "505",
"outString": [
"पांच सौ पांच"
],
"status": 2
}
]
}
```
```json convertNumber = roman theme={null}
{
"responseList": [
{
"inString": "sector V",
"outString": [
"सेक्टर 5"
],
"status": 2
}
]
}
```
### `ignoreTaggedEntities`
Specify whether you want to retain the entities like email ID and URL in the input script. Note: By default, the ignoreTaggedEntities = true and will transliterate the email ID and URL into the target language script.
**For Example**:
```bash ignoreTaggedEntities = true theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Check product details in www.reverieinc.com"],
"ignoreTaggedEntities" :true,
}'
```
```bash ignoreTaggedEntities = false theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["Check product details in www.reverieinc.com"],
"ignoreTaggedEntities" :false,
}'
```
**Response**
```json ignoreTaggedEntities = true theme={null}
{
"responseList": [
{
"inString": "Check product details in www.reverieinc.com",
"outString": [
"चेक प्रोडक्ट डिटेल्स इन डब्ल्युडब्ल्युडब्ल्यु.रेवरीइंक.कॉम"
],
"status": 2
}
]
}
```
```json ignoreTaggedEntities = false theme={null}
{
"responseList": [
{
"inString": "Check product details in www.reverieinc.com",
"outString": [
"चेक प्रोडक्ट डिटेल्स इन www.reverieinc.com"
],
"status": 2
}
]
}
```
### `convertOrdinal`
This is used for transliterating ordinal values to English numbers. Note - Default value = False
**For Example**:
```bash convertOrdinal = true theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["15th Main"],
"convertOrdinal" :true,
}'
```
```bash convertOrdinal = false theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["15th Main"],
"convertOrdinal" :false,
}'
```
**Response**
```json convertOrdinal = true theme={null}
{
"responseList": [
{
"inString": "15th Main",
"outString": [
"15 मेन"
],
"status": 2
}
]
}
```
```json convertOrdinal = false theme={null}
{
"responseList": [
{
"inString": "15th Main",
"outString": [
"फिफ्टीन्थ मेन"
],
"status": 2
}
]
}
```
### `abbreviationWithoutDot`
This is used to produce the abbreviation output without a dot. Note - Default value = False
**For Example**:
```bash abbreviationWithoutDot = true theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["SMS"],
"abbreviationWithoutDot" :true,
}'
```
```bash abbreviationWithoutDot = false theme={null}
curl --location --request POST 'https://revapi.reverieinc.com/' \
--header 'Content-Type: application/json' \
--header 'REV-API-KEY: ' \
--header 'REV-APP-ID: ' \
--header 'src_lang: en' \
--header 'tgt_lang: hi' \
--header 'domain: 1' \
--header 'REV-APPNAME: transliteration' \
--data-raw '{"data": ["SMS"],
"abbreviationWithoutDot" :false,
}'
```
**Response**
```json abbreviationWithoutDot = true theme={null}
{
"responseList": [
{
"inString": "SMS",
"outString": [
"एसएमएस"
],
"status": 2
}
]
}
```
```json abbreviationWithoutDot = false theme={null}
{
"responseList": [
{
"inString": "SMS",
"outString": [
"एस.एम.एस."
],
"status": 2
}
]
}
```
# Sample Codes
Source: https://docs.reverieinc.com/usage-guides/transliteration/sample-code
Access Python SDK samples for seamless content transliteration using Reverie’s Transliteration API. Ideal for server-side script conversion.
Explore JavaScript SDK examples to integrate real-time transliteration into web applications and browser-based experiences.
Find GoLang SDK samples for fast, scalable transliteration solutions in backend systems and APIs.
# Supported Domains
Source: https://docs.reverieinc.com/usage-guides/transliteration/supported-domains
| Domain ID | Description |
| --------- | --------------------------------------------------------------------------- |
| 1 | Transliterates generic content regardless of specific domain. |
| 2 | Transliterates people’s names and surnames. |
| 9 | Transliterates location details like street name, city name, state, etc. |
| 4 | Transliterates source content from English script to Indic language script. |
| 6 | Transliterates banking and financial terminologies accurately. |
| 7 | Transliterates brand and product catalog in the ecommerce domain. |
| 22,26 | Transliterates food and grocery items like menus, packaged food, and more. |
| 25 | Transliterates song lyrics, movie titles, artist names, and media content. |
# Supported Languages
Source: https://docs.reverieinc.com/usage-guides/transliteration/supported-languages
| Language | Language Code |
| --------- | ------------- |
| Hindi | hi |
| Assamese | as |
| Bengali | bn |
| Gujarati | gu |
| Kannada | kn |
| Malayalam | ml |
| Marathi | mr |
| Odia | or |
| Punjabi | pa |
| Tamil | ta |
| Telugu | te |
| English | en |
| Urdu | ur |
| Sindhi | sd |
| Dogri | doi |
| Nepali | ne |
| Konkani | kon |
| Bodo | brx |
| Kashmiri | ks |
| Maithili | mai |
| Manipuri | mni |
| Sanskrit | sa |
| Santhali | sat |
# Call Center Transcription
Source: https://docs.reverieinc.com/use-cases/call-center-transcription
This project demonstrates how to leverage the Reverie SDK to process and transcribe audio data from call center interactions using Automatic Speech Recognition (ASR). The overall flow of the code is designed to interact with Reverie's API to perform a variety of tasks related to speech-to-text conversion, including:
### Install Dependencies
```bash Python theme={null}
pip install pyaudio
pip install reverie-sdk
pip install python-dotenv
```
### How does it Works?
1. **Environment Setup**:
All sensitive credentials, such as API keys and application IDs, are securely loaded from environment variables. This ensures that sensitive information is not hardcoded into the script, promoting security and flexibility.
```python Python theme={null}
import os
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
```
2. **Client Initialization**:
A ReverieClient is initialized with the necessary credentials to interact with Reverie's ASR services. The client is the primary interface through which the transcription and other API services are accessed.
```python Python theme={null}
from reverie_sdk import ReverieClient
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
```
3. **Audio Processing and Transcription**:
The project is designed to handle various audio formats, processing them through Reverie’s ASR system. This includes batch processing for handling multiple files, real-time transcription, or other speech-to-text functionalities.
```python Python theme={null}
client.asr.stt_batch(
"en",
open("/home/rohnak.agarwal/Documents/sdk_sample/sample.en.rev.wav", "rb").read(),
)
```
4. **Result Management**:
After transcribing the audio, the system outputs the transcription results. These results can then be stored, analyzed, or used for further processing depending on the use case (e.g., customer service analysis, data extraction, etc.).
```python Python theme={null}
for res in client.asr.stt_batch(
"en",
open("/home/rohnak.agarwal/Documents/sdk_sample/sample.en.rev.wav", "rb").read(),
):
print(res)
```
### Sample Code
```python Python theme={null}
import os
from reverie_sdk import ReverieClient
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
for res in client.asr.stt_batch(
"en",
open("/home/rohnak.agarwal/Documents/sdk_sample/sample.en.rev.wav", "rb").read(),
):
print(res)
```
# Speech To Speech
Source: https://docs.reverieinc.com/use-cases/speech-to-speech
This Python script demonstrates a real-time Speech-to-Speech (STS) translation system using the Reverie SDK. The script captures speech from the microphone, transcribes it into text, translates it into a target language, and finally converts the translated text back into speech, which is then played back to the user.
### Install Dependencies
```bash Python theme={null}
pip install pyaudio
pip install reverie-sdk
pip install python-dotenv
pip install pydub
```
### How does it Works?
The main steps involved in the script are as follows:
1. **Environment Setup**:
The script loads essential API credentials (REVERIE\_APP\_ID and REVERIE\_API\_KEY) from environment variables using the dotenv package. These credentials are required to authenticate with the Reverie API.
```python Python theme={null}
import os
import dotenv
from reverie_sdk import ReverieClient
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
```
2. **Real-Time Audio Capture**:
The script uses pyaudio to capture real-time audio input from the microphone. This audio is then streamed asynchronously to the Reverie ASR (Automatic Speech Recognition) service for transcription into text.
```python Python theme={null}
import pyaudio
import asyncio
from reverie_sdk.services.asr import AudioStream
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
```
3. **Speech-to-Text (STT) Conversion**:
The captured audio is processed and transcribed using Reverie’s ASR service. The transcription occurs in real-time, providing immediate feedback as the speech is converted into text.
```python Python theme={null}
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
```
4. **Translation**:
Once the transcription is complete, the text is sent to Reverie’s NMT (Neural Machine Translation) service to be translated from the source language (e.g., Hindi) to a target language (e.g., English). The translated text is returned for further processing.
```python Python theme={null}
src_lang = "hi"
tgt_lang = "en"
resp: str = asyncio.run(speech_to_text(src_lang))
if len(resp.strip()) > 0:
tgt_resp = (
client.nmt.localization(
[resp],
src_lang=src_lang,
tgt_lang=tgt_lang,
enableTransliteration=False,
enableNmt=True,
)
.responseList[0]
.outString
)
print(tgt_resp)
```
5. **Text-to-Speech (TTS) Conversion**:
The translated text is then sent to Reverie’s TTS (Text-to-Speech) service to convert it into speech. The generated audio is played back to the user, providing a seamless speech-to-speech translation experience.
```python Python theme={null}
tts_resp = client.tts.tts(
f"{tgt_lang}_female",
tgt_resp,
)
print(tts_resp)
```
6. **Optional Audio Saving**:
The generated speech audio can optionally be saved to a file (e.g., .wav) for later use or playback.
```python Python theme={null}
tts_resp.save_audio("./sample.wav", overwrite_existing=True)
```
7. **Audio Playback**:
Using the pydub library, the resulting audio is played back in real-time to the user, completing the cycle of speech-to-text, translation, and speech-to-speech output.
```python Python theme={null}
from pydub import AudioSegment, playback
import io
playback.play(AudioSegment.from_file(io.BytesIO(tts_resp.audio_bytes), format="wav"))
```
8. **Error Handling**:
The script includes error handling to manage potential issues during the microphone capture, transcription, translation, and speech synthesis processes.
```python Python theme={null}
import traceback
try:
# [Audio streaming, transcription, translation, and TTS code]
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
```
### Sample Code
```python Python theme={null}
import asyncio
import io
import os
import traceback
import pyaudio
from pydub import AudioSegment, playback
from reverie_sdk import ReverieClient
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
async def speech_to_text(source_lang):
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
print("Listening at STT..")
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
try:
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
src_lang = "hi"
tgt_lang = "en"
resp: str = asyncio.run(speech_to_text(src_lang))
if len(resp.strip()) > 0:
tgt_resp = (
client.nmt.localization(
[resp],
src_lang=src_lang,
tgt_lang=tgt_lang,
enableTransliteration=False,
enableNmt=True,
)
.responseList[0]
.outString
)
print(tgt_resp)
tts_resp = client.tts.tts(
f"{tgt_lang}_female",
tgt_resp,
)
print(tts_resp)
# optional: save the audio
# tts_resp.save_audio("./sample.wav", overwrite_existing=True)
playback.play(AudioSegment.from_file(io.BytesIO(tts_resp.audio_bytes), format="wav"))
```
# Speech Translation
Source: https://docs.reverieinc.com/use-cases/speech-translation
This script demonstrates the integration of real-time Speech-to-Text (STT) and Machine Translation (NMT) using the Reverie SDK. It captures audio input from a microphone, converts the speech into text using the Reverie ASR service, and then translates the transcribed text into a target language using Reverie NMT.
### Install Dependencies
```bash Python theme={null}
pip install pyaudio
pip install reverie-sdk
pip install python-dotenv
```
### How does it Works?
The script follows these main steps:
1. **Environment Setup**:
The script loads the required credentials (REVERIE\_APP\_ID and REVERIE\_API\_KEY) from environment variables using the dotenv library. These credentials are essential for authenticating API requests to the Reverie SDK.
```python Python theme={null}
import os
import dotenv
from reverie_sdk import ReverieClient
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
```
2. **Real-Time Audio Streaming**:
The script uses pyaudio to capture audio from the microphone in real-time. The captured audio is sent to the Reverie ASR service for continuous transcription via the AudioStream object. The audio data is streamed asynchronously, providing live transcription results.
```python Python theme={null}
import pyaudio
import asyncio
from reverie_sdk.services.asr import AudioStream
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
```
3. **Speech-to-Text (STT) Conversion**:
The captured audio is processed by the Reverie ASR service, which transcribes the spoken words into text. The transcription happens in real-time, and each segment of the transcribed text is displayed as it is received.
```python Python theme={null}
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
```
4. **Callback Function for ASR Results**:
A callback function is used to handle the ASR responses. Once the transcription is finalized, the transcribed text is returned and printed.
```python Python theme={null}
from reverie_sdk.services.asr import ReverieAsrResult
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
```
5. **Text Translation**:
After obtaining the transcribed text, the script sends it to the Reverie NMT service for translation into the specified target language (e.g., from Hindi to English in this case). The translation result is then printed.
```python Python theme={null}
src_lang = "hi"
tgt_lang = "en"
resp: str = asyncio.run(speech_to_text(src_lang))
if len(resp.strip()) > 0:
tgt_resp = (
client.nmt.localization(
[resp],
src_lang=src_lang,
tgt_lang=tgt_lang,
enableTransliteration=False,
enableNmt=True,
)
.responseList[0]
.outString
)
print(tgt_resp)
```
6. **Error Handling**:
Comprehensive error handling is included to ensure smooth operation, including managing microphone input errors and any potential issues during the transcription or translation processes.
```python Python theme={null}
import traceback
try:
# [Audio streaming and transcription code]
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
```
### Sample Code
```python Python theme={null}
import asyncio
import os
import traceback
import pyaudio
from reverie_sdk import ReverieClient
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
async def speech_to_text(source_lang):
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
print("Listening at STT..")
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
try:
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
src_lang = "hi"
tgt_lang = "en"
resp: str = asyncio.run(speech_to_text(src_lang))
if len(resp.strip()) > 0:
tgt_resp = (
client.nmt.localization(
[resp],
src_lang=src_lang,
tgt_lang=tgt_lang,
enableTransliteration=False,
enableNmt=True,
)
.responseList[0]
.outString
)
print(tgt_resp)
```
# Voice Agent
Source: https://docs.reverieinc.com/use-cases/voice-agent
This Python script demonstrates how to capture real-time audio from a microphone and convert it into text using the Reverie SDK's Speech-to-Text (STT) service. The process is asynchronous and handles audio streaming efficiently to provide real-time transcription.
### Install Dependencies
```bash Python theme={null}
pip install pyaudio
pip install reverie-sdk
pip install python-dotenv
```
### How does it Works?
The main steps involved in the script are as follows:
1. **Environment Configuration**:
The script loads API credentials (REVERIE\_APP\_ID and REVERIE\_API\_KEY) from environment variables using the dotenv package. These credentials are essential for interacting with the Reverie SDK's ASR (Automatic Speech Recognition) service.
```python Python theme={null}
import os
import dotenv
from reverie_sdk import ReverieClient
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
```
2. **Real-Time Audio Capture**:
The script uses the pyaudio library to stream audio from the user's microphone in real-time. The audio is captured in 16kHz, mono format (16-bit signed integer), and streamed asynchronously to Reverie's ASR service for transcription.
```python Python theme={null}
import pyaudio
import asyncio
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
```
3. **Speech-to-Text (STT) Conversion**:
The captured audio is sent in small chunks to the Reverie ASR system, which transcribes the speech into text. The transcription is processed as it is received, with results updated in real-time.
```python Python theme={null}
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
```
4. **Asynchronous Processing**:
An asynchronous function handles the audio streaming and transcription. A callback function is used to manage the incoming transcription results, which are accumulated and processed until a final transcription result is achieved.
```python Python theme={null}
async def speech_to_text(source_lang):
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
```
5. **Error Handling**:
The script includes robust error handling to manage any issues that may arise during the microphone input, audio streaming, or ASR transcription process.
```python Python theme={null}
import traceback
try:
# [Audio streaming and transcription code]
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
```
6. **Output**:
Once the transcription is complete, the final text is printed out. The transcription happens in the source language (Hindi in this example), and it’s ready for further processing or translation if needed.
### Sample Code
```python Python theme={null}
import asyncio
import os
import traceback
import pyaudio
from reverie_sdk import ReverieClient
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
async def speech_to_text(source_lang):
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
print("Listening at STT..")
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
try:
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
asyncio.run(speech_to_text("hi"))
```
# Voice Search
Source: https://docs.reverieinc.com/use-cases/voice-search
This Python script demonstrates how to implement a real-time voice search system using Reverie SDK’s Speech-to-Text (STT) service. The script captures audio input from the microphone, transcribes it into text, and processes the text for further use (such as conducting a search query, triggering actions, or further processing).
### Install Dependencies
```bash Python theme={null}
pip install pyaudio
pip install reverie-sdk
pip install python-dotenv
```
### How does it Works?
The main steps involved in the script are as follows:
1. **Environment Configuration**:
The script loads essential credentials (REVERIE\_APP\_ID and REVERIE\_API\_KEY) from environment variables using the dotenv package. These credentials are required for accessing the Reverie SDK and its services.
```python Python theme={null}
import os
import dotenv
from reverie_sdk import ReverieClient
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
```
2. **Real-Time Audio Capture:**:
The script uses the pyaudio library to stream audio data from the microphone. The audio is captured in real-time, with the system processing 16kHz, mono audio in 16-bit signed integer format.
```python Python theme={null}
import pyaudio
import asyncio
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
```
3. **Speech-to-Text (STT) Conversion**:
The audio data is continuously streamed and sent to Reverie's Automatic Speech Recognition (ASR) service for transcription. The system listens for spoken words and converts them into text in the specified source language (in this case, English).
```python Python theme={null}
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
domain="voice_search",
)
```
4. **Voice Search Use Case:**:
The stt\_stream\_async method is used with the "voice\_search" domain. This allows the system to process and transcribe speech, making it ideal for voice search applications where users speak their search queries, and the system translates those queries into text for further action.
```python Python theme={null}
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
domain="voice_search",
)
```
5. **Real-Time Transcription:**:
The transcription occurs in real-time, with each segment of speech being converted into text and displayed immediately. Once the system recognizes a complete, final transcription, the result is returned and printed.
```python Python theme={null}
async def speech_to_text(source_lang):
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
```
6. **Error Handling:**:
The script includes error handling to manage potential issues during the audio capture, streaming, and transcription process, ensuring the system continues functioning smoothly in case of interruptions.
```
import traceback
try:
# [Audio streaming and transcription code]
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
```
7. **Output**:
The final transcribed text is printed to the console, which could then be used for various purposes, such as initiating a search query, performing a task, or further processing based on the transcription result.
### Sample Code
```python Python theme={null}
import asyncio
import os
import traceback
import pyaudio
from reverie_sdk import ReverieClient
from reverie_sdk.services.asr import ReverieAsrResult, AudioStream
import dotenv
dotenv.load_dotenv("../.env")
REVERIE_APP_ID = os.environ.get("REVERIE_APP_ID")
REVERIE_API_KEY = os.environ.get("REVERIE_API_KEY")
client = ReverieClient(
api_key=REVERIE_API_KEY,
app_id=REVERIE_APP_ID,
)
async def speech_to_text(source_lang):
stream = AudioStream()
pa = pyaudio.PyAudio()
def mic_callback(in_data, frame_count, time_info, status):
try:
asyncio.run(stream.add_chunk_async(in_data))
except Exception as e:
print(f"Error in mic callback: {e}")
return (None, pyaudio.paAbort)
return (None, pyaudio.paContinue)
pa_stream = pa.open(
rate=16000,
channels=1,
format=pyaudio.paInt16,
frames_per_buffer=1024,
input=True,
stream_callback=mic_callback,
)
pa_stream.start_stream()
print("Listening at STT..")
asr_responses: list[ReverieAsrResult] = []
def asr_callback(resp: ReverieAsrResult):
print(resp)
asr_responses.append(resp)
try:
await client.asr.stt_stream_async(
src_lang=source_lang,
bytes_or_stream=stream,
callback=asr_callback,
format="16k_int16",
punctuate="true",
domain="voice_search",
)
while True:
if len(asr_responses) == 0:
continue
if asr_responses[-1].final:
print(asr_responses[-1].display_text)
return asr_responses[-1].display_text
except Exception as err:
print(f"Error in Speech-to-Text: {err}")
traceback.print_exc()
finally:
pa_stream.stop_stream()
pa_stream.close()
asyncio.run(speech_to_text("en"))
```