http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/predictionio/obsolete.py ---------------------------------------------------------------------- diff --git a/predictionio/obsolete.py b/predictionio/obsolete.py deleted file mode 100644 index dc19a09..0000000 --- a/predictionio/obsolete.py +++ /dev/null @@ -1,1205 +0,0 @@ -# import packages -import re -try: - import httplib -except ImportError: - # pylint: disable=F0401 - # http is a Python3 module, replacing httplib - from http import client as httplib -import json -import urllib -import warnings - -from predictionio.connection import Connection -from predictionio.connection import AsyncRequest -from predictionio.connection import PredictionIOAPIError - -"""Error exception defined for this API - -Should be handled by the user -""" - - -class ServerStatusError(PredictionIOAPIError): - - "Error happened when tried to get status of the API server" - pass - - -class UserNotCreatedError(PredictionIOAPIError): - - "Error happened when tried to create user" - pass - - -class UserNotFoundError(PredictionIOAPIError): - - "Error happened when tried to get user" - pass - - -class UserNotDeletedError(PredictionIOAPIError): - - "Error happened when tried to delete user" - pass - - -class ItemNotCreatedError(PredictionIOAPIError): - - "Error happened when tried to create item" - pass - - -class ItemNotFoundError(PredictionIOAPIError): - - "Error happened when tried to get item" - pass - - -class ItemNotDeletedError(PredictionIOAPIError): - - "Error happened when tried to delete item" - pass - - -class U2IActionNotCreatedError(PredictionIOAPIError): - - "Error happened when tried to create user-to-item action" - pass - - -class ItemRecNotFoundError(PredictionIOAPIError): - - "Error happened when tried to get item recommendation" - pass - - -class ItemSimNotFoundError(PredictionIOAPIError): - - "Error happened when tried to get similar items" - pass - -class ItemRankNotFoundError(PredictionIOAPIError): - - "Error happened when treid to rank item" - pass - -class InvalidArgumentError(PredictionIOAPIError): - - "Arguments are not valid" - pass - -# map to API -LIKE_API = "like" -DISLIKE_API = "dislike" -VIEW_API = "view" -CONVERSION_API = "conversion" -RATE_API = "rate" - - -class Client(object): - - """PredictionIO client object. - - This is an object representing a PredictionIO's client. This object - provides methods for making PredictionIO API requests. - - :param appkey: the App Key provided by PredictionIO. - :param threads: number of threads to handle PredictionIO API requests. - Must be >= 1. - :param apiurl: the PredictionIO API URL path. - :param apiversion: the PredictionIO API version. (optional) - (eg. "", or "/v1") - :param qsize: the max size of the request queue (optional). - The asynchronous request becomes blocking once this size has been - reached, until the queued requests are handled. - Default value is 0, which means infinite queue size. - :param timeout: timeout for HTTP connection attempts and requests in - seconds (optional). - Default value is 5. - - """ - - def __init__(self, appkey, threads=1, apiurl="http://localhost:8000", - apiversion="", qsize=0, timeout=5): - """Constructor of Client object. - - """ - warnings.warn("predictionio.Client is deprecated. " + - "Please consider upgrading to our latest version.") - - self.appkey = appkey - self.threads = threads - self.apiurl = apiurl - self.apiversion = apiversion - self.qsize = qsize - self.timeout = timeout - - # check connection type - https_pattern = r'^https://(.*)' - http_pattern = r'^http://(.*)' - m = re.match(https_pattern, apiurl) - self.https = True - if m is None: # not matching https - m = re.match(http_pattern, apiurl) - self.https = False - if m is None: # not matching http either - raise InvalidArgumentError("apiurl is not valid: %s" % apiurl) - self.host = m.group(1) - - self._uid = None # identified uid - self._connection = Connection(host=self.host, threads=self.threads, - qsize=self.qsize, https=self.https, - timeout=self.timeout) - - def close(self): - """Close this client and the connection. - - Call this method when you want to completely terminate the connection - with PredictionIO. - It will wait for all pending requests to finish. - """ - self._connection.close() - - def pending_requests(self): - """Return the number of pending requests. - - :returns: - The number of pending requests of this client. - """ - return self._connection.pending_requests() - - def identify(self, uid): - """Identify the uid - - :param uid: user id. type str. - """ - self._uid = uid - - def get_status(self): - """Get the status of the PredictionIO API Server - - :returns: - status message. - - :raises: - ServerStatusError. - """ - path = "/" - request = AsyncRequest("GET", path) - request.set_rfunc(self._aget_status_resp) - self._connection.make_request(request) - result = self.aresp(request) - return result - - def _aget_status_resp(self, response): - """Handle the AsyncResponse of get status request""" - if response.error is not None: - raise ServerStatusError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ServerStatusError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - # data = json.loads(response.body) # convert json string to dict - return response.body - - def acreate_user(self, uid, params={}): - """Asynchronously create a user. - - :param uid: user id. type str. - :param params: optional attributes. type dictionary. - For example, - { 'custom': 'value', 'pio_inactive' : True, - 'pio_latlng': [4.5,67.8] } - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - - """ - - if "pio_latlng" in params: - params["pio_latlng"] = ",".join(map(str, params["pio_latlng"])) - if "pio_inactive" in params: - params["pio_inactive"] = str(params["pio_inactive"]).lower() - - path = "%s/users.json" % self.apiversion - request = AsyncRequest( - "POST", path, pio_appkey=self.appkey, pio_uid=uid, **params) - request.set_rfunc(self._acreate_user_resp) - self._connection.make_request(request) - - return request - - def _acreate_user_resp(self, response): - """Private function to handle the AsyncResponse of the acreate_user - request. - - :param response: AsyncResponse object. - - :returns: - None. - - :raises: - UserNotCreatedError. - - """ - if response.error is not None: - raise UserNotCreatedError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.CREATED: - raise UserNotCreatedError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - return None - - def aget_user(self, uid): - """Asynchronously get user. - - :param uid: user id. type str. - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - enc_uid = urllib.quote(uid, "") # replace special char with %xx - path = "%s/users/%s.json" % (self.apiversion, enc_uid) - request = AsyncRequest("GET", path, pio_appkey=self.appkey) - request.set_rfunc(self._aget_user_resp) - self._connection.make_request(request) - - return request - - def _aget_user_resp(self, response): - """Private function to handle the AsyncResponse of the aget_user - request . - - :param response: AsyncResponse object. - - :returns: - User data in Dictionary format. - - :rasies: - UserNotFoundError. - - """ - if response.error is not None: - raise UserNotFoundError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise UserNotFoundError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - data = json.loads(response.body) # convert json string to dict - return data - - def adelete_user(self, uid): - """Asynchronously delete user. - - :param uid: user id. type str. - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - enc_uid = urllib.quote(uid, "") # replace special char with %xx - path = "%s/users/%s.json" % (self.apiversion, enc_uid) - request = AsyncRequest("DELETE", path, pio_appkey=self.appkey) - request.set_rfunc(self._adelete_user_resp) - self._connection.make_request(request) - - return request - - def _adelete_user_resp(self, response): - """Private function to handle the AsyncResponse of the adelete_user - request. - - :param response: AsyncResponse object. - - :returns: - None. - - :raises: - UserNotDeletedError. - - """ - if response.error is not None: - raise UserNotDeletedError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise UserNotDeletedError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - return None - - def acreate_item(self, iid, itypes, params={}): - """Asynchronously create item. - - :param iid: item id. type str. - :param itypes: item types. Tuple of Str. - For example, if this item belongs to item types "t1", "t2", - "t3", "t4",then itypes=("t1", "t2", "t3", "t4"). - NOTE: if this item belongs to only one itype, use tuple of one - element, eg. itypes=("t1",) - :param params: optional attributes. type dictionary. - For example, - { 'custom': 'value', 'pio_inactive' : True, - 'pio_latlng': [4.5,67.8] } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - itypes_str = ",".join(itypes) # join items with "," - - if "pio_latlng" in params: - params["pio_latlng"] = ",".join(map(str, params["pio_latlng"])) - if "pio_inactive" in params: - params["pio_inactive"] = str(params["pio_inactive"]).lower() - - path = "%s/items.json" % self.apiversion - request = AsyncRequest("POST", path, pio_appkey=self.appkey, - pio_iid=iid, pio_itypes=itypes_str, **params) - request.set_rfunc(self._acreate_item_resp) - self._connection.make_request(request) - return request - - def _acreate_item_resp(self, response): - """Private function to handle the AsyncResponse of the acreate_item - request - - :param response: AsyncResponse object. - - :returns: - None - :raises: - ItemNotCreatedError - - """ - if response.error is not None: - raise ItemNotCreatedError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.CREATED: - raise ItemNotCreatedError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - return None - - def aget_item(self, iid): - """Asynchronously get item - - :param iid: item id. type str. - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - enc_iid = urllib.quote(iid, "") - path = "%s/items/%s.json" % (self.apiversion, enc_iid) - request = AsyncRequest("GET", path, pio_appkey=self.appkey) - request.set_rfunc(self._aget_item_resp) - self._connection.make_request(request) - return request - - def _aget_item_resp(self, response): - """Private function to handle the AsyncResponse of the aget_item - request - - :param response: AsyncResponse object. - - :returns: - item data in dictionary format. - - :raises: - ItemNotFoundError. - - """ - if response.error is not None: - raise ItemNotFoundError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ItemNotFoundError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - data = json.loads(response.body) # convert json string to dict - if "pio_itypes" in data: - # convert from list to tuple - data["pio_itypes"] = tuple(data["pio_itypes"]) - - return data - - def adelete_item(self, iid): - """Asynchronously delete item - - :param iid: item id. type str. - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - enc_iid = urllib.quote(iid, "") - path = "%s/items/%s.json" % (self.apiversion, enc_iid) - request = AsyncRequest("DELETE", path, pio_appkey=self.appkey) - request.set_rfunc(self._adelete_item_resp) - self._connection.make_request(request) - return request - - def _adelete_item_resp(self, response): - """Private function to handle the AsyncResponse of the adelete_item - request - - :param response: AsyncResponse object - - :returns: - None - - :raises: - ItemNotDeletedError - """ - if response.error is not None: - raise ItemNotDeletedError("Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ItemNotDeletedError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - return None - - def _aget_user_itemrec_topn(self, engine, uid, n, params={}): - """Private function to asynchronously get recommendations for user - - :param engine: name of the prediction engine. type str. - :param uid: user id. type str. - :param n: number of recommendation. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1","t2") } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - if "pio_itypes" in params: - params["pio_itypes"] = ",".join(params["pio_itypes"]) - if "pio_latlng" in params: - params["pio_latlng"] = ",".join(map(str, params["pio_latlng"])) - if "pio_attributes" in params: - params["pio_attributes"] = ",".join(params["pio_attributes"]) - - path = "%s/engines/itemrec/%s/topn.json" % (self.apiversion, engine) - request = AsyncRequest("GET", path, pio_appkey=self.appkey, - pio_uid=uid, pio_n=n, **params) - request.set_rfunc(self._aget_user_itemrec_topn_resp) - self._connection.make_request(request) - return request - - def _aget_user_itemrec_topn_resp(self, response): - """Private function to handle the AsyncResponse of the aget_itemrec - request - - :param response: AsyncResponse object - - :returns: - data in dictionary format. - - :raises: - ItemRecNotFoundError. - """ - if response.error is not None: - raise ItemRecNotFoundError( - "Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ItemRecNotFoundError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - data = json.loads(response.body) # convert json string to dict - return data - - def aget_itemrec_topn(self, engine, n, params={}): - """Asynchronously get recommendations for the identified user - - :param engine: name of the prediction engine. type str. - :param n: number of recommendation. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1",) } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - if self._uid is None: - raise InvalidArgumentError( - "uid is not identified. Please call identify(uid) first.") - - request = self._aget_user_itemrec_topn(engine, self._uid, n, params) - return request - - def aget_itemrec(self, uid, n, engine, **params): - """Deprecated. Asynchronously get recommendations - - :param uid: user id. type str. - :param n: number of recommendation. type int. - :param engine: name of the prediction engine. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng="123.4, 56.7" - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - request = self._aget_user_itemrec_topn(engine, uid, n, params) - return request - - def _aget_itemsim_topn(self, engine, iid, n, params={}): - """Private function to asynchronously get top n similar items of the - item - - :param engine: name of the prediction engine. type str. - :param iid: item id. type str. - :param n: number of similar items. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1","t2") } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - if "pio_itypes" in params: - params["pio_itypes"] = ",".join(params["pio_itypes"]) - if "pio_latlng" in params: - params["pio_latlng"] = ",".join(map(str, params["pio_latlng"])) - if "pio_attributes" in params: - params["pio_attributes"] = ",".join(params["pio_attributes"]) - - path = "%s/engines/itemsim/%s/topn.json" % (self.apiversion, engine) - request = AsyncRequest("GET", path, pio_appkey=self.appkey, - pio_iid=iid, pio_n=n, **params) - request.set_rfunc(self._aget_itemsim_topn_resp) - self._connection.make_request(request) - return request - - def _aget_itemsim_topn_resp(self, response): - """Private function to handle the AsyncResponse of the aget_itemsim - request - - :param response: AsyncResponse object - - :returns: - data in dictionary format. - - :raises: - ItemSimNotFoundError. - """ - if response.error is not None: - raise ItemSimNotFoundError( - "Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ItemSimNotFoundError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - data = json.loads(response.body) # convert json string to dict - return data - - def aget_itemsim_topn(self, engine, iid, n, params={}): - """Asynchronously get top n similar items of the item - - :param engine: name of the prediction engine. type str. - :param iid: item id. type str. - :param n: number of similar items. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1",) } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - request = self._aget_itemsim_topn(engine, iid, n, params) - return request - - def _aget_user_itemrank_ranked(self, engine, uid, iids, params={}): - """Private function to asynchronously get ranked item for user - - :param engine: name of the prediction engine. type str. - :param uid: user id. type str. - :param iids: items to be ranked. type list of item ids. - For example, ["i0", "i1", "i2"] - :param params: optional parameters. type dictionary - For example. { 'pio_attributes' : "name" } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - if "pio_attributes" in params: - params["pio_attributes"] = ",".join(params["pio_attributes"]) - - pio_iids = ",".join(iids) - - path = "%s/engines/itemrank/%s/ranked.json" % \ - (self.apiversion, engine) - request = AsyncRequest("GET", path, pio_appkey=self.appkey, - pio_uid=uid, pio_iids=pio_iids, **params) - request.set_rfunc(self._aget_user_itemrank_ranked_resp) - self._connection.make_request(request) - return request - - def _aget_user_itemrank_ranked_resp(self, response): - """Private function to handle the AsyncResponse of the aget_itemreoder - request - - :param response: AsyncResponse object - - :returns: - data in dictionary format. - - :raises: - ItemRankNotFoundError. - """ - if response.error is not None: - raise ItemRankNotFoundError( - "Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.OK: - raise ItemRankNotFoundError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - - data = json.loads(response.body) # convert json string to dict - return data - - def aget_itemrank_ranked(self, engine, iids, params={}): - """Asynchronously get ranked item for user - - :param engine: name of the prediction engine. type str. - :param iids: items to be ranked. type list of item ids. - For example, ["i0", "i1", "i2"] - :param params: optional parameters. type dictionary - For example. { 'pio_attributes' : "name" } - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - if self._uid is None: - raise InvalidArgumentError( - "uid is not identified. Please call identify(uid) first.") - - request = self._aget_user_itemrank_ranked(engine, - self._uid, iids, params) - return request - - def _auser_action_on_item(self, action, uid, iid, params): - """Private function to asynchronously create an user action on an item - - :param action: action type. type str. ("like", "dislike", "conversion", - "rate", "view") - :param uid: user id. type str or int. - :param iid: item id. type str or int. - :param params: optional attributes. type dictionary. - For example, { 'pio_rate' : 4, 'pio_latlng' : [1.23,4.56] } - NOTE: For "rate" action, pio_rate attribute is required. - integer value of 1-5 (1 is least preferred and 5 is most - preferred) - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - if "pio_latlng" in params: - params["pio_latlng"] = ",".join(map(str, params["pio_latlng"])) - - path = "%s/actions/u2i.json" % (self.apiversion) - request = AsyncRequest("POST", path, pio_appkey=self.appkey, - pio_action=action, pio_uid=uid, pio_iid=iid, - **params) - request.set_rfunc(self._auser_action_on_item_resp) - self._connection.make_request(request) - return request - - def _auser_action_on_item_resp(self, response): - """Private function to handle the AsyncResponse of the - _auser_action_on_item request - - :param response: AsyncResponse object - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - if response.error is not None: - raise U2IActionNotCreatedError( - "Exception happened: %s for request %s" % - (response.error, response.request)) - elif response.status != httplib.CREATED: - raise U2IActionNotCreatedError("request: %s status: %s body: %s" % - (response.request, response.status, - response.body)) - return None - - def arecord_action_on_item(self, action, iid, params={}): - """Asynchronously create action on item - - :param action: action name. type String. For example, "rate", "like", - etc - :param iid: item id. type str or int. - :param params: optional attributes. type dictionary. - For example, { 'pio_rate' : 4, 'pio_latlng': [4.5,67.8] } - NOTE: For "rate" action, pio_rate attribute is required. - integer value of 1-5 (1 is least preferred and 5 is most - preferred) - - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - - :raises: - U2IActionNotCreatedError - """ - - if self._uid is None: - raise InvalidArgumentError( - "uid is not identified. Please call identify(uid) first.") - - request = self._auser_action_on_item(action, self._uid, iid, params) - return request - - def auser_conversion_item(self, uid, iid, **params): - """Deprecated. Asynchronously create an user conversion action on an - item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - request = self._auser_action_on_item(CONVERSION_API, uid, iid, params) - return request - - def auser_dislike_item(self, uid, iid, **params): - """Deprecated. Asynchronously create an user dislike action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - request = self._auser_action_on_item(DISLIKE_API, uid, iid, params) - return request - - def auser_like_item(self, uid, iid, **params): - """Deprecated. Asynchronously create an user like action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - request = self._auser_action_on_item(LIKE_API, uid, iid, params) - return request - - def auser_rate_item(self, uid, iid, rate, **params): - """Deprecated. Asynchronously create an user rate action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param rate: rating. integer value of 1-5 (1 is least preferred and 5 - is most preferred) - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - - params['pio_rate'] = rate - request = self._auser_action_on_item(RATE_API, uid, iid, params) - return request - - def auser_view_item(self, uid, iid, **params): - """Deprecated. Asynchronously create an user view action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - :returns: - AsyncRequest object. You should call the aresp() method using this - AsyncRequest object as argument to get the final result or status - of this asynchronous request. - """ - request = self._auser_action_on_item(VIEW_API, uid, iid, params) - return request - - def aresp(self, request): - """Get the result of the asynchronous request - - :param request: AsyncRequest object. This object must be returned by - the asynchronous request function - For example, to get the result of a aget_user() - request, call this aresp() with the argument of - AsyncRequest object returned by aget_user(). - - :returns: - The result of this AsyncRequest. The return type is the same as - the return type of corresponding blocking request. - - For example, - - Calling aresp() with acreate_user() AsyncRequest returns the same - type as create_user(), which is None. - - Calling aresp() with aget_user() AsyncRequest returns the same - type as get_user(), which is dictionary data. - - :raises: - Exception may be raised if there is error happened. The type of - exception is the same as exception type of the correspdoning - blocking request. - - For example, - - Calling aresp() with acreate_user() AsyncRequest may raise - UserNotCreatedError exception. - - Calling aresp() with aget_user() AsyncRequest may raise - UserNotFoundError exception. - - """ - response = request.get_response() - result = request.rfunc(response) - return result - - def create_user(self, uid, params={}): - """Blocking request to create user - - :param uid: user id. type str. - :param params: optional attributes. type dictionary. - For example, { 'custom': 'value', 'pio_inactive' : True, - 'pio_latlng': [4.5,67.8] } - - :returns: - None. - - :raises: - UserNotCreatedError. - - """ - request = self.acreate_user(uid, params) - result = self.aresp(request) - return result - - def get_user(self, uid): - """Blocking request to get user - - :param uid: user id. type str or int. - - :returns: - User data in Dictionary format. - - :rasies: - UserNotFoundError. - - """ - request = self.aget_user(uid) - result = self.aresp(request) - return result - - def delete_user(self, uid): - """Blocking request to delete the user - - :param uid: user id. type str. - - :returns: - None. - - :raises: - UserNotDeletedError. - - """ - request = self.adelete_user(uid) - result = self.aresp(request) - return result - - def create_item(self, iid, itypes, params={}): - """Blocking request to create item - - :param iid: item id. type str. - :param itypes: item types. Tuple of Str. - For example, if this item belongs to item types "t1", "t2", - "t3", "t4", then itypes=("t1", "t2", "t3", "t4"). - NOTE: if this item belongs to only one itype, use tuple of one - element, eg. itypes=("t1",) - :param params: optional attributes. type dictionary. - For example, - { 'custom': 'value', 'pio_inactive' : True, - 'pio_latlng': [4.5,67.8] } - - :returns: - None - - :raises: - ItemNotCreatedError - - """ - request = self.acreate_item(iid, itypes, params) - result = self.aresp(request) - return result - - def get_item(self, iid): - """Blocking request to get item - - :param iid: item id. type str. - - :returns: - item data in dictionary format. - - :raises: - ItemNotFoundError. - - """ - request = self.aget_item(iid) - result = self.aresp(request) - return result - - def delete_item(self, iid): - """Blocking request to delete item - - :param iid: item id. type str. - - :returns: - None - - :raises: - ItemNotDeletedError - - """ - request = self.adelete_item(iid) - result = self.aresp(request) - return result - - def get_itemrec_topn(self, engine, n, params={}): - """Blocking request to get recommendations for the identified user - - :param engine: name of the prediction engine. type str. - :param n: number of recommendation. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1", "t2") } - :returns: - data in dictionary format. - - :raises: - ItemRecNotFoundError. - """ - request = self.aget_itemrec_topn(engine, n, params) - result = self.aresp(request) - return result - - def get_itemrec(self, uid, n, engine, **params): - """Deprecated. Blocking request to get recommendations - - :param uid: user id. type str or int. - :param n: number of recommendation. type int. - :param engine: name of the prediction engine. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - data in dictionary format. - - :raises: - ItemRecNotFoundError. - - """ - request = self.aget_itemrec(uid, n, engine, **params) - result = self.aresp(request) - return result - - def get_itemsim_topn(self, engine, iid, n, params={}): - """Blocking request to get top n similar items of the item - - :param engine: name of the prediction engine. type str. - :param iid: item id. type str. - :param n: number of similar items. type int. - :param params: optional parameters. type dictionary - For example, { 'pio_itypes' : ("t1",) } - :returns: - data in dictionary format. - - :raises: - ItemSimNotFoundError. - """ - - request = self.aget_itemsim_topn(engine, iid, n, params) - result = self.aresp(request) - return result - - def get_itemrank_ranked(self, engine, iids, params={}): - """Blocking request to get ranked item for user - - :param engine: name of the prediction engine. type str. - :param iids: items to be ranked. type list of item ids. - For example, ["i0", "i1", "i2"] - :param params: optional parameters. type dictionary - For example. { 'pio_attributes' : "name" } - :returns: - data in dictionary format. - - :raises: - ItemRankNotFoundError. - """ - request = self.aget_itemrank_ranked(engine, iids, params) - result = self.aresp(request) - return result - - def record_action_on_item(self, action, iid, params={}): - """Blocking request to create action on an item - - :param action: action name. type String. For example, "rate", "like", - etc - :param iid: item id. type str. - :param params: optional attributes. type dictionary. - For example, { 'pio_rate' : 4, 'pio_latlng' : [1.23,4.56] } - NOTE: For "rate" action, pio_rate attribute is required. - integer value of 1-5 (1 is least preferred and 5 is most - preferred) - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.arecord_action_on_item(action, iid, params) - result = self.aresp(request) - return result - - def user_conversion_item(self, uid, iid, **params): - """Deprecated. Blocking request to create user conversion action on an - item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.auser_conversion_item(uid, iid, **params) - result = self.aresp(request) - return result - - def user_dislike_item(self, uid, iid, **params): - """Deprecated. Blocking request to create user dislike action on an - item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.auser_dislike_item(uid, iid, **params) - result = self.aresp(request) - return result - - def user_like_item(self, uid, iid, **params): - """Deprecated. Blocking request to create user like action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.auser_like_item(uid, iid, **params) - result = self.aresp(request) - return result - - def user_rate_item(self, uid, iid, rate, **params): - """Deprecated. Blocking request to create user rate action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param rate: rating. integer value of 1-5 (1 is least preferred and 5 - is most preferred) - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.auser_rate_item(uid, iid, rate, **params) - result = self.aresp(request) - return result - - def user_view_item(self, uid, iid, **params): - """Deprecated. Blocking request to create user view action on an item - - :param uid: user id. type str. - :param iid: item id. type str. - :param params: keyword arguments for optional attributes. - For example, pio_latlng=[123.4, 56.7] - - :returns: - None - - :raises: - U2IActionNotCreatedError - """ - request = self.auser_view_item(uid, iid, **params) - result = self.aresp(request) - return result -
http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/setup.py ---------------------------------------------------------------------- diff --git a/setup.py b/setup.py index 24bfc03..f0e1038 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ try: - from setuptools import setup + from setuptools import setup except ImportError: - from distutils.core import setup + from distutils.core import setup __author__ = "The PredictionIO Team" __email__ = "[email protected]" @@ -10,7 +10,7 @@ __license__ = "Apache License, Version 2.0" setup( name='PredictionIO', - version="0.8.3", + version="0.8.5", author=__author__, author_email=__email__, packages=['predictionio'], @@ -18,17 +18,17 @@ setup( license='LICENSE.txt', description='PredictionIO Python SDK', classifiers=[ - 'Programming Language :: Python', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: OS Independent', - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'Intended Audience :: Science/Research', - 'Environment :: Web Environment', - 'Topic :: Internet :: WWW/HTTP', - 'Topic :: Scientific/Engineering :: Artificial Intelligence', - 'Topic :: Scientific/Engineering :: Information Analysis', - 'Topic :: Software Development :: Libraries :: Python Modules'], + 'Programming Language :: Python', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Intended Audience :: Science/Research', + 'Environment :: Web Environment', + 'Topic :: Internet :: WWW/HTTP', + 'Topic :: Scientific/Engineering :: Artificial Intelligence', + 'Topic :: Scientific/Engineering :: Information Analysis', + 'Topic :: Software Development :: Libraries :: Python Modules'], long_description="""PredictionIO Python SDK PredictionIO is a prediction server for building smart @@ -50,5 +50,5 @@ setup( PredictionIO API to Python programmers so that they can focus on their application logic. """, - install_requires=["pytz >= 2014.2",], - ) + install_requires=["pytz >= 2014.2", ], +) http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/conversion_test.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/conversion_test.py b/tests-obsolete/conversion_test.py new file mode 100644 index 0000000..b9dca97 --- /dev/null +++ b/tests-obsolete/conversion_test.py @@ -0,0 +1,16 @@ +import timeit + +if __name__ == "__main__": + a = True + + t = timeit.Timer("json.dumps(True)", "import json") + + t_bool2json = t.timeit(1000) / 1000 + print("bool 2 json") + print(t_bool2json) + + t = timeit.Timer("str(True).lower()", "") + + t_bool2string = t.timeit(1000) / 1000 + print("bool 2 string") + print(t_bool2string) http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/import_testdata.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/import_testdata.py b/tests-obsolete/import_testdata.py new file mode 100644 index 0000000..e5338c0 --- /dev/null +++ b/tests-obsolete/import_testdata.py @@ -0,0 +1,46 @@ +""" +Import simple test data for testing getting itemrec +""" +import predictionio + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" +API_URL = "http://localhost:7070" + +MIN_VERSION = '0.5.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + +if __name__ == "__main__": + client = predictionio.Client(APP_KEY, 1, API_URL) + + client.create_user("u0") + client.create_user("u1") + client.create_user("u2") + client.create_user("u3") + + client.create_item("i0", ("t1",), {"custom1": "i0c1"}) + client.create_item("i1", ("t1", "t2"), {"custom1": "i1c1", "custom2": "i1c2"}) + client.create_item("i2", ("t1", "t2"), {"custom2": "i2c2"}) + client.create_item("i3", ("t1",)) + + client.identify("u0") + client.record_action_on_item("rate", "i0", {"pio_rate": 2}) + client.record_action_on_item("rate", "i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i2", {"pio_rate": 4}) + + client.identify("u1") + client.record_action_on_item("rate", "i2", {"pio_rate": 4}) + client.record_action_on_item("rate", "i3", {"pio_rate": 1}) + + client.identify("u2") + client.record_action_on_item("rate", "i1", {"pio_rate": 2}) + client.record_action_on_item("rate", "i2", {"pio_rate": 1}) + client.record_action_on_item("rate", "i3", {"pio_rate": 3}) + + client.identify("u3") + client.record_action_on_item("rate", "i0", {"pio_rate": 5}) + client.record_action_on_item("rate", "i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i3", {"pio_rate": 2}) + + client.close() http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/import_testdata_id_mismatch.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/import_testdata_id_mismatch.py b/tests-obsolete/import_testdata_id_mismatch.py new file mode 100644 index 0000000..104f75c --- /dev/null +++ b/tests-obsolete/import_testdata_id_mismatch.py @@ -0,0 +1,46 @@ +""" +Import simple test data for testing getting itemrec +""" +import predictionio + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" +API_URL = "http://localhost:8000" + +MIN_VERSION = '0.5.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + +if __name__ == "__main__": + client = predictionio.Client(APP_KEY, 1, API_URL) + + client.create_user("u0") + client.create_user("u1") + client.create_user("u2") + client.create_user("u3") + + client.create_item("i0", ("t1",), {"custom1": "i0c1"}) + client.create_item("i1", ("t1", "t2"), {"custom1": "i1c1", "custom2": "i1c2"}) + client.create_item("i2", ("t1", "t2"), {"custom2": "i2c2"}) + client.create_item("i3", ("t1",)) + + client.identify("u0x") + client.record_action_on_item("rate", "i0", {"pio_rate": 2}) + client.record_action_on_item("rate", "i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i2", {"pio_rate": 4}) + + client.identify("u1x") + client.record_action_on_item("rate", "i2", {"pio_rate": 4}) + client.record_action_on_item("rate", "i3", {"pio_rate": 1}) + + client.identify("u2x") + client.record_action_on_item("rate", "i1", {"pio_rate": 2}) + client.record_action_on_item("rate", "i2", {"pio_rate": 1}) + client.record_action_on_item("rate", "i3", {"pio_rate": 3}) + + client.identify("u3x") + client.record_action_on_item("rate", "i0", {"pio_rate": 5}) + client.record_action_on_item("rate", "i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i3", {"pio_rate": 2}) + + client.close() http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/import_testdata_special_char.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/import_testdata_special_char.py b/tests-obsolete/import_testdata_special_char.py new file mode 100644 index 0000000..c047b6a --- /dev/null +++ b/tests-obsolete/import_testdata_special_char.py @@ -0,0 +1,46 @@ +""" +Import simple test data (id with special characters) for testing getting itemrec +""" +import predictionio + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" +API_URL = "http://localhost:8000" + +MIN_VERSION = '0.5.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + +if __name__ == "__main__": + client = predictionio.Client(APP_KEY, 1, API_URL) + + client.create_user("[email protected]") + client.create_user("[email protected]") + client.create_user("http://u2.com") + client.create_user("[email protected]") + + client.create_item("http://i0.com", ("t1",), {"custom1": "i0c1"}) + client.create_item("i1@i1", ("t1", "t2"), {"custom1": "i1c1", "custom2": "i1c2"}) + client.create_item("i2.org", ("t1", "t2"), {"custom2": "i2c2"}) + client.create_item("i3", ("t1",)) + + client.identify("[email protected]") + client.record_action_on_item("rate", "http://i0.com", {"pio_rate": 2}) + client.record_action_on_item("rate", "i1@i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i2.org", {"pio_rate": 4}) + + client.identify("[email protected]") + client.record_action_on_item("rate", "i2.org", {"pio_rate": 4}) + client.record_action_on_item("rate", "i3", {"pio_rate": 1}) + + client.identify("http://u2.com") + client.record_action_on_item("rate", "i1@i1", {"pio_rate": 2}) + client.record_action_on_item("rate", "i2.org", {"pio_rate": 1}) + client.record_action_on_item("rate", "i3", {"pio_rate": 3}) + + client.identify("[email protected]") + client.record_action_on_item("rate", "http://i0.com", {"pio_rate": 5}) + client.record_action_on_item("rate", "i1@i1", {"pio_rate": 3}) + client.record_action_on_item("rate", "i3", {"pio_rate": 2}) + + client.close() http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/predictionio_itemrec_test.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/predictionio_itemrec_test.py b/tests-obsolete/predictionio_itemrec_test.py new file mode 100644 index 0000000..3105f0f --- /dev/null +++ b/tests-obsolete/predictionio_itemrec_test.py @@ -0,0 +1,336 @@ +""" +Test getting itemrec after algo training completes. +""" + +from __future__ import print_function + +import unittest + +import predictionio + + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" # replace this with your AppKey +API_URL = "http://localhost:8000" # PredictoinIO Server + +DEBUG = True + +MIN_VERSION = '0.6.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + + +class TestPredictionIO(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_get_itemrec_exception_deprecated(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + try: + client.get_itemrec("uidwithoutrec", 10, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: # noqa + pass # expected exception + except: + raise + + client.close() + + def test_get_itemrec_exception(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + client.identify("uidwithoutrec") + + try: + client.get_itemrec_topn("python-itemrec-engine", 10) + except predictionio.ItemRecNotFoundError as e: # noqa + pass # expected exception + except: + raise + + try: + client.get_itemrec_topn("python-itemrec-engine", 10, + {"pio_itypes": ("t1",), "pio_latlng": [1.34, 5.67], "pio_within": 5.0, + "pio_unit": "km", "pio_attributes": ["custom1", "custom2"]}) + except predictionio.ItemRecNotFoundError as e: # noqa + pass # expected exception + except: + raise + + client.close() + + def test_get_itemrec_deprecated(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + # request more + try: + itemrec = client.get_itemrec("u0", 10, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"]}) + + try: + itemrec = client.get_itemrec("u1", 10, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": ["i2", "i1", "i0", "i3"]}) or + (itemrec == {"pio_iids": ["i2", "i0", "i1", "i3"]})) + + try: + itemrec = client.get_itemrec("u2", 10, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertTrue((itemrec == {"pio_iids": ["i3", "i0", "i1", "i2"]}) or + (itemrec == {"pio_iids": ["i3", "i1", "i0", "i2"]})) + + try: + itemrec = client.get_itemrec("u3", 6, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertTrue((itemrec == {"pio_iids": ["i0", "i1", "i2", "i3"]}) or + (itemrec == {"pio_iids": ["i0", "i2", "i1", "i3"]})) + + # request less + try: + itemrec = client.get_itemrec("u0", 1, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2"]}) + + try: + itemrec = client.get_itemrec("u0", 2, "python-itemrec-engine") + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3"]}) + + # request with optional attributes + + # pio_itypes + try: + itemrec = client.get_itemrec("u0", 10, "python-itemrec-engine", pio_itypes=("t1", "t2")) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"]}) + + # subset itypes + try: + itemrec = client.get_itemrec("u0", 10, "python-itemrec-engine", pio_itypes=("t2",)) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i1"]}) + + # nonexisting itypes + try: + itemrec = client.get_itemrec("u0", 10, "python-itemrec-engine", pio_itypes=("other-itype",)) + except predictionio.ItemRecNotFoundError as e: + pass # expected no recommendation + except: + raise + + # pio_attributes + try: + itemrec = client.get_itemrec("u0", 10, "python-itemrec-engine", pio_itypes=("t1",), + pio_attributes=["custom1", "custom2"]) + except predictionio.ItemRecNotFoundError as e: # noqa + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"], "custom1": [None, None, "i1c1", "i0c1"], + "custom2": ["i2c2", None, "i1c2", None]}) + + client.close() + + def test_get_itemrec(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + # request more + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"]}) + + client.identify("u1") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertTrue((itemrec == {"pio_iids": ["i2", "i1", "i0", "i3"]}) or + (itemrec == {"pio_iids": ["i2", "i0", "i1", "i3"]})) + + client.identify("u2") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertTrue((itemrec == {"pio_iids": ["i3", "i0", "i1", "i2"]}) or + (itemrec == {"pio_iids": ["i3", "i1", "i0", "i2"]})) + + client.identify("u3") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 6) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertTrue((itemrec == {"pio_iids": ["i0", "i1", "i2", "i3"]}) or + (itemrec == {"pio_iids": ["i0", "i2", "i1", "i3"]})) + + # request less + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 1) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2"]}) + + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 2) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3"]}) + + # request with optional attributes + + # pio_itypes + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10, {"pio_itypes": ("t1", "t2")}) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"]}) + + # subset itypes + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10, {"pio_itypes": ("t2",)}) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + if DEBUG: + print(itemrec) + self.assertEqual(itemrec, {"pio_iids": ["i2", "i1"]}) + + # nonexisting itypes + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10, {"pio_itypes": ("other-itype",)}) + except predictionio.ItemRecNotFoundError as e: + pass # expected no recommendation + except: + raise + + # pio_attributes + client.identify("u0") + try: + itemrec = client.get_itemrec_topn("python-itemrec-engine", 10, + {"pio_itypes": ("t1",), "pio_attributes": ["custom1", "custom2"]}) + except predictionio.ItemRecNotFoundError as e: # noqa + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": ["i2", "i3", "i1", "i0"], "custom1": [None, None, "i1c1", "i0c1"], + "custom2": ["i2c2", None, "i1c2", None]}) + + # TODO pio_latlng + # TODO pio_within + # TODO pio_unit + + client.close() + + +if __name__ == "__main__": + unittest.main() http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/predictionio_itemrec_test_special_char.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/predictionio_itemrec_test_special_char.py b/tests-obsolete/predictionio_itemrec_test_special_char.py new file mode 100644 index 0000000..a622800 --- /dev/null +++ b/tests-obsolete/predictionio_itemrec_test_special_char.py @@ -0,0 +1,366 @@ +""" +Test getting itemrec after algo training completes. +""" +import unittest + +import predictionio + + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" # replace this with your AppKey +API_URL = "http://localhost:8000" # PredictoinIO Server + +DEBUG = True + +MIN_VERSION = '0.6.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + + +class TestPredictionIO(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_get_itemrec_deprecated(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + uid0 = "[email protected]" + uid1 = "[email protected]" + uid2 = "http://u2.com" + uid3 = "[email protected]" + + iid0 = "http://i0.com" + iid1 = "i1@i1" + iid2 = "i2.org" + iid3 = "i3" + + engine_name = "itemrec" + + # request more + try: + itemrec = client.get_itemrec(uid0, 10, engine_name) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0]}) + + try: + itemrec = client.get_itemrec(uid1, 10, engine_name) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid2, iid1, iid0, iid3]}) or + (itemrec == {"pio_iids": [iid2, iid0, iid1, iid3]})) + + try: + itemrec = client.get_itemrec(uid2, 10, engine_name) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid3, iid0, iid1, iid2]}) or + (itemrec == {"pio_iids": [iid3, iid1, iid0, iid2]})) + + try: + itemrec = client.get_itemrec(uid3, 6, engine_name) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid0, iid1, iid2, iid3]}) or + (itemrec == {"pio_iids": [iid0, iid2, iid1, iid3]})) + + # request less + try: + itemrec = client.get_itemrec(uid0, 1, engine_name) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2]}) + + try: + itemrec = client.get_itemrec(uid0, 2, engine_name) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3]}) + + # request with optional attributes + + # pio_itypes + try: + itemrec = client.get_itemrec(uid0, 10, engine_name, pio_itypes=("t1", "t2")) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0]}) + + # subset itypes + try: + itemrec = client.get_itemrec(uid0, 10, engine_name, pio_itypes=("t2",)) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid1]}) + + # nonexisting itypes + try: + client.get_itemrec(uid0, 10, engine_name, pio_itypes=("other-itype",)) + except predictionio.ItemRecNotFoundError as e: + print(e) + pass # expected no recommendation + except: + raise + + # pio_attributes + try: + itemrec = client.get_itemrec(uid0, 10, engine_name, pio_itypes=("t1",), + pio_attributes=["custom1", "custom2"]) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0], "custom1": [None, None, "i1c1", "i0c1"], + "custom2": ["i2c2", None, "i1c2", None]}) + + client.close() + + def test_get_itemrec(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + uid0 = "[email protected]" + uid1 = "[email protected]" + uid2 = "http://u2.com" + uid3 = "[email protected]" + + iid0 = "http://i0.com" + iid1 = "i1@i1" + iid2 = "i2.org" + iid3 = "i3" + + engine_name = "itemrec" + + # request more + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 10) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0]}) + + client.identify(uid1) + try: + itemrec = client.get_itemrec_topn(engine_name, 10) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid2, iid1, iid0, iid3]}) or + (itemrec == {"pio_iids": [iid2, iid0, iid1, iid3]})) + + client.identify(uid2) + try: + itemrec = client.get_itemrec_topn(engine_name, 10) + except predictionio.ItemRecNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid3, iid0, iid1, iid2]}) or + (itemrec == {"pio_iids": [iid3, iid1, iid0, iid2]})) + + client.identify(uid3) + try: + itemrec = client.get_itemrec_topn(engine_name, 6) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertTrue((itemrec == {"pio_iids": [iid0, iid1, iid2, iid3]}) or + (itemrec == {"pio_iids": [iid0, iid2, iid1, iid3]})) + + # request less + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 1) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2]}) + + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 2) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3]}) + + # request with optional attributes + + # pio_itypes + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 10, {"pio_itypes": ("t1", "t2")}) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0]}) + + # subset itypes + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 10, {"pio_itypes": ("t2",)}) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid1]}) + + # nonexisting itypes + client.identify(uid0) + try: + client.get_itemrec_topn(engine_name, 10, {"pio_itypes": ("other-itype",)}) + except predictionio.ItemRecNotFoundError as e: + print(e) + pass # expected no recommendation + except: + raise + + # pio_attributes + client.identify(uid0) + try: + itemrec = client.get_itemrec_topn(engine_name, 10, + {"pio_itypes": ("t1",), "pio_attributes": ["custom1", "custom2"]}) + except predictionio.ItemRecNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemrec) + + self.assertEqual(itemrec, {"pio_iids": [iid2, iid3, iid1, iid0], "custom1": [None, None, "i1c1", "i0c1"], + "custom2": ["i2c2", None, "i1c2", None]}) + + # TODO pio_latlng + # TODO pio_within + # TODO pio_unit + + client.close() + + +if __name__ == "__main__": + unittest.main() http://git-wip-us.apache.org/repos/asf/incubator-predictionio-sdk-python/blob/bc678328/tests-obsolete/predictionio_itemsim_test.py ---------------------------------------------------------------------- diff --git a/tests-obsolete/predictionio_itemsim_test.py b/tests-obsolete/predictionio_itemsim_test.py new file mode 100644 index 0000000..45fa151 --- /dev/null +++ b/tests-obsolete/predictionio_itemsim_test.py @@ -0,0 +1,200 @@ +""" +Test getting itemsim after algo training completes (pdio-itemsimcf with cosine sim). +""" +import unittest + +import predictionio + + +APP_KEY = "gDx1XuMUC9vu1YWWPRZkLRTftoq7m73mlj2MtnZEjncPlZ1JxUS2s7oajwP9xrZQ" # replace this with your AppKey +API_URL = "http://localhost:8000" # PredictoinIO Server + +DEBUG = True + +MIN_VERSION = '0.6.0' +if predictionio.__version__ < MIN_VERSION: + err = "Require PredictionIO Python SDK version >= %s" % MIN_VERSION + raise Exception(err) + + +class TestPredictionIO(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def test_get_itemsim_exception(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + try: + client.get_itemsim_topn("python-itemsim-engine", "iidwithoutsim", 10) + except predictionio.ItemSimNotFoundError as e: + pass # expected exception + except: + raise + + try: + client.get_itemsim_topn("python-itemsim-engine", "iidwithoutsim", 10, + {"pio_itypes": ("t1",), "pio_latlng": [1.34, 5.67], "pio_within": 5.0, + "pio_unit": "km", "pio_attributes": ["custom1", "custom2"]}) + except predictionio.ItemSimNotFoundError as e: + if DEBUG: + print(e) + pass # expected exception + except: + raise + + client.close() + + def test_get_itemsim(self): + client = predictionio.Client(APP_KEY, 1, API_URL) + + # request more than what is available + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i0", 10) + except predictionio.ItemSimNotFoundError as e: + print + "ERROR: have you run import_testdata.py and then wait for the algorithm training completion?" + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertTrue((itemsim == {"pio_iids": ["i1", "i2", "i3"]}) or + (itemsim == {"pio_iids": ["i1", "i3", "i2"]})) + + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 10) + except predictionio.ItemSimNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertTrue((itemsim == {"pio_iids": ["i2", "i3", "i0"]})) + + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i2", 10) + except predictionio.ItemSimNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertTrue((itemsim == {"pio_iids": ["i1", "i3", "i0"]})) + + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i3", 10) + except predictionio.ItemSimNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertTrue((itemsim == {"pio_iids": ["i1", "i2", "i0"]})) + + # request less + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 1) + except predictionio.ItemSimNotFoundError as e: + print + "ERROR: have you run import_testdata.py and then wait for the algorithm training completion?" + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertEqual(itemsim, {"pio_iids": ["i2"]}) + + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 2) + except predictionio.ItemSimNotFoundError as e: + print + "ERROR: have you run import_testdata.py and then wait for the algorithm training completion?" + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertEqual(itemsim, {"pio_iids": ["i2", "i3"]}) + + # request with optional attributes + + # pio_itypes + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 10, {"pio_itypes": ("t1", "t2")}) + except predictionio.ItemSimNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertEqual(itemsim, {"pio_iids": ["i2", "i3", "i0"]}) + + # subset itypes + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 10, {"pio_itypes": ("t2",)}) + except predictionio.ItemSimNotFoundError as e: + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertEqual(itemsim, {"pio_iids": ["i2"]}) + + # nonexisting itypes + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i0", 10, {"pio_itypes": ("other-itype",)}) + except predictionio.ItemSimNotFoundError as e: + pass # expected no recommendation + except: + raise + + # pio_attributes + try: + itemsim = client.get_itemsim_topn("python-itemsim-engine", "i1", 10, + {"pio_itypes": ("t1",), "pio_attributes": ["custom1", "custom2"]}) + except predictionio.ItemSimNotFoundError as e: + print(e) + print("ERROR: have you run import_testdata.py and then wait for the algorithm training completion?") + raise + except: + raise + + if DEBUG: + print(itemsim) + + self.assertEqual(itemsim, {"pio_iids": ["i2", "i3", "i0"], "custom1": [None, None, "i0c1"], + "custom2": ["i2c2", None, None]}) + + # TODO pio_latlng + # TODO pio_within + # TODO pio_unit + + client.close() + + +if __name__ == "__main__": + unittest.main()
