Skip to content

Instantly share code, notes, and snippets.

@matthewmorrone
Created December 2, 2020 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewmorrone/4c1faf5f9e3573c6d22afd5f80f9faf4 to your computer and use it in GitHub Desktop.
Save matthewmorrone/4c1faf5f9e3573c6d22afd5f80f9faf4 to your computer and use it in GitHub Desktop.
groovy language detection
// Language detection and translation thanks to the Google language APIs
// Script inspired by Glen Smith's article:
// http://blogs.bytecode.com.au/glen/2009/07/30/getting-groovy-with-google-language-translation-apis.html
def text = URLEncoder.encode("J'ai envie de manger des fraises", "UTF-8")
def detectUrl = "http://www.google.com/uds/GlangDetect?v=1.0&q=${text}".toURL()
def langGuessResponse = jsonToGroovyMap(detectUrl.text)
def lang = langGuessResponse.responseData.language
println "Lang is: ${lang}"
def targetLang = "en"
def translateUrl = "http://www.google.com/uds/Gtranslate?v=1.0&q=${text}&langpair=${lang}%7C${targetLang}".toURL()
def translationResponse = jsonToGroovyMap(translateUrl.text)
def translation = translationResponse.responseData.translatedText
println "Translation is: ${translation}"
/**
* Converts a JSON string into a Groovy map.
* The difference lies in the difference in map notation: {:} in JSON vs [:] in Groovy
*/
def jsonToGroovyMap(jsonString) {
new GroovyShell().evaluate(jsonString.replaceAll(/}/, ']').replaceAll(/\{/, '['))
}​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment