Bot-Babelfish
view release on metacpan or search on metacpan
lib/Bot/Babelfish.pm view on Meta::CPAN
#print STDERR " $from -> $to : ", $args->{body}, $/;
unless(is_language_tag($from)) {
$args->{body} = "Unrecognized language tag '$from'";
$self->say($args);
return undef
}
unless(is_language_tag($to)) {
$args->{body} = "Unrecognized language tag '$to'";
$self->say($args);
return undef
}
my $from_to = "$from>$to";
my($from_lang,$to_lang) = map { I18N::LangTags::List::name($_) } $from, $to;
my $translator = new Lingua::Translate src => $from, dest => $to;
unless(defined $translator) {
$args->{body} = "Can't translate from $from_lang to $to_lang";
$self->say($args);
return undef
}
my $text = encode('utf-8', decode('iso-8859-1', $args->{body}));
my $result = $self->{babel}{cache}{$from_to}{$text};
unless($result) {
eval { $result = decode('utf-8', $translator->translate($text)) };
$self->{babel}{cache}{$from_to}{$text} = $result unless $@;
}
#print STDERR " ($@) result = $result\n";
$text = non_unicode_version(decode('utf-8', $text));
$result = non_unicode_version($result);
$args->{body} = defined($result) ? qq|$to_lang for "$text" => "$result"| : "error: $@";
$self->say($args);
return $args
}
=item help()
Prints usage.
=cut
sub help {
return "usage: babel: from to: text to translate\n".
" where 'from' and 'to' are two-letters codes of source and destination languages\n".
" see http://babelfish.altavista.com/ for the list of supported languages.\n".
" example: babel: fr en: ceci n'est pas une pipe"
}
=item non_unicode_version()
This function returns a printable version of the given string
(with a European value of "printable" C<:-)>. More precisely,
if the string only contains Latin-1 characters, it is returned
decoded from internal Perl format. If the string contains
others characters outside Latin-1, it's converted using
C<Text::Unidecode>.
=cut
sub non_unicode_version {
my $text = shift;
my $wide = 0;
ord($_) > 255 and $wide++ for split //, $text;
return $wide ? unidecode($text) : encode('iso-8859-1', $text)
}
=back
=head1 COMMANDS
=over 4
=item translation
babel from to: some text to translate
Where C<from> and C<to> are ISO-639 two-letters codes representing the languages.
See L<http://babelfish.altavista.com/> for the list of supported languages.
B<Examples>
babel: fr en: ceci n'est pas une pipe
<babel> English for "ceci n'est pas une pipe" => "this is not a pipe"
=item help
babel help
Shows how to use this bot.
=item version
babel version
Prints the version of this module and its dependencies.
=back
=head1 DIAGNOSTICS
=over 4
=item Can't create new %s object
B<(F)> Occurs in C<init()>. As the message says, we were unable to create
a new object of the given class.
=back
=head1 SEE ALSO
L<Bot::BasicBot>, L<Text::Unidecode>
( run in 0.606 second using v1.01-cache-2.11-cpan-7fcb06a456a )