Use Google Translate in your PB apps!

Share your advanced PureBasic knowledge/code with the community.
Nituvious
Addict
Addict
Posts: 1027
Joined: Sat Jul 11, 2009 4:57 am
Location: United States

Use Google Translate in your PB apps!

Post by Nituvious »

Hi all, it's been awhile since I did anything in PB so I thought I'd try this.
It uses Google Translator, which requires a connection to the internet to be established.
Please let me know how I can improve my code. I tried to make it as neat and readable as possible.

Here is the procedure with a working example(and a simpler one commented out):

Code: Select all

;{ -- Language Constants, added for completeness
#Afrikaans		= "af" : #Albanian	= "sq"
#Arabic			= "ar" : #Armenian	= "hy"
#Azerbaijani	= "az" : #Basque		= "eu"
#Belarusian		= "be" : #Bulbarian	= "bg"
#Catalan			= "ca" : #Chinese		= "zh"
#Croatian		= "hr" : #Czech		= "cs"
#Danish			= "da" : #Dutch		= "nl"
#English			= "en" : #Estonian	= "et"
#Finnish			= "fi" : #French		= "fr"
#Galician		= "gl" : #Georgian	= "ka"
#German			= "de" : #Greek		= "el"
#HaitianCreole	= "ht" : #Hebrew		= "he"
#Hindi			= "hi" : #Hungarian	= "hu"
#Icelandic		= "is" : #Indonesian = "id"
#Irish			= "ga" : #Italian		= "it"
#Japanese		= "ja" : #Korean		= "ko"
#Latin			= "la" : #Latvian		= "lv"
#Lithuanian		= "lt" : #Macedonian = "mk"
#Malay			= "ms" : #Maltese		= "mt"
#Norwegian		= "no" : #Persian		= "fa"
#Polish			= "pl" : #Portuguese = "pt"
#Romanian		= "ro" : #Russian		= "ru"
#Serbian			= "sr" : #Slovak		= "sk"
#Spanish			= "es" : #Swahili		= "sw"
#Swedish			= "sv" : #Thai			= "th"
#Turkish			= "tr" : #Ukrainian	= "uk"
#Urdu				= "ur" : #Vietnamese = "vi"
#Welsh			= "cy" : #Yiddish		= "yi"
;#Filipino = "" : #Slovenian = "" ; <- searched wikipedia for the ISO 639-1 codes but couldn't find them
;}

NewMap Language.s()
Language("Afrikaans")	= "af" : Language("Albanian")		= "sq"
Language("Arabic")		= "ar" : Language("Armenian")		= "hy"
Language("Azerbaijani") = "az" : Language("Basque")		= "eu"
Language("Belarusian")	= "be" : Language("Bulbarian")	= "bg"
Language("Catalan")		= "ca" : Language("Chinese")		= "zh"
Language("Croatian")		= "hr" : Language("Czech")			= "cs"
Language("Danish")		= "da" : Language("Dutch")			= "nl"
Language("English")		= "en" : Language("Estonian")		= "et"
Language("Finnish")		= "fi" : Language("French")		= "fr"
Language("Galician")		= "gl" : Language("Georgian")		= "ka"
Language("German")		= "de" : Language("Greek")			= "el"
Language("HaitianCreole") = "ht" : Language("Hebrew")		= "he"
Language("Hindi")			= "hi" : Language("Hungarian")	= "hu"
Language("Icelandic")	= "is" : Language("Indonesian")	= "id"
Language("Irish")			= "ga" : Language("Italian")		= "it"
Language("Japanese")		= "ja" : Language("Korean")		= "ko"
Language("Latin")			= "la" : Language("Latvian")		= "lv"
Language("Lithuanian")	= "lt" : Language("Macedonian")	= "mk"
Language("Malay")			= "ms" : Language("Maltese")		= "mt"
Language("Norwegian")	= "no" : Language("Persian")		= "fa"
Language("Polish")		= "pl" : Language("Portuguese ")	= "pt"
Language("Romanian")		= "ro" : Language("Russian")		= "ru"
Language("Serbian")		= "sr" : Language("Slovak")		= "sk"
Language("Spanish")		= "es" : Language("Swahili")		= "sw"
Language("Swedish")		= "sv" : Language("Thai")			= "th"
Language("Turkish")		= "tr" : Language("Ukrainian")	= "uk"
Language("Urdu")			= "ur" : Language("Vietnamese ")	= "vi"
Language("Welsh")			= "cy" : Language("Yiddish")		= "yi"

Declare.s TranslateText(string.s, sourceLang.s, targetLang.s)

InitNetwork()

window = OpenWindow(#PB_Any,0,0,400,350,"Google Translator in PB", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
status = CreateStatusBar(#PB_Any, WindowID(window))
AddStatusBarField(WindowWidth(window))

gadgetSend = ButtonGadget(#PB_Any, 335, 305, 60, 23, "Translate")
gadgetTranslate = EditorGadget(#PB_Any, 5, 35, 390, 265,#PB_Editor_ReadOnly)
gadgetInput	= StringGadget(#PB_Any, 5, 305, 325, 23, "Enter text you would like to translate!")
gadgetSource = ComboBoxGadget(#PB_Any, 5, 5, 100, 25)
gadgetTarget = ComboBoxGadget(#PB_Any, 140, 5, 100, 25)
TextGadget(#PB_Any, 115, 10, 10, 23, "to")
ForEach Language.s()
	AddGadgetItem(gadgetSource, s, MapKey(Language.s()))
	AddGadgetItem(gadgetTarget, s, MapKey(Language.s()))
	s + 1
Next
SetGadgetState(gadgetSource,6) : SetGadgetState(gadgetTarget,28)
Repeat : Delay(10)
	eventID.l = WaitWindowEvent(1)
	
	If eventID.l = #PB_Event_Gadget
		ForEach Language()
			If GetGadgetText(gadgetSource) = MapKey(Language()) : source.s = Language() : EndIf
			If GetGadgetText(gadgetTarget) = MapKey(Language()) : target.s = Language() : EndIf		
			StatusBarText(status, 0, "Translating " + UCase(source.s) + " to " + UCase(target.s))
		Next
		Select EventGadget()
			Case gadgetSend
				AddGadgetItem(gadgetTranslate,#PB_Any,TranslateText(GetGadgetText(gadgetInput), source.s, target.s))
		EndSelect
	EndIf
	
Until eventID.l = #PB_Event_CloseWindow

;Debug TranslateText(InputRequester("Translate","Type what you would like to translate!","Hello World!"),#English,#Greek)

Procedure.s TranslateText(string.s, sourceLang.s, targetLang.s)
	Static url.s, tempDirectory.s, fileString.s = ""
	tempDirectory.s = GetTemporaryDirectory() + "googleapitranslate.txt"
	
	;{ Create URL path based on input
	url.s = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0"
	url.s + "&q=" + URLEncoder(string.s)
	url.s + "&langpair=" + sourceLang.s + "|" + targetLang.s	;}
	
	If ReceiveHTTPFile(url.s, tempDirectory.s) ; Bad parsor below!!!
		file = ReadFile(#PB_Any, tempDirectory.s)
		fileString.s = ReadString(file);,#PB_UTF8
		fileString.s = Mid(fileString.s, FindString(fileString.s,Chr(34)+":"+Chr(34),0)+3)
		fileString.s = StringField(fileString.s,1,Chr(34)+"}, "+Chr(34))
		CloseFile(file) : DeleteFile(tempDirectory.s)
		ProcedureReturn fileString.s
	Else : MessageRequester("Error","Unable to receive translation!") : EndIf
	
EndProcedure
▓▓▓▓▓▒▒▒▒▒░░░░░
epidemicz
User
User
Posts: 86
Joined: Thu Jan 22, 2009 8:05 am
Location: USA
Contact:

Re: Use Google Translate in your PB apps!

Post by epidemicz »

Very cool Nituvious.

I think I found the ones you were missing:

Code: Select all

#Filipino = "tl"
#Slovenian = "sl"
Image
User avatar
idle
Always Here
Always Here
Posts: 5836
Joined: Fri Sep 21, 2007 5:52 am
Location: New Zealand

Re: Use Google Translate in your PB apps!

Post by idle »

nice one.
Windows 11, Manjaro, Raspberry Pi OS
Image
IdeasVacuum
Always Here
Always Here
Posts: 6426
Joined: Fri Oct 23, 2009 2:33 am
Location: Wales, UK
Contact:

Re: Use Google Translate in your PB apps!

Post by IdeasVacuum »

Very nice code. Goggle Translate however is a long way from being good enough, especially with the Asian languages, though of course it is better than nothing if English is used alongside.
IdeasVacuum
If it sounds simple, you have not grasped the complexity.
PMV
Enthusiast
Enthusiast
Posts: 727
Joined: Sat Feb 24, 2007 3:15 pm
Location: Germany

Re: Use Google Translate in your PB apps!

Post by PMV »

I don't know where you have your input, but your language-map doesn't fit
Googles documentation. :) I have made another example with my json-parser
:D ... you can expand it if you want like a detection-procedure, adding all supported
languages or make another one for version 2 :wink:

And read the rules for Google Translation API, it is not for every scenario you might
think. :)

Code: Select all

; -:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-
;
;         Google Translation API v1.0
;                                 for PureBasic v4.51+
;
; -:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-:-
;
; from:  03.05.2011
; version: 0.1
;
; {|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}
;
;
; © 2011 by PMV 
; 
;
; {|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}-{|}
;
; terms of use from Google:
; http://code.google.com/intl/de/apis/language/translate/terms.html
;
; application requirements:
; http://code.google.com/intl/de/apis/language/translate/v1/using_rest_translate.html#prereqs
;
; documentation for the Google Translation API
; http://code.google.com/intl/de/apis/language/translate/v1/using_rest_translate.html
;
; list of translatable languages:
; http://code.google.com/intl/de/apis/language/translate/v1/getting_started.html#translatableLanguages
;
; response json-format:
; {
;   "responseData": {
;     "translatedText":"Text",
;     "detectedSourceLanguage":"en"
;   }, 
;   "responseDetails": null,
;   "responseStatus": 200
; }
;
; -|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-
EnableExplicit

; can be found here:
; http://www.purebasic.fr/english/viewtopic.php?f=12&t=45348
XIncludeFile "JSON_Parser.pb"
; ---

;#GoogleTranslateAPI_Key = "your-key"

; returns a jsonObj with the all responsedata from google
Procedure.i GoogleAPI_Translate(text.s, lngDesti.s, lngSource.s = "", format.s="", userip.s="")
  Protected *respons.jsonObj
  Protected url.s = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0"
  Protected filename.s, i.i
  Protected file.i, response.s = ""
  
  url + "&langpair=" + lngSource + "%7C" + lngDesti
  url + "&q=" + URLEncoder(text)
  If format
    format = LCase(format)
    If format = "html" Or format = "text"
      url + "&format=" + format
    EndIf
  EndIf
  CompilerIf Defined(GoogleTranslateAPI_Key, #PB_Constant)
    url + "&key=" + #GoogleTranslateAPI_Key
  CompilerEndIf
  If userip
    url + "&userip=" + userip
  EndIf
  
  i = -1
  Repeat
    i + 1
    filename = GetTemporaryDirectory() + "tmp" + Str(i) + ".txt"
  Until FileSize(filename) = -1
  
  
  If ReceiveHTTPFile(url, filename)
    file = ReadFile(#PB_Any, filename)
    If file
      While Not Eof(file)
        response + ReadString(file, #PB_UTF8)
      Wend
      CloseFile(file)
      DeleteFile(filename)
      ProcedureReturn JSON_decode(response)
    EndIf
  EndIf
  ProcedureReturn #False
EndProcedure

; example
InitNetwork()
Define *json = GoogleAPI_Translate(InputRequester("Google Translate API", "your text:", "powered by Google"), "de")
If *json : JSON_Debug(*json, "") : EndIf
MFG PMV
Nituvious
Addict
Addict
Posts: 1027
Joined: Sat Jul 11, 2009 4:57 am
Location: United States

Re: Use Google Translate in your PB apps!

Post by Nituvious »

I didn't find anything stating that I could not use Google Translate v1.0 API in an application.
The only reason I went with v1.0 was because it does not require an API key(which can be cumbersome to create for some.) as well as the extra information needed to parse.

The language map was only used for the GUI, it does not reflect Google. I only took a handful of the languages that google translator uses. Here is a complete list of them:
Taken from http://code.google.com/apis/language/tr ... arted.html

Code: Select all

var google.language.Languages = {
  'AFRIKAANS' : 'af',
  'ALBANIAN' : 'sq',
  'AMHARIC' : 'am',
  'ARABIC' : 'ar',
  'ARMENIAN' : 'hy',
  'AZERBAIJANI' : 'az',
  'BASQUE' : 'eu',
  'BELARUSIAN' : 'be',
  'BENGALI' : 'bn',
  'BIHARI' : 'bh',
  'BRETON' : 'br',
  'BULGARIAN' : 'bg',
  'BURMESE' : 'my',
  'CATALAN' : 'ca',
  'CHEROKEE' : 'chr',
  'CHINESE' : 'zh',
  'CHINESE_SIMPLIFIED' : 'zh-CN',
  'CHINESE_TRADITIONAL' : 'zh-TW',
  'CORSICAN' : 'co',
  'CROATIAN' : 'hr',
  'CZECH' : 'cs',
  'DANISH' : 'da',
  'DHIVEHI' : 'dv',
  'DUTCH': 'nl',  
  'ENGLISH' : 'en',
  'ESPERANTO' : 'eo',
  'ESTONIAN' : 'et',
  'FAROESE' : 'fo',
  'FILIPINO' : 'tl',
  'FINNISH' : 'fi',
  'FRENCH' : 'fr',
  'FRISIAN' : 'fy',
  'GALICIAN' : 'gl',
  'GEORGIAN' : 'ka',
  'GERMAN' : 'de',
  'GREEK' : 'el',
  'GUJARATI' : 'gu',
  'HAITIAN_CREOLE' : 'ht',
  'HEBREW' : 'iw',
  'HINDI' : 'hi',
  'HUNGARIAN' : 'hu',
  'ICELANDIC' : 'is',
  'INDONESIAN' : 'id',
  'INUKTITUT' : 'iu',
  'IRISH' : 'ga',
  'ITALIAN' : 'it',
  'JAPANESE' : 'ja',
  'JAVANESE' : 'jw',
  'KANNADA' : 'kn',
  'KAZAKH' : 'kk',
  'KHMER' : 'km',
  'KOREAN' : 'ko',
  'KURDISH': 'ku',
  'KYRGYZ': 'ky',
  'LAO' : 'lo',
  'LATIN' : 'la',
  'LATVIAN' : 'lv',
  'LITHUANIAN' : 'lt',
  'LUXEMBOURGISH' : 'lb',
  'MACEDONIAN' : 'mk',
  'MALAY' : 'ms',
  'MALAYALAM' : 'ml',
  'MALTESE' : 'mt',
  'MAORI' : 'mi',
  'MARATHI' : 'mr',
  'MONGOLIAN' : 'mn',
  'NEPALI' : 'ne',
  'NORWEGIAN' : 'no',
  'OCCITAN' : 'oc',
  'ORIYA' : 'or',
  'PASHTO' : 'ps',
  'PERSIAN' : 'fa',
  'POLISH' : 'pl',
  'PORTUGUESE' : 'pt',
  'PORTUGUESE_PORTUGAL' : 'pt-PT',
  'PUNJABI' : 'pa',
  'QUECHUA' : 'qu',
  'ROMANIAN' : 'ro',
  'RUSSIAN' : 'ru',
  'SANSKRIT' : 'sa',
  'SCOTS_GAELIC' : 'gd',
  'SERBIAN' : 'sr',
  'SINDHI' : 'sd',
  'SINHALESE' : 'si',
  'SLOVAK' : 'sk',
  'SLOVENIAN' : 'sl',
  'SPANISH' : 'es',
  'SUNDANESE' : 'su',
  'SWAHILI' : 'sw',
  'SWEDISH' : 'sv',
  'SYRIAC' : 'syr',
  'TAJIK' : 'tg',
  'TAMIL' : 'ta',
  'TATAR' : 'tt',
  'TELUGU' : 'te',
  'THAI' : 'th',
  'TIBETAN' : 'bo',
  'TONGA' : 'to',
  'TURKISH' : 'tr',
  'UKRAINIAN' : 'uk',
  'URDU' : 'ur',
  'UZBEK' : 'uz',
  'UIGHUR' : 'ug',
  'VIETNAMESE' : 'vi',
  'WELSH' : 'cy',
  'YIDDISH' : 'yi',
  'YORUBA' : 'yo',
  'UNKNOWN' : ''
};
▓▓▓▓▓▒▒▒▒▒░░░░░
kvitaliy
Enthusiast
Enthusiast
Posts: 162
Joined: Mon May 10, 2010 4:02 pm

Re: Use Google Translate in your PB apps!

Post by kvitaliy »

Very simple translator:

Code: Select all

If OpenWindow(0, 450, 200, 476, 425, "Translate", #PB_Window_SystemMenu|#PB_Window_SizeGadget|#PB_Window_MinimizeGadget|#PB_Window_TitleBar)
     WebGadget(0, 0, 0, 495, 495, "http://translate.imtranslator.net/")
  EndIf

;{- Event loop
Repeat
  Event = WaitWindowEvent()
  Select Event
     Case #PB_Event_CloseWindow
      EventWindow = EventWindow()
      If EventWindow = 0
        CloseWindow(0)
        Break
      EndIf
  EndSelect
ForEver
;
;}
:D
PMV
Enthusiast
Enthusiast
Posts: 727
Joined: Sat Feb 24, 2007 3:15 pm
Location: Germany

Re: Use Google Translate in your PB apps!

Post by PMV »

Nituvious wrote:I didn't find anything stating that I could not use Google Translate v1.0 API in an application.
The only reason I went with v1.0 was because it does not require an API key(which can be cumbersome to create for some.) as well as the extra information needed to parse.
I have added any interesting link into the beginning of my example-code. :wink:
You didn't seen it?

One of the links goes to the documentation for v1.0 for not-javascript-languages.
So yes, it is allowed to use in applications. There are other restrictions and rules like
adding a visible branding "powered by Google". :wink:

MFG PMV
akj
Enthusiast
Enthusiast
Posts: 668
Joined: Mon Jun 09, 2003 10:08 pm
Location: Nottingham

Re: Use Google Translate in your PB apps!

Post by akj »

@Nituvious

"Bulgarian" is incorrectly spelt as "Bulbarian" in your program

Should the code for "Hebrew" be "he" (as in your program) or "iw" (as in the complete code list) ?
Anthony Jordan
PMV
Enthusiast
Enthusiast
Posts: 727
Joined: Sat Feb 24, 2007 3:15 pm
Location: Germany

Re: Use Google Translate in your PB apps!

Post by PMV »

for using google translation api only look at the docu there!
(this means the js-enumeration copied from the docu is the right one)
Nituvious
Addict
Addict
Posts: 1027
Joined: Sat Jul 11, 2009 4:57 am
Location: United States

Re: Use Google Translate in your PB apps!

Post by Nituvious »

akj wrote:@Nituvious

"Bulgarian" is incorrectly spelt as "Bulbarian" in your program

Should the code for "Hebrew" be "he" (as in your program) or "iw" (as in the complete code list) ?
You are correct! Sorry about that, I had begin adding the enumerations during an internet outage and all I had as reference was the wikipedia article! I forgot to double check on the google api website as a just in case. Sorry about that!
▓▓▓▓▓▒▒▒▒▒░░░░░
User avatar
utopiomania
Addict
Addict
Posts: 1655
Joined: Tue May 10, 2005 10:00 pm
Location: Norway

Re: Use Google Translate in your PB apps!

Post by utopiomania »

Cool, thanks for sharing! :)
Post Reply