5 |
6 |
7 |
8 |
9 |
11 |
15 |
16 |
25 | Text to Speech
26 |
27 |
28 |
29 |
30 |
31 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | # Copy this file to .env and replace the credentials with
2 | # your own before starting the app.
3 |
4 | #----------------------------------------------------------
5 | # IBM Cloud
6 | #
7 | # If your services are running on IBM Cloud,
8 | # uncomment and configure these.
9 | # Remove or comment out the IBM Cloud Pak for Data sections.
10 | #----------------------------------------------------------
11 |
12 | # TEXT_TO_SPEECH_AUTH_TYPE=iam
13 | # TEXT_TO_SPEECH_APIKEY=
14 | # TEXT_TO_SPEECH_URL=
15 |
16 | #----------------------------------------------------------
17 | # IBM Cloud Pak for Data (username and password)
18 | #
19 | # If your services are running on IBM Cloud Pak for Data,
20 | # uncomment and configure these.
21 | # Remove or comment out the IBM Cloud section.
22 | #----------------------------------------------------------
23 |
24 | # TEXT_TO_SPEECH_AUTH_TYPE=cp4d
25 | # TEXT_TO_SPEECH_URL=https://{cpd_cluster_host}{:port}/text-to-speech/{release}/instances/{instance_id}/api
26 | # TEXT_TO_SPEECH_AUTH_URL=https://{cpd_cluster_host}{:port}
27 | # TEXT_TO_SPEECH_USERNAME=
28 | # TEXT_TO_SPEECH_PASSWORD=
29 | # # If you use a self-signed certificate, you need to disable SSL verification.
30 | # # This is not secure and not recommended.
31 | # TEXT_TO_SPEECH_DISABLE_SSL=true
32 | # TEXT_TO_SPEECH_AUTH_DISABLE_SSL=true
33 |
34 |
35 | # # Optional: Instead of the above IBM Cloud Pak for Data credentials...
36 | # # For testing and development, you can use the bearer token that's displayed
37 | # # in the IBM Cloud Pak for Data web client. To find this token, view the
38 | # # details for the provisioned service instance. The details also include the
39 | # # service endpoint URL. Only disable SSL if necessary (insecure).
40 | # # Don't use this token in production because it does not expire.
41 | # #
42 | # TEXT_TO_SPEECH_AUTH_TYPE=bearertoken
43 | # TEXT_TO_SPEECH_BEARER_TOKEN=
44 | # TEXT_TO_SPEECH_URL=
45 | # # TEXT_TO_SPEECH_DISABLE_SSL=true
--------------------------------------------------------------------------------
/src/components/ServiceContainer/ServiceContainer.js:
--------------------------------------------------------------------------------
1 | import React, { useRef, useState } from 'react';
2 | import ControlContainer from '../ControlContainer';
3 | import OutputContainer from '../OutputContainer';
4 | import Toast from '../Toast';
5 | import { createError } from '../../utils';
6 | import { canPlayAudioFormat, getSearchParams } from './utils';
7 |
8 | const SYNTHESIZE_ERROR_TITLE = 'Text synthesis error';
9 | const GDPR_DISCLAIMER =
10 | 'This system is for demonstration purposes only and is not intended to process Personal Data. No Personal Data is to be entered into this system as it may not have the necessary controls in place to meet the requirements of the General Data Protection Regulation (EU) 2016/679.';
11 |
12 | export const ServiceContainer = () => {
13 | const [error, setError] = useState();
14 | let audioElementRef = useRef(null);
15 |
16 | const getSynthesizeUrl = (text, voice) => {
17 | const params = getSearchParams();
18 |
19 | params.set('text', text);
20 | params.set('voice', voice.id);
21 |
22 | let accept;
23 | if (canPlayAudioFormat('audio/mp3', audioElementRef.current)) {
24 | accept = 'audio/mp3';
25 | } else if (
26 | canPlayAudioFormat('audio/ogg;codec=opus', audioElementRef.current)
27 | ) {
28 | accept = 'audio/ogg;codec=opus';
29 | } else if (canPlayAudioFormat('audio/wav', audioElementRef.current)) {
30 | accept = 'audio/wav';
31 | }
32 | if (accept) {
33 | params.set('accept', accept);
34 | }
35 |
36 | return `/api/synthesize?${params.toString()}`;
37 | };
38 |
39 | const onSynthesize = async (text, voice) => {
40 | try {
41 | audioElementRef.current.setAttribute(
42 | 'src',
43 | getSynthesizeUrl(text, voice),
44 | );
45 | await audioElementRef.current.play();
46 | } catch (err) {
47 | setError(createError(SYNTHESIZE_ERROR_TITLE, err.message));
48 | }
49 | };
50 |
51 | return (
52 |
76 | );
77 | };
78 |
79 | export default App;
80 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@ibm-watson/text-to-speech-code-pattern",
3 | "version": "0.1.0",
4 | "proxy": "http://localhost:5000",
5 | "private": true,
6 | "dependencies": {
7 | "@carbon/react": "^1.22.0",
8 | "axios": "^0.27.2",
9 | "body-parser": "^1.20.1",
10 | "concurrently": "^7.6.0",
11 | "cross-env": "^7.0.3",
12 | "dotenv": "^16.0.3",
13 | "express": "^4.18.2",
14 | "express-rate-limit": "^6.7.0",
15 | "express-secure-only": "^0.2.1",
16 | "helmet": "^6.0.1",
17 | "husky": "^8.0.3",
18 | "ibm-watson": "^7.1.2",
19 | "lint-staged": "^13.1.1",
20 | "morgan": "^1.10.0",
21 | "sass": "^1.58.0"
22 | },
23 | "scripts": {
24 | "dev": "concurrently \"npm:client\" \"npm:server\"",
25 | "client": "react-scripts start",
26 | "server": "nodemon server.js",
27 | "start": "node server.js",
28 | "build": "INLINE_RUNTIME_CHUNK=false react-scripts build",
29 | "test": "npm run test:components && npm run test:integration",
30 | "test:components": "cross-env CI=true react-scripts test --env=jsdom --passWithNoTests",
31 | "test:integration": "JEST_PUPPETEER_CONFIG='test/jest-puppeteer.config.js' jest test -c test/jest.config.js",
32 | "prepare": "husky install"
33 | },
34 | "eslintConfig": {
35 | "extends": "react-app"
36 | },
37 | "engines": {
38 | "node": "^18.0.0"
39 | },
40 | "browserslist": {
41 | "production": [
42 | ">0.2%",
43 | "not dead",
44 | "not op_mini all"
45 | ],
46 | "development": [
47 | "last 1 chrome version",
48 | "last 1 firefox version",
49 | "last 1 safari version"
50 | ]
51 | },
52 | "lint-staged": {
53 | "./**/*.{js,scss,html,png,yaml,yml}": [
54 | "npm run build"
55 | ]
56 | },
57 | "devDependencies": {
58 | "@testing-library/jest-dom": "^5.16.5",
59 | "@testing-library/react": "^12.1.5",
60 | "@testing-library/user-event": "^14.4.3",
61 | "jest-puppeteer": "^6.2.0",
62 | "nodemon": "^2.0.20",
63 | "prettier": "^2.8.4",
64 | "puppeteer": "^18.0.3",
65 | "react": "^17.0.2",
66 | "react-dom": "^17.0.2",
67 | "react-json-tree": "^0.18.0",
68 | "react-json-view": "^1.21.3",
69 | "react-scripts": "5.0.1"
70 | },
71 | "prettier": {
72 | "trailingComma": "all",
73 | "singleQuote": true
74 | },
75 | "nodemonConfig": {
76 | "watch": [
77 | "app.js",
78 | "config/**/*.js",
79 | "server.js"
80 | ],
81 | "ext": "js",
82 | "ignore": [
83 | ".git",
84 | "node_modules",
85 | "public",
86 | "src",
87 | "test"
88 | ],
89 | "delay": 500
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/components/Header/_header.scss:
--------------------------------------------------------------------------------
1 | @use '@carbon/react/scss/spacing' as *;
2 | @use '@carbon/react/scss/colors' as *;
3 | @import './overrides';
4 |
5 | .header {
6 | background-color: $gray-100;
7 | display: flex;
8 | min-height: unset;
9 | padding: $spacing-07;
10 |
11 | .link-container {
12 | align-items: flex-end;
13 | display: flex;
14 | flex-grow: 1;
15 | justify-content: flex-end;
16 |
17 | .link-wrapper {
18 | align-items: flex-end;
19 | display: flex;
20 | flex-direction: column;
21 |
22 | @media (min-width: 992px) {
23 | justify-content: flex-end;
24 | }
25 |
26 | @media (min-width: 1200px) {
27 | align-items: center;
28 | flex-direction: row;
29 | height: min-content;
30 | }
31 |
32 | .link {
33 | color: $blue-40;
34 |
35 | &.getting-started:hover {
36 | text-decoration: none;
37 | }
38 |
39 | &:not(:last-child) {
40 | padding-bottom: $spacing-03;
41 |
42 | @media (min-width: 1200px) {
43 | padding-bottom: 0;
44 | padding-right: $spacing-07;
45 | }
46 | }
47 |
48 | &-icon {
49 | display: block;
50 | fill: $white-0;
51 |
52 | @media (min-width: 992px) {
53 | display: none;
54 | }
55 | }
56 |
57 | &-text {
58 | display: none;
59 | text-align: end;
60 |
61 | @media (min-width: 992px) {
62 | display: block;
63 | }
64 |
65 | @media (min-width: 1200px) {
66 | text-align: unset;
67 | }
68 | }
69 |
70 | &-button {
71 | border-color: $white-0;
72 | color: $white-0;
73 | display: none;
74 | text-align: end;
75 |
76 | &:hover {
77 | background-color: $white-0;
78 | color: $gray-100;
79 |
80 | .cds--btn__icon path {
81 | fill: $gray-100;
82 | }
83 | }
84 |
85 | @media (min-width: 992px) {
86 | display: block;
87 | }
88 |
89 | @media (min-width: 1200px) {
90 | text-align: unset;
91 | }
92 | }
93 | }
94 | }
95 | }
96 |
97 | .title-container {
98 | color: $gray-10;
99 | display: flex;
100 | flex-direction: column;
101 | width: 70%;
102 |
103 | @media (min-width: 1200px) {
104 | width: 40%;
105 | }
106 |
107 | .header-title {
108 | padding-bottom: $spacing-06;
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/scripts/experience_test.py:
--------------------------------------------------------------------------------
1 | import os
2 | import time
3 | import sys
4 | from selenium import webdriver
5 | from selenium.webdriver.chrome.options import Options
6 | from selenium.webdriver.common.by import By
7 |
8 | # Do an action on the app's landing page
9 | options = Options()
10 | options.add_argument('--headless')
11 | options.add_argument('--no-sandbox')
12 | options.add_argument('--disable-dev-shm-usage')
13 | driver = webdriver.Chrome(options=options)
14 |
15 | success = False
16 |
17 | try:
18 | app_url = os.environ.get("APP_URL", "http://localhost:5000/")
19 | print("APP_URL: ", app_url)
20 | driver.get(app_url) # Open a browser to the app's landing page
21 |
22 | time.sleep(3) # Init time needed?
23 |
24 | print("Title: ", driver.title)
25 | expected_title = "Text to Speech"
26 | if driver.title != expected_title:
27 | raise Exception("Title should be " + expected_title)
28 |
29 | audio_button = driver.find_element(By.CLASS_NAME, 'audio-output')
30 | src = audio_button.get_attribute("src")
31 | print("AUDIO SOURCE: ", src)
32 |
33 | # Find and select Allison V3
34 | drop_down = driver.find_element(By.XPATH, "//button[@id='downshift-0-toggle-button']")
35 | drop_down.click()
36 | drop_down_element = driver.find_element(By.XPATH, "//div[contains(text(),'Allison (V3)')]")
37 | drop_down_element.click()
38 |
39 | # Find button and click it
40 | synthesize_button = driver.find_element(By.XPATH, "//button[contains(text(),'Synthesize')]")
41 | synthesize_button.click()
42 |
43 | time.sleep(20)
44 |
45 | # Verify the action on the app's landing page
46 | # Input text
47 | text_to_say = driver.find_element(By.ID, "text-input").text
48 | print("SAY: ", text_to_say)
49 |
50 | expected = "Conscious of its spiritual and moral heritage"
51 | if expected not in text_to_say:
52 | raise Exception("Did not get the expected text to say")
53 | else:
54 | print("First Test Successful")
55 |
56 | # Test that we got some audio
57 | audio_button = driver.find_element(By.CLASS_NAME, 'audio-output')
58 | src = audio_button.get_attribute("src")
59 | print("AUDIO SOURCE: ", src)
60 |
61 | expected = "api/synthesize?text=Conscious+of+its+spiritual+and+moral+heritage"
62 | if expected not in src:
63 | raise Exception("Did not get the expected audio src")
64 | else:
65 | print("Second Test Successful")
66 |
67 | success = True
68 |
69 | except Exception as e:
70 | print("Exception: ", e)
71 | raise
72 |
73 | finally:
74 | driver.quit()
75 | if success:
76 | print("Experience Test Successful")
77 | else:
78 | sys.exit("Experience Test Failed")
79 |
--------------------------------------------------------------------------------
/src/components/Toast/Toast.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import PropTypes from 'prop-types';
3 | import { ToastNotification } from '@carbon/react';
4 |
5 | const NOTIFICATION_HAS_BEEN_SEEN = 'notificationHasBeenSeen';
6 |
7 | export const Toast = ({
8 | caption,
9 | children,
10 | className,
11 | hideAfterFirstDisplay,
12 | hideCloseButton,
13 | kind,
14 | lowContrast,
15 | onCloseButtonClick,
16 | role,
17 | subtitle,
18 | timeout,
19 | title,
20 | }) => {
21 | const [id, setId] = useState();
22 | const [hideToast, setHideToast] = useState(false);
23 |
24 | useEffect(() => {
25 | setId(
26 | Math.random().toString(36).substring(2, 15) +
27 | Math.random().toString(36).substring(2, 15),
28 | );
29 | }, []);
30 |
31 | useEffect(() => {
32 | const element = document.querySelector(`.custom-toast-${id}`);
33 | if (element) {
34 | element.className += 'enter';
35 | }
36 | }, [id]);
37 |
38 | useEffect(() => {
39 | if (
40 | hideAfterFirstDisplay &&
41 | typeof window !== undefined &&
42 | typeof window.localStorage !== undefined &&
43 | window.localStorage.getItem(NOTIFICATION_HAS_BEEN_SEEN) === 'true'
44 | ) {
45 | setHideToast(true);
46 | }
47 | }, [hideAfterFirstDisplay]);
48 |
49 | return hideToast ? null : (
50 | {
57 | if (
58 | hideAfterFirstDisplay &&
59 | typeof window !== undefined &&
60 | typeof window.localStorage !== undefined
61 | ) {
62 | window.localStorage.setItem(NOTIFICATION_HAS_BEEN_SEEN, 'true');
63 | }
64 | onCloseButtonClick();
65 | }}
66 | role={role}
67 | subtitle={subtitle}
68 | timeout={timeout}
69 | title={title}
70 | >
71 | {children}
72 |
73 | );
74 | };
75 |
76 | Toast.propTypes = {
77 | caption: PropTypes.string,
78 | children: PropTypes.node,
79 | className: PropTypes.string,
80 | hideAfterFirstDisplay: PropTypes.bool,
81 | hideCloseButton: PropTypes.bool,
82 | kind: PropTypes.string,
83 | lowContrast: PropTypes.bool,
84 | onCloseButtonClick: PropTypes.func,
85 | role: PropTypes.string,
86 | subtitle: PropTypes.string,
87 | timeout: PropTypes.number,
88 | title: PropTypes.string,
89 | };
90 |
91 | Toast.defaultProps = {
92 | caption: '',
93 | children: null,
94 | className: '',
95 | hideAfterFirstDisplay: true,
96 | hideCloseButton: false,
97 | kind: 'error',
98 | lowContrast: false,
99 | onCloseButtonClick: () => {},
100 | role: 'alert',
101 | subtitle: '',
102 | timeout: 0,
103 | title: '',
104 | };
105 |
106 | export default Toast;
107 |
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1.js');
2 | const path = require('path');
3 | const express = require('express');
4 | const app = express();
5 | require('./config/express')(app);
6 |
7 | // For starter kit env.
8 | require('dotenv').config({
9 | silent: true
10 | });
11 | const pEnv = process.env;
12 | const skitJson = JSON.parse(process.env.service_watson_text_to_speech || "{}");
13 |
14 | // Look for credentials in all the places
15 | const apikey = process.env.TEXT_TO_SPEECH_APIKEY || process.env.TEXTTOSPEECH_APIKEY || skitJson?.apikey;
16 | const url = process.env.TEXT_TO_SPEECH_URL ||
17 | process.env.TEXTTOSPEECH_URL || skitJson?.url;
18 |
19 | // A null/undefined service env var would actually cause
20 | // the core SDK to throw an error in integration tests
21 | // and fail the test, but if the env var is left unset
22 | // it won't
23 | if (apikey) {
24 | process.env.TEXT_TO_SPEECH_APIKEY = apikey;
25 | }
26 |
27 | if (url) {
28 | process.env.TEXT_TO_SPEECH_URL = url;
29 | }
30 |
31 | // Create Text to Speech client.
32 | let client;
33 | try {
34 | client = new TextToSpeechV1({ version: '2020-06-02' });
35 | } catch (err) {
36 | console.error('Error creating service client: ', err);
37 | }
38 |
39 | // Caching issues are causing alerts. Avoid cache.
40 | var options = {
41 | etag: false,
42 | maxAge: '0',
43 | setHeaders: function (res, _path, _stat) {
44 | res.set('Cache-Control', 'private, no-cache, no-store, must-revalidate');
45 | res.header('Pragma', 'no-cache');
46 | res.header('Expires', '0');
47 | }
48 | }
49 |
50 | app.use(express.static(path.join(__dirname, 'build'), options ));
51 |
52 | app.get('/health', (_, res) => {
53 | res.json({ status: 'UP' });
54 | });
55 |
56 | app.get('/api/voices', async (_, res, next) => {
57 | try {
58 | if (client) {
59 | const { result } = await client.listVoices();
60 | return res.json(result);
61 | } else {
62 | // Return Allison for testing and user still gets creds pop-up.
63 | return res.json(
64 | { voices: [
65 | { name: 'en-US_AllisonV3Voice',
66 | description: 'Allison: American English female voice. Dnn technology.',
67 | }]
68 | });
69 | }
70 | } catch (err) {
71 | console.error(err);
72 | if (!client) {
73 | err.statusCode = 401;
74 | err.description =
75 | 'Could not find valid credentials for the Text to Speech service.';
76 | err.title = 'Invalid credentials';
77 | }
78 | next(err);
79 | }
80 | });
81 |
82 | app.get('/api/synthesize', async (req, res, next) => {
83 | try {
84 | const { result } = await client.synthesize(req.query);
85 | result.pipe(res);
86 | } catch (err) {
87 | console.error(err);
88 | if (!client) {
89 | err.statusCode = 401;
90 | err.description =
91 | 'Could not find valid credentials for the Text to Speech service.';
92 | err.title = 'Invalid credentials';
93 | }
94 | next(err);
95 | }
96 | });
97 |
98 | // error-handler settings for all other routes
99 | require('./config/error-handler')(app);
100 |
101 | module.exports = app;
102 |
--------------------------------------------------------------------------------
/MAINTAINERS.md:
--------------------------------------------------------------------------------
1 | # Maintainers Guide
2 |
3 | This guide is intended for maintainers - anybody with commit access to one or
4 | more Code Pattern repositories.
5 |
6 | ## Methodology
7 |
8 | This repository does not have a traditional release management cycle, but
9 | should instead be maintained as a useful, working, and polished reference at
10 | all times. While all work can therefore be focused on the master branch, the
11 | quality of this branch should never be compromised.
12 |
13 | The remainder of this document details how to merge pull requests to the
14 | repositories.
15 |
16 | ## Merge approval
17 |
18 | The project maintainers use LGTM (Looks Good To Me) in comments on the pull
19 | request to indicate acceptance prior to merging. A change requires LGTMs from
20 | two project maintainers. If the code is written by a maintainer, the change
21 | only requires one additional LGTM.
22 |
23 | ## Reviewing Pull Requests
24 |
25 | We recommend reviewing pull requests directly within GitHub. This allows a
26 | public commentary on changes, providing transparency for all users. When
27 | providing feedback be civil, courteous, and kind. Disagreement is fine, so long
28 | as the discourse is carried out politely. If we see a record of uncivil or
29 | abusive comments, we will revoke your commit privileges and invite you to leave
30 | the project.
31 |
32 | During your review, consider the following points:
33 |
34 | ### Does the change have positive impact?
35 |
36 | Some proposed changes may not represent a positive impact to the project. Ask
37 | whether or not the change will make understanding the code easier, or if it
38 | could simply be a personal preference on the part of the author (see
39 | [bikeshedding](https://en.wiktionary.org/wiki/bikeshedding)).
40 |
41 | Pull requests that do not have a clear positive impact should be closed without
42 | merging.
43 |
44 | ### Do the changes make sense?
45 |
46 | If you do not understand what the changes are or what they accomplish, ask the
47 | author for clarification. Ask the author to add comments and/or clarify test
48 | case names to make the intentions clear.
49 |
50 | At times, such clarification will reveal that the author may not be using the
51 | code correctly, or is unaware of features that accommodate their needs. If you
52 | feel this is the case, work up a code sample that would address the pull
53 | request for them, and feel free to close the pull request once they confirm.
54 |
55 | ### Does the change introduce a new feature?
56 |
57 | For any given pull request, ask yourself "is this a new feature?" If so, does
58 | the pull request (or associated issue) contain narrative indicating the need
59 | for the feature? If not, ask them to provide that information.
60 |
61 | Are new unit tests in place that test all new behaviors introduced? If not, do
62 | not merge the feature until they are! Is documentation in place for the new
63 | feature? (See the documentation guidelines). If not do not merge the feature
64 | until it is! Is the feature necessary for general use cases? Try and keep the
65 | scope of any given component narrow. If a proposed feature does not fit that
66 | scope, recommend to the user that they maintain the feature on their own, and
67 | close the request. You may also recommend that they see if the feature gains
68 | traction among other users, and suggest they re-submit when they can show such
69 | support.
70 |
--------------------------------------------------------------------------------
/src/components/ControlContainer/ControlContainer.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import PropTypes from 'prop-types';
3 | import { VolumeUpFilled } from '@carbon/react/icons';
4 | import {
5 | Button,
6 | Dropdown,
7 | DropdownSkeleton,
8 | FormGroup,
9 | TextArea,
10 | Tile,
11 | } from '@carbon/react';
12 | import axios from 'axios';
13 | import { sampleText } from '../../data/sampleText';
14 | import { mapVoicesToDropdownItems } from './utils';
15 |
16 | const VOICES_ENDPOINT = '/api/voices';
17 |
18 | export const ControlContainer = ({ onSynthesize }) => {
19 | const [voices, setVoices] = useState([]);
20 | const [selectedVoice, setSelectedVoice] = useState();
21 | const [text, setText] = useState('');
22 | const [isLoading, setIsLoading] = useState(true);
23 | const [isError, setIsError] = useState(false);
24 |
25 | // Get voices data
26 | useEffect(() => {
27 | axios(VOICES_ENDPOINT)
28 | .then(({ data }) => setVoices(data.voices))
29 | .catch(err => {
30 | console.log(err);
31 | setIsError(true);
32 | })
33 | .finally(setIsLoading(false));
34 | }, []);
35 |
36 | // Default to initial voice once all voices are loaded.
37 | useEffect(() => {
38 | if (voices[1]) {
39 | onSelectVoice(mapVoicesToDropdownItems(voices)[1]);
40 | }
41 | }, [voices]);
42 |
43 | const onSelectVoice = voice => {
44 | setSelectedVoice(voice);
45 |
46 | const text = sampleText[voice.id];
47 | setText(text);
48 | };
49 |
50 | return (
51 |
52 |
Input
53 |
54 | For optimal naturalness, select the (V3) voices, which are built using
55 | deep neural networks.
56 |
57 |
58 | {isLoading || (voices.length === 0 && !isError) ? (
59 |
60 | ) : (
61 | {
65 | onSelectVoice(newModel.selectedItem);
66 | }}
67 | items={mapVoicesToDropdownItems(voices)}
68 | selectedItem={selectedVoice && selectedVoice.label}
69 | ariaLabel="Voice model selection dropdown"
70 | light
71 | />
72 | )}
73 |
74 |
75 |
88 |
96 |
97 | );
98 | };
99 |
100 | ControlContainer.propTypes = {
101 | onSynthesize: PropTypes.func,
102 | };
103 |
104 | ControlContainer.defaultProps = {
105 | onSynthesize: () => {},
106 | };
107 |
108 | export default ControlContainer;
109 |
--------------------------------------------------------------------------------
/doc/source/local.md:
--------------------------------------------------------------------------------
1 | # Run locally
2 |
3 | This document shows how to run the application on your local machine.
4 |
5 | ## Steps
6 |
7 | 1. [Clone the repo](#clone-the-repo)
8 | 1. [Configure credentials](#configure-credentials)
9 | 1. [Start the server](#start-the-server)
10 |
11 | ### Clone the repo
12 |
13 | Clone the repo locally. In a terminal, run:
14 |
15 | ```bash
16 | git clone https://github.com/IBM/text-to-speech-code-pattern
17 | cd text-to-speech-code-pattern
18 | ```
19 |
20 | ### Configure credentials
21 |
22 | Copy the `.env.example` file to `.env`.
23 |
24 | ```bash
25 | cp .env.example .env
26 | ```
27 |
28 | Edit the `.env` file to configure credentials before starting the Node.js server.
29 | The credentials to configure will depend on whether you are provisioning services using IBM Cloud Pak for Data or on IBM Cloud.
30 |
31 | Click to expand one:
32 |
33 | IBM Cloud Pak for Data
34 |
35 |
36 | For the **Text to Speech** service, the following settings are needed:
37 |
38 | * Set TEXT_TO_SPEECH_AUTH_TYPE to cp4d
39 | * Provide the TEXT_TO_SPEECH_URL, TEXT_TO_SPEECH_USERNAME and TEXT_TO_SPEECH_PASSWORD collected in the previous step.
40 | * For the TEXT_TO_SPEECH_AUTH_URL use the base fragment of your URL including the host and port. I.e. https://{cpd_cluster_host}{:port}.
41 | * If your CPD installation is using a self-signed certificate, you need to disable SSL verification with bothTEXT_TO_SPEECH_DISABLE_SSL and TEXT_TO_SPEECH_AUTH_DISABLE_SSL set to true. You might also need to use browser-specific steps to ignore certificate errors (try browsing to the AUTH_URL). Disable SSL only if absolutely necessary, and take steps to enable SSL as soon as possible.
42 | * Make sure the examples for IBM Cloud and bearer token auth are commented out (or removed).
43 |
44 | ```bash
45 | #----------------------------------------------------------
46 | # IBM Cloud Pak for Data (username and password)
47 | #
48 | # If your services are running on IBM Cloud Pak for Data,
49 | # uncomment and configure these.
50 | # Remove or comment out the IBM Cloud section.
51 | #----------------------------------------------------------
52 |
53 | TEXT_TO_SPEECH_AUTH_TYPE=cp4d
54 | TEXT_TO_SPEECH_URL=https://{cpd_cluster_host}{:port}/text-to-speech/{release}/instances/{instance_id}/api
55 | TEXT_TO_SPEECH_AUTH_URL=https://{cpd_cluster_host}{:port}
56 | TEXT_TO_SPEECH_USERNAME=
57 | TEXT_TO_SPEECH_PASSWORD=
58 | # # If you use a self-signed certificate, you need to disable SSL verification.
59 | # # This is not secure and not recommended.
60 | # TEXT_TO_SPEECH_DISABLE_SSL=true
61 | # TEXT_TO_SPEECH_AUTH_DISABLE_SSL=true
62 | ```
63 |
64 |
65 |
66 |
67 | IBM Cloud
68 |
69 |
70 | For the Text to Speech service, the following settings are needed:
71 |
72 | * Set TEXT_TO_SPEECH_AUTH_TYPE to iam
73 | * Provide the TEXT_TO_SPEECH_URL and TEXT_TO_SPEECH_APIKEY collected in the previous step.
74 | * Make sure the examples for IBM Cloud Pak for Data and bearer token auth are commented out (or removed).
75 |
76 |
77 | ```bash
78 | # Copy this file to .env and replace the credentials with
79 | # your own before starting the app.
80 |
81 | #----------------------------------------------------------
82 | # IBM Cloud
83 | #
84 | # If your services are running on IBM Cloud,
85 | # uncomment and configure these.
86 | # Remove or comment out the IBM Cloud Pak for Data sections.
87 | #----------------------------------------------------------
88 |
89 | TEXT_TO_SPEECH_AUTH_TYPE=iam
90 | TEXT_TO_SPEECH_APIKEY=
91 | TEXT_TO_SPEECH_URL=
92 | ```
93 |
94 |
95 |
96 |
97 | > Need more information? See the [authentication wiki](https://github.com/IBM/node-sdk-core/blob/master/AUTHENTICATION.md).
98 |
99 | ### Start the server
100 |
101 | ```bash
102 | npm install
103 | npm start
104 | ```
105 |
106 | The application will be available in your browser at http://localhost:5000. Return to the README.md for instructions on how to use the app.
107 |
108 | [](../../README.md#3-use-the-web-app)
109 |
--------------------------------------------------------------------------------
/doc/source/openshift.md:
--------------------------------------------------------------------------------
1 | # Run on Red Hat OpenShift
2 |
3 | This document shows how to deploy the server using Red Hat OpenShift.
4 |
5 | ## Prerequisites
6 |
7 | You will need a running OpenShift cluster, or OKD cluster. You can provision [OpenShift on the IBM Cloud](https://cloud.ibm.com/kubernetes/catalog/openshiftcluster).
8 |
9 | ## Steps
10 |
11 | 1. [Create an OpenShift project](#create-an-openshift-project)
12 | 1. [Create the config map](#create-the-config-map)
13 | 1. [Get a secure endpoint](#get-a-secure-endpoint)
14 | 1. [Run the web app](#run-the-web-app)
15 |
16 | ## Create an OpenShift project
17 |
18 | * Using the OpenShift web console, select the `Application Console` view.
19 |
20 | 
21 |
22 | * Use the `+Create Project` button to create a new project, then click on your project to open it.
23 |
24 | * In the `Overview` tab, click on `Browse Catalog`.
25 |
26 | 
27 |
28 | * Choose the `Node.js` app container and click `Next`.
29 |
30 | 
31 |
32 | * Give your application a name and add `https://github.com/IBM/text-to-speech-code-pattern` for the `Git Repository`, then click `Create`.
33 |
34 | 
35 |
36 | ## Create the config map
37 |
38 | Create a config map to configure credentials for the Node.js server.
39 |
40 | * Click on the `Resources` tab and choose `Config Maps` and then click the `Create Config Map` button.
41 | * Provide a `Name` for the config map.
42 | * Add items with keys and values. The necessary keys to configure will depend on whether you are provisioning services using IBM Cloud Pak for Data or on IBM Cloud.
43 |
44 | Click to expand one:
45 |
46 | IBM Cloud Pak for Data
47 |
48 |
49 | For the Text to Speech service, the following settings are needed:
50 |
51 | * Set TEXT_TO_SPEECH_AUTH_TYPE to cp4d
52 | * Provide the TEXT_TO_SPEECH_URL, TEXT_TO_SPEECH_USERNAME and TEXT_TO_SPEECH_PASSWORD for the user added to this service instance.
53 | * For the TEXT_TO_SPEECH_AUTH_URL use the base fragment of your URL including the host and port. I.e. https://{cpd_cluster_host}{:port}.
54 | * If your CPD installation is using a self-signed certificate, you need to disable SSL verification with bothTEXT_TO_SPEECH_DISABLE_SSL and TEXT_TO_SPEECH_AUTH_DISABLE_SSL set to true. You might also need to use browser-specific steps to ignore certificate errors (try browsing to the AUTH_URL). Disable SSL only if absolutely necessary, and take steps to enable SSL as soon as possible.
55 |
56 | | Key | Value |
57 | | --- | --- |
58 | | TEXT_TO_SPEECH_AUTH_TYPE | cp4d |
59 | | TEXT_TO_SPEECH_URL | https://{cpd_cluster_host}{:port}/text-to-speech/{release}/instances/{instance_id}/api |
60 | | TEXT_TO_SPEECH_AUTH_URL | https://{cpd_cluster_host}{:port} |
61 | | TEXT_TO_SPEECH_USERNAME | |
62 | | TEXT_TO_SPEECH_PASSWORD | |
63 | | TEXT_TO_SPEECH_AUTH_SSL | true or false |
64 | | TEXT_TO_SPEECH_AUTH_DISABLE_SSL | true or false |
65 | | PORT | 8080 |
66 |
67 |
68 |
69 |
70 | IBM Cloud
71 |
72 |
73 | For the Text to Speech service, the following settings are needed:
74 |
75 | * Set TEXT_TO_SPEECH_AUTH_TYPE to iam
76 | * Provide the TEXT_TO_SPEECH_URL and TEXT_TO_SPEECH_APIKEY collected when you created the services.
77 |
78 | | Key | Value |
79 | | --- | --- |
80 | | TEXT_TO_SPEECH_AUTH_TYPE | iam |
81 | | TEXT_TO_SPEECH_APIKEY | |
82 | | TEXT_TO_SPEECH_URL | |
83 | | PORT | 8080 |
84 |
85 |
86 |
87 |
88 | Create the config map and add it to your application.
89 |
90 | * Hit the `Create` button.
91 | * Click on your new Config Map's name.
92 | * Click the `Add to Application` button.
93 | * Select your application from the pulldown.
94 | * Click `Save`.
95 | * Go to the `Applications` tab, choose `Deployments` to view the status of your application.
96 |
97 | ## Get a secure endpoint
98 |
99 | * From the OpenShift or OKD UI, under `Applications` ▷ `Routes` you will see your app.
100 | * Click on the application `Name`.
101 | * Under `TLS Settings`, click on `Edit`.
102 | * Under `Security`, check the box for `Secure route`.
103 | * Hit `Save`.
104 |
105 | ## Run the web app
106 |
107 | * Go back to `Applications` ▷ `Routes`. You will see your app.
108 | * Click your app's `Hostname`. This will open the Text to Speech web app in your browser.
109 | * Go back to the README.md for instructions on how to use the app.
110 |
111 | [](../../README.md#3-use-the-web-app)
112 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WARNING: This repository is no longer maintained :warning:
2 |
3 | > This repository will not be updated. The repository will be kept available in read-only mode.
4 |
5 | [](https://github.com/IBM/text-to-speech-code-pattern/actions/workflows/nodejs.yml)
6 |
7 | # Text to Speech Code Pattern
8 |
9 | Sample React app for playing around with the Watson Text to Speech service
10 |
11 | ✨ **Demo:** https://text-to-speech-code-pattern.ng.bluemix.net/ ✨
12 |
13 | 
14 |
15 | ## Flow
16 |
17 | 1. User supplies some text as input to the application (running locally, in the IBM Cloud or in IBM Cloud Pak for Data).
18 | 1. The application sends the text to the Watson Text to Speech service.
19 | 1. As the data is processed, the Text to Speech service returns audio information to the HTML5 audio element for playback.
20 |
21 | ## Steps
22 |
23 | 1. [Provision Watson Text to Speech](#1-Provision-Watson-Text-to-Speech)
24 | 2. [Deploy the server](#2-Deploy-the-server)
25 | 3. [Use the web app](#3-Use-the-web-app)
26 |
27 | ## 1. Provision Watson Text to Speech
28 |
29 | The instructions will depend on whether you are provisioning services using IBM Cloud Pak for Data or on IBM Cloud.
30 |
31 | **Click to expand one:**
32 |
33 | IBM Cloud Pak for Data
34 |
35 |
36 |
Install and provision
37 |
38 | The service is not available by default. An administrator must install it on the IBM Cloud Pak for Data platform, and you must be given access to the service. To determine whether the service is installed, click the Services icon () and check whether the service is enabled.
39 |
40 |
Gather credentials
41 |
42 |
43 |
For production use, create a user to use for authentication. From the main navigation menu (☰), select Administer > Manage users and then + New user.
44 |
From the main navigation menu (☰), select My instances.
45 |
On the Provisioned instances tab, find your service instance, and then hover over the last column to find and click the ellipses icon. Choose View details.
46 |
Copy the URL to use as the TEXT_TO_SPEECH_URL when you configure credentials.
47 |
Optionally, copy the Bearer token to use in development testing only. It is not recommended to use the bearer token except during testing and development because that token does not expire.
48 |
Use the Menu and select Users and + Add user to grant your user access to this service instance. This is the TEXT_TO_SPEECH_USERNAME (and TEXT_TO_SPEECH_PASSWORD) you will use when you configure credentials to allow the Node.js server to authenticate.
49 |
50 |
51 |
52 |
53 | IBM Cloud
54 |
55 |
Create the service instance
56 |
57 | * If you do not have an IBM Cloud account, register for a free trial account [here](https://cloud.ibm.com/registration).
58 | * Click [here](https://cloud.ibm.com/catalog/services/text-to-speech) to create a **Text to Speech** instance.
59 | * `Select a region`.
60 | * `Select a pricing plan` (**Lite** is *free*).
61 | * Set your `Service name` or use the generated one.
62 | * Click `Create`.
63 | * Gather credentials
64 | * Copy the API Key and URL to use when you configure and [deploy the server](#2-Deploy-the-server).
65 |
66 | > If you need to find the service later, use the main navigation menu (☰) and select **Resource list** to find the service under **Services**.
67 | Click on the service name to get back to the **Manage** view (where you can collect the **API Key** and **URL**).
68 |
69 |
70 |
71 | ## 2. Deploy the server
72 |
73 | Click on one of the options below for instructions on deploying the Node.js server.
74 |
75 | | | |
76 | | - | - |
77 | | [](doc/source/local.md) | [](doc/source/openshift.md) |
78 |
79 | ## 3. Use the web app
80 |
81 | * Select an input `Voice model`.
82 |
83 | * Use the demo `Text to synthesize` or enter your own text into that text box.
84 |
85 | * Press the `Synthesize` button to create audio from that text and hear it in the selected voice.
86 |
87 | * The audio plays automatically. You can also use the `Synthesized audio` controls to pause, play, etc.
88 |
89 | 
90 |
91 | ## Developing and testing
92 |
93 | See [DEVELOPING.md](DEVELOPING.md) and [TESTING.md](TESTING.md) for more details about developing and testing this app.
94 |
95 | ## License
96 |
97 | This code pattern is licensed under the Apache License, Version 2. Separate third-party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1](https://developercertificate.org/) and the [Apache License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt).
98 |
99 | [Apache License FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN)
100 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready.then(registration => {
134 | registration.unregister();
135 | });
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/data/sampleText.js:
--------------------------------------------------------------------------------
1 | /* eslint max-len: off */
2 | const ES_TEXT =
3 | 'Consciente de su patrimonio espiritual y moral, la Unión está fundada sobre los valores indivisibles y universales de la dignidad humana, la libertad, la igualdad y la solidaridad, y se basa en los principios de la democracia y el Estado de Derecho. Al instituir la ciudadanía de la Unión y crear un espacio de libertad, seguridad y justicia, sitúa a la persona en el centro de su actuación.';
4 | const FR_TEXT =
5 | "Consciente de son patrimoine spirituel et moral, l'Union se fonde sur les valeurs indivisibles et universelles de dignité humaine, de liberté, d'égalité et de solidarité; elle repose sur le principe de la démocratie et le principe de l'État de droit. Elle place la personne au coeur de son action en instituant la citoyenneté de l'Union et en créant un espace de liberté, de sécurité et de justice.";
6 | const US_TEXT =
7 | 'Conscious of its spiritual and moral heritage, the Union is founded on the indivisible, universal values of human dignity, freedom, equality and solidarity; it is based on the principles of democracy and the rule of law. It places the individual at the heart of its activities, by establishing the citizenship of the Union and by creating an area of freedom, security and justice.';
8 | const DE_TEXT =
9 | 'In dem Bewusstsein ihres geistig-religiösen und sittlichen Erbes gründet sich die Union auf die unteilbaren und universellen Werte der Würde des Menschen, der Freiheit, der Gleichheit und der Solidarität. Sie beruht auf den Grundsätzen der Demokratie und der Rechtsstaatlichkeit. Sie stellt den Menschen in den Mittelpunkt ihres Handelns, indem sie die Unionsbürgerschaft und einen Raum der Freiheit, der Sicherheit und des Rechts begründet.';
10 | const IT_TEXT =
11 | "L'Unione contribuisce alla salvaguardia e allo sviluppo di questi valori comuni nel rispetto della diversità delle culture e delle tradizioni dei popoli d'Europa, nonché dell'identità nazionale degli Stati membri e dell'ordinamento dei loro pubblici poteri a livello nazionale, regionale e locale; essa si sforza di promuovere uno sviluppo equilibrato e sostenibile e assicura la libera circolazione delle persone, dei servizi, delle merci e dei capitali, nonché la libertà di stabilimento.";
12 | const JP_TEXT =
13 | 'こちらでは配送手続きのご予約・変更を承っております。お客様の会員番号をお願いいたします。会員番号は、01234567、ですね。確認いたしました。現在、3月25日、ご自宅へ配送のご予約を頂いております。それでは、3月25日、ご自宅へ配送の予定を、3月26日のご配送に変更いたします。3月26日は、降雪のため、配送が遅れることがあります。';
14 | const PT_TEXT =
15 | 'Consciente do seu patrimônio espiritual e moral, a União é fundamentada nos valores indivisíveis e universais da dignidade humana, liberdade, igualdade e solidariedade; é baseada nos princípios da democracia e estado de direito. Ela coloca o indivíduo no centro de suas ações, ao instituir a cidadania da União e ao criar um espaço de liberdade, segurança e justiça.';
16 | const AR_TEXT =
17 | 'تقوم خدمة I B M النص إلى خدمة الكلام بتحويل النص المكتوب إلى صوت طبيعي في مجموعة متنوعة من اللغات والأصوات.';
18 | const CN_TEXT =
19 | '基于海量数据的云计算、大数据、人工智能、区块链等新兴技术,正在对商业产生深远的影响。科技变革的步伐持续加速,各行各业的领先企业正在将关键业务应用转移到云端,并积极利用 AI,重塑业务。';
20 | const NL_TEXT =
21 | 'De volkeren van Europa hebben besloten een op gemeenschappelijke waarden gegrondveste vreedzame toekomst te delen door onderling een steeds hechter verbond tot stand te brengen. De Unie, die zich bewust is van haar geestelijke en morele erfgoed, heeft haar grondslag in de ondeelbare en universele waarden van menselijke waardigheid en van vrijheid, gelijkheid en solidariteit. Zij berust op het beginsel van democratie en het beginsel van de rechtsstaat. De Unie stelt de mens centraal in haar optreden, door het burgerschap van de Unie in te stellen en een ruimte van vrijheid, veiligheid en recht tot stand te brengen.';
22 |
23 | // Sample text values with SSML
24 | const ES_SSML =
25 | '
Consciente de su patrimonio espiritual y moral, la Unión está fundada sobre los valores indivisibles y universales de la dignidad humana, la libertad, la igualdad y la solidaridad, y se basa en los principios de la democracia y el Estado de Derecho.Al instituir la ciudadanía de la Unión y crear un espacio de libertad, seguridad y justicia, sitúa a la persona en el centro de su actuación.
';
26 | const FR_SSML =
27 | '
Consciente de son patrimoine spirituel et moral, l\'Union se fonde sur les valeurs indivisibles et universelles de dignité humaine, de liberté, d\'égalité et de solidarité; elle repose sur le principe de la démocratie et le principe de l\'État de droit . Elle place la personne au coeur de son action en instituant la citoyenneté de l\'Union et en créant un espace de liberté, de sécurité et de justice.
';
28 | const US_GB_SSML =
29 | '
Conscious of its spiritual and moral heritage , the Union is founded on the indivisible, universal values of human dignity, freedom, equality and solidarity. It is based on the principles of democracy and the rule of law . It places the individual at the heart of its activities, by establishing the citizenship of the Union and by creating an area of freedom, security and justice.
';
30 | const DE_SSML =
31 | '
In dem Bewusstsein ihres geistig-religiösen und sittlichen Erbes gründet sich die Union auf die unteilbaren und universellen Werte der Würde des Menschen, der Freiheit, der Gleichheit und der Solidarität. Sie beruht auf den Grundsätzen der Demokratie und der Rechtsstaatlichkeit. Sie stellt den Menschen in den Mittelpunkt ihres Handelns, indem sie die Unionsbürgerschaft und einen Raum der Freiheit, der Sicherheit und des Rechts begründet.
';
32 | const IT_SSML =
33 | '
Consapevole del suo patrimonio spirituale e morale, l\'Unione si fonda sui valori indivisibili e universali della dignità umana, della libertà, dell\'uguaglianza e della solidarietà; essa si basa sul principio della democrazia e sul principio dello Stato di diritto. Pone la persona al centro della sua azione istituendo la cittadinanza dell\'Unione e creando uno spazio di libertà, sicurezza e giustizia.
Consciente do seu patrimônio espiritual e moral, a União é fundamentada nos valores indivisíveis e universais da dignidade humana, liberdade, igualdade e solidariedade; é baseada nos princípios da democracia e estado de direito. Ela coloca o indivíduo no centro de suas ações, ao instituir a cidadania da União e ao criar um espaço de liberdade, segurança e justiça.
';
38 |
39 | // Sample text values with Voice Transformation SSML (Allison)
40 | const US_VOICE_SSML_ALLISON =
41 | 'Hello! I\'m Allison, but you can change my voice however you wish. For example, you can make my voice a bit softer, or a bit strained. ' +
42 | 'You can alter my voice timbre making me sound like this person, or like another person in your different applications. You can make my voice more breathy than it is normally. ' +
43 | 'I can speak like a young girl. And you can combine all this with modifications of my speech rate and my tone. ';
44 |
45 | // Sample text values with Voice Transformation SSML (Lisa)
46 | const US_VOICE_SSML_LISA =
47 | 'Hello! I\'m Lisa, but you can change my voice however you wish. For example, you can make my voice a bit softer, or a bit strained. You can alter my voice timbre making me sound like this person, or like another person in your different applications. You can make my voice more breathy than it is normally. I can speak like a young girl. And you can combine all this with modifications of my speech rate and my tone. ';
48 | const US_VOICE_SSML_MICHAEL =
49 | 'Hello! I\'m Michael, but you can change my voice however you wish. For example, you can make my voice a bit softer, or a bit strained. You can alter my voice timbre making me sound like this person, or like another person in your different applications. You can make my voice more breathy than it is normally. I can speak like a young boy. And you can combine all this with modifications of my speech rate and my tone. ';
50 |
51 | export const sampleText = {
52 | 'en-US_AllisonVoice': US_VOICE_SSML_ALLISON,
53 | 'en-US_AllisonV3Voice': US_TEXT,
54 | 'de-DE_BirgitVoice': DE_TEXT,
55 | 'de-DE_BirgitV3Voice': DE_SSML,
56 | 'de-DE_DieterVoice': DE_TEXT,
57 | 'de-DE_DieterV3Voice': DE_SSML,
58 | 'ja-JP_EmiVoice': JP_TEXT,
59 | 'ja-JP_EmiV3Voice': JP_SSML,
60 | 'nl-NL_EmmaVoice': NL_TEXT,
61 | 'es-ES_EnriqueVoice': ES_TEXT,
62 | 'es-ES_EnriqueV3Voice': ES_SSML,
63 | 'it-IT_FrancescaVoice': IT_TEXT,
64 | 'it-IT_FrancescaV3Voice': IT_SSML,
65 | 'pt-BR_IsabelaVoice': PT_TEXT,
66 | 'pt-BR_IsabelaV3Voice': PT_SSML,
67 | 'en-GB_KateVoice': US_TEXT,
68 | 'en-GB_KateV3Voice': US_GB_SSML,
69 | 'es-ES_LauraVoice': ES_TEXT,
70 | 'es-ES_LauraV3Voice': ES_SSML,
71 | 'zh-CN_LiNaVoice': CN_TEXT,
72 | 'nl-NL_LiamVoice': NL_TEXT,
73 | 'en-US_LisaVoice': US_VOICE_SSML_LISA,
74 | 'en-US_LisaV3Voice': US_TEXT,
75 | 'en-US_MichaelVoice': US_VOICE_SSML_MICHAEL,
76 | 'en-US_MichaelV3Voice': US_TEXT,
77 | 'ar-AR_OmarVoice': AR_TEXT,
78 | 'fr-FR_ReneeVoice': FR_TEXT,
79 | 'fr-FR_ReneeV3Voice': FR_SSML,
80 | 'es-LA_SofiaVoice': ES_TEXT,
81 | 'es-LA_SofiaV3Voice': ES_SSML,
82 | 'es-US_SofiaVoice': ES_TEXT,
83 | 'es-US_SofiaV3Voice': ES_SSML,
84 | 'zh-CN_WangWeiVoice': CN_TEXT,
85 | 'zh-CN_ZhangJingVoice': CN_TEXT,
86 | };
87 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------