public function testFromArray() { $str = ' { "Recognition": { "Status": "Ok", "ResponseId": "3125ae74122628f44d265c231f8fc926", "NBest": [ { "Hypothesis": "bookstores in glendale california", "LanguageId": "en-us", "Confidence": 0.9, "Grade": "accept", "ResultText": "bookstores in Glendale, CA", "Words": ["bookstores", "in", "glendale","california"], "WordScores": [0.92, 0.73, 0.81, 0.96] } ] } } '; $arr = json_decode($str, true); $r = SpeechResponse::fromArray($arr); $this->assertEquals($r->getResponseId(), '3125ae74122628f44d265c231f8fc926'); $this->assertEquals($r->getStatus(), 'Ok'); $nb = $r->getNBest(); $this->assertEquals($nb->getHypothesis(), 'bookstores in glendale california'); $this->assertEquals($nb->getLanguageId(), 'en-us'); $this->assertEquals($nb->getConfidence(), 0.9); $this->assertEquals($nb->getGrade(), "accept"); $this->assertEquals($nb->getResultText(), 'bookstores in Glendale, CA'); $this->assertEquals($nb->getWords()[0], 'bookstores'); $this->assertEquals($nb->getWordScores()[0], 0.92); }
/** * Sends a request to the API for converting speech to text. * * @param string $fname file location that contains speech * to convert. * @param string $speechContext speech context to use. * @param string|null $speechSubContext speech sub context to use, if not * null. * @param string|null $xArg optional arguments to use, if not * null. * @param boolean $chunked whether to send the request chunked. * * @return SpeechResponse API response as a SpeechResponse object. * @throws ServiceException if API request was not successful. */ public function speechToText($fname, $speechContext, $speechSubContext = null, $xArg = null, $chunked = true) { // read file $fileResource = fopen($fname, 'r'); if (!$fileResource) { throw new InvalidArgumentException('Could not open file ' . $fname); } $fileBinary = fread($fileResource, filesize($fname)); fclose($fileResource); $endpoint = $this->getFqdn() . '/speech/v3/speechToText'; $req = new RESTFulRequest($endpoint); $req->setAuthorizationHeader($this->getToken())->setHeader('Accept', 'application/json')->setHeader('Content-Type', $this->_getFileMIMEType($fname))->setHeader('X-SpeechContext', $speechContext); if ($chunked) { $req->setHeader('Content-Transfer-Encoding', 'chunked'); } else { $req->setHeader('Content-Length', filesize($fname)); } if ($xArg != null) { $req->setHeader('xArg', $xArg); } if ($speechSubContext != null) { $req->setHeader('X-SpeechSubContext', $speechSubContext); } $httpPost = new HttpPost(); $httpPost->setBody($fileBinary); $result = $req->sendHttpPost($httpPost); $jsonArr = Service::parseJson($result); return SpeechResponse::fromArray($jsonArr); }