Repository navigation
Expand file tree
/
Copy pathTestVisualRecognition.cs
More file actions
303 lines (250 loc) · 13 KB
/
Copy pathTestVisualRecognition.cs
File metadata and controls
303 lines (250 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Uncomment to train a new classifier
//#define TRAIN_CLASSIFIER
// Uncommnent to delete the trained classifier
//#define DELETE_TRAINED_CLASSIFIER
using UnityEngine;
using System.Collections;
using IBM.Watson.DeveloperCloud.Services.VisualRecognition.v3;
using IBM.Watson.DeveloperCloud.Logging;
using IBM.Watson.DeveloperCloud.Utilities;
using FullSerializer;
using System;
using System.IO;
using System.Collections.Generic;
using IBM.Watson.DeveloperCloud.Connection;
namespace IBM.Watson.DeveloperCloud.UnitTests
{
public class TestVisualRecognition : UnitTest
{
private string _apikey;
private fsSerializer _serializer = new fsSerializer();
private VisualRecognition _visualRecognition;
private string _visualRecognitionVersionDate = "2016-05-20";
private string _classifierID = "";
private string _imageURL = "https://upload.wikimedia.org/wikipedia/commons/e/e9/Official_portrait_of_Barack_Obama.jpg";
#if DELETE_TRAINED_CLASSIFIER
private string _classifierToDelete;
#endif
private bool _getClassifiersTested = false;
#if TRAIN_CLASSIFIER
private bool _trainClassifierTested = false;
private bool _getClassifierTested = false;
private bool _getCoreMLModelTested = false;
#endif
#if DELETE_TRAINED_CLASSIFIER
private bool _deleteClassifierTested = false;
#endif
private bool _classifyGetTested = false;
private bool _classifyPostTested = false;
private bool _detectFacesGetTested = false;
private bool _detectFacesPostTested = false;
public override IEnumerator RunTest()
{
LogSystem.InstallDefaultReactors();
VcapCredentials vcapCredentials = new VcapCredentials();
fsData data = null;
string result = null;
var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL");
var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME");
var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD");
using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword))
{
while (!simpleGet.IsComplete)
yield return null;
result = simpleGet.Result;
}
// Add in a parent object because Unity does not like to deserialize root level collection types.
result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");
// Convert json to fsResult
fsResult r = fsJsonParser.Parse(result, out data);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
// Convert fsResult to VcapCredentials
object obj = vcapCredentials;
r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
if (!r.Succeeded)
throw new WatsonException(r.FormattedMessages);
// Set credentials from imported credntials
Credential credential = vcapCredentials.VCAP_SERVICES["visual_recognition"];
_apikey = credential.Apikey.ToString();
_url = credential.Url.ToString();
// Create credential and instantiate service
Credentials credentials = new Credentials(_apikey, _url);
_visualRecognition = new VisualRecognition(credentials);
_visualRecognition.VersionDate = _visualRecognitionVersionDate;
// Get all classifiers
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get all classifiers");
if (!_visualRecognition.GetClassifiersBrief(OnGetClassifiers, OnFail))
Log.Debug("TestVisualRecognition.GetClassifiers()", "Failed to get all classifiers!");
while (!_getClassifiersTested)
yield return null;
#if TRAIN_CLASSIFIER
// Train classifier
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to train classifier");
string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip";
string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip";
Dictionary<string, string> positiveExamples = new Dictionary<string, string>();
positiveExamples.Add("giraffe", positiveExamplesPath);
if (!_visualRecognition.TrainClassifier(OnTrainClassifier, OnFail, "unity-test-classifier-example", positiveExamples, negativeExamplesPath))
Log.Debug("TestVisualRecognition.TrainClassifier()", "Failed to train classifier!");
while (!_trainClassifierTested)
yield return null;
// Find classifier by ID
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to find classifier by ID");
if (!_visualRecognition.GetClassifier(OnGetClassifier, OnFail, _classifierID))
Log.Debug("TestVisualRecognition.GetClassifier()", "Failed to get classifier!");
while (!_getClassifierTested)
yield return null;
// Download Core ML Model
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get Core ML Model");
if(!_visualRecognition.GetCoreMLModel(OnGetCoreMLModel, OnFail, _classifierID))
Log.Debug("TestVisualRecognition.GetCoreMLModel()", "Failed to get core ml model!");
while (!_getCoreMLModelTested)
yield return null;
#endif
// Classify get
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get classify via URL");
if (!_visualRecognition.Classify(_imageURL, OnClassifyGet, OnFail))
Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
while (!_classifyGetTested)
yield return null;
// Classify post image
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to classify via image on file system");
string imagesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg";
string[] owners = { "IBM", "me" };
string[] classifierIDs = { "default", _classifierID };
if (!_visualRecognition.Classify(OnClassifyPost, OnFail, imagesPath, owners, classifierIDs, 0.5f))
Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
while (!_classifyPostTested)
yield return null;
// Detect faces get
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via URL");
if (!_visualRecognition.DetectFaces(_imageURL, OnDetectFacesGet, OnFail))
Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
while (!_detectFacesGetTested)
yield return null;
// Detect faces post image
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via image");
string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg";
if (!_visualRecognition.DetectFaces(OnDetectFacesPost, OnFail, faceExamplePath))
Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
while (!_detectFacesPostTested)
yield return null;
#if DELETE_TRAINED_CLASSIFIER
#region Delay
Runnable.Run(Delay(_delayTime));
while (_isWaitingForDelay)
yield return null;
#endregion
// Delete classifier by ID
Log.Debug("TestVisualRecognition.RunTest()", "Attempting to delete classifier");
if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, OnFail, _classifierToDelete))
Log.Debug("TestVisualRecognition.DeleteClassifier()", "Failed to delete classifier!");
while (!_deleteClassifierTested)
yield return null;
#endif
Log.Debug("TestVisualRecognition.RunTest()", "Visual Recogition tests complete");
yield break;
}
private void OnGetClassifiers(ClassifiersBrief classifiers, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnGetClassifiers()", "VisualRecognition - GetClassifiers Response: {0}", customData["json"].ToString());
Test(classifiers != null);
_getClassifiersTested = true;
}
#if DELETE_TRAINED_CLASSIFIER
private void OnGetClassifier(ClassifierVerbose classifier, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnGetClassifier()", "VisualRecognition - GetClassifier Response: {0}", customData["json"].ToString());
Test(classifier != null);
_getClassifierTested = true;
}
#endif
#if DELETE_TRAINED_CLASSIFIER
private void OnDeleteClassifier(bool success, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnDeleteClassifier()", "VisualRecognition - DeleteClassifier Response: {0}", success);
Test(success);
_deleteClassifierTested = true;
}
#endif
#if TRAIN_CLASSIFIER
private void OnTrainClassifier(ClassifierVerbose classifier, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnTrainClassifier()", "VisualRecognition - TrainClassifier Response: {0}", customData["json"].ToString());
#if DELETE_TRAINED_CLASSIFIER
_classifierToDelete = classifier.classifier_id;
#endif
_classifierID = classifier.classifier_id;
Test(classifier != null);
_trainClassifierTested = true;
}
#endif
private void OnClassifyGet(ClassifiedImages classify, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnClassifyGet()", "VisualRecognition - ClassifyGet Response: {0}", customData["json"].ToString());
Test(classify != null);
_classifyGetTested = true;
}
private void OnClassifyPost(ClassifiedImages classify, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnClassifyPost()", "VisualRecognition - ClassifyPost Response: {0}", customData["json"].ToString());
Test(classify != null);
_classifyPostTested = true;
}
private void OnDetectFacesGet(DetectedFaces multipleImages, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnDetectFacesGet()", "VisualRecognition - DetectFacesGet Response: {0}", customData["json"].ToString());
Test(multipleImages != null);
_detectFacesGetTested = true;
}
private void OnDetectFacesPost(DetectedFaces multipleImages, Dictionary<string, object> customData)
{
Log.Debug("TestVisualRecognition.OnDetectFacesPost()", "VisualRecognition - DetectFacesPost Response: {0}", customData["json"].ToString());
Test(multipleImages != null);
_detectFacesPostTested = true;
}
#if TRAIN_CLASSIFIER
private void OnGetCoreMLModel(byte[] resp, Dictionary<string, object> customData)
{
Test(resp != null);
_getCoreMLModelTested = true;
}
#endif
#region Delay
#if DELETE_TRAINED_CLASSIFIER
// Introducing a delay because of a known issue with Visual Recognition where newly created classifiers
// will disappear without being deleted if a delete is attempted less than ~10 seconds after creation.
private float _delayTime = 15f;
private bool _isWaitingForDelay = false;
private IEnumerator Delay(float delayTime)
{
_isWaitingForDelay = true;
Log.Debug("TestVisualRecognition.Delay()", "Delaying for {0} seconds....", delayTime);
yield return new WaitForSeconds(delayTime);
_isWaitingForDelay = false;
}
#endif
#endregion
private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData)
{
Log.Error("ExampleRetrieveAndRank.OnFail()", "Error received: {0}", error.ToString());
}
}
}