Hi im trying to translate this python script to php. I don't have much knowledge of Python and limited for PHP.
The python script is:
import urllib2
import json
data = {
"Inputs": {
"input1": {
"ColumnNames": ["Client_ID"],
"Values": [ [ "0" ], [ "0" ], ]
},
},
"GlobalParameters": {}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14b17422435984943d51b5957ec7/execute?api-version=2.0&details=true'
api_key = 'abc123'
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
try:
response = urllib2.urlopen(req)
result = response.read()
print(result)
except urllib2.HTTPError, error:
print("The request failed with status code: " + str(error.code))
print(error.info())
print(json.loads(error.read()))
In a bid to try and convert it myself, here is what I have done so far:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => ["Client_ID"],
'Values' => [ [ "0" ], [ "0" ], ]
),
),
'GlobalParameters'=> array()
);
$body = json_encode($data);
$url = 'https://ussouthcentral.services.azureml.net/workspaces/3e1515433b9d477f8bd02b659428cddc/services/cb1b14d17425435984943d41a5957ec7/execute?api-version=2.0&details=true';
$api_key = 'abc123';
$headers = array('Content-Type'=>'application/json', 'Authorization'=>('Bearer '+ $api_key));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl);
var_dump($result);
im sure I have got lots wrong but would appreciate the help.
thanks
I just had to do this myself and though I'd provide an answer for you. If you're going to talk to Azure's ML platform using php, you need to build your CURL call like this:
$data = array(
'Inputs'=> array(
'input1'=> array(
'ColumnNames' => array("header1", "header2", "header3"),
'Values' => array( array("value1" , "value2" , "value3"))
),
),
'GlobalParameters'=> null
);
$body = json_encode($data);
$url = 'your-endpoint-url';
$api_key = 'your-api-key';
$headers = array('Content-Type: application/json', 'Authorization:Bearer ' . $api_key, 'Content-Length: ' . strlen($body));
$this->responseArray['body'] = $body;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
Of all the places to get hung up, it was on the GlobalParameters for me, and is for you, too. You need this instead:
GlobalParameters => null
This generates the following JSON
GlobalParameters: {}
whereas
GlobalParameters => array()
gives
GlobalParameters: []
it's a subtle distinction, but enough to make Azure throw a hissy fit.
I didn't test using your curl_setopt functions and instead used what I've included in my example. I'm assuming it will work using the curl_setopts you have, but I don't know for sure.
I had some trouble adapting this perfectly, and I wanted to be able to easily work with JSON & Guzzle. Below is the solution that I built.
First is the function for making the actual call to Azure. Note that Guzzle wants your URL to be split into the domain and URI pieces.
This should all be in your .env file (if you're using Laravel at least).
AZURE_BASE=https://ussouthcentral.services.azureml.net
AZURE_URL=/workspaces/[[YOUR_STUFF_HERE]]/services/[[YOUR_STUFF_HERE]]/execute?api-version=2.0&format=swagger
AZURE_PRIMARY_KEY=[[YOUR_KEY]]
use GuzzleHttp\Client;
public function learn () {
$client = new Client([
'base_uri' => env('AZURE_BASE'),
'timeout' => 2.0,
]);
$headers = [
'Authorization' => 'Bearer ' .env('AZURE_PRIMARY_KEY'),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
];
$data = $this->test_data();
$body = json_encode($data);
$response = $client->request('POST', env('AZURE_URL'), [
'headers' => $headers,
'body' => $body
]);
return $response;
}
As other answers have noted, the data setup is very touchy. new \stdClass is the key here, as we need to end up with a JSON Object ({}) not an array ([]). stdClass creates that empty object for us.
function test_data () {
return array(
'Inputs'=> array(
'input1'=> array(
[
'DESC' => "",
'2-week-total'=> "1",
'last-week'=> "1",
'this-week'=> "1",
'delta'=> "1",
'normalized delta'=> "1",
'delta-percent'=> "1",
'high-total-delta'=> "1",
'high-total-amt'=> "1",
'role'=> ""
]
),
),
'GlobalParameters'=> new \stdClass,
);
}
Now when you call ->learn(), you'll get back some nice JSON to do what you need.
Related
I am having trouble finding out why my script is returning "result":null,"error" rather than a successful transaction.
This curl command works when run manually;
curl --user username:password --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "sendtoaddress", "params": ["someaddress", 0.001] }' -H 'content-type: text/plain;' http://".199.42.160.41:8332
Here is the code I'm using attempting to replicate the above curl command which works;
$url = "http://199.42.160.41:8332";
$address = "address";
$address = '"'.$address.'"'; //Adding double quotation marks around the address.
$amount = 0.001;
$bounty = $address.', '.$amount;
$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$bounty] ];
$payload=json_encode($payload);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res=curl_exec($ch);
echo "<br/><br/>";
echo "Result from attempting to send transaction is below this line</br>";
print_r($res);
curl_close($ch);
With the above I can see that $payload is set as follows;
$payload is set to the following;
Array ( [jsonrpc] => 1.0 [id] => curltest [method] => sendtoaddress [params] => Array ( [0] => "sendtoaddress", 0.001 ) )
What am I missing or doing wrong?
Edit: My $payload looks like this once it's been converted to jsonrpc
{"jsonrpc":"1.0","id":"curltest","method":"sendtoaddress","params":["someaddress, 0.001"]}
From what I can tell, I need to have it look like this;
{"jsonrpc":"1.0","id":"curltest","method":"sendtoaddress","params":["someaddress", 0.001]}
Found and fixed the issue. $payload wasn't what I needed, I needed to use two variables for it to be formatted correctly for jsonrpc.
//$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$bounty] ];
$payload = ["jsonrpc" => "1.0", "id" => "curltest", "method" => "sendtoaddress", "params" => [$address, $amount] ];
Now that $payload is set correctly the script works!
I am trying to use google's text to speech in my php website to be hosted on a live Cpanel Server
I have enabled the text to speech API, Created API KEY in Credentials section, also downloaded the json file of credentials from Create service account key page.
Then I downloaded the sample files from Github and also used composer to build the library
Now I dont understand where to put my keys. At every place, it demangs to EXPORT the key in Shell, but that would work for 1 open command prompt session and will have to be exported every time.
As I want to run this code on a live cpanel based hosting, so I think it wont be possible to export.
Is there any place within the codes where I can pass the key?
On this url article at stackoverflow: the first answer exports the response of CURL to synthesize-text.txt but we require mp3 output
Another answer states that we should use jq but since its a shared hsoting server, I am not sure if we can arrange jq.
Is ther any way out to this problem?
Update
Tried the following code after referring to the answer by #V.Tur
$params = [
"audioConfig"=>[
"audioEncoding"=>"MP3",
"pitch"=> "1",
"speakingRate"=> "1",
"effectsProfileId"=> [
"medium-bluetooth-speaker-class-device"
]
],
"input"=>[
"ssml"=>'<speak>The <say-as interpret-as=\"characters\">SSML</say-as>
standard <break time=\"1s\"/>is defined by the
<sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>'
],
"voice"=>[
"languageCode"=> "hi-IN",
"name" =>"hi-IN-Wavenet-B",
'ssmlGender'=>'MALE'
]
];
$data_string = json_encode($params);
$speech_api_key = "My_Key_Here";
$url = 'https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=' . $speech_api_key;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
]
);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
if($responseDecoded['audioContent']){
return $responseDecoded['audioContent'];
}
I get the audio downloaded but the pauses/breaks I have mentioned in ssml did not work. I tried passing data to $params as below
$params = "{
'input':{
'ssml':'<speak>The <say-as interpret-as=\"characters\">SSML</say-as>
standard <break time=\"1s\"/>is defined by the
<sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>'
},
'voice':{
'languageCode':'en-us',
'name':'en-US-Standard-B',
'ssmlGender':'MALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
}";
But I get the following error:
Array ( [error] => Array ( [code] => 400 [message] => Invalid JSON
payload received. Unknown name "": Root element must be a message.
[status] => INVALID_ARGUMENT [details] => Array ( [0] => Array (
[#type] => type.googleapis.com/google.rpc.BadRequest [fieldViolations]
=> Array ( [0] => Array ( [description] => Invalid JSON payload received. Unknown name "": Root element must be a message. ) ) ) ) ) )
How to solve this?
Below my working example text-to-speech, you could redo for your needs:
public static function getSound($text)
{
$text = trim($text);
if($text == '') return false;
$params = [
"audioConfig"=>[
"audioEncoding"=>"LINEAR16",
"pitch"=> "1",
"speakingRate"=> "1",
"effectsProfileId"=> [
"medium-bluetooth-speaker-class-device"
]
],
"input"=>[
"text"=>$text
],
"voice"=>[
"languageCode"=> "en-US",
"name" =>"en-US-Wavenet-F"
]
];
$data_string = json_encode($params);
$url = 'https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=' . $speech_api_key;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
]
);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
if($responseDecoded['audioContent']){
return $responseDecoded['audioContent'];
}
return false;
}
using:
public static function saveSound($text)
{
$speech_data = SpeechAPI::getSound($text);//see method upper
if($speech_data) {
$file_name = strtolower(md5(uniqid($text)) . '.mp3');
$path = FileUpload::getFolder();//just return directory path
if(file_put_contents($path.$file_name, base64_decode($speech_data))){
return $file_name;
}
}
return null;
}
For SSML standart need to change input params:
$text = "<speak>The <say-as interpret-as=\"characters\">SSML</say-as>
standard <break time=\"1s\"/>is defined by the
<sub alias=\"World Wide Web Consortium\">W3C</sub>.</speak>";
$params = [
"audioConfig"=>[
"audioEncoding"=>"LINEAR16",
"pitch"=> "1",
"speakingRate"=> "1",
"effectsProfileId"=> [
"medium-bluetooth-speaker-class-device"
]
],
"input"=>[
//"text"=>$text
"ssml" => $text
],
"voice"=>[
"languageCode"=> "en-US",
"name" =>"en-US-Wavenet-F"
]
];
about choose audioEncoding - https://cloud.google.com/speech-to-text/docs/encoding
I am trying to create a Sales Invoice through Sage Accounting API calls (its documentation can be found here: https://developer.sage.com/api/accounting/api/)
To make my code clearer I have created a class that helps me make those calls accordingly.
Here is the method I use to make those calls:
public function postRequest()
{
$url = $this->baseEndpoint . $this->request;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if (isset($this->params)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer $this->token",
"Host: api.accounting.sage.com",
"Content-Type: application/json"
));
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
return $response;
}
How I call this method:
$params = array(
"sales_invoice" => array(
"contact_id" => "485fdfe0be154f9c9af44351de16e5be",
"date" => "2019-06-13",
"invoice_lines" => array(
array(
"description" => "description",
"ledger_account_id" => "f04157c90ff0496ab3a22f2558e46010",
"unit_price" => 10 ,
"quantity" => 1,
"tax_rate_id" => "ES_RE_STANDARD",
"tax_rate" => 0.1
)
)
)
);
$params = json_encode($params);
$request = "v3.1/sales_invoices";
$sageRequest = new SageRequest($token, $request, $params);
$sageRequest->postRequest();
According to the API documentation, that should work, but still I get this error:
[$severity] => error
[$dataCode] => UnexpectedError
[$message] => An unexpected error occurred.
[$source] =>
If there is anyone who has some experience with the Sage Accounting API, I would be more than grateful to know what I have done wrong.
This example works for me on a Spanish business:
{
"sales_invoice": {
"contact_id": "22b609fba11642238f2ecd0f5fe3e0b5",
"date": "2019-06-12",
"invoice_lines": [
{
"description": "Description",
"ledger_account_id": "829739738de811e996c90122ae3d08ca",
"quantity": 1,
"unit_price": 100,
"tax_rate_id": "ES_STANDARD"
}
],
"main_address": {
"city": "Madrid"
}
}
}
Make sure your contact is listed in the contact endpoint. Use GET https://api.accounting.sage.com/v3.1/ledger_accounts?visible_in=sales to get a list of all valid ledger accounts for sales objects.
I see your question uses ES_RE_STANDARD as tax rate. I will update this answer soon with an example for the "recargo de equivalencia" tax rate.
So i have this working in ruby and i want to be able to do this in php. I am using the wamp server if that matters.
Here's the ruby method:
def response(url, body)
uri = URI(url)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = body
http_session = Net::HTTP.new(uri.hostname, uri.port)
http_session.use_ssl = (uri.scheme == "https")
http_session.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http_session.request(request)
return response.body
end
I tried looking up other questions and this is where that got me:
$request_info = array();
$REQUEST_BODY = 'request body';
$full_response = #http_post_data(
'url',
$REQUEST_BODY,
array(
'headers' => array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
),
'timeout' => 60,
),
$request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//#HotelName') as $HotelName) {
echo strval($HotelName) . "\n";
}
http_post_data depends on pecl_http. Unless you must use http_post_data, cURL is probably installed by default on your WAMP server.
The code below is just an example; I haven't tested it but you get the idea:
$headers = array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
);
$ch = curl_init($server_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$full_response = curl_exec($ch);
curl_close($ch);
I'm sending a text push from the php API code successfully, but I wonder how to send the JSON also from the PHP API
My problem is that when I send JSON from the PHP API code it received like like a "message" type.
When i send the same JSON code from the parse control panel it works fine
I so some hint to send "uri" key in the data, but it didn't help.
What am I missing?
Thanks.
this is the PHP code that i'm using
<?php
$APPLICATION_ID = "gggggggggggggggg";
$REST_API_KEY = "xxxxxxxxxxxxxxxxxxx";
//$MESSAGE = "your-alert-message";
if (!empty($_POST)) {
$errors = array();
foreach (array('app' => 'APPLICATION_ID', 'api' => 'REST_API_KEY', 'body' => 'MESSAGE') as $key => $var) {
if (empty($_POST[$key])) {
$errors[$var] = true;
} else {
$$var = $_POST[$key];
}
}
if (!$errors) {
$url = 'https://api.parse.com/1/push';
if(strstr($MESSAGE,"{")){ //json
$data['data_type']='json';
//$MESSAGE = json_decode($MESSAGE);
}
//, 'uri' => $MESSAGE
$data = array(
'channel' => 'test1',
'type' => 'android',
'expiry' => 1451606400,
'data_type' => 'json',
'data' =>array(
'alert'=> "the link2",
'uri' => $MESSAGE
),
'uri' => $MESSAGE
);
//var_dump( $data );die;
//if(strstr($MESSAGE,"{")) //json
//$data['data_type']='json';
$_data = json_encode($data);
//var_dump( $_data );die;
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data)
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
}
?>
In the parse.com website there is a tool that you can send PUSH and in this tool you can send push with 2 types: plain text, or JSON.
it's look like that
When I try to send push with this parse.com tool in both types it works fine and I get the push properly
But, when I try to send to push from my PHP API code as a "JSON" I always got it as a "plain text"
What am I'm doing wrong ?
It depends on your JSON structure for example i want to send this:
{
"data": {
"date": "2015-12-09",
"message": "and when you open this we will show you a message.",
"title": "6 Notice Click On It :)))",
"url": ""
},
"is_background": false
}
and in your php you should send like this:
$data = array(
'where' => '{}', // send to all users
// 'channels' => '{my_channel_name}',
'data' => array(
'is_background'=>false,
'data'=>array(
'date'=>'2015-12-09',
'message'=>'and when you open this we will show you a message',
'title'=>' Notice Click On It',
'url'=>''
),
),
);