|
| 1 | +/** |
| 2 | + * Copyright 2015 IBM Corp. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | + * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | + * the License. |
| 13 | + */ |
| 14 | +package com.ibm.watson.developer_cloud.visual_recognition.v2; |
| 15 | + |
| 16 | +import java.io.File; |
| 17 | +import java.io.FileInputStream; |
| 18 | +import java.io.FileNotFoundException; |
| 19 | +import java.io.InputStream; |
| 20 | +import java.util.List; |
| 21 | + |
| 22 | +import com.google.gson.JsonArray; |
| 23 | +import com.google.gson.JsonObject; |
| 24 | +import com.google.gson.JsonPrimitive; |
| 25 | +import com.ibm.watson.developer_cloud.http.HttpMediaType; |
| 26 | +import com.ibm.watson.developer_cloud.http.InputStreamRequestBody; |
| 27 | +import com.ibm.watson.developer_cloud.http.RequestBuilder; |
| 28 | +import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.Classification; |
| 29 | +import com.ibm.watson.developer_cloud.service.WatsonService; |
| 30 | +import com.ibm.watson.developer_cloud.util.Validate; |
| 31 | +import com.ibm.watson.developer_cloud.visual_recognition.v2.model.VisualClassification; |
| 32 | +import com.ibm.watson.developer_cloud.visual_recognition.v2.model.VisualClassifier; |
| 33 | +import com.ibm.watson.developer_cloud.visual_recognition.v2.model.VisualClassifiers; |
| 34 | +import com.squareup.okhttp.MultipartBuilder; |
| 35 | +import com.squareup.okhttp.Request; |
| 36 | +import com.squareup.okhttp.RequestBody; |
| 37 | + |
| 38 | +/** |
| 39 | + * Visual Recognition allows you to derive insights from an image based on its visual content. You |
| 40 | + * can organize image libraries, understand an individual image, and create custom classifiers for |
| 41 | + * specific results that are tailored to your needs. |
| 42 | + * |
| 43 | + * @version v2 |
| 44 | + * @see <a |
| 45 | + * href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/visual-recognition.html"> |
| 46 | + * Visual Recognition</a> |
| 47 | + */ |
| 48 | +public class VisualRecognition extends WatsonService { |
| 49 | + |
| 50 | + /** The version date: 2015-12-02. */ |
| 51 | + public static final String VERSION_DATE_2015_12_02 = "2015-12-02"; |
| 52 | + private static final String POSITIVE_EXAMPLES = "positive_examples"; |
| 53 | + private static final String NEGATIVE_EXAMPLES = "negative_examples"; |
| 54 | + private static final String IMAGES_FILE = "images_file"; |
| 55 | + private static final String NAME = "name"; |
| 56 | + private static final String VERBOSE = "verbose"; |
| 57 | + private static final String CLASSIFIER_IDS = "classifier_ids"; |
| 58 | + |
| 59 | + private static final String PATH_CLASSIFIER = "/v2/classifiers/%s"; |
| 60 | + private static final String PATH_CLASSIFIERS = "/v2/classifiers"; |
| 61 | + private static final String PATH_CLASSIFY = "/v2/classify"; |
| 62 | + private static final String URL = |
| 63 | + "https://gateway.watsonplatform.net/visual-recognition-beta/api"; |
| 64 | + |
| 65 | + private String versionDate; |
| 66 | + |
| 67 | + /** |
| 68 | + * Instantiates a new Visual Recognition V2 service. |
| 69 | + * |
| 70 | + * @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value |
| 71 | + * will keep your API calls from failing when the service introduces breaking changes. |
| 72 | + */ |
| 73 | + public VisualRecognition(String versionDate) { |
| 74 | + super("visual_recognition"); |
| 75 | + setEndPoint(URL); |
| 76 | + this.versionDate = versionDate; |
| 77 | + } |
| 78 | + |
| 79 | + |
| 80 | + /** |
| 81 | + * Classifies the image/s against all the classifiers. The response includes a score for a |
| 82 | + * classifier if the score meets the minimum threshold of 0.5. If no score meets the threshold for |
| 83 | + * an image, no classifiers are returned. <br> |
| 84 | + * <br> |
| 85 | + * Here is an example of how to classify an image using all the classifiers: |
| 86 | + * |
| 87 | + * <pre> |
| 88 | + * VisualRecognition service = new VisualRecognition("2015-12-02"); |
| 89 | + * service.setUsernameAndPassword("<username>", "<password>"); |
| 90 | + * |
| 91 | + * File image = new File("car.png"); |
| 92 | + * |
| 93 | + * VisualClassification result = service.classify(image); |
| 94 | + * System.out.println(result); |
| 95 | + * </pre> |
| 96 | + * |
| 97 | + * @param imagesFile the image/s to classify |
| 98 | + * @return the visual recognition images |
| 99 | + */ |
| 100 | + public VisualClassification classify(final File imagesFile) { |
| 101 | + return classify(imagesFile, (VisualClassifier) null); |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Classifies the images against the label groups and labels. The response includes a score for a |
| 106 | + * label if the score meets the minimum threshold of 0.5. If no score meets the threshold for an |
| 107 | + * image, no labels are returned. |
| 108 | + * |
| 109 | + * <br> |
| 110 | + * <br> |
| 111 | + * Here is an example of how to classify an image using an existing classifier: |
| 112 | + * |
| 113 | + * <pre> |
| 114 | + * VisualRecognition service = new VisualRecognition("2015-12-02"); |
| 115 | + * service.setUsernameAndPassword("<username>", "<password>"); |
| 116 | + * |
| 117 | + * File image = new File("car.png"); |
| 118 | + * VisualClassifier car = new VisualClassifier("Car"); |
| 119 | + * |
| 120 | + * VisualClassification result = service.classify(image, car); |
| 121 | + * System.out.println(result); |
| 122 | + * </pre> |
| 123 | + * |
| 124 | + * @param imagesFile the image/s to classify |
| 125 | + * @param classifiers the classifiers |
| 126 | + * @return the visual recognition images |
| 127 | + */ |
| 128 | + public VisualClassification classify(final File imagesFile, final VisualClassifier... classifiers) { |
| 129 | + Validate.isTrue(imagesFile != null && imagesFile.exists(), |
| 130 | + "image cannot be null or not be found"); |
| 131 | + |
| 132 | + InputStream stream = null; |
| 133 | + try { |
| 134 | + stream = new FileInputStream(imagesFile); |
| 135 | + } catch (FileNotFoundException e) { |
| 136 | + } |
| 137 | + return classify(imagesFile.getName(), stream, classifiers); |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * Classifies the image/s against the Classifiers. The response includes a score for a classifier |
| 142 | + * only if the score meets the minimum threshold of 0.5. If no score meets the threshold for an |
| 143 | + * image, no classifiers are returned. |
| 144 | + * |
| 145 | + * <br> |
| 146 | + * <br> |
| 147 | + * Here is an example of how to classify an InputStream image with an existing classifier: |
| 148 | + * |
| 149 | + * <pre> |
| 150 | + * VisualRecognition service = new VisualRecognition("2015-12-02"); |
| 151 | + * service.setUsernameAndPassword("<username>", "<password>"); |
| 152 | + * |
| 153 | + * FileInputStream image = new FileInputStream("car.png"); |
| 154 | + * VisualClassifier car = new VisualClassifier("Car"); |
| 155 | + * |
| 156 | + * VisualClassification result = service.classify("foo.png", image, car); |
| 157 | + * System.out.println(result); |
| 158 | + * </pre> |
| 159 | + * |
| 160 | + * @param filename The file name |
| 161 | + * @param imagesInputStream the image/s input stream to classify |
| 162 | + * @param classifiers the classifiers |
| 163 | + * @return the {@link Classification} |
| 164 | + */ |
| 165 | + public VisualClassification classify(final String filename, final InputStream imagesInputStream, |
| 166 | + final VisualClassifier... classifiers) { |
| 167 | + Validate.notNull(imagesInputStream, "image cannot be null"); |
| 168 | + Validate.notNull(filename, "filename cannot be null"); |
| 169 | + |
| 170 | + final MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); |
| 171 | + bodyBuilder.addFormDataPart(IMAGES_FILE, filename, |
| 172 | + InputStreamRequestBody.create(HttpMediaType.BINARY_FILE, imagesInputStream)); |
| 173 | + |
| 174 | + if (classifiers != null && classifiers.length > 0) { |
| 175 | + JsonObject classifierIds = getClassifierIdsAsJson(classifiers); |
| 176 | + bodyBuilder.addFormDataPart(CLASSIFIER_IDS, classifierIds.toString()); |
| 177 | + } |
| 178 | + // TODO: Add the classifiers ids |
| 179 | + final RequestBuilder requestBuilder = |
| 180 | + RequestBuilder.post(PATH_CLASSIFY).withQuery(VERSION, versionDate) |
| 181 | + .withBody(bodyBuilder.build()); |
| 182 | + |
| 183 | + return executeRequest(requestBuilder.build(), VisualClassification.class); |
| 184 | + } |
| 185 | + |
| 186 | + /** |
| 187 | + * Creates a {@link JsonObject} with an array of classifier ids. |
| 188 | + * |
| 189 | + * @param classifiers the classifiers |
| 190 | + * @return the classifier ids as {@link JsonObject} |
| 191 | + */ |
| 192 | + private JsonObject getClassifierIdsAsJson(VisualClassifier... classifiers) { |
| 193 | + JsonObject ret = new JsonObject(); |
| 194 | + JsonArray array = new JsonArray(); |
| 195 | + ret.add(CLASSIFIER_IDS, array); |
| 196 | + |
| 197 | + for (VisualClassifier classifier : classifiers) { |
| 198 | + array.add(new JsonPrimitive(classifier.getId())); |
| 199 | + } |
| 200 | + return ret; |
| 201 | + } |
| 202 | + |
| 203 | + /** |
| 204 | + * Train a new classifier on the uploaded image data. Upload a compressed (.zip) file of images |
| 205 | + * (.jpg, .png, or .gif) with positive examples that show your classifier and another compressed |
| 206 | + * file with negative examples that are similar to but do NOT show your classifier. <br> |
| 207 | + * <br> |
| 208 | + * Here is an example of how to create a classifier with positive and negatives images: |
| 209 | + * |
| 210 | + * <pre> |
| 211 | + * VisualRecognition service = new VisualRecognition("2015-12-02"); |
| 212 | + * service.setUsernameAndPassword("<username>", "<password>"); |
| 213 | + * |
| 214 | + * File positiveImages = new File("positive.zip"); // zip file with at least 10 images |
| 215 | + * File negativeImages = new File("negative.zip"); |
| 216 | + * |
| 217 | + * VisualClassifier foo = service.createClassifier("foo", positiveImages, negativeImages); |
| 218 | + * System.out.println(foo); |
| 219 | + * </pre> |
| 220 | + * |
| 221 | + * |
| 222 | + * @param name the classifier name |
| 223 | + * @param positiveImages A compressed (.zip) file of images which prominently depict the visual |
| 224 | + * subject for a new classifier. Must contain a minimum of 10 images. |
| 225 | + * @param negativeImages A compressed (.zip) file of images which do not depict the subject for a |
| 226 | + * new classifier. Must contain a minimum of 10 images. |
| 227 | + * @return the created {@link VisualClassifier} |
| 228 | + * @see VisualClassifier |
| 229 | + */ |
| 230 | + public VisualClassifier createClassifier(final String name, final File positiveImages, |
| 231 | + final File negativeImages) { |
| 232 | + Validate.isTrue(positiveImages != null && positiveImages.exists(), |
| 233 | + "positiveImages cannot be null or not be found"); |
| 234 | + Validate.isTrue(negativeImages != null && negativeImages.exists(), |
| 235 | + "negativeImages cannot be null or not be found"); |
| 236 | + |
| 237 | + Validate.isTrue(name != null && !name.isEmpty(), "name cannot be null or empty"); |
| 238 | + |
| 239 | + // POST body |
| 240 | + RequestBody body = |
| 241 | + new MultipartBuilder() |
| 242 | + .type(MultipartBuilder.FORM) |
| 243 | + .addFormDataPart(POSITIVE_EXAMPLES, positiveImages.getName(), |
| 244 | + RequestBody.create(HttpMediaType.BINARY_FILE, positiveImages)) |
| 245 | + .addFormDataPart(NEGATIVE_EXAMPLES, negativeImages.getName(), |
| 246 | + RequestBody.create(HttpMediaType.BINARY_FILE, negativeImages)) |
| 247 | + .addFormDataPart(NAME, name).build(); |
| 248 | + |
| 249 | + Request request = |
| 250 | + RequestBuilder.post(PATH_CLASSIFIERS).withQuery(VERSION, versionDate).withBody(body) |
| 251 | + .build(); |
| 252 | + |
| 253 | + return executeRequest(request, VisualClassifier.class); |
| 254 | + } |
| 255 | + |
| 256 | + |
| 257 | + /** |
| 258 | + * Deletes a classifier. |
| 259 | + * |
| 260 | + * @param classifierId the classifier ID to delete |
| 261 | + * @see VisualClassifier |
| 262 | + */ |
| 263 | + public void deleteClassifier(String classifierId) { |
| 264 | + Validate.isTrue(classifierId != null && !classifierId.isEmpty(), |
| 265 | + "classifierId cannot be null or empty"); |
| 266 | + |
| 267 | + Request request = |
| 268 | + RequestBuilder.delete(String.format(PATH_CLASSIFIER, classifierId)) |
| 269 | + .withQuery(VERSION, versionDate).build(); |
| 270 | + executeWithoutResponse(request); |
| 271 | + } |
| 272 | + |
| 273 | + /** |
| 274 | + * Retrieves a classifier. |
| 275 | + * |
| 276 | + * @param classifierId the classifier ID |
| 277 | + * @return the classifier list |
| 278 | + * @see VisualClassifier |
| 279 | + */ |
| 280 | + public VisualClassifier getClassifier(String classifierId) { |
| 281 | + Validate.isTrue(classifierId != null && !classifierId.isEmpty(), |
| 282 | + "classifierId cannot be null or empty"); |
| 283 | + |
| 284 | + Request request = |
| 285 | + RequestBuilder.get(String.format(PATH_CLASSIFIER, classifierId)) |
| 286 | + .withQuery(VERSION, versionDate).build(); |
| 287 | + return executeRequest(request, VisualClassifier.class); |
| 288 | + } |
| 289 | + |
| 290 | + /** |
| 291 | + * Retrieves the list of classifiers. |
| 292 | + * |
| 293 | + * @return the classifier list |
| 294 | + * @see VisualClassifier |
| 295 | + */ |
| 296 | + public List<VisualClassifier> getClassifiers() { |
| 297 | + Request request = |
| 298 | + RequestBuilder.get(PATH_CLASSIFIERS).withQuery(VERSION, versionDate) |
| 299 | + .withQuery(VERBOSE, true).build(); |
| 300 | + VisualClassifiers classifiers = executeRequest(request, VisualClassifiers.class); |
| 301 | + return classifiers.getClassifiers(); |
| 302 | + } |
| 303 | +} |