1 # This program is copyright Jonathan Feinberg 1999.
2 # This program is distributed under the same terms as infobot.
6 # http://pobox.com/~jdf/
9 # First public release.
11 # hacked by Tim@Rikers.org to handle new URL and layout
17 #my $url = 'http://babelfish.av.com/tr';
18 my $url = 'http://babelfish.yahoo.com/translate_txt';
21 eval "use URI::Escape"; # utility functions for encoding the
22 if ($@) { $no_babelfish++ }
24 eval "use LWP::UserAgent";
25 if ($@) { $no_babelfish++ }
30 # Translate some feasible abbreviations into the ones babelfish
32 use vars qw!%lang_code $lang_regex!;
55 # Here's how we recognize the language you're asking for. It looks
56 # like RTSL saves you a few keystrokes in #perl, huh?
57 $lang_regex = join '|', keys %lang_code;
61 return '' if $no_babelfish;
62 my ( $from, $to, $phrase ) = @_;
63 &::DEBUG("babelfish($from, $to, $phrase)");
65 $from = $lang_code{$from};
66 $to = $lang_code{$to};
68 my $ua = new LWP::UserAgent;
69 $ua->proxy( 'http', $::param{'httpProxy'} ) if ( &::IsParam('httpProxy') );
72 $ua->agent( "Mozilla/5.0 " . $ua->agent );
75 my $req = HTTP::Request->new( 'POST', $url );
77 # babelfish ignored this, but it SHOULD work
78 # Accept-Charset: iso-8859-1
79 # $req->header('Accept-Charset' => 'iso-8859-1');
80 # print $req->header('Accept-Charset');
81 $req->header( 'Accept-Language' => 'en' );
82 $req->content_type('application/x-www-form-urlencoded');
84 return translate( $phrase, "${from}_${to}", $req, $ua );
88 return '' if $no_babelfish;
89 my ( $phrase, $languagepair, $req, $ua ) = @_;
90 &::DEBUG("translate($phrase, $languagepair, $req, $ua)");
92 my $trtext = uri_escape($phrase);
93 $req->content("trtext=$trtext&lp=$languagepair");
94 &::DEBUG("$url??trtext=$trtext&lp=$languagepair");
96 my $res = $ua->request($req);
99 if ( $res->is_success ) {
100 my $html = $res->content;
102 # This method subject to change with the whims of Babelfish design staff.
103 ($translated) = $html;
105 $translated =~ s/.*<\/head>//sg;
106 &::DEBUG("================================\n$translated\n========================\n");
107 # convert back to spaces
108 $translated =~ s/ / /sg;
109 # strip multiple whitespace
110 $translated =~ s/\s+/ /sg;
112 $translated =~ s/.*<div id="result">//sg;
114 $translated =~ s/<\/div.*//sg;
116 $translated =~ s/<[^>]*>//sg;
118 $translated =~ s/\n/ /g;
119 # strip multiple whitespace
120 $translated =~ s/\s+/ /sg;
122 # FIXME: any entities to utf8?
125 $translated = ":("; # failure
127 $translated = "babelfish.pl: result too long, probably an error"
128 if ( length($translated) > 700 );
135 my $babel_lang_regex =
136 "de|ge|gr|el|sp|es|en|fr|it|ja|jp|ko|kr|nl|po|pt|ru|zh|zt";
139 ($babel_lang_regex)\w* # from language?
141 ($babel_lang_regex)\w* # to language?
143 (.+) # The phrase to be translated
147 &::performStrictReply( &babelfishParam( lc $1, lc $2, lc $3 ) );
154 # vim:ts=4:sw=4:expandtab:tw=80