Joe Gregorio | 266c644 | 2011-02-23 16:08:54 -0500 | [diff] [blame] | 1 | #!/usr/bin/python2.4 |
| 2 | # |
| 3 | # -*- coding: utf-8 -*- |
| 4 | # |
| 5 | # Copyright 2011 Google Inc. All Rights Reserved. |
| 6 | |
| 7 | """Simple command-line example for Google Prediction API. |
| 8 | |
| 9 | Command-line application that trains on some data. This |
| 10 | sample does the same thing as the Hello Prediction! example. |
| 11 | |
| 12 | http://code.google.com/apis/predict/docs/hello_world.html |
| 13 | """ |
| 14 | |
| 15 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 16 | |
| 17 | import httplib2 |
| 18 | import pprint |
| 19 | import time |
| 20 | |
| 21 | from apiclient.discovery import build |
| 22 | from oauth2client.client import OAuth2WebServerFlow |
| 23 | from oauth2client.file import Storage |
| 24 | from oauth2client.tools import run |
| 25 | |
| 26 | # Uncomment to get low level HTTP logging |
| 27 | #httplib2.debuglevel = 4 |
| 28 | |
| 29 | # Name of Google Storage bucket/object that contains the training data |
| 30 | OBJECT_NAME = "apiclient-prediction-sample/prediction_models/languages" |
| 31 | |
| 32 | |
| 33 | def main(): |
| 34 | storage = Storage('prediction.dat') |
| 35 | credentials = storage.get() |
| 36 | |
| 37 | if credentials is None or credentials.invalid == True: |
| 38 | flow = OAuth2WebServerFlow( |
| 39 | # You MUST put in your client id and secret here for this sample to |
| 40 | # work. Visit https://code.google.com/apis/console to get your client |
| 41 | # credentials. |
| 42 | client_id='<Put Your Client ID Here>', |
| 43 | client_secret='<Put Your Client Secret Here>', |
| 44 | scope='https://www.googleapis.com/auth/prediction', |
| 45 | user_agent='prediction-cmdline-sample/1.0', |
| 46 | xoauth_displayname='Prediction Example App') |
| 47 | |
| 48 | credentials = run(flow, storage) |
| 49 | |
| 50 | http = httplib2.Http() |
| 51 | http = credentials.authorize(http) |
| 52 | |
| 53 | service = build("prediction", "v1.1", http=http) |
| 54 | |
| 55 | # Start training on a data set |
| 56 | train = service.training() |
| 57 | start = train.insert(data=OBJECT_NAME, body={}).execute() |
| 58 | |
| 59 | print 'Started training' |
| 60 | pprint.pprint(start) |
| 61 | |
| 62 | # Wait for the training to complete |
| 63 | while 1: |
| 64 | status = train.get(data=OBJECT_NAME).execute() |
| 65 | pprint.pprint(status) |
| 66 | if 'accuracy' in status['modelinfo']: |
| 67 | break |
| 68 | print 'Waiting for training to complete.' |
| 69 | time.sleep(10) |
| 70 | print 'Training is complete' |
| 71 | |
| 72 | # Now make a prediction using that training |
| 73 | body = {'input': {'mixture':["mucho bueno"]}} |
| 74 | prediction = service.predict(body=body, data=OBJECT_NAME).execute() |
| 75 | print 'The prediction is:' |
| 76 | pprint.pprint(prediction) |
| 77 | |
| 78 | if __name__ == '__main__': |
| 79 | main() |