Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Last active December 15, 2015 02:49
Show Gist options
  • Save t2-support-gists/5189881 to your computer and use it in GitHub Desktop.
Save t2-support-gists/5189881 to your computer and use it in GitHub Desktop.
Text To Speech Ruby RESTFul App 1
AT&T API Platform Sample Apps
--------------------------------------
This file describes how to set up, configure and run the Ruby sample
applications using the AT&T API Platform services. It covers all steps
required to register the applications on DevConnect as well as running the
sample applications locally.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application
registered on DevConnect with the proper services and endpoints, depending on
the type of client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login
with your valid username and password. Next, choose "My Apps" from the bar at
the top of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain
the URL that the OAuth provider will redirect users to when he/she
successfully authenticates and authorizes your application. The oauth
redirect field must match the redirect specified in the app's config.yml
NOTE: You MUST select the Sample Applications name in the list of services
under field 'Services' in order to enable access to the cloud api.
After your application is registered you will receive an API and Secret key.
They are necessary for your registered applications to access the AT&T
Platform APIs. See 'Adjusting parameters' below to learn how to use these
keys in your applications.
Initially your newly registered application is restricted to the "Sandbox"
environment only. To move it to production, you may promote it by clicking
the "Promote to production" button. Notice that you will get a different API
key and secret, so these values in your application should be adjusted
accordingly.
Depending on the kind of authentication used, an application may be based on
either the Autonomous Client or the Web-Server Client OAuth flow; see:
https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow
2. Installation
** Requirements
To run the examples you will need ruby 1.8+ and a few ruby gems that the
applications are built upon:
- sinatra: (http://www.sinatrarb.com/) used to construct a simple web
application and manage URLs within.
- sinatra-contrib: additional set of useful helpers, including ones used to
read settings from external files.
- rest-client: library for making restful calls
- json: used for encoding and decoding requests/responses
- att-codekit: library developed around the att cloud services (see below
to install)
- rake: compiling tool used to make att-codekit
- yard: documentation tool used by att-codekit
The easiest way to install the required gems is to use bundler.
First make sure you have bundler installed:
gem install bundler
Then inside the directory which this README resides run:
bundle install
On a *nix based system you may need to raise your access privliges, such as
prefixing the command with sudo or logging in as root by running su.
** Installing the att-codekit library
Note: this is only required if you are **not** using bundler and are using ruby 1.9+
The code kit library can be installed by using our hosted gem file.
gem sources --add http://lprod.code-api-att.com:8808
gem install att-codekit
Note that the codekit is under heavy development and is using a semantic
versioning scheme. Non-backwards compatible changes **will** increase the
major version number.
** Setting up on a different port number
In the case multiple applications need to be run at the same time, you need
to use different port numbers.
By default sinatra uses port number 4567; however only one running
application may use this port. In the case that you want to run more than one
sinatra-based application, you will need to update each applications' port
number (located in config.yml).
eg. application 1 - port: 4567, application 2 - port: 4568
The alternative is to set up your webserver to use a tool such as phusion
passenger. Setting up a webserver, however, is beyond the scope of this
article.
3. Parameters
Each application contains a config.yml file. It holds configurable parameters
described in the easy to read format YAML. You are free to adjust these to
your needs. If you introduce a change make sure to restart the application
for it to take effect.
The following are short descriptions of commonly used parameters:
REQUIRED -
1) FQDN : The main server handling requests, ex: https://api.att.com
2) api_key : set the value as per your registered application 'API
key' field value
3) secret_key : set the value as per your registered application
'Secret key' field value
OPTIONAL -
4) port : The port number which the application will run standalone
5) tokens_file : The path where the oauth token will be saved. This option
is only usable in client credential style authentication.
Must have write permissions.
Note: If your application is promoted from the Sandbox environment to
Production environment and you decide to use production application settings,
you must update api_key and secret_key as per production application details.
4. Running the application
To run the application, open up a terminal window in the application's
directory and type:
ruby (app name).rb
Where (app name) is replaced with the current directories app name.
Your application by default is accessible in a web browser at the url:
http://localhost:4567/
You may interrupt the application at any time by pressing ctrl-C.
AT&T API Samples - Speech app 1
------------------------------
This file describes how to set up, configure and run the ruby versions of the AT&T HTML5 Program sample applications.
It covers all steps required to register the application on DevConnect and, based on the generated API keys and secrets,
create and run one's own full-fledged sample applications.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application registered on DevConnect with the proper services and endpoints, depending on the type of client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login with your valid username and password. Next, choose "My Apps" from the bar at the top of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain the URL that the oAuth provider will redirect users to when he/she successfully authenticates and authorizes your application.
NOTE: You MUST select Speech in the list of services under field 'Services' in order to use this sample application code.
Having your application registered, you will get back an important pair of data: an API key and Secret key. They are necessary to get your applications working with the AT&T HTML5 APIs. See 'Adjusting parameters' below to learn how to use these keys.
Initially your newly registered application is restricted to the "Sandbox" environment only. To move it to production, you may promote it by clicking the "Promote to production" button. Notice that you will get a different API key and secret, so these values in your application should be adjusted accordingly.
Depending on the kind of authentication used, an application may be based on either the Autonomous Client or the Web-Server
Client OAuth flow (see https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow or
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow respectively).
2. Installation
** Requirements
To run the examples you need ruby 1.8+ and a few gems that the applications are heavily based on:
- sinatra (http://www.sinatrarb.com/)
used to construct a simple web application and manage URLs within.
- eventmachine
To ensure installation of the sinatra-contrib gem you must first install the gem eventmachine. Sinatra-contrib has a dependency on eventmachine. EventMachine enables programs to easily interface with other programs using TCP/IP, especially if custom protocols are required.
- sinatra-contrib
Additional set of useful helpers, including ones used to read settings from external files.
- Also make sure you have rest-client and json gems installed.
To install these gems open up a terminal window and invoke:
- gem install sinatra eventmachine sinatra-contrib rest-client json
If you are experiencing any additional difficulties installing gems, particularly sinatra-contrib, it may prove useful to install the ruby gem thin. This can be installed in the terminal by invoking:
- gem install thin
Having them installed, you are almost ready to run the sample applications.
** Setting up on a different port number
In case multiple applications need to be run at the same time, you need to consider using different port numbers.
By default sinatra uses port number 4567 and only one running application may use this port. In case you want to run one more sinatra-based application, you need to change its port number, eg. to 4568. This way you may have each application running on a unique port.
3. Parameters
Each application contains a config.yml file. It holds configurable parameters
described in an easy to read YAML format which you are free to adjust to your needs. Following are short descriptions
of parameters used by this application:
1) FQDN : https://api.att.com
2) port : port number that application binds to (default: 4567)
3) api_key : set the value as per your registered appliaction 'API key' field value
4) secret_key : set the value as per your registered appliaction 'Secret key' field value
5) tokens_file : file containing authorization and refresh tokens
Note: If your application is promoted from Sandbox environment to Production environment and you decide to use
production application settings, you must update parameters 1-2 as per production application details.
4. Running the application
To run the application, open up a terminal window and type:
ruby ./speech.rb
or
./speech.rb
Your application becomes available in a web browser, so you may visit: http://localhost:4567/ to see it working.
You may interrupt the application at any time by pressing ctrl-C.
# Licensed by AT&T under 'Software Development Kit Tools Agreement.' 2013
# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION: http://developer.att.com/sdk_agreement/
# Copyright 2013 AT&T Intellectual Property. All rights reserved. http://developer.att.com
# For more information contact developer.support@att.com
def obtain_tokens(fqdn, client_id, client_secret, scope, tokens_file)
read_tokens(tokens_file)
response = RestClient.post "#{fqdn}/oauth/token", :grant_type => 'client_credentials', :client_id => client_id, :client_secret => client_secret, :scope => scope
from_json = JSON.parse(response.to_str)
@access_token = from_json['access_token']
@refresh_token = from_json['refresh_token']
write_tokens(tokens_file)
end
def write_tokens(tokens_file)
File.open(tokens_file, 'w+') { |f| f.puts @access_token, @refresh_token }
end
def read_tokens(tokens_file)
@access_token, @refresh_token, refresh_expiration = File.foreach(tokens_file).first(2).map! &:strip!
rescue
return
end
require 'bundler'
#make sure all gems are installed
Bundler.require
begin
#require the file for ruby 1.9+
require_relative './tts'
rescue NoMethodError
#if error then we're in ruby 1.8
require './tts'
end
run Sinatra::Application
port: 51700
proxy:
api_key: 20e7ba81519527bb646b647caa501f62
secret_key: 736757594bdfc3db
tokens_file: tokens
FQDN: https://api.att.com
X_arg: "AppId=12345,OrgId=54321,VoiceName=mike"
source_link: https://gist.github.com/5189881
help_link: https://raw.github.com/attdevsupport/ATT_APIPlatform_SampleApps/master/RESTFul/TextToSpeech/Ruby/app1/README
download_link: https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/TextToSpeech/Ruby/app1
#!/usr/bin/env ruby
# Copyright 2014 AT&T
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'sinatra'
require 'sinatra/config_file'
require 'base64'
# require as a gem file load relative if fails
begin
require 'att/codekit'
rescue LoadError
# try relative, fall back to ruby 1.8 method if fails
begin
require_relative 'codekit/lib/att/codekit'
rescue NoMethodError
require File.join(File.dirname(__FILE__), 'codekit/lib/att/codekit')
end
end
include Att::Codekit
enable :sessions
config_file 'config.yml'
set :port, settings.port
set :protection, :except => :frame_options
SCOPE = "TTS"
TEXT_DIR = File.join(File.expand_path(File.dirname(__FILE__)), "public/text")
RestClient.proxy = settings.proxy
configure do
FILE_SUPPORT = (settings.tokens_file && !settings.tokens_file.strip.empty?)
FILE_EXISTS = FILE_SUPPORT && File.file?(settings.tokens_file)
OAuth = Auth::ClientCred.new(settings.FQDN,
settings.api_key,
settings.secret_key)
@@token = nil
end
before do
@ssml_content = load_content("SSMLWithPhoneme.txt")
@text_content = load_content("PlainText.txt")
begin
if @@token.nil?
if FILE_EXISTS
@@token = Auth::OAuthToken.load(settings.tokens_file)
else
@@token = OAuth.createToken(SCOPE)
end
Auth::OAuthToken.save(settings.tokens_file, @@token) if FILE_SUPPORT
end
if @@token.expired?
@@token = OAuth.refreshToken(@@token)
Auth::OAuthToken.save(settings.tokens_file, @@token) if FILE_SUPPORT
end
rescue Exception => e
@error = e.message
end
end
get '/' do
erb :tts
end
post '/TextToSpeech' do
begin
service = Service::TTSService.new(settings.FQDN, @@token)
type = params[:ContentType]
content = case type
when "application/ssml+xml" then load_content("SSMLWithPhoneme.txt")
when "text/plain" then load_content("PlainText.txt")
end
@audio = service.textToSpeech(content,
:xargs => params[:x_arg],
:type => type)
rescue Exception => e
@error = e.message
end
erb :tts
end
def load_content(text_file)
File.readlines(File.join(TEXT_DIR,text_file))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment