I want to make a simple script that uses google speech recognition, I have tried various ways so that I can access the API with Request Body, but has always failed.
Example URL: https://content-speech.googleapis.com/v1/speech:recognize?prettyPrint=true&alt=json&key=AIzaSyD-XXXXXXXXXXXXXXXXX-Al7hLQDbugrDcw
JSON example:
{
"audio": {
"content": "ZkxhQwAAACIEg....more......FzSi6SngVApeE="
},
"config": {
"encoding": "FLAC",
"sampleRateHertz": 16000,
"languageCode": "en-US"
}
}
Documentation:
https://cloud.google.com/speech-to-text/docs/basics
Code samples:
https://cloud.google.com/speech-to-text/docs/samples
Consider using a library:
Google Cloud Client Library PHP (also has code samples):
https://googlecloudplatform.github.io/google-cloud-php/#/docs/google-cloud/v0.61.0/speech/speechclient
Speech-to-Text Client Libraries
https://cloud.google.com/speech-to-text/docs/reference/libraries#client-libraries-install-php
Speaker is a 3.party library you could use:
https://github.com/duncan3dc/speaker
Quick example from google/cloud-speech:
Install:
composer require google/cloud-speech
Sample:
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Speech\SpeechClient;
# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';
# Instantiates a client
$speech = new SpeechClient([
'projectId' => $projectId,
'languageCode' => 'en-US',
]);
# The name of the audio file to transcribe
$fileName = __DIR__ . '/resources/audio.raw';
# The audio file's encoding and sample rate
$options = [
'encoding' => 'LINEAR16',
'sampleRateHertz' => 16000,
];
# Detects speech in the audio file
$results = $speech->recognize(fopen($fileName, 'r'), $options);
foreach ($results as $result) {
echo 'Transcription: ' . $result->alternatives()[0]['transcript'] . PHP_EOL;
}
Related
i tried a system s3 object storage from idrive and i did composer install for composer require aws/aws-sdk-php.
but it shows error like that in my code window.
enter image description here
<?php
require "../vendor/autoload.php";
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
// Create an S3 client for IDrive e2
$profile_credentials = [
"profile" => "default",
"endpoint" => "l4g4.ch11.idrivee2-2.com",
"region" => "Chicago",
"version" => "latest",
"use_path_style_endpoint" => true,
];
$s3 = S3Client::factory($profile_credentials);
// Get list of buckets
try {
$buckets = $s3->listBuckets();
// print bucket names
foreach ($buckets["Buckets"] as $bucket) {
echo "{$bucket["Name"]}\n";
}
} catch (AwsException $e) {
echo "Error: {$e->getMessage()}" . PHP_EOL;
}
I just want an example for this s3 object strong to work I have also tried things on the amazon aws documentation but haven't found any results and the error keeps coming
I'm trying desperately to figure out how to create a simple audio transcription script (for longer audio files) via PHP (the only language I know). I'm getting the error Class 'Google\Cloud\Storage\StorageClient' not found
I'm using the gcloud console code editor and everything should be installed (unless there is a separate composer install just for cloud storage, although I haven't been able to find anything about it in the documentation if there is).
I also entered gcloud auth application-default print-access-token which printed out an access token, but I don't know what (if any) I'm supposed to do with that other than the "set GOOGLE_APPLICATION_CREDENTIALS" command that I copied and pasted into the console shell prompt.
Here's the php code:
<?php
namespace Google\Cloud\Samples\Speech;
require __DIR__ . '/vendor/autoload.php';
use Exception;
# [START speech_transcribe_async_gcs]
use Google\Cloud\Speech\SpeechClient;
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\ExponentialBackoff;
$projectId = 'xxxx';
$speech = new SpeechClient([
'projectId' => $projectId,
'languageCode' => 'en-US',
]);
$filename = "20180925_184741_L.mp3";
# The audio file's encoding and sample rate
$options = [
'encoding' => 'LINEAR16',
'sampleRateHertz' => 16000,
'languageCode' => 'en-US',
'enableWordTimeOffsets' => false,
'enableAutomaticPunctuation' => true,
'model' => 'video',
];
function transcribe_async_gcs($bucketName, $objectName, $languageCode = 'en-US', $options = [])
{
// Create the speech client
$speech = new SpeechClient([
'languageCode' => $languageCode,
]);
// Fetch the storage object
$storage = new StorageClient();
$object = $storage->bucket($bucketName)->object($objectName);
// Create the asyncronous recognize operation
$operation = $speech->beginRecognizeOperation(
$object,
$options
);
// Wait for the operation to complete
$backoff = new ExponentialBackoff(10);
$backoff->execute(function () use ($operation) {
print('Waiting for operation to complete' . PHP_EOL);
$operation->reload();
if (!$operation->isComplete()) {
throw new Exception('Job has not yet completed', 500);
}
});
// Print the results
if ($operation->isComplete()) {
$results = $operation->results();
foreach ($results as $result) {
$alternative = $result->alternatives()[0];
printf('Transcript: %s' . PHP_EOL, $alternative['transcript']);
printf('Confidence: %s' . PHP_EOL, $alternative['confidence']);
}
}
}
# [END speech_transcribe_async_gcs]
transcribe_async_gcs("session_audio", $filename, "en-US", $options);
With apologies, PHP is not a language I'm proficient with but, I suspect you haven't (and must) install the client library for Cloud Storage so that your code may access it. This would explain its report that the Class is missing.
The PHP client library page includes two alternatives. One applies if you're using Composer, the second -- possibly what you want -- a direct download which you'll need to path correctly for your code.
Some time ago, I wrote a short blog post providing a simple example (using Cloud Storage) for each of Google's supported languages. Perhaps it will help you too.
I am trying to make a PHP application using which I can send a .flac file to the google speech service and get text in return.
Following the official guide
This is the authentication code:
require 'vendor/autoload.php';
use Google\Cloud\Core\ServiceBuilder;
// Authenticate using keyfile data
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
Then this is the speech code:
use Google\Cloud\Speech\SpeechClient;
$speech = new SpeechClient([
'languageCode' => 'en-US'
]);
// Recognize the speech in an audio file.
$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";
}
Of course the $cloud variable is never used. Where should it go?
I ran it nonetheless got
Uncaught exception 'Google\Cloud\Core\Exception\ServiceException'
with message '{ "error": { "code": 401, "message": "Request had
invalid authentication credentials. Expected OAuth 2 access token,
login cookie or other valid authentication credential. See
https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED" } }
I just want to make a simple query. Any help would be appreciated.
Try this:
use Google\Cloud\Speech\SpeechClient;
$speech = new SpeechClient([
'languageCode' => 'en-US',
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
// Recognize the speech in an audio file.
$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";
}
You bring up a good point regarding the documentation. Changes over the last few months have caused this somewhat confusing situation, and it deserves another look to clarify things. I've created an issue to resolve this.
ServiceBuilder is a class which provides factories allowing you to configure Google Cloud PHP once and create different clients (such as Speech or Datastore) which inherit that configuration. All the options on ServiceBuilder::__construct() are also available in the clients themselves, such as SpeechClient, with a couple of exceptions.
If you want to use the ServiceBuilder, you could do something like this:
use Google\Cloud\Core\ServiceBuilder;
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('b.json'), true)
]);
$speech = $cloud->speech([
'languageCode' => 'en-us'
]);
Alternatively, you can call putenv before before working with api:
/** Setting Up Authentication. */
$key_path = '/full/path/to/key-file.json';
putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . $key_path );
i am new in firebase web if it possible to upload, download, and delete file using php. i have upload file using JS but i want to download using PHP.
Here is script of download file using JS but i want in PHP.
Thanks in advance...
My Code
[START storage_quickstart]
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
# Your Google Cloud Platform project ID
$projectId = 'My project ID';
# Instantiates a client
$storage = new StorageClient([
'projectId' => $projectId
]);
# The name for the new bucket
$bucketName = 'my bucket';
# Creates the new bucket
$bucket = $storage->createBucket($bucketName);
echo 'Bucket ' . $bucket->name() . ' created.';
# [END storage_quickstart]
return $bucket;
The short answer is that you should use gcloud-php. This requires that you set up a service account (or use Google Compute Engine/Container Engine/App Engine which provide default credentials).
It's likely that you'll create a service account, download a keyfile.json, and provide it as an argument to the StorageClient, like so:
# Instantiates a client
$storage = new StorageClient([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => $projectId
]);
Alternatively, it looks like they've built another layer of abstraction, which takes the same arguments but allows you to use lots of other services:
use Google\Cloud\ServiceBuilder;
$gcloud = new ServiceBuilder([
'keyFilePath' => '/path/to/key/file.json',
'projectId' => 'myProject'
]);
$storage = $gcloud->storage();
$bucket = $storage->bucket('myBucket');
That's an old question, but I was struggling with same problem... hope my solution help someone.
In fact, I really don't know if there is an official way to do that, but I created the method below and it worked for me.
function storageFileUrl($name, $path = []) {
$base = 'https://firebasestorage.googleapis.com/v0/b/';
$projectId = 'your-project-id';
$url = $base.$projectId.'/o/';
if(sizeof($path) > 0) {
$url .= implode('%2F', $path).'%2F';
}
return $url.$name.'?alt=media';
}
To access files in the root of bucket:
$address = storageFileUrl('myFile');
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/myFile?alt=media
To access files inside some folder, do:
$address = storageFileUrl('myFile', ['folder', 'subfolder']);
Result: https://firebasestorage.googleapis.com/v0/b/your-project-id.appspot.com/o/folder%2Fsubfolder%2FmyFile?alt=media
Enjoy.
I'm trying to setup Google Bigquery with Firebase and am having some issues. I have gcloud installed on my machine (MacOS Sierra) and have google cloud installed via composer on my project.
The following code on my project:
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
# Your Google Cloud Platform project ID
$projectId = 'hidden here only';
# Instantiates a client
$bigquery = new BigQueryClient([
'projectId' => $projectId
]);
# The name for the new dataset
$datasetName = 'test_dataset';
# Creates the new dataset
$dataset = $bigquery->createDataset($datasetName);
echo 'Dataset ' . $dataset->id() . ' created.';
All I'm trying to do is just create a dataset within bigquery via the library but I'm not able to due to the following error:
Fatal error: Uncaught Google\Cloud\Exception\ServiceException: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information in /Applications/MAMP/htdocs/projects/work/bigquery-tests/vendor/google/cloud/src/RequestWrapper.php on line 219
I've tried running gcloud beta auth applications-default login as the example code says to do but after logging in on the browser, the error is still present. Any help would be great, thanks!
You were very close, just you need to setup the service account default credentials see lines with putenv and useApplicationDefaultCredentials(). This is a working code I have using the library https://github.com/google/google-api-php-client You need to obtain your service account key file from the console: https://console.cloud.google.com/iam-admin/serviceaccounts/
composer.json
{
"require": {
"google/cloud": "^0.13.0",
"google/apiclient": "^2.0"
}
}
php file
# Imports the Google Cloud client library
use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\ServiceBuilder;
$query="SELECT repository_url,
repository_has_downloads
FROM [publicdata:samples.github_timeline]
LIMIT 10";
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.dirname(__FILE__) . '/.ssh/dummyname-7f0004z148e1.json');//this can be created with other ENV mode server side
$client->useApplicationDefaultCredentials();
$builder = new ServiceBuilder([
'projectId' => 'edited',
]);
$bigQuery = $builder->bigQuery();
$job = $bigQuery->runQueryAsJob($query);
$info=$job->info();
// print_r($info);
// exit;
$queryResults = $job->queryResults();
/*$queryResults = $bigQuery->runQuery(
$query,
['useLegacySql' => true]);*/
if ($queryResults->isComplete())
{
$i = 0;
$rows = $queryResults->rows();
foreach ($rows as $row)
{
$i++;
$result[$i] = $row;
}
}
else
{
throw new Exception('The query failed to complete');
}
print_r($result);