Microsoft-Translator
view release on metacpan or search on metacpan
lib/Microsoft/Translator.pm view on Meta::CPAN
package Microsoft::Translator 0.001;
# ABSTRACT: Client wrapper for Microsoft Translator's REST API
use strict;
use warnings;
no warnings qw{experimental};
use feature qw{signatures state};
use Clone;
use Ref::Util qw{is_arrayref is_hashref};
use UUID::Tiny;
use HTTP::Tiny;
use Cpanel::JSON::XS;
use List::Util;
use Data::Dumper;
sub new( $class, $secret_key, $region, $debug ) {
return bless({ key => $secret_key, region => $region, debug => $debug }, $class);
}
sub _request ( $self, $path, $method, $params={}, $input=undef ) {
state $endpoint = 'https://api.cognitive.microsofttranslator.com/';
state $client = HTTP::Tiny->new();
# Version this module is developed against
$params->{'api-version'} = '3.0',
my $uuid = UUID::Tiny::create_uuid_as_string( UUID::Tiny::UUID_V1, UUID::Tiny::UUID_NS_DNS );
my $querystring = join('&', (map {
my $key = $_;
is_arrayref($params->{$_}) ? join("&", (map { "$key=$_" } @{$params->{$key}})) : "$key=$params->{$key}"
} keys(%$params)));
my $uri = "$endpoint$path?$querystring";
my $body = $input ? Cpanel::JSON::XS::encode_json( $input ) : undef;
my $response = $client->_request($method, $uri, {
headers => {
'Ocp-Apim-Subscription-Key' => $self->{key},
'Ocp-Apim-Subscription-Region' => $self->{region},
'Content-Type' => 'application/json',
'X-ClientTraceId' => $uuid,
},
content => $body,
});
print "$method $uri\n" if $self->{debug};
die "Request Failed: ".Dumper($response) unless $response->{success};
print "Raw Response:\n$response->{content}\n" if $self->{debug};
my $decoded = Cpanel::JSON::XS::decode_json( $response->{content} );
return $decoded;
}
sub translate ( $self, $strings=[], $source_lang="en", @target_langs ) {
return () unless @$strings;
die "Must pass at least one target language" unless @target_langs;
$self->_valid_langs('translation', $source_lang, @target_langs);
my %params = (
from => $source_lang,
to => [@target_langs]
);
( run in 3.117 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )