uploading images to Metaweb

[ permalink ] [ download ]
import metaweb             # Our metaweb utilities
import urllib2             # For downloading images from the mint server

USERNAME = 'username'      # Put your Freebase username and password here
PASSWORD = 'password'

# The ID for our US State Quarter type depends on our username
TYPEID = '/user/' + USERNAME + '/default_domain/us_state_quarter'

# Make sure we can log in before we go any further
credentials = metaweb.login(USERNAME, PASSWORD)

# All the images files are beneath this URL
imagedir = 'http://www.usmint.gov/images/mint_programs/50sq_program/states/'

# This dictionary maps state name to image name.
images = { 'Delaware': 'DE_winner.gif',
           'Pennsylvania': 'PA_winner.gif',
           'New Jersey': 'NJ_winner.gif',
           'Georgia': 'GA_winner.gif',
           'Connecticut': 'CT_winner.gif',
           'Massachusetts': 'MA_winner.gif'}

# Loop through the states
for state,filename in images.items():
    # First, download the image from the Mint's website
    image = urllib2.urlopen(imagedir + filename)
    type = image.info()['Content-Type']
    content = image.read()

    # Now upload it to Metaweb
    id = metaweb.upload(content, type, credentials)

    # Define a write query to link the quarter object to the uploaded image
    query = { 'type': TYPEID,
              'state':state,
              '/common/topic/image': { 'id':id, 'connect':'insert' }}

    # Submit the query and get the result
    result = metaweb.write(query, credentials)

    # Output the result
    print "%s: %s %s" %(state, result['/common/topic/image']['connect'], id)
hits counter