-
Notifications
You must be signed in to change notification settings - Fork 607
Cortex python client #488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Cortex python client #488
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
ecc942f
Cortex python client
vishalbollu 5d383f8
Progress
vishalbollu 8cfe002
Enforce python version in setup.py
vishalbollu afb9834
another version
vishalbollu 769512d
Again
vishalbollu 23334cd
Back to 3.6
vishalbollu 5d6cb68
Remove python version
vishalbollu 7538225
Get endpoint in deploy
vishalbollu 6369e2c
Fix linting
vishalbollu f65d6b6
Raise exception when requests fail
vishalbollu 64dba0b
Remove logging statements
vishalbollu a8f5cd0
Cleanup rount 1
vishalbollu eb4a6f6
Print resources
vishalbollu 94e56ef
Get path from context
vishalbollu 38812bb
Add docs and respond PR comments
vishalbollu e6745c6
Use pathlib
vishalbollu bb6d8d2
Drop articles
vishalbollu 421bd08
Drop leading articles in python docs
vishalbollu 1264560
Docs tweak
vishalbollu dac0961
Prevent load balancer from timing out requests (#490)
vishalbollu 0656e67
Update python-client.md
ospillinger 03feb6e
Fix linting
vishalbollu a91a662
Line up comments
vishalbollu edd9ec6
Merge branch 'master' into cortex-python-client
vishalbollu b74e425
Do not add none params
vishalbollu 1e476e6
Merge branch 'master' into cortex-python-client
vishalbollu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# Python Client | ||
|
||
The Python client can be used to programmatically deploy models to a Cortex Cluster. | ||
|
||
<!-- CORTEX_VERSION_MINOR --> | ||
``` | ||
pip install git+https://github.com/cortexlabs/cortex.git@master#egg=cortex\&subdirectory=pkg/workloads/cortex/client | ||
``` | ||
|
||
The Python client needs to be initialized with AWS credentials and an operator URL for your Cortex cluster. You can find the operator URL by running `./cortex.sh endpoints`. | ||
|
||
```python | ||
from cortex import Client | ||
|
||
cortex = Client( | ||
aws_access_key_id="<string>", # AWS access key associated with the account that the cluster is running on | ||
aws_secret_access_key="<string>", # AWS secret key associated with the AWS access key | ||
operator_url="<string>" # operator URL of your cluster | ||
) | ||
|
||
api_url = cortex.deploy( | ||
deployment_name="<string>", # deployment name (required) | ||
api_name="<string>", # API name (required) | ||
model_path="<string>", # S3 path to an exported model (required) | ||
pre_inference=callable, # function used to prepare requests for model input | ||
post_inference=callable, # function used to prepare model output for response | ||
model_format="<string>", # model format, must be "tensorflow" or "onnx" (default: "onnx" if model path ends with .onnx, "tensorflow" if model path ends with .zip or is a directory) | ||
tf_serving_key="<string>" # name of the signature def to use for prediction (required if your model has more than one signature def) | ||
) | ||
``` | ||
|
||
`api_url` contains the URL of the deployed API. The API accepts JSON POST requests. | ||
|
||
```python | ||
import requests | ||
|
||
sample = { | ||
"feature_1": 'a', | ||
"feature_2": 'b', | ||
"feature_3": 'c' | ||
} | ||
|
||
resp = requests.post(api_url, json=sample) | ||
resp.json() | ||
``` |
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# Copyright 2019 Cortex Labs, Inc. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from cortex.client import Client |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
# Copyright 2019 Cortex Labs, Inc. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import pathlib | ||
from pathlib import Path | ||
import os | ||
import types | ||
import subprocess | ||
import sys | ||
import shutil | ||
import yaml | ||
import urllib.parse | ||
import base64 | ||
|
||
import dill | ||
import requests | ||
from requests.exceptions import HTTPError | ||
import msgpack | ||
|
||
|
||
class Client(object): | ||
def __init__(self, aws_access_key_id, aws_secret_access_key, operator_url): | ||
"""Initialize a Client to a Cortex Operator | ||
|
||
Args: | ||
aws_access_key_id (string): AWS access key associated with the account that the cluster is running on | ||
aws_secret_access_key (string): AWS secret key associated with the AWS access key | ||
operator_url (string): operator URL of your cluster | ||
""" | ||
|
||
self.operator_url = operator_url | ||
self.workspace = str(Path.home() / ".cortex" / "workspace") | ||
self.aws_access_key_id = aws_access_key_id | ||
self.aws_secret_access_key = aws_secret_access_key | ||
self.headers = { | ||
"CortexAPIVersion": "master", | ||
"Authorization": "CortexAWS {}|{}".format( | ||
self.aws_access_key_id, self.aws_secret_access_key | ||
), | ||
} | ||
|
||
pathlib.Path(self.workspace).mkdir(parents=True, exist_ok=True) | ||
deliahu marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def deploy( | ||
self, | ||
deployment_name, | ||
api_name, | ||
model_path, | ||
pre_inference=None, | ||
post_inference=None, | ||
model_format=None, | ||
tf_serving_key=None, | ||
): | ||
"""Deploy an API | ||
|
||
Args: | ||
deployment_name (string): deployment name | ||
api_name (string): API name | ||
model_path (string): S3 path to an exported model | ||
pre_inference (function, optional): function used to prepare requests for model input | ||
post_inference (function, optional): function used to prepare model output for response | ||
model_format (string, optional): model format, must be "tensorflow" or "onnx" (default: "onnx" if model path ends with .onnx, "tensorflow" if model path ends with .zip or is a directory) | ||
tf_serving_key (string, optional): name of the signature def to use for prediction (required if your model has more than one signature def) | ||
|
||
Returns: | ||
string: url to the deployed API | ||
""" | ||
|
||
working_dir = os.path.join(self.workspace, deployment_name) | ||
api_working_dir = os.path.join(working_dir, api_name) | ||
pathlib.Path(api_working_dir).mkdir(parents=True, exist_ok=True) | ||
|
||
api_config = {"kind": "api", "model": model_path, "name": api_name} | ||
|
||
if tf_serving_key is not None: | ||
api_config["model_format"] = tf_serving_key | ||
|
||
if model_format is not None: | ||
api_config["model_format"] = model_format | ||
|
||
if pre_inference is not None or post_inference is not None: | ||
reqs = subprocess.check_output([sys.executable, "-m", "pip", "freeze"]) | ||
|
||
with open(os.path.join(api_working_dir, "requirements.txt"), "w") as f: | ||
f.writelines(reqs.decode()) | ||
|
||
handlers = {} | ||
|
||
if pre_inference is not None: | ||
handlers["pre_inference"] = pre_inference | ||
|
||
if post_inference is not None: | ||
handlers["post_inference"] = post_inference | ||
|
||
with open(os.path.join(api_working_dir, "request_handler.pickle"), "wb") as f: | ||
dill.dump(handlers, f, recurse=True) | ||
|
||
api_config["request_handler"] = "request_handler.pickle" | ||
|
||
cortex_config = [{"kind": "deployment", "name": deployment_name}, api_config] | ||
|
||
cortex_yaml_path = os.path.join(working_dir, "cortex.yaml") | ||
with open(cortex_yaml_path, "w") as f: | ||
f.write(yaml.dump(cortex_config)) | ||
|
||
project_zip_path = os.path.join(working_dir, "project") | ||
shutil.make_archive(project_zip_path, "zip", api_working_dir) | ||
project_zip_path += ".zip" | ||
|
||
queries = {"force": "false", "ignoreCache": "false"} | ||
|
||
with open(cortex_yaml_path, "rb") as config, open(project_zip_path, "rb") as project: | ||
files = {"cortex.yaml": config, "project.zip": project} | ||
try: | ||
resp = requests.post( | ||
urllib.parse.urljoin(self.operator_url, "deploy"), | ||
params=queries, | ||
files=files, | ||
headers=self.headers, | ||
verify=False, | ||
) | ||
resp.raise_for_status() | ||
resources = resp.json() | ||
except HTTPError as err: | ||
resp = err.response | ||
if "error" in resp.json(): | ||
raise Exception(resp.json()["error"]) from err | ||
raise | ||
|
||
b64_encoded_context = resources["context"] | ||
context_msgpack_bytestring = base64.b64decode(b64_encoded_context) | ||
ctx = msgpack.loads(context_msgpack_bytestring, raw=False) | ||
return urllib.parse.urljoin(resources["apis_base_url"], ctx["apis"][api_name]["path"]) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# Copyright 2019 Cortex Labs, Inc. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from setuptools import setup, find_packages | ||
|
||
setup( | ||
name="cortex", | ||
version="0.8.0", | ||
description="", | ||
author="Cortex Labs", | ||
author_email="[email protected]", | ||
install_requires=["dill>=0.3.0", "requests>=2.20.0", "msgpack>=0.6.0"], | ||
setup_requires=["setuptools"], | ||
packages=find_packages(), | ||
) |
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
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
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.