from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
import featherweight_api


class Classifier(object):
    def __init__(self):
        self.iris = datasets.load_iris()
        X = self.iris.data
        y = self.iris.target
        self.clf = RandomForestClassifier()
        self.clf.fit(X, y)

    def score(self, sepal_length, sepal_width, petal_length, petal_width):
        guessed_class_arr = self.clf.predict([sepal_length, sepal_width, petal_length, petal_width])
        guessed_class = guessed_class_arr[0]  # extract the only item in the array result
        guessed_class_label = self.iris.target_names[guessed_class]
        # note that guessed_class is a np.int64 and
        # guess_class_label is a Python string, they both
        # come from numpy arrays
        return {"guessed_label": guessed_class_label, "guessed_class": guessed_class}


classifier = Classifier()
featherweight_api.register(classifier.score)
featherweight_api.run()  # serve on localhost:5000 by default

# the following call will identify as class 2 ('virginica')
# http://localhost:5000/score?sepal_length=5.9&sepal_width=3&petal_length=5.1&petal_width=1.8
import numpy as np
import featherweight_api
from scipy import optimize


def f(x):
    return x**2 + 10 * np.sin(x)


def function(b, c):
    return optimize.fminbound(f, b, c)


# If called with arguments:
# http://127.0.0.1:5000/function?b=2&c=10
# we get a correct output:
# {"success": true, "error_msg": null, "result": 3.83746830432337}

if __name__ == "__main__":
    featherweight_api.register(function)
    featherweight_api.run()
import numpy as np
import featherweight_api
from scipy import optimize

def f(x):
    return x**2 + 10*np.sin(x)

def function(b, c):
    return optimize.fminbound(f, b, c)

# If called with arguments:
# http://127.0.0.1:5000/function?b=2&c=10
# we get a correct output:
# {"success": true, "error_msg": null, "result": 3.83746830432337}

if __name__ == "__main__":
    featherweight_api.register(function)
    featherweight_api.run()
import featherweight_api


def myfn(x, c):
    """Example function"""
    print("DEMO x={} c={}".format(
        x, c))  # prints to the console that ran featherweight
    result = x * x + c
    return result


# If called with arguments:
# http://localhost:5000/myfn?x=2&c=10
# we get a correct output:
# {"success": true, "result": 14.0, "error_msg": null}

# If called without arguments using:
# http://localhost:5000/myfn
# then we get a useful error message
# {"result": null, "error_msg": "TypeError(\"myfn() missing 2 required positional arguments: 'x' and 'c'\",)", "success": false}

if __name__ == "__main__":
    featherweight_api.register(myfn)
    featherweight_api.run()  # serve on localhost:5000 by default
    #featherweight_api.run(host="0.0.0.0", port=8080)  # serve on a public IP on port 8080