Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Last active October 6, 2015 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save t2-support-gists/3035532 to your computer and use it in GitHub Desktop.
Save t2-support-gists/3035532 to your computer and use it in GitHub Desktop.
Speech RESTful Php App 1
AT&T API Platform Samples - SpeechToText app 1
------------------------------
This file describes how to set-up, configure and run the PHP Applications
using AT&T API Platform services.
It covers all steps required to register the application on 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
1. Configuration
Configuration consists of a few steps necessary to get an application
registered with the proper services and
endpoints, depending on the type of client-side application
(autonomous/non-autonomous).
To register an application, go to
https://developer.att.com/developer/mvc/auth/login 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".
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 API Platform. 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://developer.att.com/apis/oauth-2/docs).
2. Installation
** Requirements
Apache web server
PHP 5.4+
Apache and PHP configured, on most GNU/Linux systems if installed using packages
this will be done automatically.
Copy the sample application folder to Apache web root folder, for example
/var/www/html.
3. Parameters
Each application contains a config.php file. This file holds configurable parameters described in an
easy-to-read format. Please modify the config.php file using the comments specified within the file.
Note: If your application is promoted from Sandbox environment to Production environment and you decide to use
production application settings, you must update parameters as per production application details.
<?php
$api_key = "4bf126e402d74a1e922a8c8bf256b2ac";
$secret_key = "5b5e0d7003967dc6";
$FQDN = "https://api.att.com";
$scope = "SPEECH";
$oauth_file = "speechoauthtoken.php";
$speech_context_config = array('Generic', 'TV', 'BusinessSearch', 'Websearch',
'SMS', 'Voicemail', 'QuestionAndAnswer', 'Gaming', 'SocialMedia');
$default_file = "default.wav";
$x_arg = "ClientApp=NoteTaker, ClientVersion=1.0.1,DeviceType=Linux";
$xSpeechSubContext = 'Chat';
$audioFolder = "audio";
$linkSource = 'https://gist.github.com/3035532';
$linkDownload = 'https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/Speech/PHP/app1';
$linkHelp = 'https://raw.github.com/attdevsupport/ATT_APIPlatform_SampleApps/master/RESTFul/Speech/PHP/app1/README.txt';
$endpoint = $FQDN . "/speech/v3/speechToText";
?>
<?php
session_start();
require __DIR__ . '/config.php';
require_once __DIR__ . '/src/Controller/SpeechController.php';
require_once __DIR__ . '/lib/Util/Util.php';
use Att\Api\Util\Util;
$controller = new SpeechController();
$controller->handleRequest();
$results = $controller->getResults();
$errors = $controller->getErrors();
?>
<!DOCTYPE html>
<!--
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.
-->
<!--[if lt IE 7]> <html class="ie6" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="ie7" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="ie8" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<title>AT&amp;T Sample Speech Application - Speech to Text(Generic)</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta id="viewport" name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style/common.css">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-33466541-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="pageContainer" class="pageContainer">
<div id="header">
<div class="logo" id="top"></div>
<div id="menuButton" class="hide">
<a id="jump" href="#nav">Main Navigation</a>
</div>
<ul class="links" id="nav">
<li>
<a href="<?php echo $linkSource; ?>"
target="_blank">Source<img src="images/source.png" alt="Source" /></a>
<span class="divider"> |&nbsp;</span>
</li>
<li>
<a href="<?php echo $linkDownload; ?>"
target="_blank">Download<img src="images/download.png" alt="Link"></a>
<span class="divider">|&nbsp;</span>
</li>
<li><a href="<?php echo $linkHelp; ?>" target="_blank">Help</a></li>
<li id="back"><a href="#top">Back to top</a></li>
</ul> <!-- end of links -->
</div> <!-- end of header -->
<div class="content">
<div class="contentHeading">
<h1>AT&amp;T Sample Application - Speech to Text</h1>
<div id="introtext">
<div><b>Server Time:&nbsp;</b><?php echo Util::getServerTime(); ?></div>
<div>
<b>Client Time:&nbsp;</b>
<script>
document.write("" + new Date());
</script>
</div>
<div>
<b>User Agent:&nbsp;</b>
<script>
document.write("" + navigator.userAgent);
</script>
</div>
</div> <!-- end of introtext -->
</div><!-- end of contentHeading -->
<div class="formBox" id="formBox">
<div id="formContainer" class="formContainer">
<form name="SpeechToText" action="index.php" method="post">
<div id="formData">
<!-- start context select -->
<h3>Speech Context:</h3>
<select name="SpeechContext">
<?php
$speechContexts = $controller->getSpeechContexts();
foreach ($speechContexts as $sname) {
$selected = '';
if ($controller->isSpeechContextSelected($sname)) $selected = 'selected ';
?>
<option <?php echo $selected; ?>value="<?php echo $sname ?>"><?php echo $sname ?></option>
<?php } ?>
</select>
<!-- end context select -->
<!-- start audio file select -->
<h3>Audio File:</h3>
<select name="audio_file">
<?php
$audioFiles = $controller->getAudioFiles();
foreach ($audioFiles as $fname) {
$selected = '';
if ($controller->isAudioFileSelected($fname)) $selected ='selected ';
?>
<option <?php echo $selected; ?>value="<?php echo $fname ?>"><?php echo $fname ?></option>
<?php } ?>
</select>
<!-- end audio file select -->
<div id="chunked">
<br>
<b>Send Chunked:</b>
<?php $chked = $controller->isChunkedSelected() ? ' checked' : ''; ?>
<input name="chkChunked" value="Send Chunked" type="checkbox"<?php echo $chked; ?>>
</div>
<h3>X-Arg:</h3>
<textarea id="x_arg" name="x_arg" readonly="readonly"
rows="4" value="<?php echo $x_arg?>"><?php echo $x_arg ?></textarea>
<h3>X-SpeechSubContext</h3>
<textarea id="x_subContext" name="x_arg" readonly="readonly" rows="4"
value="<?php echo $xSpeechSubContext?>"><?php echo $xSpeechSubContext?></textarea>
<br>
<button type="submit" id="btnSubmit" name="SpeechToText">Submit</button>
</div> <!-- end of formData -->
</form> <!-- end of SpeechToText form -->
</div> <!-- end of formContainer -->
<?php
if (isset($errors[SpeechController::ERROR_SPEECH_TO_TEXT])) {
$error = $errors[SpeechController::ERROR_SPEECH_TO_TEXT];
?>
<div class="errorWide">
<strong>ERROR:</strong><br><?php echo htmlspecialchars($error); ?>
</div>
<?php } else if (isset($results[SpeechController::RESULT_SPEECH_TO_TEXT])) {
$response = $results[SpeechController::RESULT_SPEECH_TO_TEXT];
?>
<div class="successWide">
<strong>SUCCESS:</strong> <br>Response parameters listed below.
</div>
<table class="kvp">
<thead>
<tr>
<th class="label">Parameter</th>
<th class="label">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td class="cell" align="center"><em><?php echo 'ResponseID'; ?></em></td>
<td class="cell" align="center"><em><?php echo $response->getResponseId(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'Status'; ?></em></td>
<td class="cell" align="center"><em><?php echo $response->getStatus(); ?></em></td>
</tr>
<?php
$nbest = $response->getNBest();
if ($nbest != NULL) { ?>
<tr>
<td class="cell" align="center"><em><?php echo 'Hypothesis'; ?></em></td>
<td class="cell" align="center"><em><?php echo $nbest->getHypothesis(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'LanguageId'; ?></em></td>
<td class="cell" align="center"><em><?php echo $nbest->getLanguageId(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'Confidence'; ?></em></td>
<td class="cell" align="center"><em><?php echo $nbest->getConfidence(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'Grade'; ?></em></td>
<td class="cell" align="center"><em><?php echo $nbest->getGrade(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'ResultText'; ?></em></td>
<td class="cell" align="center"><em><?php echo $nbest->getResultText(); ?></em></td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'Words'; ?></em></td>
<td class="cell" align="center">
<em><?php echo json_encode($nbest->getWords()); ?></em>
</td>
</tr>
<tr>
<td class="cell" align="center"><em><?php echo 'WordScores'; ?></em></td>
<td class="cell" align="center">
<em><?php echo json_encode($nbest->getWordScores()); ?></em>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</div> <!-- end of formBox -->
</div> <!-- end of content -->
<div id="footer">
<div id="ft">
<div id="powered_by">Powered by AT&amp;T Cloud Architecture</div>
<p>
The Application hosted on this site are working examples intended to be used for reference in creating
products to consume AT&amp;T Services and not meant to be used as part of your product. The data in
these pages is for test purposes only and intended only for use as a reference in how the services
perform.
<br> <br>
To access your apps, please go to
<a href="https://developer.att.com/developer/mvc/auth/login"
target="_blank">https://developer.att.com/developer/mvc/auth/login</a>
<br> For support refer to
<a href="https://developer.att.com/support">https://developer.att.com/support</a>
<br> <br>
&copy; 2014 AT&amp;T Intellectual Property. All rights reserved.
<a href="http://developer.att.com/" target="_blank">http://developer.att.com</a>
</p>
</div> <!-- end of ft -->
</div> <!-- end of footer -->
</div> <!-- end of page_container -->
</body>
</html>
<?php /*
de647198bfbadbd90f553513040339f4
0
f4a859292ac9b7177bc4057a9ec362c4dbd27203
*/ ?>
<?php
include($oauth_file);
function RefreshToken($FQDN,$api_key,$secret_key,$scope,$fullToken){
$refreshToken=$fullToken["refreshToken"];
$accessTok_Url = $FQDN."/oauth/token";
//http header values
$accessTok_headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
//Invoke the URL
$post_data="client_id=".$api_key."&client_secret=".$secret_key."&refresh_token=".$refreshToken."&grant_type=refresh_token";
$accessTok = curl_init();
curl_setopt($accessTok, CURLOPT_URL, $accessTok_Url);
curl_setopt($accessTok, CURLOPT_HTTPGET, 1);
curl_setopt($accessTok, CURLOPT_HEADER, 0);
curl_setopt($accessTok, CURLINFO_HEADER_OUT, 0);
curl_setopt($accessTok, CURLOPT_HTTPHEADER, $accessTok_headers);
curl_setopt($accessTok, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($accessTok, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($accessTok, CURLOPT_POST, 1);
curl_setopt($accessTok, CURLOPT_POSTFIELDS,$post_data);
$accessTok_response = curl_exec($accessTok);
$currentTime=time();
$responseCode=curl_getinfo($accessTok,CURLINFO_HTTP_CODE);
if($responseCode==200){
$jsonObj = json_decode($accessTok_response);
$accessToken = $jsonObj->{'access_token'};//fetch the access token from the response.
$refreshToken = $jsonObj->{'refresh_token'};
$expiresIn = $jsonObj->{'expires_in'};
if($expiresIn == 0) {
$expiresIn = 24*60*60;
}
$refreshTime=$currentTime+(int)($expiresIn); // Time for token refresh
$updateTime=$currentTime + ( 24*60*60); // Time to get for a new token update, current time + 24h
$fullToken["accessToken"]=$accessToken;
$fullToken["refreshToken"]=$refreshToken;
$fullToken["refreshTime"]=$refreshTime;
$fullToken["updateTime"]=$updateTime;
}
else{
$fullToken["accessToken"]=null;
$fullToken["errorMessage"]=curl_error($accessTok).$accessTok_response;
}
curl_close ($accessTok);
return $fullToken;
}
function GetAccessToken($FQDN,$api_key,$secret_key,$scope){
$accessTok_Url = $FQDN."/oauth/token";
//http header values
$accessTok_headers = array(
'Content-Type: application/x-www-form-urlencoded'
);
//Invoke the URL
$post_data = "client_id=".$api_key."&client_secret=".$secret_key."&scope=".$scope."&grant_type=client_credentials";
$accessTok = curl_init();
curl_setopt($accessTok, CURLOPT_URL, $accessTok_Url);
curl_setopt($accessTok, CURLOPT_HTTPGET, 1);
curl_setopt($accessTok, CURLOPT_HEADER, 0);
curl_setopt($accessTok, CURLINFO_HEADER_OUT, 0);
curl_setopt($accessTok, CURLOPT_HTTPHEADER, $accessTok_headers);
curl_setopt($accessTok, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($accessTok, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($accessTok, CURLOPT_POST, 1);
curl_setopt($accessTok, CURLOPT_POSTFIELDS,$post_data);
$accessTok_response = curl_exec($accessTok);
$responseCode=curl_getinfo($accessTok,CURLINFO_HTTP_CODE);
$currentTime=time();
/*
If URL invocation is successful fetch the access token and store it in session,
else display the error.
*/
if($responseCode==200)
{
$jsonObj = json_decode($accessTok_response);
$accessToken = $jsonObj->{'access_token'};//fetch the access token from the response.
$refreshToken = $jsonObj->{'refresh_token'};
$expiresIn = $jsonObj->{'expires_in'};
if($expiresIn == 0) {
$expiresIn = 24*60*60*365*100;
}
$refreshTime=$currentTime+(int)($expiresIn); // Time for token refresh
$updateTime=$currentTime + ( 24*60*60); // Time to get for a new token update, current time + 24h
$fullToken["accessToken"]=$accessToken;
$fullToken["refreshToken"]=$refreshToken;
$fullToken["refreshTime"]=$refreshTime;
$fullToken["updateTime"]=$updateTime;
}else{
$fullToken["accessToken"]=null;
$fullToken["errorMessage"]=curl_error($accessTok).$accessTok_response;
}
curl_close ($accessTok);
return $fullToken;
}
function SaveToken( $fullToken,$oauth_file ){
$accessToken=$fullToken["accessToken"];
$refreshToken=$fullToken["refreshToken"];
$refreshTime=$fullToken["refreshTime"];
$updateTime=$fullToken["updateTime"];
$tokenfile = $oauth_file;
$fh = fopen($tokenfile, 'w');
$tokenfile="<?php \$accessToken=\"".$accessToken."\"; \$refreshToken=\"".$refreshToken."\";?>";
fwrite($fh,$tokenfile);
fclose($fh);
}
function check_token( $FQDN,$api_key,$secret_key,$scope, $fullToken,$oauth_file){
$currentTime=time();
if ( ($fullToken["updateTime"] == null) || ($fullToken["updateTime"] <= $currentTime)){
$fullToken=GetAccessToken($FQDN,$api_key,$secret_key,$scope);
if( $fullToken["accessToken"] == null ){
// echo $fullToken["errorMessage"];
}else{
// echo $fullToken["accessToken"];
SaveToken( $fullToken,$oauth_file );
}
}
elseif ($fullToken["refreshTime"]<= $currentTime){
$fullToken=RefreshToken($FQDN,$api_key,$secret_key,$scope, $fullToken);
if( $fullToken["accessToken"] == null ){
// echo $fullToken["errorMessage"];
}else{
// echo $fullToken["accessToken"];
SaveToken( $fullToken,$oauth_file );
}
}
return $fullToken;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment