REST Endpoint in Grasshopper C#

Hi!

I am trying to host a trained machine learning model locally through the Grasshopper C# component.
I am using Lobe app for the machine learning, the local export option allows to call the model via a REST endpoint.

Here is the export option from the Lobe app:

Prepare Request:

URL http://localhost:38100/predict/6be7396e-4ca9-4598-b772-cd927ffe6133

var client = new RestClient(“http://localhost:38100/predict/6be7396e-4ca9-4598-b772-cd927ffe6133”);
var request = new RestRequest(Method.POST);
request.AddParameter(“undefined”, “{“inputs”:{“Image”:”"}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Parse Output:

{
“labels”: [
{
“name”: “Cat”,
“type”: “”
},
{
“name”: “Dog”,
“type”: “”
}
],
“prediction”: “Cat”
}

Does anyone know how to use this in Grasshopper? The model needs to take an image from a folder and return the parsed output. This export code does not work directly in grasshopper.

I would be incredibly grateful for any help!:slight_smile:

that response is in a form called JSON — you could spit out the response and use something like jSwan to parse it in a way grasshopper can understand

Andrew, thanks for the response! My problem though is in hosting the model in the first place (the prepare request part) to get that response within grasshopper. The c# in gh probably uses different libraries to those which Lobe uses to describe the request, so just inputting this request into c# gh doesn’t work

Alternatively here is how it looks in python:

import requests

url = “http://localhost:38100/predict/f11f5e08-db12-4379-ab08-482fd6cf5e47

payload = “{“inputs”:{“Image”:”"}}"
response = requests.request(“POST”, url, data=payload)

print(response.text)

But also doesn’t work directly in GH

JSON format is interchangeable across many platforms. Python (and PHP and Java and probably C?) have built-in methods for handling it.

Blockquote

I’d do this by a python grasshopper component that starts a subprocess which calls a CPython script that does the request and then exports the results to JSON. You can then import the result to grasshopper without needing to install requests in grasshopper.

1 Like

You need to add a reference to the folder path where your requests Python module in located on your harddrive (see this old thread) in order to import it in GHPython (as it is not a standard Python library, as far as I can tell). But as Martin said, you might still not be able to run it in IronPython (i.e. the .NET version of Python that Rhino implements).

1 Like

Ah, okay I see — Lobe must be using RestSharp. Try adding a reference to the RestSharp dll to your C# script component, then the code you’ve pasted above should work to make the REST request.

1 Like

Thank you everyone for your suggestions! I ended up hosting the inference in a separate .py file and triggering it by updating images in a folder through a grasshopper c# script.