Skip to content
May 27, 2011 / stevebaer

Outside the Box – Using Web Services from Python

gtranslate_ghx
I’ve been trying to learn more about things like web services and APIs provided by internet companies (gotta figure out what all of these buzzwords are.) One thing I’ve noticed is that many companies now provide a REST API which return JSON objects. There are enough resources on the web that describe REST and JSON that I don’t need to repeat it here; I’m just going to get to my python experiments on this technology.

So what does it do?
The python script uses the Google Translate API to translate text from one language to another. Maybe not the most useful new tool for Rhino, but it shows how simple it is to format a request to a web service and get at the results.

Some important things to note:

  1. The scripts in both attachments are exactly the same. There is code in the script to figure out if it is running as a normal Rhino python script or inside of Grasshopper.
  2. The script does different things when it is running in Rhino versus when running in Grasshopper. In Rhino, the script converts text dot text which in Grasshopper the script uses input and output variables.
  3. I’m using the sticky variable to cache results. This way we don’t have to keep going out to Google if we are translating the same text over and over again

Search around on the internet for REST apis that return JSON data. Your python scripts that use these other services will end up looking pretty similar to the samples I posted (unless you don’t like my scripting style;)) Here are some interesting APIs to look at:
http://code.google.com/more/
http://friendfeed.com/api/documentation
http://www.flickr.com/services/api/
http://developer.ning.com/docs/ningapi/1.0/index.html
http://develop.github.com/
http://api.pachube.com/

"""Use Google translate web service"""
import rhinoscriptsyntax as rs
import json, urllib
import scriptcontext
# Api key that I (Steve Baer) got from Google
# http://code.google.com/apis/console-help/#UsingKeys
# You might want to generate your own key, but I don't care
# if you continue to use this one.
KEY = "AIzaSyAZGoS-GjZGaSHZMZdoczfdUtWTjm_D-p4"
def translate(text, source="en", target="fr"):
"""Translate text from one language to another. Returns the
translated text on success or None on failure
"""
# see if we already have a cached answer
cache_dict_name = "translate " + source + ":" + target
if scriptcontext.sticky.has_key(cache_dict_name):
cache = scriptcontext.sticky[cache_dict_name]
if cache.has_key(text): return cache[text]
url = "https://www.googleapis.com/language/translate/v2"
url += "?key=" + KEY
url += "&q="+urllib.quote(text.encode('utf-8'))
url += "&source="+source
url += "&target="+target
f = urllib.urlopen(url)
s = f.read().decode('UTF-8')
# it seems that the google translate api return html encoded strings
htmlcodes = ('&', '&amp;'),('<', '&lt;'),('>', '&gt;'),('"', '&quot;'),("'", '&#39;')
for c, code in htmlcodes: s = s.replace(code, c)
f.close()
rc = json.loads(s)
if rc.has_key("data"):
translated = rc["data"]["translations"][0]["translatedText"]
if not scriptcontext.sticky.has_key(cache_dict_name):
scriptcontext.sticky[cache_dict_name] = {}
scriptcontext.sticky[cache_dict_name][text] = translated
return translated
# use __name__ test to determine if this script is directly being
# executed or if it is being loaded as a library
if( __name__=="__main__" ):
if rs.ContextIsGrasshopper():
# if this script is running in grasshopper, translate the input
# variable and set the output variables
spanish = translate(english, "en", "es")
german = translate(english, "en", "de")
french = translate(english, "en", "fr")
italian = translate(english, "en", "it")
japanese = translate(english, "en", "ja")
elif rs.ContextIsRhino():
# get text dots and translate their contents
dots = rs.GetObjects("Select dots to translate", rs.filter.textdot)
if dots:
langs = { "English":"en",
"ChineseSimplified":"zh-CN",
"ChineseTraditional":"zh-TW",
"Czech":"cs",
"French":"fr",
"German":"de",
"Italian":"it",
"Japanese":"ja",
"Korean":"ko",
"Polish":"pl",
"Spanish":"es"
}
source_lang = rs.GetString("source", "English", langs.keys())
source_lang = langs[source_lang]
target_lang = rs.GetString("target", "Spanish", langs.keys())
target_lang = langs[target_lang]
for dot in dots:
s = rs.TextDotText(dot)
s = translate(s, source_lang, target_lang)
rs.TextDotText(dot, s)

view raw
googletranslate.py
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: