blib/lib/Lingua/Translator/Microsoft.pm

filter: Statementstmt 98.0% 102 / 104 Branchbran 66.6% 4 / 6 Conditioncond 100% 7 / 7 MC/DCmcdc 100% 4 / 4 Subroutinesub 100% 25 / 25 Podpod 100% 4 / 4 totaltotal 97.3% 146 / 150 CC 7 SCAR 4.2
CC
7
Cov
97%
get_translations
3.0
_get_token
3.0
_make_api_call
2.0
CRAP 1.5
↑ Summary
1 package Lingua::Translator::Microsoft;
2 2 ▶use 5.10.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 2 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use MooseX::HasDefaults::RO;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use MooseX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Params::Validate qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use XML::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 2 our $VERSION = qv('1.0.1');
18  
19 2 has api_key => (
20 isa => 'Str',
21 required => 1,
22 );
23  
24 2 has app_id => (
25 isa => 'Str',
26 required => 1,
27 );
28  
29 2 has auth_url => (
30 isa => 'Str',
31 default => 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
32 );
33  
34 2 has api_url => (
35 isa => 'Str',
36 default => 'http://api.microsofttranslator.com/v2/Http.svc',
37 );
38  
39 # so that the token doesn't expire after checking it but before the request
40 # is processed on the other side.
41 2 has token_expiry_shift => (
42 isa => 'Str',
43 required => 0,
44 default => 10,
45 );
46  
47 has clock => (
48 isa => 'CodeRef',
49 8 ▶ default => sub {sub {time}}
Subroutine __ANON__: called CC=1 SCAR=0.0
50 2 );
51  
52 2 has ua_string => (
53 isa => 'Str',
54 default => "Lingua-Translator-Microsoft/$VERSION",
55 );
56  
57 2 has _token => (
58 is => 'rw',
59 isa => 'Maybe[Str]',
60 default => undef,
61 init_arg => undef,
62 );
63  
64 2 has _token_expiry => (
65 is => 'rw',
66 isa => 'Int',
67 default => 0,
68 init_arg => undef,
69 );
70  
71 2 has _ua_token => (
72 isa => 'LWP::UserAgent',
73 builder => '_build_ua_token',
74 lazy => 1,
75 init_arg => undef,
76 );
77  
78 2 has _ua_bing => (
79 isa => 'LWP::UserAgent',
80 builder => '_build_ua_bing',
81 lazy => 1,
82 init_arg => undef,
83 );
84  
85 sub _build_ua_token {
86 8 ▶ my $self = shift;
Subroutine _build_ua_token: called CC=1 SCAR=0.0
87 8 my $ua = LWP::UserAgent->new(
88 agent => $self->ua_string,
89 );
90 8 $ua->default_header(
91 'Content-Type' => 'application/x-www-form-urlencoded'
92 );
93 8 return $ua;
94 }
95  
96 sub _build_ua_bing {
97 8 ▶ my $self = shift;
Subroutine _build_ua_bing: called CC=1 SCAR=0.0
98 8 return LWP::UserAgent->new(
99 agent => $self->ua_string,
100 #default_headers => {
101 # "Content-Type" => "text/xml",
102 #},
103 );
104 }
105  
106 sub translate {
107 11 ▶ my $self = shift;
Subroutine translate: called CC=1 SCAR=0.0
Pod documented
108 11 my ($from, $to, $text) = validate_pos(
109 @_,
110 {type => SCALAR, regex => '.+'},
111 {type => SCALAR, regex => '.+'},
112 {type => SCALAR},
113 );
114  
115 return $self->_make_api_call(
116 {
117 call => 'Translate',
118 method => 'GET',
119 args => {
120 text => $text,
121 from => $from,
122 to => $to,
123 },
124 process_response => sub {
125 4 ▶ my $r = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
126 4 my $xml = XML::Simple::XMLin($r);
127 4 return $xml->{content};
128 }
129 }
130 5 );
131 }
132  
133 sub get_translations {
134 13 ▶ my $self = shift;
Subroutine get_translations: called CC=3 SCAR=11.0
Pod documented
135 13 my ($from, $to, $text, $opts) = validate_pos(
136 @_,
137 {type => SCALAR, regex => '.+'},
138 {type => SCALAR, regex => '.+'},
139 {type => SCALAR},
140 {type => HASHREF, regex => '.+', optional => 1},
141 );
142 6 ▶ $opts //= {};
Condition100%2/2
$opts //= {}
l!l
51
MC/DC100%1/1
$opts //= {}
$opts
Truth table100%2/2
A
A= $opts
Aresult
11
00
143 6 ▶ my $max_translations = $opts->{max_translations} // 5;
Condition100%2/2
$opts->{"max_translations"} // 5
l!l
42
MC/DC100%1/1
$opts->{"max_translations"} // 5
$opts->{"max_translations"}
Truth table100%2/2
A
A= $opts->{"max_translations"}
Aresult
11
00
144  
145 return $self->_make_api_call(
146 {
147 call => 'GetTranslations',
148 method => 'POST',
149 args => {
150 text => $text,
151 from => $from,
152 to => $to,
153 maxTranslations => $max_translations,
154 },
155 process_response => sub {
156 4 ▶ my $r = shift;
Subroutine __ANON__: called CC=2 SCAR=7.0
157 4 my $xml = XML::Simple::XMLin($r, ForceArray => 'TranslationMatch');
158 4 my @translations = map { $_->{TranslatedText}->[0] } @{$xml->{Translations}->[0]->{TranslationMatch}};
159 4 ▶ return wantarray ? @translations : \@translations;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 4 4
160 },
161 }
162 6 );
163 }
164  
165 sub detect {
166 7 ▶ my $self = shift;
Subroutine detect: called CC=1 SCAR=0.0
Pod documented
167 7 my ($text) = validate_pos(@_, {type => SCALAR});
168  
169 return $self->_make_api_call(
170 {
171 call => 'Detect',
172 method => 'GET',
173 args => {
174 text => $text,
175 },
176 process_response => sub {
177 4 ▶ my $r = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
178 4 my $xml = XML::Simple::XMLin($r);
179 4 return $xml->{content};
180 },
181 }
182 5 );
183 }
184  
185 sub speak {
186 9 ▶ my $self = shift;
Subroutine speak: called CC=1 SCAR=0.0
Pod documented
187 9 my ($language, $text) = validate_pos(
188 @_,
189 {type => SCALAR, regex => '.+'},
190 {type => SCALAR},
191 );
192  
193 return $self->_make_api_call(
194 {
195 call => 'speak',
196 method => 'GET',
197 args => {
198 language => $language,
199 text => $text,
200 },
201 process_response => sub {
202 4 ▶ my $r = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
203 4 return $r;
204 },
205 }
206 5 );
207 }
208  
209 sub _get_token {
210 16 ▶ my $self = shift;
Subroutine _get_token: called CC=3 SCAR=11.0
211 16 ▶ return $self->_token if($self->_token && $self->clock->() < $self->_token_expiry);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_token and $self->clock->() < $self->_token_expiry 4 12 16
Condition100%3/3
$self->_token and $self->clock->() < $self->_token_expiry
!ll&&!rl&&r
844
MC/DC100%2/2
$self->_token and $self->clock->() < $self->_token_expiry
$self->_token $self->clock->() < $self->_token_expiry
Truth table100%3/3
A and B
A= $self->_tokenB= $self->clock->() < $self->_token_expiry
ABresult
0X0
100
111
212 12 my $ua = $self->_ua_token;
213 12 my $r = $ua->post($self->auth_url, {
214 grant_type => 'client_credentials',
215 client_id => $self->app_id,
216 client_secret => $self->api_key,
217 scope => "http://api.microsofttranslator.com",
218 });
219 12 my $resp_data = JSON::decode_json $r->decoded_content;
220 12 $self->_token($resp_data->{access_token});
221 12 $self->_token_expiry($self->clock->() + $resp_data->{expires_in} - $self->token_expiry_shift);
222 12 return $self->_token;
223 }
224  
225 sub _make_api_call {
226 16 ▶ my ($self, $args) = @_;
Subroutine _make_api_call: called CC=2 SCAR=7.2
227  
228 16 my $method = lc $args->{method};
229 16 $self->_ua_bing->default_header(
230 'Authorization' => 'Bearer ' . $self->_get_token,
231 );
232 16 my $uri = URI->new($self->api_url . "/" . $args->{call});
233 16 $uri->query_form(%{$args->{args}});
234 16 my $response = $self->_ua_bing->$method( $uri->as_string );
235 16 ▶ if($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_success) { } 16 0 16
236 16 return $args->{process_response}->($response->decoded_content);
237 } else {
238 0 my @err = ($response->code, $response->message, $response->decoded_content);
239 0 croak "@err";
240 }
241 }
242  
243 2 __PACKAGE__->meta->make_immutable;
244  
245 2 1;
246  
247 =pod
248  
249 =encoding utf8
250  
251 =head1 NAME
252  
253 Lingua::Translator::Microsoft - A client library for the Microsoft Translator API
254  
255 =head1 SYNOPSIS
256  
257 my $api_key = read_file('/home/myapp/priv/translator.priv');
258 my $translator = Lingua::Translator::Microsoft->new(
259 api_key => $api_key,
260 app_id => $app_id,
261 );
262  
263 say $translator->translate('nl', 'en', 'voorbeeld'); # outputs 'example'
264  
265 my $wav = $translator->speak('de', 'Worüber man nicht sprechen kann, darüber muss man schweigen');
266 open(my $fh, ">", "tractatus.wav");
267 print $fh $wav;
268 system("mplayer tractatus.wav");
269  
270 say $translator->detect("Ci vuole un fiore."); # outputs 'it'
271  
272 =head1 DESCRIPTION
273  
274 This is a client library for Microsoft's translate service. Currently you can use the following calls from the API:
275  
276 =over 4
277  
278 =item Translate
279  
280 =item GetTranslations
281  
282 =item Detect
283  
284 =item Speak
285  
286 =back
287  
288 All API-calling methods croak() unless they get a successful reply from the service.
289  
290 =head1 FUNCTIONS
291  
292 =head2 Lingua::Translator::Microsoft->new(api_key => $api_key, app_id => $app_id);
293  
294 Instantiate a new Lingua::Translator::Microsoft object.
295  
296 Arguments:
297  
298 =over 4
299  
300 =item
301  
302 api_key [required]
303  
304 The API key (client secret).
305  
306 =item
307  
308 app_id [required]
309  
310 Your application ID (client id). You need to register your application to be able to use the service.
311  
312 =item
313  
314 auth_url [optional]
315  
316 The URL to get the OAuth token from. Defaults to https://datamarket.accesscontrol.windows.net/v2/OAuth2-13. You probably don't need to change this.
317  
318 =item
319  
320 api_url [optional]
321  
322 The URL for the Microsoft Translator API (v2). Defaults to http://api.microsofttranslator.com/v2/Http.svc. You probably don't need to change this.
323  
324 =back
325  
326 Returns:
327  
328 =over 4
329  
330 =item
331  
332 A new Lingua::Translator::Microsoft instance.
333  
334 =back
335  
336 =head2 $translator->translate($source_language_code, $target_language_code, $text)
337  
338 Translate some text
339  
340 Arguments:
341  
342 =over 4
343  
344 =item
345  
346 source_language_code [required] (String)
347  
348 =item
349  
350 target_language_code [required] (String)
351  
352 =item
353  
354 text [required] (String)
355  
356 The text to translate.
357  
358 =back
359  
360 Returns:
361  
362 =over 4
363  
364 =item
365  
366 The translated text as a string.
367  
368 =back
369  
370 =head2 $translator->get_translations($source_language_code, $target_language_code, $text, { max_translations => 3})
371  
372 Translate some text (with multiple results).
373  
374 This function is sensitive to context. It returns an arrayref of translation in scalar context but a list of translations in list context.
375  
376 Arguments:
377  
378 =over 4
379  
380 =item
381  
382 source_language_code [required] (String)
383  
384 =item
385  
386 target_language_code [required] (String)
387  
388 =item
389  
390 text [required] (String)
391  
392 The text to translate.
393  
394 =item
395  
396 options [optional] (Hashref)
397  
398 A struct containing options to the call. For now the only option that you can put here is max_translations
399 which limits the number of results to a given number. max_translations defaults to 5.
400  
401 =back
402  
403 Returns:
404  
405 =over 4
406  
407 =item
408  
409 In list context the results as a list of strings (translations).
410  
411 =item
412  
413 In scalar context an arrayref of strings (translations).
414  
415 =back
416  
417 =head2 $translator->speak($language_code, $text)
418  
419 Pronounce some text
420  
421 Arguments:
422  
423 =over 4
424  
425 =item
426  
427 language_code [required] (String)
428  
429 =item
430  
431 text [required] (String)
432  
433 The text to synthetize.
434  
435 =back
436  
437 Returns:
438  
439 =over 4
440  
441 =item
442  
443 A wav stream containing the text spoken in the chosen language.
444  
445 =back
446  
447 =head2 $translator->detect($text)
448  
449 Detect the language of a text.
450  
451 Arguments:
452  
453 =over 4
454  
455 =item
456  
457 text [required] (String)
458  
459 The text to do language detection on.
460  
461 =back
462  
463 Returns:
464  
465 =over 4
466  
467 =item
468  
469 The code of the detected language.
470  
471 =back
472  
473 =head1 AUTHOR
474  
475 This module is written by Larion Garaczi <larion@cpan.org> (2016)
476  
477 =head1 SOURCE CODE
478  
479 The source code for this module is hosted on GitHub L<https://github.com/larion/lingua-translator-microsoft>.
480  
481 Feel free to contribute :)
482  
483 =head1 LICENSE AND COPYRIGHT
484  
485 This module is free software and is published under the same
486 terms as Perl itself.
487  
488 =cut
↑ Summary