12 Haziran 2009 Cuma

Translator

Bildiğiniz gibi bir süre önce Google yeni bir uygulamasını daha duyurdu: "Google Translate". Uygulamanın Türkçe dil desteği de var. Google'ın arama sayfasından çıkan sonuçların yanında yer alan "[ Bu sayfanın çevirisini yap ]" linkini tıkladığınızda mevcut sayfanın çevrisi karşınıza geliyor. Her ne kadar Türkçe çevirisinde sıkıntılar olsa da bu konuda yeni standartlar oluşturulacağına da inanıyorum. Aksi takdirde, örneğin kodların yer aldığı bir sitenin çevirisinde, "import ....." ifadesinin "ithal ...." çevirisi oldukça eğlenceli görünüyor.

Google'ın bir çeviri uygulaması da http://translate.google.com sitesinde yer alan metin çevirisi. 41 dilde sunulan destek oldukça iyi bir uygulama. Ki Google'ın ücretsiz sunduğu bu iki uygulama çeviri dünyasında yeni bir soluk getirecek.

Yine Google'ın Java Developer'lar için yazdığı bir de API'si mevcut. Bu yazıda sizlerle bu API'yı paylaşacağız. Bu API'yı kullanarak siz de ufak bir translator uygulaması geliştirebilirsiniz. Üstelik çeviriler Google'ın Ajax Dili API'sinin koştuğu siteden yapılıyor:

Başlamadan önce gerekli olan bazı jar'ları indirmeniz gerekiyor:
1- google-api-translate-java-0.53.jar
2- org.json.JSONObject

Bunları kullandığınız editor'deki "Libraries" klasörüne ekledikten sonra iki class'ı yazmanız gerekecek. Bunlardan ilki
Translate.java. Kodlar da aşağıda:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webdestek.Language; //Kendi package'ınızı buraya belirtin...

/**
*
* @author Ömürhan
*/
/**
* Language.java
*
* Copyright (C) 2007, Richard Midwinter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

import java.util.Arrays;
import java.util.List;

/**
* Defines language information for the Google Translate API.
*
* @author Richard Midwinter
*/

public final class Language {

public static final String ARABIC = "ar";
public static final String BULGARIAN = "bg";
public static final String CATALAN = "ca";
public static final String CHINESE = "zh";
public static final String CHINESE_SIMPLIFIED = "zh-CN";
public static final String CHINESE_TRADITIONAL = "zh-TW";
public static final String CROATIAN = "cr";
public static final String CZECH = "cs";
public static final String DANISH = "da";
public static final String DUTCH = "nl";
public static final String ENGLISH = "en";
public static final String FILIPINO = "tl";
public static final String FINNISH = "fi";
public static final String FRENCH = "fr";
public static final String GERMAN = "de";
public static final String GREEK = "el";
public static final String HEBREW = "iw";
public static final String HINDI = "hi";
public static final String INDONESIAN = "id";
public static final String ITALIAN = "it";
public static final String JAPANESE = "ja";
public static final String KOREAN = "ko";
public static final String LATVIAN = "lv";
public static final String LITHUANIAN = "lt";
public static final String NORWEGIAN = "no";
public static final String POLISH = "pl";
public static final String PORTUGESE = "pt";
public static final String ROMANIAN = "ro";
public static final String RUSSIAN = "ru";
public static final String SERBIAN = "sr";
public static final String SLOVAK = "sk";
public static final String SLOVENIAN = "sl";
public static final String SPANISH = "es";
public static final String SWEDISH = "sv";
public static final String TURKISH = "tr";
public static final String UKRANIAN = "uk";
public static final String VIETNAMESE = "vi";
public static final List validLanguages = Arrays.asList(new String[]{
ARABIC, BULGARIAN, CATALAN, CHINESE, CHINESE_SIMPLIFIED,
CHINESE_TRADITIONAL, CROATIAN, CZECH, DANISH, DUTCH,
ENGLISH, FILIPINO, FRENCH, GERMAN, GREEK, HEBREW,
ITALIAN, JAPANESE, KOREAN, LATVIAN, LITHUANIAN, NORWEGIAN,
POLISH, PORTUGESE, ROMANIAN, RUSSIAN, SERBIAN, SLOVAK,
SLOVENIAN, SPANISH, SWEDISH, TURKISH, UKRANIAN, VIETNAMESE
});

/**
* Checks a given language is available to use with Google Translate.
*
* @param language The language code to check for.
* @return true if this language is available to use with Google Translate, false otherwise.
*/
public static boolean isValidLanguage(String language) {
return validLanguages.contains(language);
}
}
-----
Yukarıda da söylediğimiz gibi Google'ın (şimdilik) 41 dilde desteği var. Yukarıdaki class'ta her ne kadar 37 dil gösteriliyor olsa da bu listeden kontrol ederek, Google'ın desteklediği diğer diller için de class'ta düzenleme yapabilirsiniz.

Yazmamız gereken ikinci class ise Translate.java adında. Uzun uzun anlatmaya gerek yok çünkü Google'ın bu hizmeti veren Ajax API'sının yer aldığı sayfadan sizin gönderdiğiniz data'nın eşleşmesini yapıyor ve console'da görüntülüyor.



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package webdestek.Language;
//Kendi package'ınızı buraya belirtin...

/**
*
* @author Ömürhan
*/
/**
* Translate.java
*
* Copyright (C) 2007, Richard Midwinter
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;


/**
* Makes the Google Translate API available to Java applications.
*
* @author Richard Midwinter
* @author Emeric Vernat
* @author Juan B Cabral
*/
public class Translate {

private static final String ENCODING = "UTF-8";
private static final String URL_STRING = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=";
private static final String TEXT_VAR = "&q=";

/**
* Translates text from a given language to another given language using Google Translate
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws MalformedURLException
* @throws IOException
*/
public static String translate(String text, String from, String to) throws Exception {
return retrieveTranslation(text, from, to);
}

/**
* Forms an HTTP request and parses the response for a translation.
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws Exception
*/
private static String retrieveTranslation(String text, String from, String to) throws Exception {
try {
StringBuilder url = new StringBuilder();
url.append(URL_STRING).append(from).append("%7C").append(to);
url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
try {
String result = toString(uc.getInputStream());

JSONObject json = new JSONObject(result);
return ((JSONObject) json.get("responseData")).getString("translatedText");
} finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
uc.getInputStream().close();
if (uc.getErrorStream() != null) {
uc.getErrorStream().close();
}
}
} catch (Exception ex) {
throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
}
}

/**
* Reads an InputStream and returns its contents as a String. Also effects rate control.
* @param inputStream The InputStream to read from.
* @return The contents of the InputStream as a String.
* @throws Exception
*/
private static String toString(InputStream inputStream) throws Exception {
StringBuilder outputBuilder = new StringBuilder();
try {
String string;
if (inputStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
while (null != (string = reader.readLine())) {
outputBuilder.append(string).append('\n');
}
}
} catch (Exception ex) {
throw new Exception("[google-api-translate-java] Error reading translation stream.", ex);
}
return outputBuilder.toString();
}
}

--------

Uygulamamız bu kadar. Bu uygulamayı geliştirmek sizin elinizde. Bir combobox koyup, desteklenen dilleri içinde yazdırıp, kullanıcının istediği kelimeyi hangi dilden hangi dile çevirmek istediği bilgisini alarak ekranda görüntülemek oldukça kolay. İlerleyen zamanlarda (gerekirse veya soru gelirse) buna yönelik bir uygulama daha koyabiliriz.

Hiç yorum yok:

Yorum Gönder