|
| 1 | +import base64 |
| 2 | +import io |
| 3 | +import json |
| 4 | +import os |
| 5 | +import urllib |
| 6 | + |
| 7 | +import requests |
| 8 | +from PIL import Image |
| 9 | + |
| 10 | +from roboflow.config import CLASSIFICATION_MODEL |
| 11 | +from roboflow.models.inference import InferenceModel |
| 12 | +from roboflow.util.image_utils import check_image_url |
| 13 | +from roboflow.util.prediction import PredictionGroup |
| 14 | + |
| 15 | + |
| 16 | +class KeypointDetectionModel(InferenceModel): |
| 17 | + """ |
| 18 | + Run inference on a classification model hosted on Roboflow or served through |
| 19 | + Roboflow Inference. |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + api_key: str, |
| 25 | + id: str, |
| 26 | + name: str = None, |
| 27 | + version: int = None, |
| 28 | + local: bool = False, |
| 29 | + ): |
| 30 | + """ |
| 31 | + Create a ClassificationModel object through which you can run inference. |
| 32 | +
|
| 33 | + Args: |
| 34 | + api_key (str): private roboflow api key |
| 35 | + id (str): the workspace/project id |
| 36 | + name (str): is the name of the project |
| 37 | + version (int): version number |
| 38 | + local (bool): whether the image is local or hosted |
| 39 | + colors (dict): colors to use for the image |
| 40 | + preprocessing (dict): preprocessing to use for the image |
| 41 | +
|
| 42 | + Returns: |
| 43 | + ClassificationModel Object |
| 44 | + """ |
| 45 | + # Instantiate different API URL parameters |
| 46 | + super(KeypointDetectionModel, self).__init__(api_key, id, version=version) |
| 47 | + self.__api_key = api_key |
| 48 | + self.id = id |
| 49 | + self.name = name |
| 50 | + self.version = version |
| 51 | + self.base_url = "https://detect.roboflow.com/" |
| 52 | + |
| 53 | + if self.name is not None and version is not None: |
| 54 | + self.__generate_url() |
| 55 | + |
| 56 | + if local: |
| 57 | + print("initalizing local keypoint detection model hosted at :" + local) |
| 58 | + self.base_url = local |
| 59 | + |
| 60 | + def predict(self, image_path, hosted=False): |
| 61 | + """ |
| 62 | + Run inference on an image. |
| 63 | +
|
| 64 | + Args: |
| 65 | + image_path (str): path to the image you'd like to perform prediction on |
| 66 | + hosted (bool): whether the image you're providing is hosted on Roboflow |
| 67 | +
|
| 68 | + Returns: |
| 69 | + PredictionGroup Object |
| 70 | +
|
| 71 | + Example: |
| 72 | + >>> import roboflow |
| 73 | +
|
| 74 | + >>> rf = roboflow.Roboflow(api_key="") |
| 75 | +
|
| 76 | + >>> project = rf.workspace().project("PROJECT_ID") |
| 77 | +
|
| 78 | + >>> model = project.version("1").model |
| 79 | +
|
| 80 | + >>> prediction = model.predict("YOUR_IMAGE.jpg") |
| 81 | + """ |
| 82 | + self.__generate_url() |
| 83 | + self.__exception_check(image_path_check=image_path) |
| 84 | + # If image is local image |
| 85 | + if not hosted: |
| 86 | + # Open Image in RGB Format |
| 87 | + image = Image.open(image_path).convert("RGB") |
| 88 | + # Create buffer |
| 89 | + buffered = io.BytesIO() |
| 90 | + image.save(buffered, quality=90, format="JPEG") |
| 91 | + img_dims = image.size |
| 92 | + # Base64 encode image |
| 93 | + img_str = base64.b64encode(buffered.getvalue()) |
| 94 | + img_str = img_str.decode("ascii") |
| 95 | + # Post to API and return response |
| 96 | + resp = requests.post( |
| 97 | + self.api_url, |
| 98 | + data=img_str, |
| 99 | + headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 100 | + ) |
| 101 | + else: |
| 102 | + # Create API URL for hosted image (slightly different) |
| 103 | + self.api_url += "&image=" + urllib.parse.quote_plus(image_path) |
| 104 | + # POST to the API |
| 105 | + resp = requests.post(self.api_url) |
| 106 | + img_dims = {"width": "0", "height": "0"} |
| 107 | + |
| 108 | + if resp.status_code != 200: |
| 109 | + raise Exception(resp.text) |
| 110 | + |
| 111 | + return PredictionGroup.create_prediction_group( |
| 112 | + resp.json(), |
| 113 | + image_dims=img_dims, |
| 114 | + image_path=image_path, |
| 115 | + prediction_type=CLASSIFICATION_MODEL, |
| 116 | + colors=self.colors, |
| 117 | + ) |
| 118 | + |
| 119 | + def load_model(self, name, version): |
| 120 | + """ |
| 121 | + Load a model. |
| 122 | +
|
| 123 | + Args: |
| 124 | + name (str): is the name of the model you'd like to load |
| 125 | + version (int): version number |
| 126 | + """ |
| 127 | + # Load model based on user defined characteristics |
| 128 | + self.name = name |
| 129 | + self.version = version |
| 130 | + self.__generate_url() |
| 131 | + |
| 132 | + def __generate_url(self): |
| 133 | + """ |
| 134 | + Generate a Roboflow API URL on which to run inference. |
| 135 | +
|
| 136 | + Returns: |
| 137 | + url (str): the url on which to run inference |
| 138 | + """ |
| 139 | + |
| 140 | + # Generates URL based on all parameters |
| 141 | + splitted = self.id.rsplit("/") |
| 142 | + without_workspace = splitted[1] |
| 143 | + version = self.version |
| 144 | + if not version and len(splitted) > 2: |
| 145 | + version = splitted[2] |
| 146 | + |
| 147 | + self.api_url = "".join( |
| 148 | + [ |
| 149 | + self.base_url + without_workspace + "/" + str(version), |
| 150 | + "?api_key=" + self.__api_key, |
| 151 | + "&name=YOUR_IMAGE.jpg", |
| 152 | + ] |
| 153 | + ) |
| 154 | + |
| 155 | + def __exception_check(self, image_path_check=None): |
| 156 | + """ |
| 157 | + Check to see if an image exists. |
| 158 | +
|
| 159 | + Args: |
| 160 | + image_path_check (str): path to the image to check |
| 161 | +
|
| 162 | + Raises: |
| 163 | + Exception: if image does not exist |
| 164 | + """ |
| 165 | + # Checks if image exists |
| 166 | + if image_path_check is not None: |
| 167 | + if not os.path.exists(image_path_check) and not check_image_url(image_path_check): |
| 168 | + raise Exception("Image does not exist at " + image_path_check + "!") |
| 169 | + |
| 170 | + def __str__(self): |
| 171 | + """ |
| 172 | + String representation of classification object |
| 173 | + """ |
| 174 | + json_value = { |
| 175 | + "name": self.name, |
| 176 | + "version": self.version, |
| 177 | + "base_url": self.base_url, |
| 178 | + } |
| 179 | + |
| 180 | + return json.dumps(json_value, indent=2) |
0 commit comments