Skip to content

Instantly share code, notes, and snippets.

@randyphoa
Created June 7, 2022 05:18
Show Gist options
  • Save randyphoa/289527fe93d83469257cb771f80655c3 to your computer and use it in GitHub Desktop.
Save randyphoa/289527fe93d83469257cb771f80655c3 to your computer and use it in GitHub Desktop.
Deploy R in online mode - deploy python function to call R
params = {
"wml_credentials": wml_credentials,
"space_id": SPACE_ID,
"script": "predict.R",
"required_assets": ["iris_xgb.model"],
"r_packages": ["jsonlite", "xgboost"],
}
def r_function(params=params):
"""
Deployable Python function which downloads the required assets from a WML deployment space and runs the specified R Script.
"""
import json
import subprocess
from ibm_watson_machine_learning import APIClient
wml_client = APIClient(params["wml_credentials"])
wml_client.set.default_space(params["space_id"])
script = params["script"]
assets = {x["metadata"]["name"]: x["metadata"]["asset_id"] for x in wml_client.data_assets.get_details()["resources"]}
# download required assets
wml_client.data_assets.download(assets[script], script)
for x in params["required_assets"]:
wml_client.data_assets.download(assets[x], x)
# install R and other libraries
# subprocess.run(["mamba", "install", "-c", "conda-forge", "r-base", "r-essentials"])
subprocess.run(["Rscript", "-e", 'install.packages(c("jsonlite", "data.table", "stringi", "stringr"), repos="https://cloud.r-project.org")'])
if "xgboost" in params["r_packages"]:
params["r_packages"].remove("xgboost")
subprocess.run(["Rscript", "-e", 'install.packages("https://cloud.r-project.org/src/contrib/Archive/xgboost/xgboost_1.5.2.1.tar.gz", repos=NULL, type="source")'])
subprocess.run(["Rscript", "-e", 'install.packages(c(' + ",".join([f'"{x}"' for x in params["r_packages"]]) + '), repos="https://cloud.r-project.org")'])
def score(payload):
d = payload["input_data"][0]["values"][0]
inputs = d["inputs"]
inputs = json.dumps(inputs)
result = subprocess.run(["Rscript", "--vanilla", script, inputs], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = result.stdout.decode("utf-8")
try:
out = json.loads(out)
except:
out = result.stdout.decode("utf-8")
err = result.stderr.decode("utf-8")
return {"predictions": [{"out": out, "err": err}]}
return score
meta_props = {
wml_client.repository.FunctionMetaNames.NAME: "iris xgb",
wml_client.repository.FunctionMetaNames.SOFTWARE_SPEC_ID: wml_client.software_specifications.get_uid_by_name("custom-r"),
}
function_details = wml_client.repository.store_function(function=r_function, meta_props=meta_props)
function_uid = wml_client.repository.get_function_id(function_details)
meta_props = {
wml_client.deployments.ConfigurationMetaNames.NAME: "iris xgb deployment",
wml_client.deployments.ConfigurationMetaNames.ONLINE: {},
}
wml_client.deployments.create(function_uid, meta_props=meta_props)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment