Created
December 2, 2020 18:39
-
-
Save matthewmorrone/4c1faf5f9e3573c6d22afd5f80f9faf4 to your computer and use it in GitHub Desktop.
groovy language detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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