reference_sf = graphlab.SFrame('data/sf_processed.sframe/')
pretrained_model = graphlab.load_model('data/imagenet_model')
nn_model = graphlab.load_model('data/nearest_dress_model')

reference_sf

def dress_similar(url):
    img = graphlab.Image(url)
    image_sf = graphlab.SFrame()
    image_sf['image'] = [img]
    image_sf['features'] = pretrained_model.extract_features(image_sf)
    ans = nn_model.query(image_sf, k=5)
    return ans 

QUERY_URL = 'http://static.ddmcdn.com/gif/blue-dress.jpg'
Image(QUERY_URL)

def retrieve_image(nearest_neighbors_output, input_sframe):
    joined = input_sframe.join(nearest_neighbors_output, on={'_id':'reference_label'})
    sorted_sf = joined.sort('rank')
    return sorted_sf['image']

images = retrieve_image(dress_similar(QUERY_URL), reference_sf)

images.show()

"""
Explanation: Overview: Deploying the Dress Recommender
Let's say you want to make an app which can recommend dresses to you based on a photo you took. 
You need a way to deploy the model previously built. Turi Predictive Services helps do this in an easy and scalable way. In this notebook, we demonstrate how do that for the dress recommender model.
<img src='images/predictive_services_overview.png'></img>

Deployment Steps
The notebook has three sections: 

<a href='#cpo'>Create a model</a>
<a href='#create'>Create a predictive service</a>
<a href='#query'>Query the model</a>

1. Create a model <a id='cpo'></a>
Let us try and deploy the dress recommender. First, we define a function similar_dress that takes a query and returns similar dresses. 
<img src="images/left.png"></img>
We start by loading the already trained models and datasets.
End of explanation
"""


import graphlab as gl

# Replace with your path.
ps_state_path = 's3://<your-bucket-name>/predictive_service/ps'

# Set your AWS credentials.
gl.aws.set_credentials(<key>, <secret>)

# Create an EC2 config
ec2_config = gl.deploy.Ec2Config()

# Launch a predictive service
ps = gl.deploy.predictive_service.create(name = 'sklearn-predictive-service', 
              ec2_config = ec2_config, state_path = ps_state_path, num_hosts = 1)

"""
Explanation: 2. Create a Predictive Service (One time) <a id='create'></a>
This section shows you how to deploy a Predictive Service to EC2. The EC2 instances used by the Predictive Service will be launched in your own AWS account, so you will be responsible for the cost. 
<img src="images/middle.png"></img>
We add our similar_dress function to the predictive service, so that it can be queried by the outside world. Note: In order to follow along here, you need AWS credentials. You can then uncomment the code below. Be sure that the deployment state path is in an s3 bucket you have access to.
End of explanation
"""


import graphlab as gl
ps = gl.deploy.predictive_service.load('s3://gl-demo-usw2/predictive_service/demolab/ps-1.6')
ps

#ps.add('dress_similar', dress_similar)
ps.update('dress_similar', dress_similar)
ps.apply_changes()

"""
Explanation: Load an already created service
End of explanation
"""


ps.query('dress_similar', url=QUERY_URL)

"""
Explanation: Query the model <a id='query'></a>
The Predictive Service is now up! Let's query it and explore the response. 
<img src="images/right.png"></img>
End of explanation
"""


import json
import requests

def restful_query(url):
    # Query the service.
    headers = {'content-type': 'application/json' }
    payload = {'api_key':'b437e588-0f2b-45e1-81c8-ce3acfa81ade', 'data':{'url':url}}
    end_point = 'http://demolab-one-six-2015364754.us-west-2.elb.amazonaws.com/query/dress_similar'
    resp = requests.post(end_point,json.dumps(payload), headers=headers)

    # Join with existing data.
    ans = gl.SArray(json.loads(resp.content)['response']).unpack('')
    return retrieve_image(ans, reference_sf)

restful_query('http://static.ddmcdn.com/gif/blue-dress.jpg').show()

"""
Explanation: Query via REST
Query from anywhere. Here, we issue a request via the requests library, and convert the returning JSON  back into an SFrame. This could easily be done from outside of Python, though.
End of explanation
"""


