From f065088d2aa26db2190944141540b1bb72ce0f1b Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Sun, 3 Mar 2019 17:57:42 -0600 Subject: [PATCH 01/13] fix: Fix warnings and minor inconsistencies --- .swift-version | 1 - README.md | 4 +- Scripts/coverage.sh | 2 +- .../SpeechToText+Recognize.swift | 4 - .../WebSockets/SpeechToTextRecorder.swift | 4 - .../WebSockets/SpeechToTextSession.swift | 6 +- Source/SupportingFiles/Shared.swift | 5 +- .../VisualRecognition+UIImage.swift | 4 - Tests/TestUtilities.swift | 2 +- .../VisualRecognition+UIImageTests.swift | 2 - .../VisualRecognitionUnitTests.swift | 427 +++++++++--------- .../project.pbxproj | 20 +- .../xcschemes/AssistantV1.xcscheme | 2 +- .../xcschemes/AssistantV2.xcscheme | 2 +- .../xcschemes/DiscoveryV1.xcscheme | 2 +- .../xcschemes/LanguageTranslatorV3.xcscheme | 2 +- .../NaturalLanguageClassifierV1.xcscheme | 2 +- .../NaturalLanguageUnderstandingV1.xcscheme | 2 +- .../xcschemes/PersonalityInsightsV3.xcscheme | 2 +- .../xcschemes/SpeechToTextV1.xcscheme | 2 +- .../xcschemes/TextToSpeechV1.xcscheme | 2 +- .../xcschemes/ToneAnalyzerV3.xcscheme | 2 +- .../xcschemes/VisualRecognitionV3.xcscheme | 2 +- 23 files changed, 247 insertions(+), 256 deletions(-) delete mode 100644 .swift-version diff --git a/.swift-version b/.swift-version deleted file mode 100644 index 5186d0706..000000000 --- a/.swift-version +++ /dev/null @@ -1 +0,0 @@ -4.0 diff --git a/README.md b/README.md index 026f504dc..9604b6e56 100755 --- a/README.md +++ b/README.md @@ -55,11 +55,9 @@ This SDK provides classes and methods to access the following Watson services. ## Requirements - Xcode 9.3+ -- Swift 4.1+ +- Swift 4.2+ - iOS 10.0+ - - ## Installation The IBM Watson Swift SDK can be installed with [Cocoapods](http://cocoapods.org/), [Carthage](https://github.com/Carthage/Carthage), or [Swift Package Manager](https://swift.org/package-manager/). diff --git a/Scripts/coverage.sh b/Scripts/coverage.sh index 85e02e7e7..cc298bf0f 100755 --- a/Scripts/coverage.sh +++ b/Scripts/coverage.sh @@ -8,7 +8,7 @@ #################### # the device to build for -DESTINATION=${DESTINATION:-"OS=11.3,name=iPhone 7"} +DESTINATION=${DESTINATION:-"OS=11.4,name=iPhone X"} # the schemes to build, which must be invoked from the root directory of the project SCHEMES=$(xcodebuild -list | awk 'schemes { if (NF>0) { print $1 } } /Schemes:$/ { schemes = 1 }') diff --git a/Source/SpeechToTextV1/SpeechToText+Recognize.swift b/Source/SpeechToTextV1/SpeechToText+Recognize.swift index dfac439e7..5676f79ed 100644 --- a/Source/SpeechToTextV1/SpeechToText+Recognize.swift +++ b/Source/SpeechToTextV1/SpeechToText+Recognize.swift @@ -210,11 +210,7 @@ extension SpeechToText { // make sure the AVAudioSession shared instance is properly configured do { let audioSession = AVAudioSession.sharedInstance() - #if swift(>=4.2) try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: [.defaultToSpeaker, .mixWithOthers]) - #else - try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker, .mixWithOthers]) - #endif try audioSession.setActive(true) } catch { let failureReason = "Failed to setup the AVAudioSession sharedInstance properly." diff --git a/Source/SpeechToTextV1/WebSockets/SpeechToTextRecorder.swift b/Source/SpeechToTextV1/WebSockets/SpeechToTextRecorder.swift index d345847ae..83a79eaf0 100644 --- a/Source/SpeechToTextV1/WebSockets/SpeechToTextRecorder.swift +++ b/Source/SpeechToTextV1/WebSockets/SpeechToTextRecorder.swift @@ -127,11 +127,7 @@ internal class SpeechToTextRecorder { userInfo: nil, repeats: true ) - #if swift(>=4.2) RunLoop.current.add(powerTimer!, forMode: RunLoop.Mode.common) - #else - RunLoop.current.add(powerTimer!, forMode: RunLoopMode.commonModes) - #endif } internal func startRecording() throws { diff --git a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift index 3c585d77c..896c62b59 100644 --- a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift +++ b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift @@ -98,7 +98,7 @@ public class SpeechToTextSession { defaultHeaders: self.defaultHeaders ) socket.onDisconnect = { [weak self] in - guard let `self` = self else { return } + guard let self = self else { return } if self.recorder.isRecording { self.stopMicrophone() } @@ -325,7 +325,7 @@ public class SpeechToTextSession { // callback if uncompressed let onMicrophoneDataPCM = { [weak self] (pcm: Data) in - guard let `self` = self else { return } + guard let self = self else { return } guard pcm.count > 0 else { return } self.socket.writeAudio(audio: pcm) self.onMicrophoneData?(pcm) @@ -333,7 +333,7 @@ public class SpeechToTextSession { // callback if compressed let onMicrophoneDataOpus = { [weak self] (pcm: Data) in - guard let `self` = self else { return } + guard let self = self else { return } guard pcm.count > 0 else { return } // swiftlint:disable:next force_try try! self.encoder.encode(pcm: pcm) diff --git a/Source/SupportingFiles/Shared.swift b/Source/SupportingFiles/Shared.swift index 0ff3fb5b5..79b6a3311 100644 --- a/Source/SupportingFiles/Shared.swift +++ b/Source/SupportingFiles/Shared.swift @@ -35,7 +35,6 @@ internal struct Shared { static let sdkVersion = "1.4.0" - /// For Basic Authentication, switch to using IAM tokens for "apikey" usernames, /// but only for api keys that are not for ICP (which currently does not support IAM token authentication) static func getAuthMethod(username: String, password: String) -> AuthenticationMethod { @@ -62,10 +61,8 @@ internal struct Shared { if let apiKey = credentials[Constant.apiKey] { let iamURL = credentials[Constant.iamURL] return getAuthMethod(apiKey: apiKey, iamURL: iamURL) - } - else if let username = credentials[Constant.username], + } else if let username = credentials[Constant.username], let password = credentials[Constant.password] { - return getAuthMethod(username: username, password: password) } return nil diff --git a/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift b/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift index 8d540c940..17e5e6ae5 100644 --- a/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift +++ b/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift @@ -180,11 +180,7 @@ extension VisualRecognition { let filename = UUID().uuidString + ".jpg" let directory = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) guard let file = directory.appendingPathComponent(filename) else { throw WatsonError.urlEncoding(path: filename) } - #if swift(>=4.2) guard let data = image.jpegData(compressionQuality: 0.75) else { throw WatsonError.serialization(values: "classify image") } - #else - guard let data = UIImageJPEGRepresentation(image, 0.75) else { throw WatsonError.serialization(values: "classify image") } - #endif try data.write(to: file) return file } diff --git a/Tests/TestUtilities.swift b/Tests/TestUtilities.swift index 1929afebd..52b1a5037 100644 --- a/Tests/TestUtilities.swift +++ b/Tests/TestUtilities.swift @@ -145,7 +145,7 @@ func numberOfFieldsInMultiPartFormBody(request: URLRequest) -> Int? { var count = 0 var rangeStart = bodyData.startIndex while true { - if let boundaryRange = bodyData.range(of: boundaryData, options: [], in: Range.init(rangeStart ..< bodyData.endIndex)) { + if let boundaryRange = bodyData.range(of: boundaryData, options: [], in: rangeStart ..< bodyData.endIndex) { count += 1 rangeStart = boundaryRange.upperBound } else { diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift index a75d104a1..8e823fce2 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift @@ -204,8 +204,6 @@ class VisualRecognitionUIImageTests: XCTestCase { XCTFail("Failed to delete the local model: \(error)") } - } else { - XCTFail("Core ML required iOS 11+") } } } diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift index efb0eb64d..79a87dc73 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift @@ -362,252 +362,258 @@ class VisualRecognitionUnitTests: XCTestCase { // MARK: - VisualRecognition+CoreML - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testGetAndDeleteLocalModel() { - let classifierID = "watson_tools" + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierID = "watson_tools" + + do { + // Save a CoreML file to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_tools.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: [classifierID]) + } - do { - // Save a CoreML file to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_tools.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: [classifierID]) + // Then check if getLocalModel() can properly retrieve that model + let localModel = try visualRecognition.getLocalModel(classifierID: classifierID) + XCTAssertEqual(localModel.modelDescription.metadata[MLModelMetadataKey.author] as? String, "IBM") + } catch { + XCTFail(error.localizedDescription) } - - // Then check if getLocalModel() can properly retrieve that model - let localModel = try visualRecognition.getLocalModel(classifierID: classifierID) - XCTAssertEqual(localModel.modelDescription.metadata[MLModelMetadataKey.author] as? String, "IBM") - } catch { - XCTFail(error.localizedDescription) } } - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testUpdateLocalModelWithOutdatedModel() { - let classifierID = "watson_sample" - - // Pretend that the VR service has a newly-retrained version of the CoreML model - class MockVisualRecognition: VisualRecognition { - - let expectation: XCTestExpectation + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierID = "watson_sample" - init(version: String, accessToken: String, expectation: XCTestExpectation) { - self.expectation = expectation - super.init(version: version, accessToken: accessToken) - } + // Pretend that the VR service has a newly-retrained version of the CoreML model + class MockVisualRecognition: VisualRecognition { - override func getClassifier( - classifierID: String, - headers: [String: String]?, - completionHandler: @escaping (RestResponse?, WatsonError?) -> Void) { + let expectation: XCTestExpectation - expectation.fulfill() + init(version: String, accessToken: String, expectation: XCTestExpectation) { + self.expectation = expectation + super.init(version: version, accessToken: accessToken) + } - var response: RestResponse = RestResponse(statusCode: 200) - response.result = Classifier( - classifierID: classifierID, - name: classifierID, - owner: nil, - status: "ready", - coreMLEnabled: true, - explanation: nil, - created: nil, - classes: nil, - retrained: Date(), - updated: nil) - completionHandler(response, nil) + override func getClassifier( + classifierID: String, + headers: [String: String]?, + completionHandler: @escaping (RestResponse?, WatsonError?) -> Void) { + + expectation.fulfill() + + var response: RestResponse = RestResponse(statusCode: 200) + response.result = Classifier( + classifierID: classifierID, + name: classifierID, + owner: nil, + status: "ready", + coreMLEnabled: true, + explanation: nil, + created: nil, + classes: nil, + retrained: Date(), + updated: nil) + completionHandler(response, nil) + } } - } - - // We expect the newer CoreML model to be downloaded - MockURLProtocol.requestHandler = { request in - XCTAssertEqual(request.httpMethod, "GET") - let endOfURL = request.url!.pathComponents.suffix(3) - XCTAssertEqual(endOfURL[endOfURL.startIndex], "classifiers") - XCTAssertEqual(endOfURL[endOfURL.startIndex + 1], classifierID) - XCTAssertEqual(endOfURL[endOfURL.startIndex + 2], "core_ml_model") - XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) - XCTAssertNil(request.httpBodyStream) - XCTAssertNotNil(request.allHTTPHeaderFields) - let response = HTTPURLResponse(url: exampleURL, statusCode: 200, httpVersion: nil, headerFields: nil)! - return (response, Data()) - } + // We expect the newer CoreML model to be downloaded + MockURLProtocol.requestHandler = { request in + XCTAssertEqual(request.httpMethod, "GET") + let endOfURL = request.url!.pathComponents.suffix(3) + XCTAssertEqual(endOfURL[endOfURL.startIndex], "classifiers") + XCTAssertEqual(endOfURL[endOfURL.startIndex + 1], classifierID) + XCTAssertEqual(endOfURL[endOfURL.startIndex + 2], "core_ml_model") + XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) + XCTAssertNil(request.httpBodyStream) + XCTAssertNotNil(request.allHTTPHeaderFields) + + let response = HTTPURLResponse(url: exampleURL, statusCode: 200, httpVersion: nil, headerFields: nil)! + return (response, Data()) + } - // Save a CoreML file to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_sample.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: [classifierID]) - } + // Save a CoreML file to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_sample.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: [classifierID]) + } - let classifierExpectation = self.expectation(description: "getClassifier() should get called") - let visualRecognition = MockVisualRecognition(version: versionDate, accessToken: accessToken, expectation: classifierExpectation) - createMockSession(for: visualRecognition) + let classifierExpectation = self.expectation(description: "getClassifier() should get called") + let visualRecognition = MockVisualRecognition(version: versionDate, accessToken: accessToken, expectation: classifierExpectation) + createMockSession(for: visualRecognition) - // If there is a newer version of the CoreML model available in the VisualRecognition service, - // it should be downloaded to replace the local outdated model. - let expectation = self.expectation(description: "updateLocalModel with outdated model") - visualRecognition.updateLocalModel(classifierID: classifierID) { - _, _ in - expectation.fulfill() + // If there is a newer version of the CoreML model available in the VisualRecognition service, + // it should be downloaded to replace the local outdated model. + let expectation = self.expectation(description: "updateLocalModel with outdated model") + visualRecognition.updateLocalModel(classifierID: classifierID) { + _, _ in + expectation.fulfill() + } + waitForExpectations(timeout: timeout) } - waitForExpectations(timeout: timeout) } - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testUpdateLocalModelWithUpToDateModel() { - let classifierID = "watson_sample" + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierID = "watson_sample" + + // Pretend that the VR service has a newly-retrained version of the CoreML model + class MockVisualRecognition: VisualRecognition { - // Pretend that the VR service has a newly-retrained version of the CoreML model - class MockVisualRecognition: VisualRecognition { + let expectation: XCTestExpectation - let expectation: XCTestExpectation + init(version: String, accessToken: String, expectation: XCTestExpectation) { + self.expectation = expectation + super.init(version: version, accessToken: accessToken) + } - init(version: String, accessToken: String, expectation: XCTestExpectation) { - self.expectation = expectation - super.init(version: version, accessToken: accessToken) + override func getClassifier( + classifierID: String, + headers: [String: String]?, + completionHandler: @escaping (RestResponse?, WatsonError?) -> Void) { + + expectation.fulfill() + + let oldDate = Date(timeIntervalSinceReferenceDate: 0) + var response: RestResponse = RestResponse(statusCode: 200) + response.result = Classifier( + classifierID: classifierID, + name: classifierID, + owner: nil, + status: "ready", + coreMLEnabled: true, + explanation: nil, + created: nil, + classes: nil, + retrained: oldDate, + updated: nil) + completionHandler(response, nil) + } } - override func getClassifier( - classifierID: String, - headers: [String: String]?, - completionHandler: @escaping (RestResponse?, WatsonError?) -> Void) { + // Save a CoreML file to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_sample.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: [classifierID]) + } + let classifierExpectation = self.expectation(description: "getClassifier() should get called") + let visualRecognition = MockVisualRecognition(version: versionDate, accessToken: accessToken, expectation: classifierExpectation) + createMockSession(for: visualRecognition) + + // If the local copy of the CoreML model is at least as updated as + // the model available in the VisualRecognition service, then there is no need to download. + let expectation = self.expectation(description: "updateLocalModel with up to date model") + visualRecognition.updateLocalModel(classifierID: classifierID) { + response, error in + XCTAssertNil(response) + XCTAssertNil(error) expectation.fulfill() - - let oldDate = Date(timeIntervalSinceReferenceDate: 0) - var response: RestResponse = RestResponse(statusCode: 200) - response.result = Classifier( - classifierID: classifierID, - name: classifierID, - owner: nil, - status: "ready", - coreMLEnabled: true, - explanation: nil, - created: nil, - classes: nil, - retrained: oldDate, - updated: nil) - completionHandler(response, nil) } + waitForExpectations(timeout: timeout) } - - // Save a CoreML file to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_sample.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: [classifierID]) - } - - let classifierExpectation = self.expectation(description: "getClassifier() should get called") - let visualRecognition = MockVisualRecognition(version: versionDate, accessToken: accessToken, expectation: classifierExpectation) - createMockSession(for: visualRecognition) - - // If the local copy of the CoreML model is at least as updated as - // the model available in the VisualRecognition service, then there is no need to download. - let expectation = self.expectation(description: "updateLocalModel with up to date model") - visualRecognition.updateLocalModel(classifierID: classifierID) { - response, error in - XCTAssertNil(response) - XCTAssertNil(error) - expectation.fulfill() - } - waitForExpectations(timeout: timeout) } - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testListLocalModels() { - // Save 2 Core ML models first - let toolsClassifierID = "watson_tools" - let sampleClassifierID = "watson_sample" - - // Save 2 CoreML files to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: toolsClassifierID, modelURL: watson_tools.urlOfModelInThisBundle) - saveCoreMLModelToSimulator(name: sampleClassifierID, modelURL: watson_sample.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: [toolsClassifierID, sampleClassifierID]) - } + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + // Save 2 Core ML models first + let toolsClassifierID = "watson_tools" + let sampleClassifierID = "watson_sample" + + // Save 2 CoreML files to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: toolsClassifierID, modelURL: watson_tools.urlOfModelInThisBundle) + saveCoreMLModelToSimulator(name: sampleClassifierID, modelURL: watson_sample.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: [toolsClassifierID, sampleClassifierID]) + } - // Then check if we can retrieve those models - do { - let localModels = try visualRecognition.listLocalModels() - XCTAssertTrue(localModels.contains(toolsClassifierID)) - XCTAssertTrue(localModels.contains(sampleClassifierID)) - } catch { - XCTFail(error.localizedDescription) + // Then check if we can retrieve those models + do { + let localModels = try visualRecognition.listLocalModels() + XCTAssertTrue(localModels.contains(toolsClassifierID)) + XCTAssertTrue(localModels.contains(sampleClassifierID)) + } catch { + XCTFail(error.localizedDescription) + } } } - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testClassifyWithLocalModel() { - let classifierIDs = ["watson_tools"] - let data = try! Data(contentsOf: car) + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierIDs = ["watson_tools"] + let data = try! Data(contentsOf: car) - // Save a CoreML file to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: classifierIDs.first!, modelURL: watson_tools.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: classifierIDs) - } + // Save a CoreML file to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: classifierIDs.first!, modelURL: watson_tools.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: classifierIDs) + } - MockURLProtocol.requestHandler = { request in - XCTAssertEqual(request.httpMethod, "POST") - XCTAssertEqual(request.url?.lastPathComponent, "classify") - XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) - XCTAssertNotNil(request.httpBodyStream) - XCTAssertNotNil(request.allHTTPHeaderFields) + MockURLProtocol.requestHandler = { request in + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.lastPathComponent, "classify") + XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) + XCTAssertNotNil(request.httpBodyStream) + XCTAssertNotNil(request.allHTTPHeaderFields) - let bodyFieldsCount = numberOfFieldsInMultiPartFormBody(request: request) - XCTAssertEqual(bodyFieldsCount, 4) + let bodyFieldsCount = numberOfFieldsInMultiPartFormBody(request: request) + XCTAssertEqual(bodyFieldsCount, 4) - return (dummyResponse, Data()) - } + return (dummyResponse, Data()) + } - let expectation = self.expectation(description: "classifyWithLocalModel") - visualRecognition.classifyWithLocalModel(imageData: data, classifierIDs: classifierIDs, threshold: 1.0) { - _, _ in - expectation.fulfill() + let expectation = self.expectation(description: "classifyWithLocalModel") + visualRecognition.classifyWithLocalModel(imageData: data, classifierIDs: classifierIDs, threshold: 1.0) { + _, _ in + expectation.fulfill() + } + waitForExpectations(timeout: timeout) } - waitForExpectations(timeout: timeout) } // Check that error handling is correct when the download // fails to download a CoreML model or fails to save the downloaded CoreML model - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testDownloadClassifierWithoutCoreMLModel() { - let classifierID = "watson_tools" + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierID = "watson_tools" - // Save a CoreML file to the Application Support directory on the simulator for the duration of this test - saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_tools.urlOfModelInThisBundle) - defer { - deleteLocalCoreMLModels(classifierIDs: [classifierID]) - } - - MockURLProtocol.requestHandler = { request in - XCTAssertEqual(request.httpMethod, "GET") - let endOfURL = request.url!.pathComponents.suffix(3) - XCTAssertEqual(endOfURL[endOfURL.startIndex], "classifiers") - XCTAssertEqual(endOfURL[endOfURL.startIndex + 1], classifierID) - XCTAssertEqual(endOfURL[endOfURL.startIndex + 2], "core_ml_model") - XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) - XCTAssertNil(request.httpBodyStream) - XCTAssertNotNil(request.allHTTPHeaderFields) + // Save a CoreML file to the Application Support directory on the simulator for the duration of this test + saveCoreMLModelToSimulator(name: classifierID, modelURL: watson_tools.urlOfModelInThisBundle) + defer { + deleteLocalCoreMLModels(classifierIDs: [classifierID]) + } - let response = HTTPURLResponse(url: exampleURL, statusCode: 200, httpVersion: nil, headerFields: nil)! - // The download receives empty Data() instead of a CoreML model - return (response, Data()) - } + MockURLProtocol.requestHandler = { request in + XCTAssertEqual(request.httpMethod, "GET") + let endOfURL = request.url!.pathComponents.suffix(3) + XCTAssertEqual(endOfURL[endOfURL.startIndex], "classifiers") + XCTAssertEqual(endOfURL[endOfURL.startIndex + 1], classifierID) + XCTAssertEqual(endOfURL[endOfURL.startIndex + 2], "core_ml_model") + XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) + XCTAssertNil(request.httpBodyStream) + XCTAssertNotNil(request.allHTTPHeaderFields) + + let response = HTTPURLResponse(url: exampleURL, statusCode: 200, httpVersion: nil, headerFields: nil)! + // The download receives empty Data() instead of a CoreML model + return (response, Data()) + } - let expectation = self.expectation(description: "downloadClassifier without CoreML model") - visualRecognition.downloadClassifier(classifierID: classifierID) { - _, error in + let expectation = self.expectation(description: "downloadClassifier without CoreML model") + visualRecognition.downloadClassifier(classifierID: classifierID) { + _, error in - if case .some(WatsonError.other(let message)) = error, - let errorMessage = message { - XCTAssertTrue(errorMessage.contains("Could not compile Core ML model from source")) - } else { - XCTFail(missingErrorMessage) + if case .some(WatsonError.other(let message)) = error, + let errorMessage = message { + XCTAssertTrue(errorMessage.contains("Could not compile Core ML model from source")) + } else { + XCTFail(missingErrorMessage) + } + expectation.fulfill() } - expectation.fulfill() + waitForExpectations(timeout: timeout) } - waitForExpectations(timeout: timeout) } // MARK: Helpers @@ -692,30 +698,31 @@ class VisualRecognitionUnitTests: XCTestCase { waitForExpectations(timeout: timeout) } - @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) func testClassifyWithLocalModelUIImage() { - let classifierIDs = ["1"] - let image = UIImage(contentsOfFile: car.path)! + if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { + let classifierIDs = ["1"] + let image = UIImage(contentsOfFile: car.path)! - MockURLProtocol.requestHandler = { request in - XCTAssertEqual(request.httpMethod, "POST") - XCTAssertEqual(request.url?.lastPathComponent, "classify") - XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) - XCTAssertNotNil(request.httpBodyStream) - XCTAssertNotNil(request.allHTTPHeaderFields) + MockURLProtocol.requestHandler = { request in + XCTAssertEqual(request.httpMethod, "POST") + XCTAssertEqual(request.url?.lastPathComponent, "classify") + XCTAssertTrue(request.url?.query?.contains("version=\(versionDate)") ?? false) + XCTAssertNotNil(request.httpBodyStream) + XCTAssertNotNil(request.allHTTPHeaderFields) - let bodyFieldsCount = numberOfFieldsInMultiPartFormBody(request: request) - XCTAssertEqual(bodyFieldsCount, 4) + let bodyFieldsCount = numberOfFieldsInMultiPartFormBody(request: request) + XCTAssertEqual(bodyFieldsCount, 4) - return (dummyResponse, Data()) - } + return (dummyResponse, Data()) + } - let expectation = self.expectation(description: "classifyWithLocalModel using UIImage") - visualRecognition.classifyWithLocalModel(image: image, classifierIDs: classifierIDs, threshold: 1.0) { - _, _ in - expectation.fulfill() + let expectation = self.expectation(description: "classifyWithLocalModel using UIImage") + visualRecognition.classifyWithLocalModel(image: image, classifierIDs: classifierIDs, threshold: 1.0) { + _, _ in + expectation.fulfill() + } + waitForExpectations(timeout: timeout) } - waitForExpectations(timeout: timeout) } #endif diff --git a/WatsonDeveloperCloud.xcodeproj/project.pbxproj b/WatsonDeveloperCloud.xcodeproj/project.pbxproj index d3bdef01e..2ba12b769 100644 --- a/WatsonDeveloperCloud.xcodeproj/project.pbxproj +++ b/WatsonDeveloperCloud.xcodeproj/project.pbxproj @@ -3139,7 +3139,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1010; - LastUpgradeCheck = 0930; + LastUpgradeCheck = 1010; ORGANIZATIONNAME = "IBM Corporation"; TargetAttributes = { 1241DFAD1E380F0A00B8B33E = { @@ -3228,7 +3228,7 @@ }; 92866190219110390064C6FD = { CreatedOnToolsVersion = 10.1; - ProvisioningStyle = Automatic; + ProvisioningStyle = Manual; }; 9286619C2191104C0064C6FD = { CreatedOnToolsVersion = 10.1; @@ -5033,7 +5033,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -5085,7 +5085,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; @@ -5624,9 +5624,10 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_IDENTITY = "iPhone Developer"; - CODE_SIGN_STYLE = Automatic; + CODE_SIGN_IDENTITY = ""; + CODE_SIGN_STYLE = Manual; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -5643,6 +5644,7 @@ MTL_FAST_MATH = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.ibm.watson.developer-cloud.CompareComplyV1"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SKIP_INSTALL = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_VERSION = 4.2; @@ -5659,9 +5661,10 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_IDENTITY = "iPhone Developer"; - CODE_SIGN_STYLE = Automatic; + CODE_SIGN_IDENTITY = ""; + CODE_SIGN_STYLE = Manual; DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; DYLIB_COMPATIBILITY_VERSION = 1; DYLIB_CURRENT_VERSION = 1; DYLIB_INSTALL_NAME_BASE = "@rpath"; @@ -5677,6 +5680,7 @@ MTL_FAST_MATH = YES; PRODUCT_BUNDLE_IDENTIFIER = "com.ibm.watson.developer-cloud.CompareComplyV1"; PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + PROVISIONING_PROFILE_SPECIFIER = ""; SKIP_INSTALL = YES; SWIFT_VERSION = 4.2; TARGETED_DEVICE_FAMILY = "1,2"; diff --git a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV1.xcscheme b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV1.xcscheme index b84fc6b5c..24d8e8701 100644 --- a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV1.xcscheme +++ b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV1.xcscheme @@ -1,6 +1,6 @@ Date: Mon, 4 Mar 2019 08:27:09 -0600 Subject: [PATCH 02/13] feat(SpeechToTextV1): Make STT websocketURL and tokenURL computed properties --- .../SpeechToText+Recognize.swift | 15 +++--- Source/SpeechToTextV1/SpeechToText.swift | 10 ---- .../WebSockets/SpeechToTextSession.swift | 21 ++++++-- .../SpeechToTextRecognizeTests.swift | 2 - .../SpeechToTextUnitTests.swift | 49 ++++++++++++------- 5 files changed, 57 insertions(+), 40 deletions(-) diff --git a/Source/SpeechToTextV1/SpeechToText+Recognize.swift b/Source/SpeechToTextV1/SpeechToText+Recognize.swift index 5676f79ed..33df54101 100644 --- a/Source/SpeechToTextV1/SpeechToText+Recognize.swift +++ b/Source/SpeechToTextV1/SpeechToText+Recognize.swift @@ -25,6 +25,13 @@ private var microphoneSession: SpeechToTextSession? extension SpeechToText { + /// The URL that shall be used to stream audio for transcription. + internal var websocketsURL: String { + return serviceURL + .replacingOccurrences(of: "http", with: "ws", options: .anchored, range: nil) + + "/v1/recognize" + } + /** Perform speech recognition for an audio file. @@ -126,9 +133,7 @@ extension SpeechToText { customerID: customerID ) - // set urls - session.serviceURL = serviceURL - session.tokenURL = tokenURL + // set url session.websocketsURL = websocketsURL // set headers @@ -234,9 +239,7 @@ extension SpeechToText { customerID: customerID ) - // set urls - session.serviceURL = serviceURL - session.tokenURL = tokenURL + // set url session.websocketsURL = websocketsURL // set headers diff --git a/Source/SpeechToTextV1/SpeechToText.swift b/Source/SpeechToTextV1/SpeechToText.swift index 925fe2cce..97f97ae65 100644 --- a/Source/SpeechToTextV1/SpeechToText.swift +++ b/Source/SpeechToTextV1/SpeechToText.swift @@ -42,19 +42,9 @@ public class SpeechToText { if serviceURL.last == "/" { serviceURL.removeLast() } - // websocketsURL and tokenURL are both derivative of serviceURL - websocketsURL = serviceURL.replacingOccurrences(of: "http", with: "ws", options: .anchored, range: nil) - websocketsURL.append("/v1/recognize") - - tokenURL = serviceURL.replacingOccurrences(of: "/speech-to-text/api", with: "/authorization/api/v1/token") } } - /// The URL that shall be used to stream audio for transcription. - internal var websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize" - - /// The URL that shall be used to obtain a token. - internal var tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" internal let serviceName = "SpeechToText" internal let serviceVersion = "v1" diff --git a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift index 896c62b59..67efdcf7c 100644 --- a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift +++ b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift @@ -33,14 +33,25 @@ import RestKit */ public class SpeechToTextSession { + /// The URL that shall be used to stream audio for transcription. + public var websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize" { + didSet { + // serviceURL and tokenURL are both derivative of websocketsURL + if websocketsURL.last == "/" { + websocketsURL.removeLast() + } + serviceURL = websocketsURL + .replacingOccurrences(of: "ws", with: "http", options: .anchored, range: nil) + .replacingOccurrences(of: "/v1/recognize", with: "") + tokenURL = serviceURL.replacingOccurrences(of: "/speech-to-text/api", with: "/authorization/api/v1/token") + } + } + /// The base URL of the Speech to Text service. - public var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" + internal var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" /// The URL that shall be used to obtain a token. - public var tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" - - /// The URL that shall be used to stream audio for transcription. - public var websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize" + internal var tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" /// The default HTTP headers for all requests to the service. public var defaultHeaders = [String: String]() diff --git a/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift b/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift index c79262fef..1c5fbca24 100644 --- a/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift +++ b/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift @@ -47,8 +47,6 @@ class SpeechToTextRecognizeTests: XCTestCase { } if let url = WatsonCredentials.SpeechToTextURL { speechToText.serviceURL = url - let wsUrl = url.replacingOccurrences(of: "https", with: "wss").appending("/v1/recognize") - speechToText.websocketsURL = wsUrl } speechToText.defaultHeaders["X-Watson-Learning-Opt-Out"] = "true" speechToText.defaultHeaders["X-Watson-Test"] = "true" diff --git a/Tests/SpeechToTextV1Tests/SpeechToTextUnitTests.swift b/Tests/SpeechToTextV1Tests/SpeechToTextUnitTests.swift index 5fb2fbeba..b51be15cb 100644 --- a/Tests/SpeechToTextV1Tests/SpeechToTextUnitTests.swift +++ b/Tests/SpeechToTextV1Tests/SpeechToTextUnitTests.swift @@ -31,35 +31,50 @@ class SpeechToTextUnitTests: XCTestCase { // MARK: - URLs - func testServiceURLSetsWebsocketsURL() { - speechToText.serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" - XCTAssertEqual(speechToText.websocketsURL, "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize") + func testWebsocketsURLSetsServiceURL() { + let apiKey = "your-api-key" + let speechToTextSession = SpeechToTextSession(apiKey: apiKey) + + // Default URLs value + XCTAssertEqual(speechToTextSession.websocketsURL, "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize") + XCTAssertEqual(speechToTextSession.serviceURL, "https://stream.watsonplatform.net/speech-to-text/api") + + // Set websockets URL and verify serviceURL + speechToTextSession.websocketsURL = "wss://gateway-syd.watsonplatform.net/speech-to-text/api/v1/recognize" + XCTAssertEqual(speechToTextSession.serviceURL, "https://gateway-syd.watsonplatform.net/speech-to-text/api") // Trailing forward slash - speechToText.serviceURL = "https://stream.watsonplatform.net/speech-to-text/api/" - XCTAssertEqual(speechToText.serviceURL, "https://stream.watsonplatform.net/speech-to-text/api") - XCTAssertEqual(speechToText.websocketsURL, "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize") + speechToTextSession.websocketsURL = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize/" + XCTAssertEqual(speechToTextSession.serviceURL, "https://stream.watsonplatform.net/speech-to-text/api") // http instead of https - speechToText.serviceURL = "http://stream.watsonplatform.net/speech-to-text/api" - XCTAssertEqual(speechToText.websocketsURL, "ws://stream.watsonplatform.net/speech-to-text/api/v1/recognize") + speechToTextSession.websocketsURL = "ws://stream.watsonplatform.net/speech-to-text/api/v1/recognize" + XCTAssertEqual(speechToTextSession.serviceURL, "http://stream.watsonplatform.net/speech-to-text/api") // Different base URL - speechToText.serviceURL = "https://example.com/speech-to-text/api" - XCTAssertEqual(speechToText.websocketsURL, "wss://example.com/speech-to-text/api/v1/recognize") + speechToTextSession.websocketsURL = "wss://example.com/speech-to-text/api/v1/recognize/v1/recognize" + XCTAssertEqual(speechToTextSession.serviceURL, "https://example.com/speech-to-text/api") } - func testServiceURLSetsTokenURL() { - speechToText.serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" - XCTAssertEqual(speechToText.tokenURL, "https://stream.watsonplatform.net/authorization/api/v1/token") + func testWebsocketsURLSetsTokenURL() { + let apiKey = "your-api-key" + let speechToTextSession = SpeechToTextSession(apiKey: apiKey) + + // Default URLs value + XCTAssertEqual(speechToTextSession.websocketsURL, "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize") + XCTAssertEqual(speechToTextSession.tokenURL, "https://stream.watsonplatform.net/authorization/api/v1/token") + + // Set websockets URL and verify tokenURL + speechToTextSession.websocketsURL = "wss://gateway-syd.watsonplatform.net/speech-to-text/api/v1/recognize" + XCTAssertEqual(speechToTextSession.tokenURL, "https://gateway-syd.watsonplatform.net/authorization/api/v1/token") // http instead of https - speechToText.serviceURL = "http://stream.watsonplatform.net/speech-to-text/api" - XCTAssertEqual(speechToText.tokenURL, "http://stream.watsonplatform.net/authorization/api/v1/token") + speechToTextSession.websocketsURL = "ws://stream.watsonplatform.net/speech-to-text/api/v1/recognize" + XCTAssertEqual(speechToTextSession.tokenURL, "http://stream.watsonplatform.net/authorization/api/v1/token") // Different base URL - speechToText.serviceURL = "https://example.com/speech-to-text/api" - XCTAssertEqual(speechToText.tokenURL, "https://example.com/authorization/api/v1/token") + speechToTextSession.websocketsURL = "wss://example.com/speech-to-text/api/v1/recognize/v1/recognize" + XCTAssertEqual(speechToTextSession.tokenURL, "https://example.com/authorization/api/v1/token") } // MARK - Websockets From 7510d1db8d99ad166c9b4ac6a52f75e59c9f9603 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Sun, 3 Mar 2019 18:22:55 -0600 Subject: [PATCH 03/13] feat: Generated code for major release BREAKING CHANGE --- .gitignore | 2 + Source/AssistantV1/Assistant.swift | 466 ++++++++-------- Source/AssistantV1/Models/CaptureGroup.swift | 6 +- Source/AssistantV1/Models/Context.swift | 2 +- .../AssistantV1/Models/Counterexample.swift | 35 +- .../Models/CounterexampleCollection.swift | 2 +- .../Models/CreateCounterexample.swift | 53 -- .../AssistantV1/Models/CreateDialogNode.swift | 271 ---------- Source/AssistantV1/Models/CreateEntity.swift | 42 +- Source/AssistantV1/Models/CreateExample.swift | 61 --- Source/AssistantV1/Models/CreateIntent.swift | 24 +- Source/AssistantV1/Models/CreateSynonym.swift | 52 -- Source/AssistantV1/Models/CreateValue.swift | 58 +- .../AssistantV1/Models/CreateWorkspace.swift | 114 ++-- Source/AssistantV1/Models/DialogNode.swift | 164 ++++-- .../AssistantV1/Models/DialogNodeAction.swift | 2 +- .../Models/DialogNodeCollection.swift | 2 +- .../Models/DialogNodeNextStep.swift | 2 +- .../AssistantV1/Models/DialogNodeOutput.swift | 4 +- .../Models/DialogNodeOutputGeneric.swift | 2 +- .../Models/DialogNodeOutputModifiers.swift | 2 +- .../DialogNodeOutputOptionsElement.swift | 2 +- .../DialogNodeOutputOptionsElementValue.swift | 6 +- .../DialogNodeOutputTextValuesElement.swift | 16 +- .../Models/DialogNodeVisitedDetails.swift | 2 +- .../Models/DialogRuntimeResponseGeneric.swift | 13 +- .../AssistantV1/Models/DialogSuggestion.swift | 15 +- .../Models/DialogSuggestionValue.swift | 6 +- Source/AssistantV1/Models/Entity.swift | 43 +- .../AssistantV1/Models/EntityCollection.swift | 6 +- Source/AssistantV1/Models/EntityExport.swift | 69 --- Source/AssistantV1/Models/EntityMention.swift | 10 +- .../Models/EntityMentionCollection.swift | 2 +- Source/AssistantV1/Models/Example.swift | 51 +- .../Models/ExampleCollection.swift | 2 +- Source/AssistantV1/Models/InputData.swift | 71 --- Source/AssistantV1/Models/Intent.swift | 28 +- .../AssistantV1/Models/IntentCollection.swift | 4 +- .../Models/{LogExport.swift => Log.swift} | 6 +- Source/AssistantV1/Models/LogCollection.swift | 4 +- Source/AssistantV1/Models/LogMessage.swift | 2 +- Source/AssistantV1/Models/LogPagination.swift | 2 +- .../Models/{Mentions.swift => Mention.swift} | 8 +- .../Models/MessageContextMetadata.swift | 2 +- Source/AssistantV1/Models/MessageInput.swift | 43 +- .../AssistantV1/Models/MessageRequest.swift | 61 ++- .../AssistantV1/Models/MessageResponse.swift | 6 +- Source/AssistantV1/Models/OutputData.swift | 2 +- Source/AssistantV1/Models/Pagination.swift | 2 +- Source/AssistantV1/Models/RuntimeEntity.swift | 2 +- Source/AssistantV1/Models/RuntimeIntent.swift | 2 +- Source/AssistantV1/Models/Synonym.swift | 38 +- .../Models/SynonymCollection.swift | 2 +- .../AssistantV1/Models/SystemResponse.swift | 2 +- .../Models/UpdateCounterexample.swift | 33 +- .../AssistantV1/Models/UpdateDialogNode.swift | 45 +- Source/AssistantV1/Models/UpdateEntity.swift | 24 +- Source/AssistantV1/Models/UpdateExample.swift | 24 +- Source/AssistantV1/Models/UpdateIntent.swift | 30 +- Source/AssistantV1/Models/UpdateSynonym.swift | 22 +- Source/AssistantV1/Models/UpdateValue.swift | 52 +- .../AssistantV1/Models/UpdateWorkspace.swift | 114 ++-- Source/AssistantV1/Models/Value.swift | 46 +- .../AssistantV1/Models/ValueCollection.swift | 4 +- Source/AssistantV1/Models/ValueExport.swift | 77 --- Source/AssistantV1/Models/Workspace.swift | 81 ++- .../Models/WorkspaceCollection.swift | 2 +- .../AssistantV1/Models/WorkspaceExport.swift | 123 ----- .../Models/WorkspaceSystemSettings.swift | 2 +- ...orkspaceSystemSettingsDisambiguation.swift | 2 +- .../WorkspaceSystemSettingsTooling.swift | 2 +- Source/AssistantV2/Assistant.swift | 77 +-- Source/AssistantV2/Models/CaptureGroup.swift | 2 +- .../AssistantV2/Models/DialogLogMessage.swift | 2 +- .../AssistantV2/Models/DialogNodeAction.swift | 2 +- .../DialogNodeOutputOptionsElement.swift | 2 +- .../DialogNodeOutputOptionsElementValue.swift | 2 +- .../Models/DialogNodesVisited.swift | 2 +- .../Models/DialogRuntimeResponseGeneric.swift | 4 +- .../AssistantV2/Models/DialogSuggestion.swift | 2 +- .../Models/DialogSuggestionValue.swift | 2 +- .../AssistantV2/Models/MessageContext.swift | 18 +- .../Models/MessageContextGlobal.swift | 8 +- .../Models/MessageContextGlobalSystem.swift | 9 +- .../Models/MessageContextSkill.swift | 48 ++ .../Models/MessageContextSkills.swift | 6 +- Source/AssistantV2/Models/MessageInput.swift | 2 +- .../Models/MessageInputOptions.swift | 2 +- Source/AssistantV2/Models/MessageOutput.swift | 2 +- .../Models/MessageOutputDebug.swift | 2 +- .../AssistantV2/Models/MessageRequest.swift | 9 +- .../Models/MessageRequestContext.swift | 43 ++ .../AssistantV2/Models/MessageResponse.swift | 6 +- .../Models/MessageResponseContext.swift | 44 ++ Source/AssistantV2/Models/RuntimeEntity.swift | 2 +- Source/AssistantV2/Models/RuntimeIntent.swift | 2 +- .../AssistantV2/Models/SessionResponse.swift | 2 +- Source/CompareComplyV1/CompareComply.swift | 310 +++++------ Source/CompareComplyV1/Models/Address.swift | 2 +- .../Models/AlignedElement.swift | 16 +- Source/CompareComplyV1/Models/Attribute.swift | 5 +- .../CompareComplyV1/Models/BatchStatus.swift | 2 +- Source/CompareComplyV1/Models/Batches.swift | 2 +- Source/CompareComplyV1/Models/BodyCells.swift | 37 +- Source/CompareComplyV1/Models/Category.swift | 8 +- .../Models/CategoryComparison.swift | 64 +++ .../Models/ClassifyReturn.swift | 19 +- ...nHeaderIds.swift => ColumnHeaderIDs.swift} | 2 +- .../Models/ColumnHeaderTexts.swift | 2 +- .../Models/ColumnHeaderTextsNormalized.swift | 2 +- .../Models/ColumnHeaders.swift | 5 +- .../Models/CompareReturn.swift | 28 +- Source/CompareComplyV1/Models/Contact.swift | 2 +- .../CompareComplyV1/Models/ContractAmts.swift | 2 +- .../CompareComplyV1/Models/ContractType.swift | 56 ++ Source/CompareComplyV1/Models/DocCounts.swift | 2 +- Source/CompareComplyV1/Models/DocInfo.swift | 2 +- .../CompareComplyV1/Models/DocStructure.swift | 2 +- Source/CompareComplyV1/Models/Document.swift | 2 +- .../Models/EffectiveDates.swift | 2 +- Source/CompareComplyV1/Models/Element.swift | 2 +- .../Models/ElementLocations.swift | 2 +- .../CompareComplyV1/Models/ElementPair.swift | 10 +- .../Models/FeedbackDataInput.swift | 2 +- .../Models/FeedbackDataOutput.swift | 2 +- .../Models/FeedbackDeleted.swift | 2 +- .../Models/FeedbackInput.swift | 2 +- .../CompareComplyV1/Models/FeedbackList.swift | 2 +- .../Models/FeedbackReturn.swift | 2 +- .../CompareComplyV1/Models/GetFeedback.swift | 2 +- .../CompareComplyV1/Models/HTMLReturn.swift | 2 +- Source/CompareComplyV1/Models/Key.swift | 47 ++ .../CompareComplyV1/Models/KeyValuePair.swift | 40 ++ Source/CompareComplyV1/Models/Label.swift | 2 +- .../Models/LeadingSentence.swift | 2 +- Source/CompareComplyV1/Models/Location.swift | 2 +- .../Models/OriginalLabelsIn.swift | 2 +- .../Models/OriginalLabelsOut.swift | 2 +- .../CompareComplyV1/Models/Pagination.swift | 2 +- Source/CompareComplyV1/Models/Parties.swift | 2 +- ...{RowHeaderIds.swift => RowHeaderIDs.swift} | 2 +- .../Models/RowHeaderTexts.swift | 2 +- .../Models/RowHeaderTextsNormalized.swift | 2 +- .../CompareComplyV1/Models/RowHeaders.swift | 5 +- .../CompareComplyV1/Models/SectionTitle.swift | 2 +- .../Models/SectionTitles.swift | 2 +- Source/CompareComplyV1/Models/ShortDoc.swift | 2 +- .../CompareComplyV1/Models/TableHeaders.swift | 5 +- .../CompareComplyV1/Models/TableReturn.swift | 2 +- Source/CompareComplyV1/Models/Tables.swift | 8 +- .../Models/TerminationDates.swift | 2 +- Source/CompareComplyV1/Models/TypeLabel.swift | 2 +- .../Models/TypeLabelComparison.swift | 35 ++ .../Models/UnalignedElement.swift | 10 +- .../Models/UpdatedLabelsIn.swift | 2 +- .../Models/UpdatedLabelsOut.swift | 2 +- Source/CompareComplyV1/Models/Value.swift | 47 ++ Source/DiscoveryV1/Discovery.swift | 509 +++++++++--------- .../Models/AggregationResult.swift | 10 +- Source/DiscoveryV1/Models/Calculation.swift | 5 +- Source/DiscoveryV1/Models/Collection.swift | 9 +- .../Models/CollectionDiskUsage.swift | 2 +- .../DiscoveryV1/Models/CollectionUsage.swift | 2 +- Source/DiscoveryV1/Models/Configuration.swift | 2 +- Source/DiscoveryV1/Models/Conversions.swift | 2 +- .../Models/CreateCollectionRequest.swift | 3 +- .../Models/CreateEnvironmentRequest.swift | 2 +- .../Models/CreateEventObject.swift | 2 +- .../Models/CreateEventResponse.swift | 2 +- .../Models/CredentialDetails.swift | 54 +- Source/DiscoveryV1/Models/Credentials.swift | 6 +- .../DiscoveryV1/Models/CredentialsList.swift | 2 +- .../Models/DeleteCollectionResponse.swift | 2 +- .../Models/DeleteConfigurationResponse.swift | 2 +- .../Models/DeleteCredentials.swift | 2 +- .../Models/DeleteDocumentResponse.swift | 2 +- .../Models/DeleteEnvironmentResponse.swift | 2 +- Source/DiscoveryV1/Models/DiskUsage.swift | 2 +- .../DiscoveryV1/Models/DocumentAccepted.swift | 2 +- .../DiscoveryV1/Models/DocumentCounts.swift | 2 +- .../DiscoveryV1/Models/DocumentSnapshot.swift | 11 +- .../DiscoveryV1/Models/DocumentStatus.swift | 14 +- Source/DiscoveryV1/Models/Enrichment.swift | 18 +- .../Models/EnrichmentOptions.swift | 10 +- Source/DiscoveryV1/Models/Environment.swift | 2 +- .../Models/EnvironmentDocuments.swift | 2 +- Source/DiscoveryV1/Models/EventData.swift | 2 +- Source/DiscoveryV1/Models/Expansion.swift | 2 +- Source/DiscoveryV1/Models/Expansions.swift | 2 +- Source/DiscoveryV1/Models/Field.swift | 2 +- Source/DiscoveryV1/Models/Filter.swift | 5 +- Source/DiscoveryV1/Models/FontSetting.swift | 32 +- Source/DiscoveryV1/Models/Gateway.swift | 2 +- Source/DiscoveryV1/Models/GatewayDelete.swift | 2 +- Source/DiscoveryV1/Models/GatewayList.swift | 2 +- Source/DiscoveryV1/Models/GatewayName.swift | 2 +- Source/DiscoveryV1/Models/HTMLSettings.swift | 22 +- Source/DiscoveryV1/Models/Histogram.swift | 5 +- Source/DiscoveryV1/Models/IndexCapacity.swift | 2 +- .../Models/ListCollectionFieldsResponse.swift | 2 +- .../Models/ListCollectionsResponse.swift | 2 +- .../Models/ListConfigurationsResponse.swift | 2 +- .../Models/ListEnvironmentsResponse.swift | 2 +- .../DiscoveryV1/Models/LogQueryResponse.swift | 5 +- .../Models/LogQueryResponseResult.swift | 2 +- .../LogQueryResponseResultDocuments.swift | 5 +- ...ogQueryResponseResultDocumentsResult.swift | 2 +- Source/DiscoveryV1/Models/MemoryUsage.swift | 58 ++ .../Models/MetricAggregation.swift | 5 +- .../Models/MetricAggregationResult.swift | 2 +- .../DiscoveryV1/Models/MetricResponse.swift | 5 +- .../Models/MetricTokenAggregation.swift | 5 +- .../Models/MetricTokenAggregationResult.swift | 2 +- .../Models/MetricTokenResponse.swift | 5 +- Source/DiscoveryV1/Models/Nested.swift | 5 +- .../DiscoveryV1/Models/NewTrainingQuery.swift | 17 +- .../Models/NluEnrichmentCategories.swift | 2 +- .../Models/NluEnrichmentConcepts.swift | 2 +- .../Models/NluEnrichmentEmotion.swift | 2 +- .../Models/NluEnrichmentEntities.swift | 12 +- .../Models/NluEnrichmentFeatures.swift | 2 +- .../Models/NluEnrichmentKeywords.swift | 2 +- .../Models/NluEnrichmentRelations.swift | 2 +- .../Models/NluEnrichmentSemanticRoles.swift | 2 +- .../Models/NluEnrichmentSentiment.swift | 2 +- .../Models/NormalizationOperation.swift | 26 +- Source/DiscoveryV1/Models/Notice.swift | 14 +- .../Models/PDFHeadingDetection.swift | 2 +- Source/DiscoveryV1/Models/PDFSettings.swift | 2 +- .../DiscoveryV1/Models/QueryAggregation.swift | 114 ++-- Source/DiscoveryV1/Models/QueryEntities.swift | 2 +- .../Models/QueryEntitiesContext.swift | 2 +- .../Models/QueryEntitiesEntity.swift | 2 +- .../Models/QueryEntitiesResponse.swift | 7 +- .../Models/QueryEntitiesResponseItem.swift | 2 +- Source/DiscoveryV1/Models/QueryEvidence.swift | 2 +- .../Models/QueryEvidenceEntity.swift | 2 +- .../DiscoveryV1/Models/QueryFilterType.swift | 2 +- Source/DiscoveryV1/Models/QueryLarge.swift | 6 +- .../Models/QueryNoticesResponse.swift | 17 +- .../Models/QueryNoticesResult.swift | 12 +- Source/DiscoveryV1/Models/QueryPassages.swift | 2 +- .../DiscoveryV1/Models/QueryRelations.swift | 7 +- .../Models/QueryRelationsArgument.swift | 5 +- .../Models/QueryRelationsEntity.swift | 2 +- .../Models/QueryRelationsFilter.swift | 12 +- .../Models/QueryRelationsRelationship.swift | 2 +- .../Models/QueryRelationsResponse.swift | 5 +- Source/DiscoveryV1/Models/QueryResponse.swift | 17 +- Source/DiscoveryV1/Models/QueryResult.swift | 12 +- .../Models/QueryResultMetadata.swift | 4 +- .../DiscoveryV1/Models/RetrievalDetails.swift | 2 +- Source/DiscoveryV1/Models/SearchStatus.swift | 2 +- .../DiscoveryV1/Models/SegmentSettings.swift | 8 +- Source/DiscoveryV1/Models/Source.swift | 6 +- Source/DiscoveryV1/Models/SourceOptions.swift | 27 +- .../Models/SourceOptionsBuckets.swift | 59 ++ .../Models/SourceOptionsFolder.swift | 2 +- .../Models/SourceOptionsObject.swift | 2 +- .../Models/SourceOptionsSiteColl.swift | 2 +- .../Models/SourceOptionsWebCrawl.swift | 2 +- .../DiscoveryV1/Models/SourceSchedule.swift | 2 +- Source/DiscoveryV1/Models/SourceStatus.swift | 13 +- Source/DiscoveryV1/Models/Term.swift | 5 +- Source/DiscoveryV1/Models/TestDocument.swift | 2 +- Source/DiscoveryV1/Models/Timeslice.swift | 5 +- Source/DiscoveryV1/Models/TokenDict.swift | 2 +- Source/DiscoveryV1/Models/TokenDictRule.swift | 22 +- .../Models/TokenDictStatusResponse.swift | 2 +- Source/DiscoveryV1/Models/TopHits.swift | 5 +- .../DiscoveryV1/Models/TopHitsResults.swift | 2 +- .../DiscoveryV1/Models/TrainingDataSet.swift | 11 +- .../DiscoveryV1/Models/TrainingExample.swift | 17 +- .../Models/TrainingExampleList.swift | 5 +- .../Models/TrainingExamplePatch.swift | 12 +- Source/DiscoveryV1/Models/TrainingQuery.swift | 14 +- .../DiscoveryV1/Models/TrainingStatus.swift | 29 +- .../Models/UpdateCollectionRequest.swift | 2 +- .../Models/UpdateEnvironmentRequest.swift | 2 +- .../Models/WordHeadingDetection.swift | 2 +- Source/DiscoveryV1/Models/WordSettings.swift | 2 +- Source/DiscoveryV1/Models/WordStyle.swift | 12 +- Source/DiscoveryV1/Models/XPathPatterns.swift | 7 +- .../LanguageTranslator.swift | 104 ++-- .../Models/DeleteModelResult.swift | 2 +- .../Models/IdentifiableLanguage.swift | 2 +- .../Models/IdentifiableLanguages.swift | 2 +- .../Models/IdentifiedLanguage.swift | 2 +- .../Models/IdentifiedLanguages.swift | 2 +- .../Models/TranslateRequest.swift | 2 +- .../Models/Translation.swift | 2 +- .../Models/TranslationModel.swift | 2 +- .../Models/TranslationModels.swift | 2 +- .../Models/TranslationResult.swift | 2 +- .../Models/Classification.swift | 2 +- .../Models/ClassificationCollection.swift | 2 +- .../Models/ClassifiedClass.swift | 2 +- .../Models/Classifier.swift | 2 +- .../Models/ClassifierList.swift | 2 +- .../Models/ClassifyCollectionInput.swift | 2 +- .../Models/ClassifyInput.swift | 2 +- .../Models/CollectionItem.swift | 2 +- .../NaturalLanguageClassifier.swift | 89 +-- .../Models/AnalysisResults.swift | 22 +- .../Models/AnalysisResultsEmotion.swift | 37 ++ .../Models/AnalysisResultsMetadata.swift | 58 ++ .../Models/AnalysisResultsSentiment.swift | 37 ++ .../Models/AnalysisResultsUsage.swift | 46 ++ .../Models/Author.swift | 2 +- .../Models/CategoriesOptions.swift | 16 +- .../Models/CategoriesResult.swift | 2 +- .../Models/ConceptsOptions.swift | 2 +- .../Models/ConceptsResult.swift | 2 +- .../Models/DeleteModelResults.swift | 2 +- .../Models/DisambiguationResult.swift | 2 +- .../Models/DocumentEmotionResults.swift | 2 +- .../DocumentEmotionResultsEmotion.swift | 58 ++ .../Models/DocumentSentimentResults.swift | 2 +- .../Models/EmotionOptions.swift | 2 +- .../Models/EmotionResult.swift | 2 +- .../Models/EmotionScores.swift | 2 +- .../Models/EntitiesOptions.swift | 2 +- .../Models/EntitiesResult.swift | 2 +- .../EntitiesResultDisambiguation.swift} | 37 +- .../Models/EntitiesResultEmotion.swift | 58 ++ .../Models/EntitiesResultSentiment.swift | 34 ++ .../Models/EntityMention.swift | 2 +- .../Models/FeatureSentimentResults.swift | 2 +- .../Models/Features.swift | 13 +- .../Models/Feed.swift | 2 +- .../Models/KeywordsOptions.swift | 2 +- .../Models/KeywordsResult.swift | 2 +- .../Models/KeywordsResultEmotion.swift | 58 ++ .../Models/KeywordsResultSentiment.swift | 34 ++ .../Models/ListModelsResults.swift | 2 +- .../Models/MetadataOptions.swift | 7 +- .../Models/Model.swift | 2 +- .../Models/Parameters.swift | 10 +- .../Models/ParametersFeatures.swift | 106 ++++ .../Models/RelationArgument.swift | 2 +- .../Models/RelationEntity.swift | 2 +- .../Models/RelationsOptions.swift | 2 +- .../Models/RelationsResult.swift | 2 +- .../Models/SemanticRolesEntity.swift | 2 +- .../Models/SemanticRolesKeyword.swift | 2 +- .../Models/SemanticRolesOptions.swift | 2 +- .../Models/SemanticRolesResult.swift | 8 +- .../Models/SemanticRolesResultAction.swift | 43 ++ .../Models/SemanticRolesResultObject.swift | 40 ++ .../Models/SemanticRolesResultSubject.swift | 46 ++ .../Models/SemanticRolesVerb.swift | 2 +- .../Models/SentenceResult.swift | 38 ++ .../Models/SentimentOptions.swift | 2 +- .../Models/SentimentResult.swift | 2 +- .../Models/SyntaxOptions.swift | 57 ++ .../Models/SyntaxOptionsTokens.swift | 40 ++ .../Models/SyntaxResult.swift | 34 ++ .../Models/TargetedEmotionResults.swift | 2 +- .../TargetedEmotionResultsEmotion.swift | 58 ++ .../Models/TargetedSentimentResults.swift | 2 +- .../Models/TokenResult.swift | 75 +++ .../NaturalLanguageUnderstanding.swift | 78 +-- .../Models/Behavior.swift | 2 +- .../Models/ConsumptionPreferences.swift | 2 +- .../ConsumptionPreferencesCategory.swift | 2 +- .../Models/Content.swift | 2 +- .../Models/ContentItem.swift | 2 +- .../Models/Profile.swift | 2 +- .../Models/ProfileContent.swift | 5 +- .../PersonalityInsightsV3/Models/Trait.swift | 2 +- .../Models/Warning.swift | 2 +- .../PersonalityInsights.swift | 72 ++- .../SpeechToTextV1/Models/AcousticModel.swift | 2 +- .../Models/AcousticModels.swift | 2 +- .../SpeechToTextV1/Models/AudioDetails.swift | 2 +- .../SpeechToTextV1/Models/AudioListing.swift | 7 +- .../Models/AudioListingContainer.swift | 77 +++ .../Models/AudioListingDetails.swift | 85 +++ .../SpeechToTextV1/Models/AudioResource.swift | 6 +- .../Models/AudioResourceDetails.swift | 85 +++ .../Models/AudioResources.swift | 2 +- Source/SpeechToTextV1/Models/Corpora.swift | 2 +- Source/SpeechToTextV1/Models/Corpus.swift | 2 +- .../Models/CreateAcousticModel.swift | 2 +- .../Models/CreateLanguageModel.swift | 2 +- Source/SpeechToTextV1/Models/CustomWord.swift | 2 +- .../SpeechToTextV1/Models/CustomWords.swift | 2 +- Source/SpeechToTextV1/Models/Grammar.swift | 2 +- Source/SpeechToTextV1/Models/Grammars.swift | 2 +- .../SpeechToTextV1/Models/KeywordResult.swift | 2 +- .../SpeechToTextV1/Models/LanguageModel.swift | 2 +- .../Models/LanguageModels.swift | 2 +- .../Models/RecognitionJob.swift | 2 +- .../Models/RecognitionJobs.swift | 2 +- .../Models/RegisterStatus.swift | 2 +- .../Models/SpeakerLabelsResult.swift | 2 +- .../SpeechToTextV1/Models/SpeechModel.swift | 2 +- .../SpeechToTextV1/Models/SpeechModels.swift | 2 +- .../Models/SpeechRecognitionAlternative.swift | 6 +- .../Models/SpeechRecognitionResult.swift | 2 +- .../Models/SpeechRecognitionResults.swift | 2 +- .../Models/SupportedFeatures.swift | 2 +- Source/SpeechToTextV1/Models/Word.swift | 2 +- .../Models/WordAlternativeResult.swift | 2 +- .../Models/WordAlternativeResults.swift | 2 +- Source/SpeechToTextV1/Models/WordError.swift | 2 +- Source/SpeechToTextV1/Models/Words.swift | 2 +- Source/SpeechToTextV1/SpeechToText.swift | 386 +++++++------ .../Models/CreateVoiceModel.swift | 2 +- .../TextToSpeechV1/Models/Pronunciation.swift | 2 +- .../Models/SupportedFeatures.swift | 2 +- Source/TextToSpeechV1/Models/Text.swift | 2 +- .../TextToSpeechV1/Models/Translation.swift | 2 +- .../Models/UpdateVoiceModel.swift | 2 +- Source/TextToSpeechV1/Models/Voice.swift | 2 +- .../Models/VoiceCustomization.swift | 84 +++ Source/TextToSpeechV1/Models/VoiceModel.swift | 2 +- .../TextToSpeechV1/Models/VoiceModels.swift | 2 +- Source/TextToSpeechV1/Models/Voices.swift | 2 +- Source/TextToSpeechV1/Models/Word.swift | 2 +- Source/TextToSpeechV1/Models/Words.swift | 2 +- Source/TextToSpeechV1/TextToSpeech.swift | 170 +++--- .../Models/DocumentAnalysis.swift | 2 +- .../Models/SentenceAnalysis.swift | 2 +- .../ToneAnalyzerV3/Models/ToneAnalysis.swift | 2 +- .../ToneAnalyzerV3/Models/ToneCategory.swift | 2 +- .../ToneAnalyzerV3/Models/ToneChatInput.swift | 2 +- .../ToneAnalyzerV3/Models/ToneChatScore.swift | 2 +- .../ToneAnalyzerV3/Models/ToneContent.swift | 5 +- Source/ToneAnalyzerV3/Models/ToneInput.swift | 2 +- Source/ToneAnalyzerV3/Models/ToneScore.swift | 2 +- Source/ToneAnalyzerV3/Models/Utterance.swift | 2 +- .../Models/UtteranceAnalyses.swift | 2 +- .../Models/UtteranceAnalysis.swift | 2 +- Source/ToneAnalyzerV3/ToneAnalyzer.swift | 72 ++- Source/VisualRecognitionV3/Models/Class.swift | 2 +- .../Models/ClassResult.swift | 2 +- .../Models/ClassifiedImage.swift | 2 +- .../Models/ClassifiedImages.swift | 2 +- .../Models/Classifier.swift | 2 +- .../Models/ClassifierResult.swift | 2 +- .../Models/Classifiers.swift | 2 +- .../Models/DetectedFaces.swift | 2 +- .../Models/ErrorInfo.swift | 2 +- Source/VisualRecognitionV3/Models/Face.swift | 2 +- .../VisualRecognitionV3/Models/FaceAge.swift | 2 +- .../Models/FaceGender.swift | 2 +- .../Models/FaceLocation.swift | 2 +- .../Models/ImageWithFaces.swift | 2 +- .../Models/WarningInfo.swift | 2 +- .../VisualRecognition.swift | 185 +++---- .../project.pbxproj | 194 +++++-- 452 files changed, 5143 insertions(+), 3095 deletions(-) delete mode 100644 Source/AssistantV1/Models/CreateCounterexample.swift delete mode 100644 Source/AssistantV1/Models/CreateDialogNode.swift delete mode 100644 Source/AssistantV1/Models/CreateExample.swift delete mode 100644 Source/AssistantV1/Models/CreateSynonym.swift delete mode 100644 Source/AssistantV1/Models/EntityExport.swift delete mode 100644 Source/AssistantV1/Models/InputData.swift rename Source/AssistantV1/Models/{LogExport.swift => Log.swift} (95%) rename Source/AssistantV1/Models/{Mentions.swift => Mention.swift} (89%) delete mode 100644 Source/AssistantV1/Models/ValueExport.swift delete mode 100644 Source/AssistantV1/Models/WorkspaceExport.swift create mode 100644 Source/AssistantV2/Models/MessageContextSkill.swift create mode 100644 Source/AssistantV2/Models/MessageRequestContext.swift create mode 100644 Source/AssistantV2/Models/MessageResponseContext.swift create mode 100644 Source/CompareComplyV1/Models/CategoryComparison.swift rename Source/CompareComplyV1/Models/{ColumnHeaderIds.swift => ColumnHeaderIDs.swift} (96%) create mode 100644 Source/CompareComplyV1/Models/ContractType.swift create mode 100644 Source/CompareComplyV1/Models/Key.swift create mode 100644 Source/CompareComplyV1/Models/KeyValuePair.swift rename Source/CompareComplyV1/Models/{RowHeaderIds.swift => RowHeaderIDs.swift} (96%) create mode 100644 Source/CompareComplyV1/Models/TypeLabelComparison.swift create mode 100644 Source/CompareComplyV1/Models/Value.swift create mode 100644 Source/DiscoveryV1/Models/MemoryUsage.swift create mode 100644 Source/DiscoveryV1/Models/SourceOptionsBuckets.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsEmotion.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsSentiment.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsUsage.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResultsEmotion.swift rename Source/{AssistantV1/Models/IntentExport.swift => NaturalLanguageUnderstandingV1/Models/EntitiesResultDisambiguation.swift} (54%) create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultEmotion.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultSentiment.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultEmotion.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultSentiment.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/ParametersFeatures.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultAction.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultObject.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultSubject.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SentenceResult.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptions.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptionsTokens.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/SyntaxResult.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResultsEmotion.swift create mode 100644 Source/NaturalLanguageUnderstandingV1/Models/TokenResult.swift create mode 100644 Source/SpeechToTextV1/Models/AudioListingContainer.swift create mode 100644 Source/SpeechToTextV1/Models/AudioListingDetails.swift create mode 100644 Source/SpeechToTextV1/Models/AudioResourceDetails.swift create mode 100644 Source/TextToSpeechV1/Models/VoiceCustomization.swift diff --git a/.gitignore b/.gitignore index 72ac1fa86..454f0025b 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,5 @@ Carthage/ # swagger-codegen .swagger-codegen-ignore .swagger-codegen/ +.openapi-generator-ignore +.openapi-generator/ diff --git a/Source/AssistantV1/Assistant.swift b/Source/AssistantV1/Assistant.swift index 0a154c09c..2de240a97 100644 --- a/Source/AssistantV1/Assistant.swift +++ b/Source/AssistantV1/Assistant.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,22 +36,23 @@ public class Assistant { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `Assistant` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "assistant") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "assistant") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -61,20 +62,22 @@ public class Assistant { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `Assistant` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -88,6 +91,7 @@ public class Assistant { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -98,8 +102,9 @@ public class Assistant { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -122,16 +127,25 @@ public class Assistant { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -142,14 +156,14 @@ public class Assistant { - parameter workspaceID: Unique identifier of the workspace. - parameter input: An input object that includes the input text. - - parameter alternateIntents: Whether to return more than one intent. Set to `true` to return all matching - intents. - - parameter context: State information for the conversation. To maintain state, include the context from the - previous response. - - parameter entities: Entities to use when evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new input. - parameter intents: Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. + - parameter entities: Entities to use when evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new input. + - parameter alternateIntents: Whether to return more than one intent. A value of `true` indicates that all + matching intents are returned. + - parameter context: State information for the conversation. To maintain state, include the context from the + previous response. - parameter output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - parameter nodesVisitedDetails: Whether to include additional diagnostic information about the dialog nodes that @@ -159,11 +173,11 @@ public class Assistant { */ public func message( workspaceID: String, - input: InputData? = nil, + input: MessageInput? = nil, + intents: [RuntimeIntent]? = nil, + entities: [RuntimeEntity]? = nil, alternateIntents: Bool? = nil, context: Context? = nil, - entities: [RuntimeEntity]? = nil, - intents: [RuntimeIntent]? = nil, output: OutputData? = nil, nodesVisitedDetails: Bool? = nil, headers: [String: String]? = nil, @@ -172,12 +186,12 @@ public class Assistant { // construct body let messageRequest = MessageRequest( input: input, + intents: intents, + entities: entities, alternateIntents: alternateIntents, context: context, - entities: entities, - intents: intents, output: output) - guard let body = try? JSONEncoder().encodeIfPresent(messageRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(messageRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -187,8 +201,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "message") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "message") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -251,8 +265,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWorkspaces") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWorkspaces") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -306,15 +320,16 @@ public class Assistant { - parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter language: The language of the workspace. + - parameter metadata: Any metadata related to the workspace. + - parameter learningOptOut: Whether training data from the workspace (including artifacts such as intents and + entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is + not to be used. + - parameter systemSettings: Global settings for the workspace. - parameter intents: An array of objects defining the intents for the workspace. - - parameter entities: An array of objects defining the entities for the workspace. - - parameter dialogNodes: An array of objects defining the nodes in the dialog. + - parameter entities: An array of objects describing the entities for the workspace. + - parameter dialogNodes: An array of objects describing the dialog nodes in the workspace. - parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input. - - parameter metadata: Any metadata related to the workspace. - - parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - - parameter systemSettings: Global settings for the workspace. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -322,13 +337,13 @@ public class Assistant { name: String? = nil, description: String? = nil, language: String? = nil, - intents: [CreateIntent]? = nil, - entities: [CreateEntity]? = nil, - dialogNodes: [CreateDialogNode]? = nil, - counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil, systemSettings: WorkspaceSystemSettings? = nil, + intents: [CreateIntent]? = nil, + entities: [CreateEntity]? = nil, + dialogNodes: [DialogNode]? = nil, + counterexamples: [Counterexample]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -337,14 +352,14 @@ public class Assistant { name: name, description: description, language: language, + metadata: metadata, + learningOptOut: learningOptOut, + systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, - counterexamples: counterexamples, - metadata: metadata, - learningOptOut: learningOptOut, - systemSettings: systemSettings) - guard let body = try? JSONEncoder().encodeIfPresent(createWorkspaceRequest) else { + counterexamples: counterexamples) + guard let body = try? JSON.encoder.encodeIfPresent(createWorkspaceRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -354,8 +369,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createWorkspace") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createWorkspace") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -404,15 +419,15 @@ public class Assistant { includeAudit: Bool? = nil, sort: String? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWorkspace") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWorkspace") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -464,15 +479,16 @@ public class Assistant { - parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter language: The language of the workspace. + - parameter metadata: Any metadata related to the workspace. + - parameter learningOptOut: Whether training data from the workspace (including artifacts such as intents and + entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is + not to be used. + - parameter systemSettings: Global settings for the workspace. - parameter intents: An array of objects defining the intents for the workspace. - - parameter entities: An array of objects defining the entities for the workspace. - - parameter dialogNodes: An array of objects defining the nodes in the dialog. + - parameter entities: An array of objects describing the entities for the workspace. + - parameter dialogNodes: An array of objects describing the dialog nodes in the workspace. - parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input. - - parameter metadata: Any metadata related to the workspace. - - parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - - parameter systemSettings: Global settings for the workspace. - parameter append: Whether the new data is to be appended to the existing data in the workspace. If **append**=`false`, elements included in the new data completely replace the corresponding existing elements, including all subelements. For example, if the new data includes **entities** and **append**=`false`, all @@ -487,13 +503,13 @@ public class Assistant { name: String? = nil, description: String? = nil, language: String? = nil, - intents: [CreateIntent]? = nil, - entities: [CreateEntity]? = nil, - dialogNodes: [CreateDialogNode]? = nil, - counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil, systemSettings: WorkspaceSystemSettings? = nil, + intents: [CreateIntent]? = nil, + entities: [CreateEntity]? = nil, + dialogNodes: [DialogNode]? = nil, + counterexamples: [Counterexample]? = nil, append: Bool? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) @@ -503,14 +519,14 @@ public class Assistant { name: name, description: description, language: language, + metadata: metadata, + learningOptOut: learningOptOut, + systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, - counterexamples: counterexamples, - metadata: metadata, - learningOptOut: learningOptOut, - systemSettings: systemSettings) - guard let body = try? JSONEncoder().encodeIfPresent(updateWorkspaceRequest) else { + counterexamples: counterexamples) + guard let body = try? JSON.encoder.encodeIfPresent(updateWorkspaceRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -520,8 +536,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateWorkspace") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateWorkspace") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -574,8 +590,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWorkspace") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWorkspace") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -639,8 +655,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listIntents") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listIntents") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -712,7 +728,7 @@ public class Assistant { workspaceID: String, intent: String, description: String? = nil, - examples: [CreateExample]? = nil, + examples: [Example]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -721,7 +737,7 @@ public class Assistant { intent: intent, description: description, examples: examples) - guard let body = try? JSONEncoder().encode(createIntentRequest) else { + guard let body = try? JSON.encoder.encode(createIntentRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -731,8 +747,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createIntent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createIntent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -784,15 +800,15 @@ public class Assistant { export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getIntent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getIntent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -840,7 +856,8 @@ public class Assistant { - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. - - parameter newDescription: The description of the intent. + - parameter newDescription: The description of the intent. This string cannot contain carriage return, newline, + or tab characters, and it must be no longer than 128 characters. - parameter newExamples: An array of user input examples for the intent. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error @@ -850,7 +867,7 @@ public class Assistant { intent: String, newIntent: String? = nil, newDescription: String? = nil, - newExamples: [CreateExample]? = nil, + newExamples: [Example]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -859,7 +876,7 @@ public class Assistant { intent: newIntent, description: newDescription, examples: newExamples) - guard let body = try? JSONEncoder().encode(updateIntentRequest) else { + guard let body = try? JSON.encoder.encode(updateIntentRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -869,8 +886,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateIntent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateIntent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -921,8 +938,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteIntent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteIntent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -983,8 +1000,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listExamples") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listExamples") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1051,15 +1068,15 @@ public class Assistant { workspaceID: String, intent: String, text: String, - mentions: [Mentions]? = nil, + mentions: [Mention]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let createExampleRequest = CreateExample( + let createExampleRequest = Example( text: text, mentions: mentions) - guard let body = try? JSONEncoder().encode(createExampleRequest) else { + guard let body = try? JSON.encoder.encode(createExampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1069,8 +1086,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1126,8 +1143,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1180,7 +1197,7 @@ public class Assistant { intent: String, text: String, newText: String? = nil, - newMentions: [Mentions]? = nil, + newMentions: [Mention]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -1188,7 +1205,7 @@ public class Assistant { let updateExampleRequest = UpdateExample( text: newText, mentions: newMentions) - guard let body = try? JSONEncoder().encode(updateExampleRequest) else { + guard let body = try? JSON.encoder.encode(updateExampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1198,8 +1215,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1252,8 +1269,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1312,8 +1329,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCounterexamples") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCounterexamples") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1382,9 +1399,9 @@ public class Assistant { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let createCounterexampleRequest = CreateCounterexample( + let createCounterexampleRequest = Counterexample( text: text) - guard let body = try? JSONEncoder().encode(createCounterexampleRequest) else { + guard let body = try? JSON.encoder.encode(createCounterexampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1394,8 +1411,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCounterexample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCounterexample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1449,8 +1466,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCounterexample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCounterexample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1489,7 +1506,11 @@ public class Assistant { - parameter workspaceID: Unique identifier of the workspace. - parameter text: The text of a user input counterexample (for example, `What are you wearing?`). - - parameter newText: The text of a user input counterexample. + - parameter newText: The text of a user input marked as irrelevant input. This string must conform to the + following restrictions: + - It cannot contain carriage return, newline, or tab characters + - It cannot consist of only whitespace characters + - It must be no longer than 1024 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -1503,7 +1524,7 @@ public class Assistant { // construct body let updateCounterexampleRequest = UpdateCounterexample( text: newText) - guard let body = try? JSONEncoder().encode(updateCounterexampleRequest) else { + guard let body = try? JSON.encoder.encode(updateCounterexampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1513,8 +1534,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCounterexample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCounterexample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1565,8 +1586,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCounterexample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCounterexample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1630,8 +1651,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listEntities") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listEntities") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1696,9 +1717,9 @@ public class Assistant { that you want to enable. (Any entity content specified with the request is ignored.). - parameter description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - - parameter metadata: Any metadata related to the value. - - parameter values: An array of objects describing the entity values. + - parameter metadata: Any metadata related to the entity. - parameter fuzzyMatch: Whether to use fuzzy matching for the entity. + - parameter values: An array of objects describing the entity values. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -1707,8 +1728,8 @@ public class Assistant { entity: String, description: String? = nil, metadata: [String: JSON]? = nil, - values: [CreateValue]? = nil, fuzzyMatch: Bool? = nil, + values: [CreateValue]? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -1717,9 +1738,9 @@ public class Assistant { entity: entity, description: description, metadata: metadata, - values: values, - fuzzyMatch: fuzzyMatch) - guard let body = try? JSONEncoder().encode(createEntityRequest) else { + fuzzyMatch: fuzzyMatch, + values: values) + guard let body = try? JSON.encoder.encode(createEntityRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1729,8 +1750,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEntity") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEntity") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1782,15 +1803,15 @@ public class Assistant { export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getEntity") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getEntity") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1842,7 +1863,7 @@ public class Assistant { or tab characters, and it must be no longer than 128 characters. - parameter newMetadata: Any metadata related to the entity. - parameter newFuzzyMatch: Whether to use fuzzy matching for the entity. - - parameter newValues: An array of entity values. + - parameter newValues: An array of objects describing the entity values. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -1864,7 +1885,7 @@ public class Assistant { metadata: newMetadata, fuzzyMatch: newFuzzyMatch, values: newValues) - guard let body = try? JSONEncoder().encode(updateEntityRequest) else { + guard let body = try? JSON.encoder.encode(updateEntityRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1874,8 +1895,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateEntity") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateEntity") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1926,8 +1947,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteEntity") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteEntity") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1984,8 +2005,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listMentions") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listMentions") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2058,8 +2079,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listValues") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listValues") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2111,7 +2132,7 @@ public class Assistant { } /** - Add entity value. + Create entity value. Create a new value for an entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. @@ -2123,16 +2144,16 @@ public class Assistant { - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter metadata: Any metadata related to the entity value. - - parameter synonyms: An array containing any synonyms for the entity value. You can provide either synonyms or - patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: + - parameter valueType: Specifies the type of entity value. + - parameter synonyms: An array of synonyms for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - - parameter patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as - indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more - information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). - - parameter valueType: Specifies the type of value. + - parameter patterns: An array of patterns for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A pattern is a regular expression no longer than 512 characters. For + more information about how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -2141,9 +2162,9 @@ public class Assistant { entity: String, value: String, metadata: [String: JSON]? = nil, + valueType: String? = nil, synonyms: [String]? = nil, patterns: [String]? = nil, - valueType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -2151,10 +2172,10 @@ public class Assistant { let createValueRequest = CreateValue( value: value, metadata: metadata, + valueType: valueType, synonyms: synonyms, - patterns: patterns, - valueType: valueType) - guard let body = try? JSONEncoder().encode(createValueRequest) else { + patterns: patterns) + guard let body = try? JSON.encoder.encode(createValueRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2164,8 +2185,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createValue") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createValue") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2218,15 +2239,15 @@ public class Assistant { export: Bool? = nil, includeAudit: Bool? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct header parameters var headerParameters = defaultHeaders if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getValue") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getValue") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2276,16 +2297,16 @@ public class Assistant { - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter newMetadata: Any metadata related to the entity value. - - parameter newType: Specifies the type of value. - - parameter newSynonyms: An array of synonyms for the entity value. You can provide either synonyms or patterns - (as indicated by **type**), but not both. A synonym must conform to the following resrictions: + - parameter newValueType: Specifies the type of entity value. + - parameter newSynonyms: An array of synonyms for the entity value. A value can specify either synonyms or + patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - - parameter newPatterns: An array of patterns for the entity value. You can provide either synonyms or patterns - (as indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For - more information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). + - parameter newPatterns: An array of patterns for the entity value. A value can specify either synonyms or + patterns (depending on the value type), but not both. A pattern is a regular expression no longer than 512 + characters. For more information about how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -2295,7 +2316,7 @@ public class Assistant { value: String, newValue: String? = nil, newMetadata: [String: JSON]? = nil, - newType: String? = nil, + newValueType: String? = nil, newSynonyms: [String]? = nil, newPatterns: [String]? = nil, headers: [String: String]? = nil, @@ -2305,10 +2326,10 @@ public class Assistant { let updateValueRequest = UpdateValue( value: newValue, metadata: newMetadata, - valueType: newType, + valueType: newValueType, synonyms: newSynonyms, patterns: newPatterns) - guard let body = try? JSONEncoder().encode(updateValueRequest) else { + guard let body = try? JSON.encoder.encode(updateValueRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2318,8 +2339,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateValue") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateValue") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2372,8 +2393,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteValue") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteValue") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2436,8 +2457,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listSynonyms") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listSynonyms") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2485,7 +2506,7 @@ public class Assistant { } /** - Add entity value synonym. + Create entity value synonym. Add a new synonym to an entity value. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. @@ -2509,9 +2530,9 @@ public class Assistant { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let createSynonymRequest = CreateSynonym( + let createSynonymRequest = Synonym( synonym: synonym) - guard let body = try? JSONEncoder().encode(createSynonymRequest) else { + guard let body = try? JSON.encoder.encode(createSynonymRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2521,8 +2542,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSynonym") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSynonym") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2580,8 +2601,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getSynonym") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getSynonym") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2641,7 +2662,7 @@ public class Assistant { // construct body let updateSynonymRequest = UpdateSynonym( synonym: newSynonym) - guard let body = try? JSONEncoder().encode(updateSynonymRequest) else { + guard let body = try? JSON.encoder.encode(updateSynonymRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2651,8 +2672,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateSynonym") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateSynonym") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2707,8 +2728,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteSynonym") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteSynonym") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2767,8 +2788,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listDialogNodes") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listDialogNodes") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2829,14 +2850,15 @@ public class Assistant { or tab characters, and it must be no longer than 128 characters. - parameter conditions: The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. - - parameter parent: The ID of the parent dialog node. - - parameter previousSibling: The ID of the previous dialog node. + - parameter parent: The ID of the parent dialog node. This property is omitted if the dialog node has no parent. + - parameter previousSibling: The ID of the previous sibling dialog node. This property is omitted if the dialog + node has no previous sibling. - parameter output: The output of the dialog node. For more information about how to specify dialog node output, - see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + see the + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). - parameter context: The context for the dialog node. - parameter metadata: The metadata for the dialog node. - parameter nextStep: The next step to execute following this dialog node. - - parameter actions: An array of objects describing any actions to be invoked by the dialog node. - parameter title: The alias used to identify the dialog node. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. @@ -2844,6 +2866,7 @@ public class Assistant { - parameter nodeType: How the dialog node is processed. - parameter eventName: How an `event_handler` node is processed. - parameter variable: The location in the dialog context where output is stored. + - parameter actions: An array of objects describing any actions to be invoked by the dialog node. - parameter digressIn: Whether this top-level dialog node can be digressed into. - parameter digressOut: Whether this dialog node can be returned to after a digression. - parameter digressOutSlots: Whether the user can digress to top-level nodes while filling out slots. @@ -2863,11 +2886,11 @@ public class Assistant { context: [String: JSON]? = nil, metadata: [String: JSON]? = nil, nextStep: DialogNodeNextStep? = nil, - actions: [DialogNodeAction]? = nil, title: String? = nil, nodeType: String? = nil, eventName: String? = nil, variable: String? = nil, + actions: [DialogNodeAction]? = nil, digressIn: String? = nil, digressOut: String? = nil, digressOutSlots: String? = nil, @@ -2876,7 +2899,7 @@ public class Assistant { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let createDialogNodeRequest = CreateDialogNode( + let createDialogNodeRequest = DialogNode( dialogNode: dialogNode, description: description, conditions: conditions, @@ -2886,16 +2909,16 @@ public class Assistant { context: context, metadata: metadata, nextStep: nextStep, - actions: actions, title: title, nodeType: nodeType, eventName: eventName, variable: variable, + actions: actions, digressIn: digressIn, digressOut: digressOut, digressOutSlots: digressOutSlots, userLabel: userLabel) - guard let body = try? JSONEncoder().encode(createDialogNodeRequest) else { + guard let body = try? JSON.encoder.encode(createDialogNodeRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2905,8 +2928,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createDialogNode") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createDialogNode") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2960,8 +2983,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getDialogNode") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getDialogNode") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3007,10 +3030,13 @@ public class Assistant { newline, or tab characters, and it must be no longer than 128 characters. - parameter newConditions: The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. - - parameter newParent: The ID of the parent dialog node. - - parameter newPreviousSibling: The ID of the previous sibling dialog node. + - parameter newParent: The ID of the parent dialog node. This property is omitted if the dialog node has no + parent. + - parameter newPreviousSibling: The ID of the previous sibling dialog node. This property is omitted if the + dialog node has no previous sibling. - parameter newOutput: The output of the dialog node. For more information about how to specify dialog node - output, see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + output, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). - parameter newContext: The context for the dialog node. - parameter newMetadata: The metadata for the dialog node. - parameter newNextStep: The next step to execute following this dialog node. @@ -3018,7 +3044,7 @@ public class Assistant { restrictions: - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - It must be no longer than 64 characters. - - parameter newType: How the dialog node is processed. + - parameter newNodeType: How the dialog node is processed. - parameter newEventName: How an `event_handler` node is processed. - parameter newVariable: The location in the dialog context where output is stored. - parameter newActions: An array of objects describing any actions to be invoked by the dialog node. @@ -3043,7 +3069,7 @@ public class Assistant { newMetadata: [String: JSON]? = nil, newNextStep: DialogNodeNextStep? = nil, newTitle: String? = nil, - newType: String? = nil, + newNodeType: String? = nil, newEventName: String? = nil, newVariable: String? = nil, newActions: [DialogNodeAction]? = nil, @@ -3066,7 +3092,7 @@ public class Assistant { metadata: newMetadata, nextStep: newNextStep, title: newTitle, - nodeType: newType, + nodeType: newNodeType, eventName: newEventName, variable: newVariable, actions: newActions, @@ -3074,7 +3100,7 @@ public class Assistant { digressOut: newDigressOut, digressOutSlots: newDigressOutSlots, userLabel: newUserLabel) - guard let body = try? JSONEncoder().encode(updateDialogNodeRequest) else { + guard let body = try? JSON.encoder.encode(updateDialogNodeRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -3084,8 +3110,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateDialogNode") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateDialogNode") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -3136,8 +3162,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDialogNode") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDialogNode") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3176,7 +3202,7 @@ public class Assistant { order, prefix the parameter value with a minus sign (`-`). - parameter filter: A cacheable parameter that limits the results to those matching the specified filter. For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-query-syntax). + [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-reference-syntax). - parameter pageLimit: The number of records to return in each page of results. - parameter cursor: A token identifying the page of results to retrieve. - parameter headers: A dictionary of request headers to be sent with this request. @@ -3196,8 +3222,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLogs") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLogs") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3250,7 +3276,7 @@ public class Assistant { - parameter filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that includes a value for `language`, as well as a value for `workspace_id` or `request.context.metadata.deployment`. For more information, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-query-syntax). + [documentation](https://cloud.ibm.com/docs/services/assistant/filter-reference.html#filter-reference-syntax). - parameter sort: How to sort the returned log events. You can sort by **request_timestamp**. To reverse the sort order, prefix the parameter value with a minus sign (`-`). - parameter pageLimit: The number of records to return in each page of results. @@ -3271,8 +3297,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAllLogs") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAllLogs") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3330,8 +3356,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters diff --git a/Source/AssistantV1/Models/CaptureGroup.swift b/Source/AssistantV1/Models/CaptureGroup.swift index 3bf1fb3b9..4ba185c64 100644 --- a/Source/AssistantV1/Models/CaptureGroup.swift +++ b/Source/AssistantV1/Models/CaptureGroup.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ import Foundation -/** CaptureGroup. */ +/** + A recognized capture group for a pattern-based entity. + */ public struct CaptureGroup: Codable, Equatable { /** diff --git a/Source/AssistantV1/Models/Context.swift b/Source/AssistantV1/Models/Context.swift index de699cadc..d2810e2ba 100644 --- a/Source/AssistantV1/Models/Context.swift +++ b/Source/AssistantV1/Models/Context.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/Counterexample.swift b/Source/AssistantV1/Models/Counterexample.swift index 1d1c7cf99..06930253b 100644 --- a/Source/AssistantV1/Models/Counterexample.swift +++ b/Source/AssistantV1/Models/Counterexample.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,20 @@ import Foundation public struct Counterexample: Codable, Equatable { /** - The text of the counterexample. + The text of a user input marked as irrelevant input. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters + - It cannot consist of only whitespace characters + - It must be no longer than 1024 characters. */ public var text: String /** - The timestamp for creation of the counterexample. + The timestamp for creation of the object. */ public var created: Date? /** - The timestamp for the last update to the counterexample. + The timestamp for the most recent update to the object. */ public var updated: Date? @@ -41,4 +44,28 @@ public struct Counterexample: Codable, Equatable { case updated = "updated" } + /** + Initialize a `Counterexample` with member variables. + + - parameter text: The text of a user input marked as irrelevant input. This string must conform to the following + restrictions: + - It cannot contain carriage return, newline, or tab characters + - It cannot consist of only whitespace characters + - It must be no longer than 1024 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + + - returns: An initialized `Counterexample`. + */ + public init( + text: String, + created: Date? = nil, + updated: Date? = nil + ) + { + self.text = text + self.created = created + self.updated = updated + } + } diff --git a/Source/AssistantV1/Models/CounterexampleCollection.swift b/Source/AssistantV1/Models/CounterexampleCollection.swift index 05e09733c..f81baf32b 100644 --- a/Source/AssistantV1/Models/CounterexampleCollection.swift +++ b/Source/AssistantV1/Models/CounterexampleCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/CreateCounterexample.swift b/Source/AssistantV1/Models/CreateCounterexample.swift deleted file mode 100644 index 1c18693a2..000000000 --- a/Source/AssistantV1/Models/CreateCounterexample.swift +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation - -/** CreateCounterexample. */ -public struct CreateCounterexample: Codable, Equatable { - - /** - The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - - It cannot contain carriage return, newline, or tab characters - - It cannot consist of only whitespace characters - - It must be no longer than 1024 characters. - */ - public var text: String - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case text = "text" - } - - /** - Initialize a `CreateCounterexample` with member variables. - - - parameter text: The text of a user input marked as irrelevant input. This string must conform to the following - restrictions: - - It cannot contain carriage return, newline, or tab characters - - It cannot consist of only whitespace characters - - It must be no longer than 1024 characters. - - - returns: An initialized `CreateCounterexample`. - */ - public init( - text: String - ) - { - self.text = text - } - -} diff --git a/Source/AssistantV1/Models/CreateDialogNode.swift b/Source/AssistantV1/Models/CreateDialogNode.swift deleted file mode 100644 index de125b060..000000000 --- a/Source/AssistantV1/Models/CreateDialogNode.swift +++ /dev/null @@ -1,271 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation -import RestKit - -/** CreateDialogNode. */ -public struct CreateDialogNode: Codable, Equatable { - - /** - How the dialog node is processed. - */ - public enum NodeType: String { - case standard = "standard" - case eventHandler = "event_handler" - case frame = "frame" - case slot = "slot" - case responseCondition = "response_condition" - case folder = "folder" - } - - /** - How an `event_handler` node is processed. - */ - public enum EventName: String { - case focus = "focus" - case input = "input" - case filled = "filled" - case validate = "validate" - case filledMultiple = "filled_multiple" - case generic = "generic" - case nomatch = "nomatch" - case nomatchResponsesDepleted = "nomatch_responses_depleted" - case digressionReturnPrompt = "digression_return_prompt" - } - - /** - Whether this top-level dialog node can be digressed into. - */ - public enum DigressIn: String { - case notAvailable = "not_available" - case returns = "returns" - case doesNotReturn = "does_not_return" - } - - /** - Whether this dialog node can be returned to after a digression. - */ - public enum DigressOut: String { - case allowReturning = "allow_returning" - case allowAll = "allow_all" - case allowAllNeverReturn = "allow_all_never_return" - } - - /** - Whether the user can digress to top-level nodes while filling out slots. - */ - public enum DigressOutSlots: String { - case notAllowed = "not_allowed" - case allowReturning = "allow_returning" - case allowAll = "allow_all" - } - - /** - The dialog node ID. This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - - It must be no longer than 1024 characters. - */ - public var dialogNode: String - - /** - The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it - must be no longer than 128 characters. - */ - public var description: String? - - /** - The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab - characters, and it must be no longer than 2048 characters. - */ - public var conditions: String? - - /** - The ID of the parent dialog node. - */ - public var parent: String? - - /** - The ID of the previous dialog node. - */ - public var previousSibling: String? - - /** - The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). - */ - public var output: DialogNodeOutput? - - /** - The context for the dialog node. - */ - public var context: [String: JSON]? - - /** - The metadata for the dialog node. - */ - public var metadata: [String: JSON]? - - /** - The next step to execute following this dialog node. - */ - public var nextStep: DialogNodeNextStep? - - /** - An array of objects describing any actions to be invoked by the dialog node. - */ - public var actions: [DialogNodeAction]? - - /** - The alias used to identify the dialog node. This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - - It must be no longer than 64 characters. - */ - public var title: String? - - /** - How the dialog node is processed. - */ - public var nodeType: String? - - /** - How an `event_handler` node is processed. - */ - public var eventName: String? - - /** - The location in the dialog context where output is stored. - */ - public var variable: String? - - /** - Whether this top-level dialog node can be digressed into. - */ - public var digressIn: String? - - /** - Whether this dialog node can be returned to after a digression. - */ - public var digressOut: String? - - /** - Whether the user can digress to top-level nodes while filling out slots. - */ - public var digressOutSlots: String? - - /** - A label that can be displayed externally to describe the purpose of the node to users. This string must be no - longer than 512 characters. - */ - public var userLabel: String? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case dialogNode = "dialog_node" - case description = "description" - case conditions = "conditions" - case parent = "parent" - case previousSibling = "previous_sibling" - case output = "output" - case context = "context" - case metadata = "metadata" - case nextStep = "next_step" - case actions = "actions" - case title = "title" - case nodeType = "type" - case eventName = "event_name" - case variable = "variable" - case digressIn = "digress_in" - case digressOut = "digress_out" - case digressOutSlots = "digress_out_slots" - case userLabel = "user_label" - } - - /** - Initialize a `CreateDialogNode` with member variables. - - - parameter dialogNode: The dialog node ID. This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - - It must be no longer than 1024 characters. - - parameter description: The description of the dialog node. This string cannot contain carriage return, - newline, or tab characters, and it must be no longer than 128 characters. - - parameter conditions: The condition that will trigger the dialog node. This string cannot contain carriage - return, newline, or tab characters, and it must be no longer than 2048 characters. - - parameter parent: The ID of the parent dialog node. - - parameter previousSibling: The ID of the previous dialog node. - - parameter output: The output of the dialog node. For more information about how to specify dialog node output, - see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). - - parameter context: The context for the dialog node. - - parameter metadata: The metadata for the dialog node. - - parameter nextStep: The next step to execute following this dialog node. - - parameter actions: An array of objects describing any actions to be invoked by the dialog node. - - parameter title: The alias used to identify the dialog node. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - - It must be no longer than 64 characters. - - parameter nodeType: How the dialog node is processed. - - parameter eventName: How an `event_handler` node is processed. - - parameter variable: The location in the dialog context where output is stored. - - parameter digressIn: Whether this top-level dialog node can be digressed into. - - parameter digressOut: Whether this dialog node can be returned to after a digression. - - parameter digressOutSlots: Whether the user can digress to top-level nodes while filling out slots. - - parameter userLabel: A label that can be displayed externally to describe the purpose of the node to users. - This string must be no longer than 512 characters. - - - returns: An initialized `CreateDialogNode`. - */ - public init( - dialogNode: String, - description: String? = nil, - conditions: String? = nil, - parent: String? = nil, - previousSibling: String? = nil, - output: DialogNodeOutput? = nil, - context: [String: JSON]? = nil, - metadata: [String: JSON]? = nil, - nextStep: DialogNodeNextStep? = nil, - actions: [DialogNodeAction]? = nil, - title: String? = nil, - nodeType: String? = nil, - eventName: String? = nil, - variable: String? = nil, - digressIn: String? = nil, - digressOut: String? = nil, - digressOutSlots: String? = nil, - userLabel: String? = nil - ) - { - self.dialogNode = dialogNode - self.description = description - self.conditions = conditions - self.parent = parent - self.previousSibling = previousSibling - self.output = output - self.context = context - self.metadata = metadata - self.nextStep = nextStep - self.actions = actions - self.title = title - self.nodeType = nodeType - self.eventName = eventName - self.variable = variable - self.digressIn = digressIn - self.digressOut = digressOut - self.digressOutSlots = digressOutSlots - self.userLabel = userLabel - } - -} diff --git a/Source/AssistantV1/Models/CreateEntity.swift b/Source/AssistantV1/Models/CreateEntity.swift index d376d615e..d3eddd070 100644 --- a/Source/AssistantV1/Models/CreateEntity.swift +++ b/Source/AssistantV1/Models/CreateEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,27 +36,39 @@ public struct CreateEntity: Codable, Equatable { public var description: String? /** - Any metadata related to the value. + Any metadata related to the entity. */ public var metadata: [String: JSON]? /** - An array of objects describing the entity values. + Whether to use fuzzy matching for the entity. */ - public var values: [CreateValue]? + public var fuzzyMatch: Bool? /** - Whether to use fuzzy matching for the entity. + The timestamp for creation of the object. */ - public var fuzzyMatch: Bool? + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + + /** + An array of objects describing the entity values. + */ + public var values: [CreateValue]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case entity = "entity" case description = "description" case metadata = "metadata" - case values = "values" case fuzzyMatch = "fuzzy_match" + case created = "created" + case updated = "updated" + case values = "values" } /** @@ -69,9 +81,11 @@ public struct CreateEntity: Codable, Equatable { that you want to enable. (Any entity content specified with the request is ignored.). - parameter description: The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - - parameter metadata: Any metadata related to the value. - - parameter values: An array of objects describing the entity values. + - parameter metadata: Any metadata related to the entity. - parameter fuzzyMatch: Whether to use fuzzy matching for the entity. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + - parameter values: An array of objects describing the entity values. - returns: An initialized `CreateEntity`. */ @@ -79,15 +93,19 @@ public struct CreateEntity: Codable, Equatable { entity: String, description: String? = nil, metadata: [String: JSON]? = nil, - values: [CreateValue]? = nil, - fuzzyMatch: Bool? = nil + fuzzyMatch: Bool? = nil, + created: Date? = nil, + updated: Date? = nil, + values: [CreateValue]? = nil ) { self.entity = entity self.description = description self.metadata = metadata - self.values = values self.fuzzyMatch = fuzzyMatch + self.created = created + self.updated = updated + self.values = values } } diff --git a/Source/AssistantV1/Models/CreateExample.swift b/Source/AssistantV1/Models/CreateExample.swift deleted file mode 100644 index ff7148c6f..000000000 --- a/Source/AssistantV1/Models/CreateExample.swift +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation - -/** CreateExample. */ -public struct CreateExample: Codable, Equatable { - - /** - The text of a user input example. This string must conform to the following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - - It must be no longer than 1024 characters. - */ - public var text: String - - /** - An array of contextual entity mentions. - */ - public var mentions: [Mentions]? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case text = "text" - case mentions = "mentions" - } - - /** - Initialize a `CreateExample` with member variables. - - - parameter text: The text of a user input example. This string must conform to the following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - - It must be no longer than 1024 characters. - - parameter mentions: An array of contextual entity mentions. - - - returns: An initialized `CreateExample`. - */ - public init( - text: String, - mentions: [Mentions]? = nil - ) - { - self.text = text - self.mentions = mentions - } - -} diff --git a/Source/AssistantV1/Models/CreateIntent.swift b/Source/AssistantV1/Models/CreateIntent.swift index bd34f4269..fe04c227e 100644 --- a/Source/AssistantV1/Models/CreateIntent.swift +++ b/Source/AssistantV1/Models/CreateIntent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,15 +33,27 @@ public struct CreateIntent: Codable, Equatable { */ public var description: String? + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + /** An array of user input examples for the intent. */ - public var examples: [CreateExample]? + public var examples: [Example]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case intent = "intent" case description = "description" + case created = "created" + case updated = "updated" case examples = "examples" } @@ -54,6 +66,8 @@ public struct CreateIntent: Codable, Equatable { - It must be no longer than 128 characters. - parameter description: The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - parameter examples: An array of user input examples for the intent. - returns: An initialized `CreateIntent`. @@ -61,11 +75,15 @@ public struct CreateIntent: Codable, Equatable { public init( intent: String, description: String? = nil, - examples: [CreateExample]? = nil + created: Date? = nil, + updated: Date? = nil, + examples: [Example]? = nil ) { self.intent = intent self.description = description + self.created = created + self.updated = updated self.examples = examples } diff --git a/Source/AssistantV1/Models/CreateSynonym.swift b/Source/AssistantV1/Models/CreateSynonym.swift deleted file mode 100644 index 2928fc9eb..000000000 --- a/Source/AssistantV1/Models/CreateSynonym.swift +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation - -/** CreateSynonym. */ -internal struct CreateSynonym: Codable, Equatable { - - /** - The text of the synonym. This string must conform to the following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - - It must be no longer than 64 characters. - */ - public var synonym: String - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case synonym = "synonym" - } - - /** - Initialize a `CreateSynonym` with member variables. - - - parameter synonym: The text of the synonym. This string must conform to the following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - - It must be no longer than 64 characters. - - - returns: An initialized `CreateSynonym`. - */ - public init( - synonym: String - ) - { - self.synonym = synonym - } - -} diff --git a/Source/AssistantV1/Models/CreateValue.swift b/Source/AssistantV1/Models/CreateValue.swift index 486a2d447..2440c5510 100644 --- a/Source/AssistantV1/Models/CreateValue.swift +++ b/Source/AssistantV1/Models/CreateValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import RestKit public struct CreateValue: Codable, Equatable { /** - Specifies the type of value. + Specifies the type of entity value. */ public enum ValueType: String { case synonyms = "synonyms" @@ -42,8 +42,13 @@ public struct CreateValue: Codable, Equatable { public var metadata: [String: JSON]? /** - An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by - **type**), but not both. A synonym must conform to the following restrictions: + Specifies the type of entity value. + */ + public var valueType: String? + + /** + An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. @@ -51,25 +56,32 @@ public struct CreateValue: Codable, Equatable { public var synonyms: [String]? /** - An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), - but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to - specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). + An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A pattern is a regular expression no longer than 512 characters. For more information about + how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). */ public var patterns: [String]? /** - Specifies the type of value. + The timestamp for creation of the object. */ - public var valueType: String? + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case value = "value" case metadata = "metadata" + case valueType = "type" case synonyms = "synonyms" case patterns = "patterns" - case valueType = "type" + case created = "created" + case updated = "updated" } /** @@ -80,32 +92,38 @@ public struct CreateValue: Codable, Equatable { - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter metadata: Any metadata related to the entity value. - - parameter synonyms: An array containing any synonyms for the entity value. You can provide either synonyms or - patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: + - parameter valueType: Specifies the type of entity value. + - parameter synonyms: An array of synonyms for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - - parameter patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as - indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more - information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). - - parameter valueType: Specifies the type of value. + - parameter patterns: An array of patterns for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A pattern is a regular expression no longer than 512 characters. For + more information about how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `CreateValue`. */ public init( value: String, metadata: [String: JSON]? = nil, + valueType: String? = nil, synonyms: [String]? = nil, patterns: [String]? = nil, - valueType: String? = nil + created: Date? = nil, + updated: Date? = nil ) { self.value = value self.metadata = metadata + self.valueType = valueType self.synonyms = synonyms self.patterns = patterns - self.valueType = valueType + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/CreateWorkspace.swift b/Source/AssistantV1/Models/CreateWorkspace.swift index f2bc56a4d..bfb72195c 100644 --- a/Source/AssistantV1/Models/CreateWorkspace.swift +++ b/Source/AssistantV1/Models/CreateWorkspace.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,17 @@ import RestKit /** CreateWorkspace. */ internal struct CreateWorkspace: Codable, Equatable { + /** + The current status of the workspace. + */ + public enum Status: String { + case nonExistent = "Non Existent" + case training = "Training" + case failed = "Failed" + case available = "Available" + case unavailable = "Unavailable" + } + /** The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. @@ -38,53 +49,77 @@ internal struct CreateWorkspace: Codable, Equatable { public var language: String? /** - An array of objects defining the intents for the workspace. + Any metadata related to the workspace. */ - public var intents: [CreateIntent]? + public var metadata: [String: JSON]? /** - An array of objects defining the entities for the workspace. + Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is not to be used. */ - public var entities: [CreateEntity]? + public var learningOptOut: Bool? /** - An array of objects defining the nodes in the dialog. + Global settings for the workspace. */ - public var dialogNodes: [CreateDialogNode]? + public var systemSettings: WorkspaceSystemSettings? /** - An array of objects defining input examples that have been marked as irrelevant input. + The workspace ID of the workspace. */ - public var counterexamples: [CreateCounterexample]? + public var workspaceID: String? /** - Any metadata related to the workspace. + The current status of the workspace. */ - public var metadata: [String: JSON]? + public var status: String? /** - Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that - workspace training data is not to be used. + The timestamp for creation of the object. */ - public var learningOptOut: Bool? + public var created: Date? /** - Global settings for the workspace. + The timestamp for the most recent update to the object. */ - public var systemSettings: WorkspaceSystemSettings? + public var updated: Date? + + /** + An array of objects defining the intents for the workspace. + */ + public var intents: [CreateIntent]? + + /** + An array of objects describing the entities for the workspace. + */ + public var entities: [CreateEntity]? + + /** + An array of objects describing the dialog nodes in the workspace. + */ + public var dialogNodes: [DialogNode]? + + /** + An array of objects defining input examples that have been marked as irrelevant input. + */ + public var counterexamples: [Counterexample]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case description = "description" case language = "language" + case metadata = "metadata" + case learningOptOut = "learning_opt_out" + case systemSettings = "system_settings" + case workspaceID = "workspace_id" + case status = "status" + case created = "created" + case updated = "updated" case intents = "intents" case entities = "entities" case dialogNodes = "dialog_nodes" case counterexamples = "counterexamples" - case metadata = "metadata" - case learningOptOut = "learning_opt_out" - case systemSettings = "system_settings" } /** @@ -95,15 +130,20 @@ internal struct CreateWorkspace: Codable, Equatable { - parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter language: The language of the workspace. + - parameter metadata: Any metadata related to the workspace. + - parameter learningOptOut: Whether training data from the workspace (including artifacts such as intents and + entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is + not to be used. + - parameter systemSettings: Global settings for the workspace. + - parameter workspaceID: The workspace ID of the workspace. + - parameter status: The current status of the workspace. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - parameter intents: An array of objects defining the intents for the workspace. - - parameter entities: An array of objects defining the entities for the workspace. - - parameter dialogNodes: An array of objects defining the nodes in the dialog. + - parameter entities: An array of objects describing the entities for the workspace. + - parameter dialogNodes: An array of objects describing the dialog nodes in the workspace. - parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input. - - parameter metadata: Any metadata related to the workspace. - - parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - - parameter systemSettings: Global settings for the workspace. - returns: An initialized `CreateWorkspace`. */ @@ -111,25 +151,33 @@ internal struct CreateWorkspace: Codable, Equatable { name: String? = nil, description: String? = nil, language: String? = nil, - intents: [CreateIntent]? = nil, - entities: [CreateEntity]? = nil, - dialogNodes: [CreateDialogNode]? = nil, - counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil, - systemSettings: WorkspaceSystemSettings? = nil + systemSettings: WorkspaceSystemSettings? = nil, + workspaceID: String? = nil, + status: String? = nil, + created: Date? = nil, + updated: Date? = nil, + intents: [CreateIntent]? = nil, + entities: [CreateEntity]? = nil, + dialogNodes: [DialogNode]? = nil, + counterexamples: [Counterexample]? = nil ) { self.name = name self.description = description self.language = language + self.metadata = metadata + self.learningOptOut = learningOptOut + self.systemSettings = systemSettings + self.workspaceID = workspaceID + self.status = status + self.created = created + self.updated = updated self.intents = intents self.entities = entities self.dialogNodes = dialogNodes self.counterexamples = counterexamples - self.metadata = metadata - self.learningOptOut = learningOptOut - self.systemSettings = systemSettings } } diff --git a/Source/AssistantV1/Models/DialogNode.swift b/Source/AssistantV1/Models/DialogNode.swift index 3a15b9497..429cdca6c 100644 --- a/Source/AssistantV1/Models/DialogNode.swift +++ b/Source/AssistantV1/Models/DialogNode.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,44 +75,47 @@ public struct DialogNode: Codable, Equatable { } /** - The dialog node ID. + The dialog node ID. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. + - It must be no longer than 1024 characters. */ - public var dialogNodeID: String + public var dialogNode: String /** - The description of the dialog node. + The description of the dialog node. This string cannot contain carriage return, newline, or tab characters, and it + must be no longer than 128 characters. */ public var description: String? /** - The condition that triggers the dialog node. + The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab + characters, and it must be no longer than 2048 characters. */ public var conditions: String? /** - The ID of the parent dialog node. This property is not returned if the dialog node has no parent. + The ID of the parent dialog node. This property is omitted if the dialog node has no parent. */ public var parent: String? /** - The ID of the previous sibling dialog node. This property is not returned if the dialog node has no previous - sibling. + The ID of the previous sibling dialog node. This property is omitted if the dialog node has no previous sibling. */ public var previousSibling: String? /** The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). */ public var output: DialogNodeOutput? /** - The context (if defined) for the dialog node. + The context for the dialog node. */ public var context: [String: JSON]? /** - Any metadata for the dialog node. + The metadata for the dialog node. */ public var metadata: [String: JSON]? @@ -122,30 +125,12 @@ public struct DialogNode: Codable, Equatable { public var nextStep: DialogNodeNextStep? /** - The timestamp for creation of the dialog node. - */ - public var created: Date? - - /** - The timestamp for the most recent update to the dialog node. - */ - public var updated: Date? - - /** - The actions for the dialog node. - */ - public var actions: [DialogNodeAction]? - - /** - The alias used to identify the dialog node. + The alias used to identify the dialog node. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. + - It must be no longer than 64 characters. */ public var title: String? - /** - For internal use only. - */ - public var disabled: Bool? - /** How the dialog node is processed. */ @@ -161,6 +146,11 @@ public struct DialogNode: Codable, Equatable { */ public var variable: String? + /** + An array of objects describing any actions to be invoked by the dialog node. + */ + public var actions: [DialogNodeAction]? + /** Whether this top-level dialog node can be digressed into. */ @@ -182,9 +172,24 @@ public struct DialogNode: Codable, Equatable { */ public var userLabel: String? + /** + For internal use only. + */ + public var disabled: Bool? + + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case dialogNodeID = "dialog_node" + case dialogNode = "dialog_node" case description = "description" case conditions = "conditions" case parent = "parent" @@ -193,18 +198,103 @@ public struct DialogNode: Codable, Equatable { case context = "context" case metadata = "metadata" case nextStep = "next_step" - case created = "created" - case updated = "updated" - case actions = "actions" case title = "title" - case disabled = "disabled" case nodeType = "type" case eventName = "event_name" case variable = "variable" + case actions = "actions" case digressIn = "digress_in" case digressOut = "digress_out" case digressOutSlots = "digress_out_slots" case userLabel = "user_label" + case disabled = "disabled" + case created = "created" + case updated = "updated" + } + + /** + Initialize a `DialogNode` with member variables. + + - parameter dialogNode: The dialog node ID. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. + - It must be no longer than 1024 characters. + - parameter description: The description of the dialog node. This string cannot contain carriage return, + newline, or tab characters, and it must be no longer than 128 characters. + - parameter conditions: The condition that will trigger the dialog node. This string cannot contain carriage + return, newline, or tab characters, and it must be no longer than 2048 characters. + - parameter parent: The ID of the parent dialog node. This property is omitted if the dialog node has no parent. + - parameter previousSibling: The ID of the previous sibling dialog node. This property is omitted if the dialog + node has no previous sibling. + - parameter output: The output of the dialog node. For more information about how to specify dialog node output, + see the + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). + - parameter context: The context for the dialog node. + - parameter metadata: The metadata for the dialog node. + - parameter nextStep: The next step to execute following this dialog node. + - parameter title: The alias used to identify the dialog node. This string must conform to the following + restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. + - It must be no longer than 64 characters. + - parameter nodeType: How the dialog node is processed. + - parameter eventName: How an `event_handler` node is processed. + - parameter variable: The location in the dialog context where output is stored. + - parameter actions: An array of objects describing any actions to be invoked by the dialog node. + - parameter digressIn: Whether this top-level dialog node can be digressed into. + - parameter digressOut: Whether this dialog node can be returned to after a digression. + - parameter digressOutSlots: Whether the user can digress to top-level nodes while filling out slots. + - parameter userLabel: A label that can be displayed externally to describe the purpose of the node to users. + This string must be no longer than 512 characters. + - parameter disabled: For internal use only. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + + - returns: An initialized `DialogNode`. + */ + public init( + dialogNode: String, + description: String? = nil, + conditions: String? = nil, + parent: String? = nil, + previousSibling: String? = nil, + output: DialogNodeOutput? = nil, + context: [String: JSON]? = nil, + metadata: [String: JSON]? = nil, + nextStep: DialogNodeNextStep? = nil, + title: String? = nil, + nodeType: String? = nil, + eventName: String? = nil, + variable: String? = nil, + actions: [DialogNodeAction]? = nil, + digressIn: String? = nil, + digressOut: String? = nil, + digressOutSlots: String? = nil, + userLabel: String? = nil, + disabled: Bool? = nil, + created: Date? = nil, + updated: Date? = nil + ) + { + self.dialogNode = dialogNode + self.description = description + self.conditions = conditions + self.parent = parent + self.previousSibling = previousSibling + self.output = output + self.context = context + self.metadata = metadata + self.nextStep = nextStep + self.title = title + self.nodeType = nodeType + self.eventName = eventName + self.variable = variable + self.actions = actions + self.digressIn = digressIn + self.digressOut = digressOut + self.digressOutSlots = digressOutSlots + self.userLabel = userLabel + self.disabled = disabled + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/DialogNodeAction.swift b/Source/AssistantV1/Models/DialogNodeAction.swift index 034cf1265..dfcfcb84b 100644 --- a/Source/AssistantV1/Models/DialogNodeAction.swift +++ b/Source/AssistantV1/Models/DialogNodeAction.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeCollection.swift b/Source/AssistantV1/Models/DialogNodeCollection.swift index 946778efc..1a8e1a31f 100644 --- a/Source/AssistantV1/Models/DialogNodeCollection.swift +++ b/Source/AssistantV1/Models/DialogNodeCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeNextStep.swift b/Source/AssistantV1/Models/DialogNodeNextStep.swift index 0519cc224..2e5c8b6d8 100644 --- a/Source/AssistantV1/Models/DialogNodeNextStep.swift +++ b/Source/AssistantV1/Models/DialogNodeNextStep.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeOutput.swift b/Source/AssistantV1/Models/DialogNodeOutput.swift index 5f8dfa5ff..70983f313 100644 --- a/Source/AssistantV1/Models/DialogNodeOutput.swift +++ b/Source/AssistantV1/Models/DialogNodeOutput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import RestKit /** The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). */ public struct DialogNodeOutput: Codable, Equatable { diff --git a/Source/AssistantV1/Models/DialogNodeOutputGeneric.swift b/Source/AssistantV1/Models/DialogNodeOutputGeneric.swift index 46b4c6bab..7b9c99dd5 100644 --- a/Source/AssistantV1/Models/DialogNodeOutputGeneric.swift +++ b/Source/AssistantV1/Models/DialogNodeOutputGeneric.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeOutputModifiers.swift b/Source/AssistantV1/Models/DialogNodeOutputModifiers.swift index 94c43a70a..2c40c4e21 100644 --- a/Source/AssistantV1/Models/DialogNodeOutputModifiers.swift +++ b/Source/AssistantV1/Models/DialogNodeOutputModifiers.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeOutputOptionsElement.swift b/Source/AssistantV1/Models/DialogNodeOutputOptionsElement.swift index bcd06194b..bafc085dc 100644 --- a/Source/AssistantV1/Models/DialogNodeOutputOptionsElement.swift +++ b/Source/AssistantV1/Models/DialogNodeOutputOptionsElement.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogNodeOutputOptionsElementValue.swift b/Source/AssistantV1/Models/DialogNodeOutputOptionsElementValue.swift index 95305cc10..02a065f2a 100644 --- a/Source/AssistantV1/Models/DialogNodeOutputOptionsElementValue.swift +++ b/Source/AssistantV1/Models/DialogNodeOutputOptionsElementValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ public struct DialogNodeOutputOptionsElementValue: Codable, Equatable { /** An input object that includes the input text. */ - public var input: InputData? + public var input: MessageInput? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { @@ -40,7 +40,7 @@ public struct DialogNodeOutputOptionsElementValue: Codable, Equatable { - returns: An initialized `DialogNodeOutputOptionsElementValue`. */ public init( - input: InputData? = nil + input: MessageInput? = nil ) { self.input = input diff --git a/Source/AssistantV1/Models/DialogNodeOutputTextValuesElement.swift b/Source/AssistantV1/Models/DialogNodeOutputTextValuesElement.swift index e5cca9903..c3d6a8b73 100644 --- a/Source/AssistantV1/Models/DialogNodeOutputTextValuesElement.swift +++ b/Source/AssistantV1/Models/DialogNodeOutputTextValuesElement.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,8 @@ import Foundation public struct DialogNodeOutputTextValuesElement: Codable, Equatable { /** - The text of a response. This string can include newline characters (` - `), Markdown tagging, or other special characters, if supported by the channel. It must be no longer than 4096 - characters. + The text of a response. This string can include newline characters (`\\n`), Markdown tagging, or other special + characters, if supported by the channel. It must be no longer than 4096 characters. */ public var text: String? @@ -34,15 +33,14 @@ public struct DialogNodeOutputTextValuesElement: Codable, Equatable { /** Initialize a `DialogNodeOutputTextValuesElement` with member variables. - - parameter text: The text of a response. This string can include newline characters (` - `), Markdown tagging, or other special characters, if supported by the channel. It must be no longer than 4096 - characters. + - parameter text: The text of a response. This string can include newline characters (`\\n`), Markdown tagging, + or other special characters, if supported by the channel. It must be no longer than 4096 characters. - returns: An initialized `DialogNodeOutputTextValuesElement`. */ public init( - text: String? = nil - ) + text: String? = nil + ) { self.text = text } diff --git a/Source/AssistantV1/Models/DialogNodeVisitedDetails.swift b/Source/AssistantV1/Models/DialogNodeVisitedDetails.swift index 4d2f62ccf..de07332d0 100644 --- a/Source/AssistantV1/Models/DialogNodeVisitedDetails.swift +++ b/Source/AssistantV1/Models/DialogNodeVisitedDetails.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/DialogRuntimeResponseGeneric.swift b/Source/AssistantV1/Models/DialogRuntimeResponseGeneric.swift index 1ac950405..b9ab7f6ba 100644 --- a/Source/AssistantV1/Models/DialogRuntimeResponseGeneric.swift +++ b/Source/AssistantV1/Models/DialogRuntimeResponseGeneric.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -100,6 +100,12 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { */ public var topic: String? + /** + The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the + value of the dialog node's **user_label** property. + */ + public var dialogNode: String? + /** An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium @@ -120,6 +126,7 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { case options = "options" case messageToHumanAgent = "message_to_human_agent" case topic = "topic" + case dialogNode = "dialog_node" case suggestions = "suggestions" } @@ -142,6 +149,8 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { conversation. - parameter topic: A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. + - parameter dialogNode: The ID of the dialog node that the **topic** property is taken from. The **topic** + property is populated using the value of the dialog node's **user_label** property. - parameter suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium @@ -161,6 +170,7 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { options: [DialogNodeOutputOptionsElement]? = nil, messageToHumanAgent: String? = nil, topic: String? = nil, + dialogNode: String? = nil, suggestions: [DialogSuggestion]? = nil ) { @@ -175,6 +185,7 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { self.options = options self.messageToHumanAgent = messageToHumanAgent self.topic = topic + self.dialogNode = dialogNode self.suggestions = suggestions } diff --git a/Source/AssistantV1/Models/DialogSuggestion.swift b/Source/AssistantV1/Models/DialogSuggestion.swift index 26e014f79..0c0ee6b86 100644 --- a/Source/AssistantV1/Models/DialogSuggestion.swift +++ b/Source/AssistantV1/Models/DialogSuggestion.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,11 +38,18 @@ public struct DialogSuggestion: Codable, Equatable { */ public var output: [String: JSON]? + /** + The ID of the dialog node that the **label** property is taken from. The **label** property is populated using the + value of the dialog node's **user_label** property. + */ + public var dialogNode: String? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case label = "label" case value = "value" case output = "output" + case dialogNode = "dialog_node" } /** @@ -54,18 +61,22 @@ public struct DialogSuggestion: Codable, Equatable { Assistant service if the user selects the corresponding disambiguation option. - parameter output: The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. + - parameter dialogNode: The ID of the dialog node that the **label** property is taken from. The **label** + property is populated using the value of the dialog node's **user_label** property. - returns: An initialized `DialogSuggestion`. */ public init( label: String, value: DialogSuggestionValue, - output: [String: JSON]? = nil + output: [String: JSON]? = nil, + dialogNode: String? = nil ) { self.label = label self.value = value self.output = output + self.dialogNode = dialogNode } } diff --git a/Source/AssistantV1/Models/DialogSuggestionValue.swift b/Source/AssistantV1/Models/DialogSuggestionValue.swift index 11b245061..f1b0ff388 100644 --- a/Source/AssistantV1/Models/DialogSuggestionValue.swift +++ b/Source/AssistantV1/Models/DialogSuggestionValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ public struct DialogSuggestionValue: Codable, Equatable { /** An input object that includes the input text. */ - public var input: InputData? + public var input: MessageInput? /** An array of intents to be sent along with the user input. @@ -54,7 +54,7 @@ public struct DialogSuggestionValue: Codable, Equatable { - returns: An initialized `DialogSuggestionValue`. */ public init( - input: InputData? = nil, + input: MessageInput? = nil, intents: [RuntimeIntent]? = nil, entities: [RuntimeEntity]? = nil ) diff --git a/Source/AssistantV1/Models/Entity.swift b/Source/AssistantV1/Models/Entity.swift index 96a8d368a..b820b9688 100644 --- a/Source/AssistantV1/Models/Entity.swift +++ b/Source/AssistantV1/Models/Entity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,43 +21,54 @@ import RestKit public struct Entity: Codable, Equatable { /** - The name of the entity. + The name of the entity. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen characters. + - It must be no longer than 64 characters. + If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity + that you want to enable. (Any entity content specified with the request is ignored.). */ - public var entityName: String + public var entity: String /** - The timestamp for creation of the entity. + The description of the entity. This string cannot contain carriage return, newline, or tab characters, and it must + be no longer than 128 characters. */ - public var created: Date? + public var description: String? /** - The timestamp for the last update to the entity. + Any metadata related to the entity. */ - public var updated: Date? + public var metadata: [String: JSON]? /** - The description of the entity. + Whether to use fuzzy matching for the entity. */ - public var description: String? + public var fuzzyMatch: Bool? /** - Any metadata related to the entity. + The timestamp for creation of the object. */ - public var metadata: [String: JSON]? + public var created: Date? /** - Whether fuzzy matching is used for the entity. + The timestamp for the most recent update to the object. */ - public var fuzzyMatch: Bool? + public var updated: Date? + + /** + An array of objects describing the entity values. + */ + public var values: [Value]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case entityName = "entity" - case created = "created" - case updated = "updated" + case entity = "entity" case description = "description" case metadata = "metadata" case fuzzyMatch = "fuzzy_match" + case created = "created" + case updated = "updated" + case values = "values" } } diff --git a/Source/AssistantV1/Models/EntityCollection.swift b/Source/AssistantV1/Models/EntityCollection.swift index 8c2b2804a..abe4d89ea 100644 --- a/Source/AssistantV1/Models/EntityCollection.swift +++ b/Source/AssistantV1/Models/EntityCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,14 +17,14 @@ import Foundation /** - An array of entities. + An array of objects describing the entities for the workspace. */ public struct EntityCollection: Codable, Equatable { /** An array of objects describing the entities defined for the workspace. */ - public var entities: [EntityExport] + public var entities: [Entity] /** The pagination data for the returned objects. diff --git a/Source/AssistantV1/Models/EntityExport.swift b/Source/AssistantV1/Models/EntityExport.swift deleted file mode 100644 index a323d87b1..000000000 --- a/Source/AssistantV1/Models/EntityExport.swift +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation -import RestKit - -/** EntityExport. */ -public struct EntityExport: Codable, Equatable { - - /** - The name of the entity. - */ - public var entityName: String - - /** - The timestamp for creation of the entity. - */ - public var created: Date? - - /** - The timestamp for the last update to the entity. - */ - public var updated: Date? - - /** - The description of the entity. - */ - public var description: String? - - /** - Any metadata related to the entity. - */ - public var metadata: [String: JSON]? - - /** - Whether fuzzy matching is used for the entity. - */ - public var fuzzyMatch: Bool? - - /** - An array objects describing the entity values. - */ - public var values: [ValueExport]? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case entityName = "entity" - case created = "created" - case updated = "updated" - case description = "description" - case metadata = "metadata" - case fuzzyMatch = "fuzzy_match" - case values = "values" - } - -} diff --git a/Source/AssistantV1/Models/EntityMention.swift b/Source/AssistantV1/Models/EntityMention.swift index d526c34cf..50affddf6 100644 --- a/Source/AssistantV1/Models/EntityMention.swift +++ b/Source/AssistantV1/Models/EntityMention.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ public struct EntityMention: Codable, Equatable { /** The text of the user input example. */ - public var exampleText: String + public var text: String /** The name of the intent. */ - public var intentName: String + public var intent: String /** An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. @@ -38,8 +38,8 @@ public struct EntityMention: Codable, Equatable { // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case exampleText = "text" - case intentName = "intent" + case text = "text" + case intent = "intent" case location = "location" } diff --git a/Source/AssistantV1/Models/EntityMentionCollection.swift b/Source/AssistantV1/Models/EntityMentionCollection.swift index 4d416cf0d..da5844102 100644 --- a/Source/AssistantV1/Models/EntityMentionCollection.swift +++ b/Source/AssistantV1/Models/EntityMentionCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/Example.swift b/Source/AssistantV1/Models/Example.swift index d77a7a00d..a55fccfdd 100644 --- a/Source/AssistantV1/Models/Example.swift +++ b/Source/AssistantV1/Models/Example.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,31 +20,60 @@ import Foundation public struct Example: Codable, Equatable { /** - The text of the user input example. + The text of a user input example. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 1024 characters. */ - public var exampleText: String + public var text: String /** - The timestamp for creation of the example. + An array of contextual entity mentions. */ - public var created: Date? + public var mentions: [Mention]? /** - The timestamp for the last update to the example. + The timestamp for creation of the object. */ - public var updated: Date? + public var created: Date? /** - An array of contextual entity mentions. + The timestamp for the most recent update to the object. */ - public var mentions: [Mentions]? + public var updated: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case exampleText = "text" + case text = "text" + case mentions = "mentions" case created = "created" case updated = "updated" - case mentions = "mentions" + } + + /** + Initialize a `Example` with member variables. + + - parameter text: The text of a user input example. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 1024 characters. + - parameter mentions: An array of contextual entity mentions. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + + - returns: An initialized `Example`. + */ + public init( + text: String, + mentions: [Mention]? = nil, + created: Date? = nil, + updated: Date? = nil + ) + { + self.text = text + self.mentions = mentions + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/ExampleCollection.swift b/Source/AssistantV1/Models/ExampleCollection.swift index 0e4261232..8cdf14d40 100644 --- a/Source/AssistantV1/Models/ExampleCollection.swift +++ b/Source/AssistantV1/Models/ExampleCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/InputData.swift b/Source/AssistantV1/Models/InputData.swift deleted file mode 100644 index 497231cec..000000000 --- a/Source/AssistantV1/Models/InputData.swift +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation -import RestKit - -/** - An input object that includes the input text. - */ -public struct InputData: Codable, Equatable { - - /** - The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be - no longer than 2048 characters. - */ - public var text: String - - /// Additional properties associated with this model. - public var additionalProperties: [String: JSON] - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case text = "text" - static let allValues = [text] - } - - /** - Initialize a `InputData` with member variables. - - - parameter text: The text of the user input. This string cannot contain carriage return, newline, or tab - characters, and it must be no longer than 2048 characters. - - - returns: An initialized `InputData`. - */ - public init( - text: String, - additionalProperties: [String: JSON] = [:] - ) - { - self.text = text - self.additionalProperties = additionalProperties - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - text = try container.decode(String.self, forKey: .text) - let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self) - additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues) - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(text, forKey: .text) - var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self) - try dynamicContainer.encodeIfPresent(additionalProperties) - } - -} diff --git a/Source/AssistantV1/Models/Intent.swift b/Source/AssistantV1/Models/Intent.swift index 0ea66bcee..1d8a90737 100644 --- a/Source/AssistantV1/Models/Intent.swift +++ b/Source/AssistantV1/Models/Intent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,31 +20,41 @@ import Foundation public struct Intent: Codable, Equatable { /** - The name of the intent. + The name of the intent. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. + - It cannot begin with the reserved prefix `sys-`. + - It must be no longer than 128 characters. */ - public var intentName: String + public var intent: String /** - The timestamp for creation of the intent. + The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must + be no longer than 128 characters. + */ + public var description: String? + + /** + The timestamp for creation of the object. */ public var created: Date? /** - The timestamp for the last update to the intent. + The timestamp for the most recent update to the object. */ public var updated: Date? /** - The description of the intent. + An array of user input examples for the intent. */ - public var description: String? + public var examples: [Example]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case intentName = "intent" + case intent = "intent" + case description = "description" case created = "created" case updated = "updated" - case description = "description" + case examples = "examples" } } diff --git a/Source/AssistantV1/Models/IntentCollection.swift b/Source/AssistantV1/Models/IntentCollection.swift index 430667868..75550fae4 100644 --- a/Source/AssistantV1/Models/IntentCollection.swift +++ b/Source/AssistantV1/Models/IntentCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ public struct IntentCollection: Codable, Equatable { /** An array of objects describing the intents defined for the workspace. */ - public var intents: [IntentExport] + public var intents: [Intent] /** The pagination data for the returned objects. diff --git a/Source/AssistantV1/Models/LogExport.swift b/Source/AssistantV1/Models/Log.swift similarity index 95% rename from Source/AssistantV1/Models/LogExport.swift rename to Source/AssistantV1/Models/Log.swift index bdc555553..1942de836 100644 --- a/Source/AssistantV1/Models/LogExport.swift +++ b/Source/AssistantV1/Models/Log.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ import Foundation -/** LogExport. */ -public struct LogExport: Codable, Equatable { +/** Log. */ +public struct Log: Codable, Equatable { /** A request sent to the workspace, including the user input and context. diff --git a/Source/AssistantV1/Models/LogCollection.swift b/Source/AssistantV1/Models/LogCollection.swift index 43d2065f6..82336dcd6 100644 --- a/Source/AssistantV1/Models/LogCollection.swift +++ b/Source/AssistantV1/Models/LogCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ public struct LogCollection: Codable, Equatable { /** An array of objects describing log events. */ - public var logs: [LogExport] + public var logs: [Log] /** The pagination data for the returned objects. diff --git a/Source/AssistantV1/Models/LogMessage.swift b/Source/AssistantV1/Models/LogMessage.swift index fb24571d4..543b9a02c 100644 --- a/Source/AssistantV1/Models/LogMessage.swift +++ b/Source/AssistantV1/Models/LogMessage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/LogPagination.swift b/Source/AssistantV1/Models/LogPagination.swift index a8f1e6c82..0eb01414e 100644 --- a/Source/AssistantV1/Models/LogPagination.swift +++ b/Source/AssistantV1/Models/LogPagination.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/Mentions.swift b/Source/AssistantV1/Models/Mention.swift similarity index 89% rename from Source/AssistantV1/Models/Mentions.swift rename to Source/AssistantV1/Models/Mention.swift index be079baa4..cdbe4fa91 100644 --- a/Source/AssistantV1/Models/Mentions.swift +++ b/Source/AssistantV1/Models/Mention.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import Foundation /** A mention of a contextual entity. */ -public struct Mentions: Codable, Equatable { +public struct Mention: Codable, Equatable { /** The name of the entity. @@ -38,13 +38,13 @@ public struct Mentions: Codable, Equatable { } /** - Initialize a `Mentions` with member variables. + Initialize a `Mention` with member variables. - parameter entity: The name of the entity. - parameter location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. - - returns: An initialized `Mentions`. + - returns: An initialized `Mention`. */ public init( entity: String, diff --git a/Source/AssistantV1/Models/MessageContextMetadata.swift b/Source/AssistantV1/Models/MessageContextMetadata.swift index 3cb6becb6..f5ca6da2c 100644 --- a/Source/AssistantV1/Models/MessageContextMetadata.swift +++ b/Source/AssistantV1/Models/MessageContextMetadata.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/MessageInput.swift b/Source/AssistantV1/Models/MessageInput.swift index 3626ce458..7b5a4f5db 100644 --- a/Source/AssistantV1/Models/MessageInput.swift +++ b/Source/AssistantV1/Models/MessageInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,57 @@ **/ import Foundation +import RestKit /** - The text of the user input. + An input object that includes the input text. */ public struct MessageInput: Codable, Equatable { /** - The user's input. + The text of the user input. This string cannot contain carriage return, newline, or tab characters, and it must be + no longer than 2048 characters. */ public var text: String? + /// Additional properties associated with this model. + public var additionalProperties: [String: JSON] + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" + static let allValues = [text] + } + + /** + Initialize a `MessageInput` with member variables. + + - parameter text: The text of the user input. This string cannot contain carriage return, newline, or tab + characters, and it must be no longer than 2048 characters. + + - returns: An initialized `MessageInput`. + */ + public init( + text: String? = nil, + additionalProperties: [String: JSON] = [:] + ) + { + self.text = text + self.additionalProperties = additionalProperties + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + text = try container.decodeIfPresent(String.self, forKey: .text) + let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self) + additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(text, forKey: .text) + var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self) + try dynamicContainer.encodeIfPresent(additionalProperties) } } diff --git a/Source/AssistantV1/Models/MessageRequest.swift b/Source/AssistantV1/Models/MessageRequest.swift index 14732d2d2..c6235868e 100644 --- a/Source/AssistantV1/Models/MessageRequest.swift +++ b/Source/AssistantV1/Models/MessageRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,17 +24,13 @@ public struct MessageRequest: Codable, Equatable { /** An input object that includes the input text. */ - public var input: InputData? + public var input: MessageInput? /** - Whether to return more than one intent. Set to `true` to return all matching intents. - */ - public var alternateIntents: Bool? - - /** - State information for the conversation. To maintain state, include the context from the previous response. + Intents to use when evaluating the user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. */ - public var context: Context? + public var intents: [RuntimeIntent]? /** Entities to use when evaluating the message. Include entities from the previous response to continue using those @@ -43,10 +39,14 @@ public struct MessageRequest: Codable, Equatable { public var entities: [RuntimeEntity]? /** - Intents to use when evaluating the user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. + Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. */ - public var intents: [RuntimeIntent]? + public var alternateIntents: Bool? + + /** + State information for the conversation. To maintain state, include the context from the previous response. + */ + public var context: Context? /** An output object that includes the response to the user, the dialog nodes that were triggered, and messages from @@ -54,48 +54,57 @@ public struct MessageRequest: Codable, Equatable { */ public var output: OutputData? + /** + An array of objects describing any actions requested by the dialog node. + */ + public var actions: [DialogNodeAction]? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case input = "input" + case intents = "intents" + case entities = "entities" case alternateIntents = "alternate_intents" case context = "context" - case entities = "entities" - case intents = "intents" case output = "output" + case actions = "actions" } /** Initialize a `MessageRequest` with member variables. - parameter input: An input object that includes the input text. - - parameter alternateIntents: Whether to return more than one intent. Set to `true` to return all matching - intents. - - parameter context: State information for the conversation. To maintain state, include the context from the - previous response. - - parameter entities: Entities to use when evaluating the message. Include entities from the previous response - to continue using those entities rather than detecting entities in the new input. - parameter intents: Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. + - parameter entities: Entities to use when evaluating the message. Include entities from the previous response + to continue using those entities rather than detecting entities in the new input. + - parameter alternateIntents: Whether to return more than one intent. A value of `true` indicates that all + matching intents are returned. + - parameter context: State information for the conversation. To maintain state, include the context from the + previous response. - parameter output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. + - parameter actions: An array of objects describing any actions requested by the dialog node. - returns: An initialized `MessageRequest`. */ public init( - input: InputData? = nil, + input: MessageInput? = nil, + intents: [RuntimeIntent]? = nil, + entities: [RuntimeEntity]? = nil, alternateIntents: Bool? = nil, context: Context? = nil, - entities: [RuntimeEntity]? = nil, - intents: [RuntimeIntent]? = nil, - output: OutputData? = nil + output: OutputData? = nil, + actions: [DialogNodeAction]? = nil ) { self.input = input + self.intents = intents + self.entities = entities self.alternateIntents = alternateIntents self.context = context - self.entities = entities - self.intents = intents self.output = output + self.actions = actions } } diff --git a/Source/AssistantV1/Models/MessageResponse.swift b/Source/AssistantV1/Models/MessageResponse.swift index ce9a8fc2f..db32ad1b4 100644 --- a/Source/AssistantV1/Models/MessageResponse.swift +++ b/Source/AssistantV1/Models/MessageResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import Foundation public struct MessageResponse: Codable, Equatable { /** - The text of the user input. + An input object that includes the input text. */ - public var input: MessageInput? + public var input: MessageInput /** An array of intents recognized in the user input, sorted in descending order of confidence. diff --git a/Source/AssistantV1/Models/OutputData.swift b/Source/AssistantV1/Models/OutputData.swift index 953c49bb5..8619c7081 100644 --- a/Source/AssistantV1/Models/OutputData.swift +++ b/Source/AssistantV1/Models/OutputData.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/Pagination.swift b/Source/AssistantV1/Models/Pagination.swift index ee7f022eb..7593feeae 100644 --- a/Source/AssistantV1/Models/Pagination.swift +++ b/Source/AssistantV1/Models/Pagination.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/RuntimeEntity.swift b/Source/AssistantV1/Models/RuntimeEntity.swift index 19f9fa11f..da8b2626e 100644 --- a/Source/AssistantV1/Models/RuntimeEntity.swift +++ b/Source/AssistantV1/Models/RuntimeEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/RuntimeIntent.swift b/Source/AssistantV1/Models/RuntimeIntent.swift index 93c9fde9c..86acc46c7 100644 --- a/Source/AssistantV1/Models/RuntimeIntent.swift +++ b/Source/AssistantV1/Models/RuntimeIntent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/Synonym.swift b/Source/AssistantV1/Models/Synonym.swift index 365de0a94..e23cabfba 100644 --- a/Source/AssistantV1/Models/Synonym.swift +++ b/Source/AssistantV1/Models/Synonym.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,25 +20,51 @@ import Foundation public struct Synonym: Codable, Equatable { /** - The text of the synonym. + The text of the synonym. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 64 characters. */ - public var synonymText: String + public var synonym: String /** - The timestamp for creation of the synonym. + The timestamp for creation of the object. */ public var created: Date? /** - The timestamp for the most recent update to the synonym. + The timestamp for the most recent update to the object. */ public var updated: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case synonymText = "synonym" + case synonym = "synonym" case created = "created" case updated = "updated" } + /** + Initialize a `Synonym` with member variables. + + - parameter synonym: The text of the synonym. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 64 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + + - returns: An initialized `Synonym`. + */ + public init( + synonym: String, + created: Date? = nil, + updated: Date? = nil + ) + { + self.synonym = synonym + self.created = created + self.updated = updated + } + } diff --git a/Source/AssistantV1/Models/SynonymCollection.swift b/Source/AssistantV1/Models/SynonymCollection.swift index 9b7e18c61..fa05485bf 100644 --- a/Source/AssistantV1/Models/SynonymCollection.swift +++ b/Source/AssistantV1/Models/SynonymCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/SystemResponse.swift b/Source/AssistantV1/Models/SystemResponse.swift index 239459b7d..1fd8907cc 100644 --- a/Source/AssistantV1/Models/SystemResponse.swift +++ b/Source/AssistantV1/Models/SystemResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/UpdateCounterexample.swift b/Source/AssistantV1/Models/UpdateCounterexample.swift index 8430dda8f..85f6beb10 100644 --- a/Source/AssistantV1/Models/UpdateCounterexample.swift +++ b/Source/AssistantV1/Models/UpdateCounterexample.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,27 +20,52 @@ import Foundation internal struct UpdateCounterexample: Codable, Equatable { /** - The text of a user input counterexample. + The text of a user input marked as irrelevant input. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters + - It cannot consist of only whitespace characters + - It must be no longer than 1024 characters. */ public var text: String? + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" + case created = "created" + case updated = "updated" } /** Initialize a `UpdateCounterexample` with member variables. - - parameter text: The text of a user input counterexample. + - parameter text: The text of a user input marked as irrelevant input. This string must conform to the following + restrictions: + - It cannot contain carriage return, newline, or tab characters + - It cannot consist of only whitespace characters + - It must be no longer than 1024 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `UpdateCounterexample`. */ public init( - text: String? = nil + text: String? = nil, + created: Date? = nil, + updated: Date? = nil ) { self.text = text + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/UpdateDialogNode.swift b/Source/AssistantV1/Models/UpdateDialogNode.swift index c6d3c2528..c2d3fd2d6 100644 --- a/Source/AssistantV1/Models/UpdateDialogNode.swift +++ b/Source/AssistantV1/Models/UpdateDialogNode.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -94,18 +94,18 @@ internal struct UpdateDialogNode: Codable, Equatable { public var conditions: String? /** - The ID of the parent dialog node. + The ID of the parent dialog node. This property is omitted if the dialog node has no parent. */ public var parent: String? /** - The ID of the previous sibling dialog node. + The ID of the previous sibling dialog node. This property is omitted if the dialog node has no previous sibling. */ public var previousSibling: String? /** The output of the dialog node. For more information about how to specify dialog node output, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). */ public var output: DialogNodeOutput? @@ -172,6 +172,21 @@ internal struct UpdateDialogNode: Codable, Equatable { */ public var userLabel: String? + /** + For internal use only. + */ + public var disabled: Bool? + + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case dialogNode = "dialog_node" @@ -192,6 +207,9 @@ internal struct UpdateDialogNode: Codable, Equatable { case digressOut = "digress_out" case digressOutSlots = "digress_out_slots" case userLabel = "user_label" + case disabled = "disabled" + case created = "created" + case updated = "updated" } /** @@ -204,10 +222,12 @@ internal struct UpdateDialogNode: Codable, Equatable { newline, or tab characters, and it must be no longer than 128 characters. - parameter conditions: The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 2048 characters. - - parameter parent: The ID of the parent dialog node. - - parameter previousSibling: The ID of the previous sibling dialog node. + - parameter parent: The ID of the parent dialog node. This property is omitted if the dialog node has no parent. + - parameter previousSibling: The ID of the previous sibling dialog node. This property is omitted if the dialog + node has no previous sibling. - parameter output: The output of the dialog node. For more information about how to specify dialog node output, - see the [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#complex). + see the + [documentation](https://cloud.ibm.com/docs/services/assistant/dialog-overview.html#dialog-overview-responses). - parameter context: The context for the dialog node. - parameter metadata: The metadata for the dialog node. - parameter nextStep: The next step to execute following this dialog node. @@ -224,6 +244,9 @@ internal struct UpdateDialogNode: Codable, Equatable { - parameter digressOutSlots: Whether the user can digress to top-level nodes while filling out slots. - parameter userLabel: A label that can be displayed externally to describe the purpose of the node to users. This string must be no longer than 512 characters. + - parameter disabled: For internal use only. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `UpdateDialogNode`. */ @@ -245,7 +268,10 @@ internal struct UpdateDialogNode: Codable, Equatable { digressIn: String? = nil, digressOut: String? = nil, digressOutSlots: String? = nil, - userLabel: String? = nil + userLabel: String? = nil, + disabled: Bool? = nil, + created: Date? = nil, + updated: Date? = nil ) { self.dialogNode = dialogNode @@ -266,6 +292,9 @@ internal struct UpdateDialogNode: Codable, Equatable { self.digressOut = digressOut self.digressOutSlots = digressOutSlots self.userLabel = userLabel + self.disabled = disabled + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/UpdateEntity.swift b/Source/AssistantV1/Models/UpdateEntity.swift index 78f0f64f8..7f2d9428b 100644 --- a/Source/AssistantV1/Models/UpdateEntity.swift +++ b/Source/AssistantV1/Models/UpdateEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,17 @@ internal struct UpdateEntity: Codable, Equatable { public var fuzzyMatch: Bool? /** - An array of entity values. + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + + /** + An array of objects describing the entity values. */ public var values: [CreateValue]? @@ -55,6 +65,8 @@ internal struct UpdateEntity: Codable, Equatable { case description = "description" case metadata = "metadata" case fuzzyMatch = "fuzzy_match" + case created = "created" + case updated = "updated" case values = "values" } @@ -69,7 +81,9 @@ internal struct UpdateEntity: Codable, Equatable { tab characters, and it must be no longer than 128 characters. - parameter metadata: Any metadata related to the entity. - parameter fuzzyMatch: Whether to use fuzzy matching for the entity. - - parameter values: An array of entity values. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. + - parameter values: An array of objects describing the entity values. - returns: An initialized `UpdateEntity`. */ @@ -78,6 +92,8 @@ internal struct UpdateEntity: Codable, Equatable { description: String? = nil, metadata: [String: JSON]? = nil, fuzzyMatch: Bool? = nil, + created: Date? = nil, + updated: Date? = nil, values: [CreateValue]? = nil ) { @@ -85,6 +101,8 @@ internal struct UpdateEntity: Codable, Equatable { self.description = description self.metadata = metadata self.fuzzyMatch = fuzzyMatch + self.created = created + self.updated = updated self.values = values } diff --git a/Source/AssistantV1/Models/UpdateExample.swift b/Source/AssistantV1/Models/UpdateExample.swift index 48bed8cf4..38234d4fe 100644 --- a/Source/AssistantV1/Models/UpdateExample.swift +++ b/Source/AssistantV1/Models/UpdateExample.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,24 @@ internal struct UpdateExample: Codable, Equatable { /** An array of contextual entity mentions. */ - public var mentions: [Mentions]? + public var mentions: [Mention]? + + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" case mentions = "mentions" + case created = "created" + case updated = "updated" } /** @@ -46,16 +58,22 @@ internal struct UpdateExample: Codable, Equatable { - It cannot consist of only whitespace characters. - It must be no longer than 1024 characters. - parameter mentions: An array of contextual entity mentions. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `UpdateExample`. */ public init( text: String? = nil, - mentions: [Mentions]? = nil + mentions: [Mention]? = nil, + created: Date? = nil, + updated: Date? = nil ) { self.text = text self.mentions = mentions + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/UpdateIntent.swift b/Source/AssistantV1/Models/UpdateIntent.swift index db6497891..278906437 100644 --- a/Source/AssistantV1/Models/UpdateIntent.swift +++ b/Source/AssistantV1/Models/UpdateIntent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,19 +28,32 @@ internal struct UpdateIntent: Codable, Equatable { public var intent: String? /** - The description of the intent. + The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must + be no longer than 128 characters. */ public var description: String? + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + /** An array of user input examples for the intent. */ - public var examples: [CreateExample]? + public var examples: [Example]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case intent = "intent" case description = "description" + case created = "created" + case updated = "updated" case examples = "examples" } @@ -51,7 +64,10 @@ internal struct UpdateIntent: Codable, Equatable { - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters. - - parameter description: The description of the intent. + - parameter description: The description of the intent. This string cannot contain carriage return, newline, or + tab characters, and it must be no longer than 128 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - parameter examples: An array of user input examples for the intent. - returns: An initialized `UpdateIntent`. @@ -59,11 +75,15 @@ internal struct UpdateIntent: Codable, Equatable { public init( intent: String? = nil, description: String? = nil, - examples: [CreateExample]? = nil + created: Date? = nil, + updated: Date? = nil, + examples: [Example]? = nil ) { self.intent = intent self.description = description + self.created = created + self.updated = updated self.examples = examples } diff --git a/Source/AssistantV1/Models/UpdateSynonym.swift b/Source/AssistantV1/Models/UpdateSynonym.swift index 088cc2928..2775b0e0e 100644 --- a/Source/AssistantV1/Models/UpdateSynonym.swift +++ b/Source/AssistantV1/Models/UpdateSynonym.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,21 @@ internal struct UpdateSynonym: Codable, Equatable { */ public var synonym: String? + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case synonym = "synonym" + case created = "created" + case updated = "updated" } /** @@ -39,14 +51,20 @@ internal struct UpdateSynonym: Codable, Equatable { - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `UpdateSynonym`. */ public init( - synonym: String? = nil + synonym: String? = nil, + created: Date? = nil, + updated: Date? = nil ) { self.synonym = synonym + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/UpdateValue.swift b/Source/AssistantV1/Models/UpdateValue.swift index 28fae516e..6c013b71f 100644 --- a/Source/AssistantV1/Models/UpdateValue.swift +++ b/Source/AssistantV1/Models/UpdateValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import RestKit internal struct UpdateValue: Codable, Equatable { /** - Specifies the type of value. + Specifies the type of entity value. */ public enum ValueType: String { case synonyms = "synonyms" @@ -42,13 +42,13 @@ internal struct UpdateValue: Codable, Equatable { public var metadata: [String: JSON]? /** - Specifies the type of value. + Specifies the type of entity value. */ public var valueType: String? /** - An array of synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), - but not both. A synonym must conform to the following resrictions: + An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. @@ -56,13 +56,23 @@ internal struct UpdateValue: Codable, Equatable { public var synonyms: [String]? /** - An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), - but not both. A pattern is a regular expression no longer than 512 characters. For more information about how to - specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). + An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A pattern is a regular expression no longer than 512 characters. For more information about + how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). */ public var patterns: [String]? + /** + The timestamp for creation of the object. + */ + public var created: Date? + + /** + The timestamp for the most recent update to the object. + */ + public var updated: Date? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case value = "value" @@ -70,6 +80,8 @@ internal struct UpdateValue: Codable, Equatable { case valueType = "type" case synonyms = "synonyms" case patterns = "patterns" + case created = "created" + case updated = "updated" } /** @@ -80,16 +92,18 @@ internal struct UpdateValue: Codable, Equatable { - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - parameter metadata: Any metadata related to the entity value. - - parameter valueType: Specifies the type of value. - - parameter synonyms: An array of synonyms for the entity value. You can provide either synonyms or patterns (as - indicated by **type**), but not both. A synonym must conform to the following resrictions: + - parameter valueType: Specifies the type of entity value. + - parameter synonyms: An array of synonyms for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters. - - parameter patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as - indicated by **type**), but not both. A pattern is a regular expression no longer than 512 characters. For more - information about how to specify a pattern, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#creating-entities). + - parameter patterns: An array of patterns for the entity value. A value can specify either synonyms or patterns + (depending on the value type), but not both. A pattern is a regular expression no longer than 512 characters. For + more information about how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - returns: An initialized `UpdateValue`. */ @@ -98,7 +112,9 @@ internal struct UpdateValue: Codable, Equatable { metadata: [String: JSON]? = nil, valueType: String? = nil, synonyms: [String]? = nil, - patterns: [String]? = nil + patterns: [String]? = nil, + created: Date? = nil, + updated: Date? = nil ) { self.value = value @@ -106,6 +122,8 @@ internal struct UpdateValue: Codable, Equatable { self.valueType = valueType self.synonyms = synonyms self.patterns = patterns + self.created = created + self.updated = updated } } diff --git a/Source/AssistantV1/Models/UpdateWorkspace.swift b/Source/AssistantV1/Models/UpdateWorkspace.swift index 7264065b7..47c2536d7 100644 --- a/Source/AssistantV1/Models/UpdateWorkspace.swift +++ b/Source/AssistantV1/Models/UpdateWorkspace.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,17 @@ import RestKit /** UpdateWorkspace. */ internal struct UpdateWorkspace: Codable, Equatable { + /** + The current status of the workspace. + */ + public enum Status: String { + case nonExistent = "Non Existent" + case training = "Training" + case failed = "Failed" + case available = "Available" + case unavailable = "Unavailable" + } + /** The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 64 characters. @@ -38,53 +49,77 @@ internal struct UpdateWorkspace: Codable, Equatable { public var language: String? /** - An array of objects defining the intents for the workspace. + Any metadata related to the workspace. */ - public var intents: [CreateIntent]? + public var metadata: [String: JSON]? /** - An array of objects defining the entities for the workspace. + Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is not to be used. */ - public var entities: [CreateEntity]? + public var learningOptOut: Bool? /** - An array of objects defining the nodes in the dialog. + Global settings for the workspace. */ - public var dialogNodes: [CreateDialogNode]? + public var systemSettings: WorkspaceSystemSettings? /** - An array of objects defining input examples that have been marked as irrelevant input. + The workspace ID of the workspace. */ - public var counterexamples: [CreateCounterexample]? + public var workspaceID: String? /** - Any metadata related to the workspace. + The current status of the workspace. */ - public var metadata: [String: JSON]? + public var status: String? /** - Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that - workspace training data is not to be used. + The timestamp for creation of the object. */ - public var learningOptOut: Bool? + public var created: Date? /** - Global settings for the workspace. + The timestamp for the most recent update to the object. */ - public var systemSettings: WorkspaceSystemSettings? + public var updated: Date? + + /** + An array of objects defining the intents for the workspace. + */ + public var intents: [CreateIntent]? + + /** + An array of objects describing the entities for the workspace. + */ + public var entities: [CreateEntity]? + + /** + An array of objects describing the dialog nodes in the workspace. + */ + public var dialogNodes: [DialogNode]? + + /** + An array of objects defining input examples that have been marked as irrelevant input. + */ + public var counterexamples: [Counterexample]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case description = "description" case language = "language" + case metadata = "metadata" + case learningOptOut = "learning_opt_out" + case systemSettings = "system_settings" + case workspaceID = "workspace_id" + case status = "status" + case created = "created" + case updated = "updated" case intents = "intents" case entities = "entities" case dialogNodes = "dialog_nodes" case counterexamples = "counterexamples" - case metadata = "metadata" - case learningOptOut = "learning_opt_out" - case systemSettings = "system_settings" } /** @@ -95,15 +130,20 @@ internal struct UpdateWorkspace: Codable, Equatable { - parameter description: The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be no longer than 128 characters. - parameter language: The language of the workspace. + - parameter metadata: Any metadata related to the workspace. + - parameter learningOptOut: Whether training data from the workspace (including artifacts such as intents and + entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is + not to be used. + - parameter systemSettings: Global settings for the workspace. + - parameter workspaceID: The workspace ID of the workspace. + - parameter status: The current status of the workspace. + - parameter created: The timestamp for creation of the object. + - parameter updated: The timestamp for the most recent update to the object. - parameter intents: An array of objects defining the intents for the workspace. - - parameter entities: An array of objects defining the entities for the workspace. - - parameter dialogNodes: An array of objects defining the nodes in the dialog. + - parameter entities: An array of objects describing the entities for the workspace. + - parameter dialogNodes: An array of objects describing the dialog nodes in the workspace. - parameter counterexamples: An array of objects defining input examples that have been marked as irrelevant input. - - parameter metadata: Any metadata related to the workspace. - - parameter learningOptOut: Whether training data from the workspace can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - - parameter systemSettings: Global settings for the workspace. - returns: An initialized `UpdateWorkspace`. */ @@ -111,25 +151,33 @@ internal struct UpdateWorkspace: Codable, Equatable { name: String? = nil, description: String? = nil, language: String? = nil, - intents: [CreateIntent]? = nil, - entities: [CreateEntity]? = nil, - dialogNodes: [CreateDialogNode]? = nil, - counterexamples: [CreateCounterexample]? = nil, metadata: [String: JSON]? = nil, learningOptOut: Bool? = nil, - systemSettings: WorkspaceSystemSettings? = nil + systemSettings: WorkspaceSystemSettings? = nil, + workspaceID: String? = nil, + status: String? = nil, + created: Date? = nil, + updated: Date? = nil, + intents: [CreateIntent]? = nil, + entities: [CreateEntity]? = nil, + dialogNodes: [DialogNode]? = nil, + counterexamples: [Counterexample]? = nil ) { self.name = name self.description = description self.language = language + self.metadata = metadata + self.learningOptOut = learningOptOut + self.systemSettings = systemSettings + self.workspaceID = workspaceID + self.status = status + self.created = created + self.updated = updated self.intents = intents self.entities = entities self.dialogNodes = dialogNodes self.counterexamples = counterexamples - self.metadata = metadata - self.learningOptOut = learningOptOut - self.systemSettings = systemSettings } } diff --git a/Source/AssistantV1/Models/Value.swift b/Source/AssistantV1/Models/Value.swift index b03114d50..5e9c899da 100644 --- a/Source/AssistantV1/Models/Value.swift +++ b/Source/AssistantV1/Models/Value.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import RestKit public struct Value: Codable, Equatable { /** - Specifies the type of value. + Specifies the type of entity value. */ public enum ValueType: String { case synonyms = "synonyms" @@ -29,9 +29,12 @@ public struct Value: Codable, Equatable { } /** - The text of the entity value. + The text of the entity value. This string must conform to the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 64 characters. */ - public var valueText: String + public var value: String /** Any metadata related to the entity value. @@ -39,39 +42,46 @@ public struct Value: Codable, Equatable { public var metadata: [String: JSON]? /** - The timestamp for creation of the entity value. + Specifies the type of entity value. */ - public var created: Date? + public var valueType: String /** - The timestamp for the last update to the entity value. + An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A synonym must conform to the following resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + - It must be no longer than 64 characters. */ - public var updated: Date? + public var synonyms: [String]? /** - An array containing any synonyms for the entity value. + An array of patterns for the entity value. A value can specify either synonyms or patterns (depending on the value + type), but not both. A pattern is a regular expression no longer than 512 characters. For more information about + how to specify a pattern, see the + [documentation](https://cloud.ibm.com/docs/services/assistant/entities.html#entities-create-dictionary-based). */ - public var synonyms: [String]? + public var patterns: [String]? /** - An array containing any patterns for the entity value. + The timestamp for creation of the object. */ - public var patterns: [String]? + public var created: Date? /** - Specifies the type of value. + The timestamp for the most recent update to the object. */ - public var valueType: String + public var updated: Date? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case valueText = "value" + case value = "value" case metadata = "metadata" - case created = "created" - case updated = "updated" + case valueType = "type" case synonyms = "synonyms" case patterns = "patterns" - case valueType = "type" + case created = "created" + case updated = "updated" } } diff --git a/Source/AssistantV1/Models/ValueCollection.swift b/Source/AssistantV1/Models/ValueCollection.swift index a5b6704be..18c4243a0 100644 --- a/Source/AssistantV1/Models/ValueCollection.swift +++ b/Source/AssistantV1/Models/ValueCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ public struct ValueCollection: Codable, Equatable { /** An array of entity values. */ - public var values: [ValueExport] + public var values: [Value] /** The pagination data for the returned objects. diff --git a/Source/AssistantV1/Models/ValueExport.swift b/Source/AssistantV1/Models/ValueExport.swift deleted file mode 100644 index 129aba23b..000000000 --- a/Source/AssistantV1/Models/ValueExport.swift +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation -import RestKit - -/** ValueExport. */ -public struct ValueExport: Codable, Equatable { - - /** - Specifies the type of value. - */ - public enum ValueType: String { - case synonyms = "synonyms" - case patterns = "patterns" - } - - /** - The text of the entity value. - */ - public var valueText: String - - /** - Any metadata related to the entity value. - */ - public var metadata: [String: JSON]? - - /** - The timestamp for creation of the entity value. - */ - public var created: Date? - - /** - The timestamp for the last update to the entity value. - */ - public var updated: Date? - - /** - An array containing any synonyms for the entity value. - */ - public var synonyms: [String]? - - /** - An array containing any patterns for the entity value. - */ - public var patterns: [String]? - - /** - Specifies the type of value. - */ - public var valueType: String - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case valueText = "value" - case metadata = "metadata" - case created = "created" - case updated = "updated" - case synonyms = "synonyms" - case patterns = "patterns" - case valueType = "type" - } - -} diff --git a/Source/AssistantV1/Models/Workspace.swift b/Source/AssistantV1/Models/Workspace.swift index c63987cb6..53a08e944 100644 --- a/Source/AssistantV1/Models/Workspace.swift +++ b/Source/AssistantV1/Models/Workspace.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,24 +21,48 @@ import RestKit public struct Workspace: Codable, Equatable { /** - The name of the workspace. + The current status of the workspace. + */ + public enum Status: String { + case nonExistent = "Non Existent" + case training = "Training" + case failed = "Failed" + case available = "Available" + case unavailable = "Unavailable" + } + + /** + The name of the workspace. This string cannot contain carriage return, newline, or tab characters, and it must be + no longer than 64 characters. */ public var name: String + /** + The description of the workspace. This string cannot contain carriage return, newline, or tab characters, and it + must be no longer than 128 characters. + */ + public var description: String? + /** The language of the workspace. */ public var language: String /** - The timestamp for creation of the workspace. + Any metadata related to the workspace. */ - public var created: Date? + public var metadata: [String: JSON]? /** - The timestamp for the last update to the workspace. + Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is not to be used. */ - public var updated: Date? + public var learningOptOut: Bool + + /** + Global settings for the workspace. + */ + public var systemSettings: WorkspaceSystemSettings? /** The workspace ID of the workspace. @@ -46,37 +70,56 @@ public struct Workspace: Codable, Equatable { public var workspaceID: String /** - The description of the workspace. + The current status of the workspace. */ - public var description: String? + public var status: String? /** - Any metadata related to the workspace. + The timestamp for creation of the object. */ - public var metadata: [String: JSON]? + public var created: Date? /** - Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for - general service improvements. `true` indicates that workspace training data is not to be used. + The timestamp for the most recent update to the object. */ - public var learningOptOut: Bool? + public var updated: Date? /** - Global settings for the workspace. + An array of intents. */ - public var systemSettings: WorkspaceSystemSettings? + public var intents: [Intent]? + + /** + An array of objects describing the entities for the workspace. + */ + public var entities: [Entity]? + + /** + An array of objects describing the dialog nodes in the workspace. + */ + public var dialogNodes: [DialogNode]? + + /** + An array of counterexamples. + */ + public var counterexamples: [Counterexample]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" - case language = "language" - case created = "created" - case updated = "updated" - case workspaceID = "workspace_id" case description = "description" + case language = "language" case metadata = "metadata" case learningOptOut = "learning_opt_out" case systemSettings = "system_settings" + case workspaceID = "workspace_id" + case status = "status" + case created = "created" + case updated = "updated" + case intents = "intents" + case entities = "entities" + case dialogNodes = "dialog_nodes" + case counterexamples = "counterexamples" } } diff --git a/Source/AssistantV1/Models/WorkspaceCollection.swift b/Source/AssistantV1/Models/WorkspaceCollection.swift index 544d09898..2012abbdd 100644 --- a/Source/AssistantV1/Models/WorkspaceCollection.swift +++ b/Source/AssistantV1/Models/WorkspaceCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/WorkspaceExport.swift b/Source/AssistantV1/Models/WorkspaceExport.swift deleted file mode 100644 index f5e253ae8..000000000 --- a/Source/AssistantV1/Models/WorkspaceExport.swift +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Copyright IBM Corporation 2018 - * - * 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. - **/ - -import Foundation -import RestKit - -/** WorkspaceExport. */ -public struct WorkspaceExport: Codable, Equatable { - - /** - The current status of the workspace. - */ - public enum Status: String { - case nonExistent = "Non Existent" - case training = "Training" - case failed = "Failed" - case available = "Available" - case unavailable = "Unavailable" - } - - /** - The name of the workspace. - */ - public var name: String - - /** - The description of the workspace. - */ - public var description: String - - /** - The language of the workspace. - */ - public var language: String - - /** - Any metadata that is required by the workspace. - */ - public var metadata: [String: JSON] - - /** - The timestamp for creation of the workspace. - */ - public var created: Date? - - /** - The timestamp for the last update to the workspace. - */ - public var updated: Date? - - /** - The workspace ID of the workspace. - */ - public var workspaceID: String - - /** - The current status of the workspace. - */ - public var status: String - - /** - Whether training data from the workspace can be used by IBM for general service improvements. `true` indicates that - workspace training data is not to be used. - */ - public var learningOptOut: Bool - - /** - Global settings for the workspace. - */ - public var systemSettings: WorkspaceSystemSettings? - - /** - An array of intents. - */ - public var intents: [IntentExport]? - - /** - An array of entities. - */ - public var entities: [EntityExport]? - - /** - An array of counterexamples. - */ - public var counterexamples: [Counterexample]? - - /** - An array of objects describing the dialog nodes in the workspace. - */ - public var dialogNodes: [DialogNode]? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case name = "name" - case description = "description" - case language = "language" - case metadata = "metadata" - case created = "created" - case updated = "updated" - case workspaceID = "workspace_id" - case status = "status" - case learningOptOut = "learning_opt_out" - case systemSettings = "system_settings" - case intents = "intents" - case entities = "entities" - case counterexamples = "counterexamples" - case dialogNodes = "dialog_nodes" - } - -} diff --git a/Source/AssistantV1/Models/WorkspaceSystemSettings.swift b/Source/AssistantV1/Models/WorkspaceSystemSettings.swift index 3e046d770..3c453792f 100644 --- a/Source/AssistantV1/Models/WorkspaceSystemSettings.swift +++ b/Source/AssistantV1/Models/WorkspaceSystemSettings.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/WorkspaceSystemSettingsDisambiguation.swift b/Source/AssistantV1/Models/WorkspaceSystemSettingsDisambiguation.swift index 95b7aa3dd..98a0441a7 100644 --- a/Source/AssistantV1/Models/WorkspaceSystemSettingsDisambiguation.swift +++ b/Source/AssistantV1/Models/WorkspaceSystemSettingsDisambiguation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/WorkspaceSystemSettingsTooling.swift b/Source/AssistantV1/Models/WorkspaceSystemSettingsTooling.swift index c848ce5a0..f059f177c 100644 --- a/Source/AssistantV1/Models/WorkspaceSystemSettingsTooling.swift +++ b/Source/AssistantV1/Models/WorkspaceSystemSettingsTooling.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Assistant.swift b/Source/AssistantV2/Assistant.swift index 3fac37cd1..d45054b9e 100644 --- a/Source/AssistantV2/Assistant.swift +++ b/Source/AssistantV2/Assistant.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,22 +36,23 @@ public class Assistant { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `Assistant` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "assistant") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "assistant") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -61,20 +62,22 @@ public class Assistant { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `Assistant` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -88,6 +91,7 @@ public class Assistant { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -98,8 +102,9 @@ public class Assistant { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -122,16 +127,25 @@ public class Assistant { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { + errorMessage = message + } else if case let .some(.string(message)) = json["error"] { errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -142,7 +156,7 @@ public class Assistant { - parameter assistantID: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/create-assistant.html#creating-assistants). + [documentation](https://console.bluemix.net/docs/services/assistant/assistant-add.html#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error @@ -157,10 +171,9 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSession") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSession") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" - headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() @@ -193,7 +206,7 @@ public class Assistant { - parameter assistantID: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/create-assistant.html#creating-assistants). + [documentation](https://console.bluemix.net/docs/services/assistant/assistant-add.html#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. - parameter sessionID: Unique identifier of the session. - parameter headers: A dictionary of request headers to be sent with this request. @@ -210,8 +223,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteSession") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteSession") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -246,11 +259,13 @@ public class Assistant { - parameter assistantID: Unique identifier of the assistant. You can find the assistant ID of an assistant on the **Assistants** tab of the Watson Assistant tool. For information about creating assistants, see the - [documentation](https://cloud.ibm.com/docs/services/assistant/create-assistant.html#creating-assistants). + [documentation](https://console.bluemix.net/docs/services/assistant/assistant-add.html#assistant-add-task). **Note:** Currently, the v2 API does not support creating assistants. - parameter sessionID: Unique identifier of the session. - parameter input: An input object that includes the input text. - - parameter context: State information for the conversation. + - parameter context: State information for the conversation. The context is stored by the assistant on a + per-session basis. You can use this property to set or modify context variables, which can also be accessed by + dialog nodes. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -266,7 +281,7 @@ public class Assistant { let messageRequest = MessageRequest( input: input, context: context) - guard let body = try? JSONEncoder().encodeIfPresent(messageRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(messageRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -276,8 +291,8 @@ public class Assistant { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "message") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "message") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" diff --git a/Source/AssistantV2/Models/CaptureGroup.swift b/Source/AssistantV2/Models/CaptureGroup.swift index 3bf1fb3b9..e180d90ef 100644 --- a/Source/AssistantV2/Models/CaptureGroup.swift +++ b/Source/AssistantV2/Models/CaptureGroup.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogLogMessage.swift b/Source/AssistantV2/Models/DialogLogMessage.swift index 977c0a960..2251525b0 100644 --- a/Source/AssistantV2/Models/DialogLogMessage.swift +++ b/Source/AssistantV2/Models/DialogLogMessage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogNodeAction.swift b/Source/AssistantV2/Models/DialogNodeAction.swift index 6519b39aa..314c1cbb5 100644 --- a/Source/AssistantV2/Models/DialogNodeAction.swift +++ b/Source/AssistantV2/Models/DialogNodeAction.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogNodeOutputOptionsElement.swift b/Source/AssistantV2/Models/DialogNodeOutputOptionsElement.swift index 123aa8d27..51097c7c4 100644 --- a/Source/AssistantV2/Models/DialogNodeOutputOptionsElement.swift +++ b/Source/AssistantV2/Models/DialogNodeOutputOptionsElement.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogNodeOutputOptionsElementValue.swift b/Source/AssistantV2/Models/DialogNodeOutputOptionsElementValue.swift index c0a329879..0f58a63b0 100644 --- a/Source/AssistantV2/Models/DialogNodeOutputOptionsElementValue.swift +++ b/Source/AssistantV2/Models/DialogNodeOutputOptionsElementValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogNodesVisited.swift b/Source/AssistantV2/Models/DialogNodesVisited.swift index 4c93a6054..574c779bd 100644 --- a/Source/AssistantV2/Models/DialogNodesVisited.swift +++ b/Source/AssistantV2/Models/DialogNodesVisited.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogRuntimeResponseGeneric.swift b/Source/AssistantV2/Models/DialogRuntimeResponseGeneric.swift index d7d75814e..42b1b5b86 100644 --- a/Source/AssistantV2/Models/DialogRuntimeResponseGeneric.swift +++ b/Source/AssistantV2/Models/DialogRuntimeResponseGeneric.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ public struct DialogRuntimeResponseGeneric: Codable, Equatable { public var source: String? /** - The title to show before the response. + The title or introductory text to show before the response. */ public var title: String? diff --git a/Source/AssistantV2/Models/DialogSuggestion.swift b/Source/AssistantV2/Models/DialogSuggestion.swift index a953031db..0e6047910 100644 --- a/Source/AssistantV2/Models/DialogSuggestion.swift +++ b/Source/AssistantV2/Models/DialogSuggestion.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/DialogSuggestionValue.swift b/Source/AssistantV2/Models/DialogSuggestionValue.swift index 3ffe079be..743b7cf5c 100644 --- a/Source/AssistantV2/Models/DialogSuggestionValue.swift +++ b/Source/AssistantV2/Models/DialogSuggestionValue.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/MessageContext.swift b/Source/AssistantV2/Models/MessageContext.swift index 1b5fbb73a..e366d2d95 100644 --- a/Source/AssistantV2/Models/MessageContext.swift +++ b/Source/AssistantV2/Models/MessageContext.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,18 @@ import Foundation -/** - State information for the conversation. - */ +/** MessageContext. */ public struct MessageContext: Codable, Equatable { /** - Contains information that can be shared by all skills within the Assistant. + Information that is shared by all skills used by the Assistant. */ public var global: MessageContextGlobal? /** - Contains information specific to particular skills within the Assistant. + Information specific to particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that + apply to the dialog skill used by the assistant. */ public var skills: MessageContextSkills? @@ -40,8 +40,10 @@ public struct MessageContext: Codable, Equatable { /** Initialize a `MessageContext` with member variables. - - parameter global: Contains information that can be shared by all skills within the Assistant. - - parameter skills: Contains information specific to particular skills within the Assistant. + - parameter global: Information that is shared by all skills used by the Assistant. + - parameter skills: Information specific to particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that + apply to the dialog skill used by the assistant. - returns: An initialized `MessageContext`. */ diff --git a/Source/AssistantV2/Models/MessageContextGlobal.swift b/Source/AssistantV2/Models/MessageContextGlobal.swift index b341ae1f2..c5ba7a5f1 100644 --- a/Source/AssistantV2/Models/MessageContextGlobal.swift +++ b/Source/AssistantV2/Models/MessageContextGlobal.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ import Foundation /** - Contains information that can be shared by all skills within the Assistant. + Information that is shared by all skills used by the Assistant. */ public struct MessageContextGlobal: Codable, Equatable { /** - Properties that are shared by all skills used by the assistant. + Built-in system properties that apply to all skills used by the assistant. */ public var system: MessageContextGlobalSystem? @@ -34,7 +34,7 @@ public struct MessageContextGlobal: Codable, Equatable { /** Initialize a `MessageContextGlobal` with member variables. - - parameter system: Properties that are shared by all skills used by the assistant. + - parameter system: Built-in system properties that apply to all skills used by the assistant. - returns: An initialized `MessageContextGlobal`. */ diff --git a/Source/AssistantV2/Models/MessageContextGlobalSystem.swift b/Source/AssistantV2/Models/MessageContextGlobalSystem.swift index 5463017f2..0d204fc94 100644 --- a/Source/AssistantV2/Models/MessageContextGlobalSystem.swift +++ b/Source/AssistantV2/Models/MessageContextGlobalSystem.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Foundation /** - Properties that are shared by all skills used by the assistant. + Built-in system properties that apply to all skills used by the assistant. */ public struct MessageContextGlobalSystem: Codable, Equatable { @@ -36,7 +36,8 @@ public struct MessageContextGlobalSystem: Codable, Equatable { /** A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is - the the first turn of a new conversation, which can affect the behavior of some skills. + the the first turn of a new conversation, which can affect the behavior of some skills (for example, triggering the + start node of a dialog). */ public var turnCount: Int? @@ -58,7 +59,7 @@ public struct MessageContextGlobalSystem: Codable, Equatable { return, newline, or tab characters. - parameter turnCount: A counter that is automatically incremented with each turn of the conversation. A value of 1 indicates that this is the the first turn of a new conversation, which can affect the behavior of some - skills. + skills (for example, triggering the start node of a dialog). - returns: An initialized `MessageContextGlobalSystem`. */ diff --git a/Source/AssistantV2/Models/MessageContextSkill.swift b/Source/AssistantV2/Models/MessageContextSkill.swift new file mode 100644 index 000000000..747f1d249 --- /dev/null +++ b/Source/AssistantV2/Models/MessageContextSkill.swift @@ -0,0 +1,48 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Contains information specific to a particular skill used by the Assistant. + */ +public struct MessageContextSkill: Codable, Equatable { + + /** + Arbitrary variables that can be read and written by a particular skill. + */ + public var userDefined: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case userDefined = "user_defined" + } + + /** + Initialize a `MessageContextSkill` with member variables. + + - parameter userDefined: Arbitrary variables that can be read and written by a particular skill. + + - returns: An initialized `MessageContextSkill`. + */ + public init( + userDefined: String? = nil + ) + { + self.userDefined = userDefined + } + +} diff --git a/Source/AssistantV2/Models/MessageContextSkills.swift b/Source/AssistantV2/Models/MessageContextSkills.swift index e2c41b606..559a6013f 100644 --- a/Source/AssistantV2/Models/MessageContextSkills.swift +++ b/Source/AssistantV2/Models/MessageContextSkills.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,9 @@ import Foundation import RestKit /** - Contains information specific to particular skills within the Assistant. + Information specific to particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that apply + to the dialog skill used by the assistant. */ public struct MessageContextSkills: Codable, Equatable { diff --git a/Source/AssistantV2/Models/MessageInput.swift b/Source/AssistantV2/Models/MessageInput.swift index 8903873e5..8ac77e78f 100644 --- a/Source/AssistantV2/Models/MessageInput.swift +++ b/Source/AssistantV2/Models/MessageInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/MessageInputOptions.swift b/Source/AssistantV2/Models/MessageInputOptions.swift index 457bd7828..259d17d70 100644 --- a/Source/AssistantV2/Models/MessageInputOptions.swift +++ b/Source/AssistantV2/Models/MessageInputOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/MessageOutput.swift b/Source/AssistantV2/Models/MessageOutput.swift index aa56242b7..c15bd5a29 100644 --- a/Source/AssistantV2/Models/MessageOutput.swift +++ b/Source/AssistantV2/Models/MessageOutput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/MessageOutputDebug.swift b/Source/AssistantV2/Models/MessageOutputDebug.swift index d7b9c2061..4e6ddd218 100644 --- a/Source/AssistantV2/Models/MessageOutputDebug.swift +++ b/Source/AssistantV2/Models/MessageOutputDebug.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/MessageRequest.swift b/Source/AssistantV2/Models/MessageRequest.swift index 6cda4bfa0..3b6a359aa 100644 --- a/Source/AssistantV2/Models/MessageRequest.swift +++ b/Source/AssistantV2/Models/MessageRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,8 @@ internal struct MessageRequest: Codable, Equatable { public var input: MessageInput? /** - State information for the conversation. + State information for the conversation. The context is stored by the assistant on a per-session basis. You can use + this property to set or modify context variables, which can also be accessed by dialog nodes. */ public var context: MessageContext? @@ -41,7 +42,9 @@ internal struct MessageRequest: Codable, Equatable { Initialize a `MessageRequest` with member variables. - parameter input: An input object that includes the input text. - - parameter context: State information for the conversation. + - parameter context: State information for the conversation. The context is stored by the assistant on a + per-session basis. You can use this property to set or modify context variables, which can also be accessed by + dialog nodes. - returns: An initialized `MessageRequest`. */ diff --git a/Source/AssistantV2/Models/MessageRequestContext.swift b/Source/AssistantV2/Models/MessageRequestContext.swift new file mode 100644 index 000000000..0a7d043ff --- /dev/null +++ b/Source/AssistantV2/Models/MessageRequestContext.swift @@ -0,0 +1,43 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + State information for the conversation. The context is stored by the assistant on a per-session basis. You can use this + property to set or modify context variables, which can also be accessed by dialog nodes. + */ +public struct MessageRequestContext: Codable, Equatable { + + /** + Information that is shared by all skills used by the Assistant. + */ + public var global: MessageContextGlobal? + + /** + Information specific to particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that + apply to the dialog skill used by the assistant. + */ + public var skills: [String: MessageContextSkill]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case global = "global" + case skills = "skills" + } + +} diff --git a/Source/AssistantV2/Models/MessageResponse.swift b/Source/AssistantV2/Models/MessageResponse.swift index 9577c8bb6..19d3b5242 100644 --- a/Source/AssistantV2/Models/MessageResponse.swift +++ b/Source/AssistantV2/Models/MessageResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,9 @@ public struct MessageResponse: Codable, Equatable { public var output: MessageOutput /** - State information for the conversation. + State information for the conversation. The context is stored by the assistant on a per-session basis. You can use + this property to access context variables. + **Note:** The context is included in message responses only if **return_context**=`true` in the message request. */ public var context: MessageContext? diff --git a/Source/AssistantV2/Models/MessageResponseContext.swift b/Source/AssistantV2/Models/MessageResponseContext.swift new file mode 100644 index 000000000..58dc23629 --- /dev/null +++ b/Source/AssistantV2/Models/MessageResponseContext.swift @@ -0,0 +1,44 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + State information for the conversation. The context is stored by the assistant on a per-session basis. You can use this + property to access context variables. **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. + */ +public struct MessageResponseContext: Codable, Equatable { + + /** + Information that is shared by all skills used by the Assistant. + */ + public var global: MessageContextGlobal? + + /** + Information specific to particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that + apply to the dialog skill used by the assistant. + */ + public var skills: [String: MessageContextSkill]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case global = "global" + case skills = "skills" + } + +} diff --git a/Source/AssistantV2/Models/RuntimeEntity.swift b/Source/AssistantV2/Models/RuntimeEntity.swift index 11cb5e656..ebf297d11 100644 --- a/Source/AssistantV2/Models/RuntimeEntity.swift +++ b/Source/AssistantV2/Models/RuntimeEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/RuntimeIntent.swift b/Source/AssistantV2/Models/RuntimeIntent.swift index 71b69bd13..b15c99843 100644 --- a/Source/AssistantV2/Models/RuntimeIntent.swift +++ b/Source/AssistantV2/Models/RuntimeIntent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV2/Models/SessionResponse.swift b/Source/AssistantV2/Models/SessionResponse.swift index 6a14df523..fc3e6d855 100644 --- a/Source/AssistantV2/Models/SessionResponse.swift +++ b/Source/AssistantV2/Models/SessionResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/CompareComply.swift b/Source/CompareComplyV1/CompareComply.swift index c336f3f23..886ad838f 100644 --- a/Source/CompareComplyV1/CompareComply.swift +++ b/Source/CompareComplyV1/CompareComply.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,22 +36,23 @@ public class CompareComply { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `CompareComply` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "compare_comply") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "compare_comply") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -61,8 +62,9 @@ public class CompareComply { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `CompareComply` object. @@ -75,6 +77,7 @@ public class CompareComply { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -85,8 +88,9 @@ public class CompareComply { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -109,46 +113,52 @@ public class CompareComply { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { + errorMessage = message + } else if case let .some(.string(message)) = json["error"] { errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** - Convert file to HTML. + Convert document to HTML. - Convert an uploaded file to HTML. + Converts a document to HTML. - - parameter file: The file to convert. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter file: The document to convert. + - parameter filename: The filename for file. - parameter fileContentType: The content type of file. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func convertToHTML( - file: URL, - modelID: String? = nil, + file: Data, + filename: String, fileContentType: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: filename) guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -159,16 +169,16 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "convertToHTML") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "convertToHTML") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -191,31 +201,26 @@ public class CompareComply { /** Classify the elements of a document. - Analyze an uploaded file's structural and semantic elements. + Analyzes the structural and semantic elements of a document. - - parameter file: The file to classify. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter file: The document to classify. - parameter fileContentType: The content type of file. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func classifyElements( - file: URL, - modelID: String? = nil, + file: Data, fileContentType: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: "filename") guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -226,16 +231,16 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classifyElements") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classifyElements") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -258,31 +263,26 @@ public class CompareComply { /** Extract a document's tables. - Extract and analyze an uploaded file's tables. + Analyzes the tables in a document. - - parameter file: The file on which to run table extraction. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter file: The document on which to run table extraction. - parameter fileContentType: The content type of file. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func extractTables( - file: URL, - modelID: String? = nil, + file: Data, fileContentType: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: "filename") guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -293,16 +293,16 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "extractTables") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "extractTables") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -325,45 +325,35 @@ public class CompareComply { /** Compare two documents. - Compare two uploaded input files. Uploaded files must be in the same file format. + Compares two input documents. Documents must be in the same format. - - parameter file1: The first file to compare. - - parameter file2: The second file to compare. - - parameter file1Label: A text label for the first file. - - parameter file2Label: A text label for the second file. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter file1: The first document to compare. + - parameter file2: The second document to compare. - parameter file1ContentType: The content type of file1. - parameter file2ContentType: The content type of file2. + - parameter file1Label: A text label for the first document. + - parameter file2Label: A text label for the second document. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func compareDocuments( - file1: URL, - file2: URL, - file1Label: String? = nil, - file2Label: String? = nil, - modelID: String? = nil, + file1: Data, + file2: Data, file1ContentType: String? = nil, file2ContentType: String? = nil, + file1Label: String? = nil, + file2Label: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: file1, withName: "file_1") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file1.path)")) - return - } - do { - try multipartFormData.append(file: file2, withName: "file_2") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file2.path)")) - return - } + multipartFormData.append(file1, withName: "file_1", mimeType: file1ContentType, fileName: "filename") + multipartFormData.append(file2, withName: "file_2", mimeType: file2ContentType, fileName: "filename") guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -374,8 +364,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "compareDocuments") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "compareDocuments") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -390,8 +380,8 @@ public class CompareComply { let queryParameter = URLQueryItem(name: "file_2_label", value: file2Label) queryParameters.append(queryParameter) } - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -436,7 +426,7 @@ public class CompareComply { feedbackData: feedbackData, userID: userID, comment: comment) - guard let body = try? JSONEncoder().encode(addFeedbackRequest) else { + guard let body = try? JSON.encoder.encode(addFeedbackRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -446,8 +436,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addFeedback") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addFeedback") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -472,7 +462,9 @@ public class CompareComply { } /** - List the feedback in documents. + List the feedback in a document. + + Lists the feedback in a document. - parameter feedbackType: An optional string that filters the output to include only feedback with the specified feedback type. The only permitted value is `element_classification`. @@ -541,8 +533,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listFeedback") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listFeedback") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -631,16 +623,18 @@ public class CompareComply { /** List a specified feedback entry. + Lists a feedback entry with a specified `feedback_id`. + - parameter feedbackID: A string that specifies the feedback entry to be included in the output. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func getFeedback( feedbackID: String, - modelID: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -649,15 +643,15 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getFeedback") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getFeedback") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -682,18 +676,20 @@ public class CompareComply { } /** - Deletes a specified feedback entry. + Delete a specified feedback entry. + + Deletes a feedback entry with a specified `feedback_id`. - parameter feedbackID: A string that specifies the feedback entry to be deleted from the document. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func deleteFeedback( feedbackID: String, - modelID: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -702,15 +698,15 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteFeedback") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteFeedback") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -756,44 +752,34 @@ public class CompareComply { - parameter outputBucketLocation: The geographical location of the Cloud Object Storage output bucket as listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - parameter outputBucketName: The name of the Cloud Object Storage output bucket. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createBatch( function: String, - inputCredentialsFile: URL, + inputCredentialsFile: Data, inputBucketLocation: String, inputBucketName: String, - outputCredentialsFile: URL, + outputCredentialsFile: Data, outputBucketLocation: String, outputBucketName: String, - modelID: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: inputCredentialsFile, withName: "input_credentials_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(inputCredentialsFile.path)")) - return - } + multipartFormData.append(inputCredentialsFile, withName: "input_credentials_file", fileName: "filename") if let inputBucketLocationData = inputBucketLocation.data(using: .utf8) { multipartFormData.append(inputBucketLocationData, withName: "input_bucket_location") } if let inputBucketNameData = inputBucketName.data(using: .utf8) { multipartFormData.append(inputBucketNameData, withName: "input_bucket_name") } - do { - try multipartFormData.append(file: outputCredentialsFile, withName: "output_credentials_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(outputCredentialsFile.path)")) - return - } + multipartFormData.append(outputCredentialsFile, withName: "output_credentials_file", fileName: "filename") if let outputBucketLocationData = outputBucketLocation.data(using: .utf8) { multipartFormData.append(outputBucketLocationData, withName: "output_bucket_location") } @@ -810,8 +796,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createBatch") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createBatch") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -819,8 +805,8 @@ public class CompareComply { var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) queryParameters.append(URLQueryItem(name: "function", value: function)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } @@ -843,7 +829,7 @@ public class CompareComply { /** List submitted batch-processing jobs. - List the batch-processing jobs submitted by users. + Lists batch-processing jobs submitted by users. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error @@ -857,8 +843,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listBatches") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listBatches") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -881,11 +867,11 @@ public class CompareComply { } /** - Get information about a specific batch-processing request. + Get information about a specific batch-processing job. - Get information about a batch-processing request with a specified ID. + Gets information about a batch-processing job with a specified ID. - - parameter batchID: The ID of the batch-processing request whose information you want to retrieve. + - parameter batchID: The ID of the batch-processing job whose information you want to retrieve. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -899,8 +885,8 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getBatch") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getBatch") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -928,23 +914,23 @@ public class CompareComply { } /** - Update a pending or active batch-processing request. + Update a pending or active batch-processing job. - Update a pending or active batch-processing request. You can rescan the input bucket to check for new documents or - cancel a request. + Updates a pending or active batch-processing job. You can rescan the input bucket to check for new documents or + cancel a job. - - parameter batchID: The ID of the batch-processing request you want to update. - - parameter action: The action you want to perform on the specified batch-processing request. - - parameter modelID: The analysis model to be used by the service. For the `/v1/element_classification` and - `/v1/comparison` methods, the default is `contracts`. For the `/v1/tables` method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. + - parameter batchID: The ID of the batch-processing job you want to update. + - parameter action: The action you want to perform on the specified batch-processing job. + - parameter model: The analysis model to be used by the service. For the **Element classification** and **Compare + two documents** methods, the default is `contracts`. For the **Extract tables** method, the default is `tables`. + These defaults apply to the standalone methods as well as to the methods' use in batch-processing requests. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func updateBatch( batchID: String, action: String, - modelID: String? = nil, + model: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -953,16 +939,16 @@ public class CompareComply { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateBatch") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateBatch") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() queryParameters.append(URLQueryItem(name: "version", value: version)) queryParameters.append(URLQueryItem(name: "action", value: action)) - if let modelID = modelID { - let queryParameter = URLQueryItem(name: "model_id", value: modelID) + if let model = model { + let queryParameter = URLQueryItem(name: "model", value: model) queryParameters.append(queryParameter) } diff --git a/Source/CompareComplyV1/Models/Address.swift b/Source/CompareComplyV1/Models/Address.swift index e9e7a1dae..6eaef5325 100644 --- a/Source/CompareComplyV1/Models/Address.swift +++ b/Source/CompareComplyV1/Models/Address.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/AlignedElement.swift b/Source/CompareComplyV1/Models/AlignedElement.swift index 9e060d71b..b0c9b6e6b 100644 --- a/Source/CompareComplyV1/Models/AlignedElement.swift +++ b/Source/CompareComplyV1/Models/AlignedElement.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,26 +25,28 @@ public struct AlignedElement: Codable, Equatable { public var elementPair: [ElementPair]? /** - Specifies whether the text is identical. + Specifies whether the aligned element is identical. Elements are considered identical despite minor differences + such as leading punctuation, end-of-sentence punctuation, whitespace, the presence or absence of definite or + indefinite articles, and others. */ public var identicalText: Bool? /** - Indicates that the elements aligned are contractual clauses of significance. + One or more hashed values that you can send to IBM to provide feedback or receive support. */ - public var significantElements: Bool? + public var provenanceIDs: [String]? /** - One or more hashed values that you can send to IBM to provide feedback or receive support. + Indicates that the elements aligned are contractual clauses of significance. */ - public var provenanceIDs: [String]? + public var significantElements: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case elementPair = "element_pair" case identicalText = "identical_text" - case significantElements = "significant_elements" case provenanceIDs = "provenance_ids" + case significantElements = "significant_elements" } } diff --git a/Source/CompareComplyV1/Models/Attribute.swift b/Source/CompareComplyV1/Models/Attribute.swift index c3e292319..3734cc688 100644 --- a/Source/CompareComplyV1/Models/Attribute.swift +++ b/Source/CompareComplyV1/Models/Attribute.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,12 @@ public struct Attribute: Codable, Equatable { The type of attribute. */ public enum TypeEnum: String { - case address = "Address" case currency = "Currency" case datetime = "DateTime" + case duration = "Duration" case location = "Location" case organization = "Organization" + case percentage = "Percentage" case person = "Person" } diff --git a/Source/CompareComplyV1/Models/BatchStatus.swift b/Source/CompareComplyV1/Models/BatchStatus.swift index ff3aa3fd6..1fa4ca0c9 100644 --- a/Source/CompareComplyV1/Models/BatchStatus.swift +++ b/Source/CompareComplyV1/Models/BatchStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Batches.swift b/Source/CompareComplyV1/Models/Batches.swift index 98768326e..b664e1731 100644 --- a/Source/CompareComplyV1/Models/Batches.swift +++ b/Source/CompareComplyV1/Models/Batches.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/BodyCells.swift b/Source/CompareComplyV1/Models/BodyCells.swift index f77bbb47a..8cc65be6e 100644 --- a/Source/CompareComplyV1/Models/BodyCells.swift +++ b/Source/CompareComplyV1/Models/BodyCells.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import Foundation public struct BodyCells: Codable, Equatable { /** - A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column - header cell in the input document. + The unique ID of the cell in the current table. */ public var cellID: String? @@ -58,37 +57,17 @@ public struct BodyCells: Codable, Equatable { */ public var columnIndexEnd: Int? - /** - An array of values, each being the `id` value of a row header that is applicable to this body cell. - */ - public var rowHeaderIDs: [String]? + public var rowHeaderIDs: [RowHeaderIDs]? - /** - An array of values, each being the `text` value of a row header that is applicable to this body cell. - */ - public var rowHeaderTexts: [String]? + public var rowHeaderTexts: [RowHeaderTexts]? - /** - If you provide customization input, the normalized version of the row header texts according to the customization; - otherwise, the same value as `row_header_texts`. - */ - public var rowHeaderTextsNormalized: [String]? + public var rowHeaderTextsNormalized: [RowHeaderTextsNormalized]? - /** - An array of values, each being the `id` value of a column header that is applicable to the current cell. - */ - public var columnHeaderIDs: [String]? + public var columnHeaderIDs: [ColumnHeaderIDs]? - /** - An array of values, each being the `text` value of a column header that is applicable to the current cell. - */ - public var columnHeaderTexts: [String]? + public var columnHeaderTexts: [ColumnHeaderTexts]? - /** - If you provide customization input, the normalized version of the column header texts according to the - customization; otherwise, the same value as `column_header_texts`. - */ - public var columnHeaderTextsNormalized: [String]? + public var columnHeaderTextsNormalized: [ColumnHeaderTextsNormalized]? public var attributes: [Attribute]? diff --git a/Source/CompareComplyV1/Models/Category.swift b/Source/CompareComplyV1/Models/Category.swift index cca1ee8d8..fd494fb70 100644 --- a/Source/CompareComplyV1/Models/Category.swift +++ b/Source/CompareComplyV1/Models/Category.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,14 +40,14 @@ public struct Category: Codable, Equatable { case insurance = "Insurance" case intellectualProperty = "Intellectual Property" case liability = "Liability" - case paymentTermsAndBilling = "Payment Terms & Billing" - case pricingAndTaxes = "Pricing & Taxes" + case paymentTermsBilling = "Payment Terms & Billing" + case pricingTaxes = "Pricing & Taxes" case privacy = "Privacy" case responsibilities = "Responsibilities" case safetyAndSecurity = "Safety and Security" case scopeOfWork = "Scope of Work" case subcontracts = "Subcontracts" - case termAndTermination = "Term & Termination" + case termTermination = "Term & Termination" case warranties = "Warranties" } diff --git a/Source/CompareComplyV1/Models/CategoryComparison.swift b/Source/CompareComplyV1/Models/CategoryComparison.swift new file mode 100644 index 000000000..60406d180 --- /dev/null +++ b/Source/CompareComplyV1/Models/CategoryComparison.swift @@ -0,0 +1,64 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Information defining an element's subject matter. + */ +public struct CategoryComparison: Codable, Equatable { + + /** + The category of the associated element. + */ + public enum Label: String { + case amendments = "Amendments" + case assetUse = "Asset Use" + case assignments = "Assignments" + case audits = "Audits" + case businessContinuity = "Business Continuity" + case communication = "Communication" + case confidentiality = "Confidentiality" + case deliverables = "Deliverables" + case delivery = "Delivery" + case disputeResolution = "Dispute Resolution" + case forceMajeure = "Force Majeure" + case indemnification = "Indemnification" + case insurance = "Insurance" + case intellectualProperty = "Intellectual Property" + case liability = "Liability" + case paymentTermsBilling = "Payment Terms & Billing" + case pricingTaxes = "Pricing & Taxes" + case privacy = "Privacy" + case responsibilities = "Responsibilities" + case safetyAndSecurity = "Safety and Security" + case scopeOfWork = "Scope of Work" + case subcontracts = "Subcontracts" + case termTermination = "Term & Termination" + case warranties = "Warranties" + } + + /** + The category of the associated element. + */ + public var label: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case label = "label" + } + +} diff --git a/Source/CompareComplyV1/Models/ClassifyReturn.swift b/Source/CompareComplyV1/Models/ClassifyReturn.swift index b5bd1fd51..fb64c61ea 100644 --- a/Source/CompareComplyV1/Models/ClassifyReturn.swift +++ b/Source/CompareComplyV1/Models/ClassifyReturn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Foundation /** - The analysis of objects returned by the `/v1/element_classification` method. + The analysis of objects returned by the **Element classification** method. */ public struct ClassifyReturn: Codable, Equatable { @@ -27,7 +27,7 @@ public struct ClassifyReturn: Codable, Equatable { public var document: Document? /** - The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid + The analysis model used to classify the input document. For the **Element classification** method, the only valid value is `contracts`. */ public var modelID: String? @@ -58,20 +58,26 @@ public struct ClassifyReturn: Codable, Equatable { public var parties: [Parties]? /** - The effective dates of the input document. + The date or dates on which the document becomes effective. */ public var effectiveDates: [EffectiveDates]? /** - The monetary amounts identified in the input document. + The monetary amounts that identify the total amount of the contract that needs to be paid from one party to + another. */ public var contractAmounts: [ContractAmts]? /** - The input document's termination dates. + The date or dates on which the document is to be terminated. */ public var terminationDates: [TerminationDates]? + /** + The document's contract type or types as declared in the document. + */ + public var contractType: [ContractType]? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case document = "document" @@ -84,6 +90,7 @@ public struct ClassifyReturn: Codable, Equatable { case effectiveDates = "effective_dates" case contractAmounts = "contract_amounts" case terminationDates = "termination_dates" + case contractType = "contract_type" } } diff --git a/Source/CompareComplyV1/Models/ColumnHeaderIds.swift b/Source/CompareComplyV1/Models/ColumnHeaderIDs.swift similarity index 96% rename from Source/CompareComplyV1/Models/ColumnHeaderIds.swift rename to Source/CompareComplyV1/Models/ColumnHeaderIDs.swift index 6a84a1881..dddafb315 100644 --- a/Source/CompareComplyV1/Models/ColumnHeaderIds.swift +++ b/Source/CompareComplyV1/Models/ColumnHeaderIDs.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ColumnHeaderTexts.swift b/Source/CompareComplyV1/Models/ColumnHeaderTexts.swift index 472f1dde3..5ecb844ac 100644 --- a/Source/CompareComplyV1/Models/ColumnHeaderTexts.swift +++ b/Source/CompareComplyV1/Models/ColumnHeaderTexts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ColumnHeaderTextsNormalized.swift b/Source/CompareComplyV1/Models/ColumnHeaderTextsNormalized.swift index 3e06dc493..d9ad38c8e 100644 --- a/Source/CompareComplyV1/Models/ColumnHeaderTextsNormalized.swift +++ b/Source/CompareComplyV1/Models/ColumnHeaderTextsNormalized.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ColumnHeaders.swift b/Source/CompareComplyV1/Models/ColumnHeaders.swift index 77903c3eb..00a50b61d 100644 --- a/Source/CompareComplyV1/Models/ColumnHeaders.swift +++ b/Source/CompareComplyV1/Models/ColumnHeaders.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,7 @@ import RestKit public struct ColumnHeaders: Codable, Equatable { /** - A string value in the format `columnHeader-x-y`, where `x` and `y` are the begin and end offsets of this column - header cell in the input document. + The unique ID of the cell in the current table. */ public var cellID: String? diff --git a/Source/CompareComplyV1/Models/CompareReturn.swift b/Source/CompareComplyV1/Models/CompareReturn.swift index c3849714a..300d44ac9 100644 --- a/Source/CompareComplyV1/Models/CompareReturn.swift +++ b/Source/CompareComplyV1/Models/CompareReturn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,38 +22,38 @@ import Foundation public struct CompareReturn: Codable, Equatable { /** - Information about the documents being compared. + The analysis model used to compare the input documents. For the **Compare two documents** method, the only valid + value is `contracts`. */ - public var documents: [Document]? + public var modelID: String? /** - A list of pairs of elements that semantically align between the compared documents. + The version of the analysis model identified by the value of the `model_id` key. */ - public var alignedElements: [AlignedElement]? + public var modelVersion: String? /** - A list of elements that do not semantically align between the compared documents. + Information about the documents being compared. */ - public var unalignedElements: [UnalignedElement]? + public var documents: [Document]? /** - The analysis model used to classify the input document. For the `/v1/element_classification` method, the only valid - value is `contracts`. + A list of pairs of elements that semantically align between the compared documents. */ - public var modelID: String? + public var alignedElements: [AlignedElement]? /** - The version of the analysis model identified by the value of the `model_id` key. + A list of elements that do not semantically align between the compared documents. */ - public var modelVersion: String? + public var unalignedElements: [UnalignedElement]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { + case modelID = "model_id" + case modelVersion = "model_version" case documents = "documents" case alignedElements = "aligned_elements" case unalignedElements = "unaligned_elements" - case modelID = "model_id" - case modelVersion = "model_version" } } diff --git a/Source/CompareComplyV1/Models/Contact.swift b/Source/CompareComplyV1/Models/Contact.swift index 56ff63b88..273050ca2 100644 --- a/Source/CompareComplyV1/Models/Contact.swift +++ b/Source/CompareComplyV1/Models/Contact.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ContractAmts.swift b/Source/CompareComplyV1/Models/ContractAmts.swift index b64e75782..76126fe49 100644 --- a/Source/CompareComplyV1/Models/ContractAmts.swift +++ b/Source/CompareComplyV1/Models/ContractAmts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ContractType.swift b/Source/CompareComplyV1/Models/ContractType.swift new file mode 100644 index 000000000..e215d34ea --- /dev/null +++ b/Source/CompareComplyV1/Models/ContractType.swift @@ -0,0 +1,56 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + The contract type identified in the input document. + */ +public struct ContractType: Codable, Equatable { + + /** + The confidence level in the identification of the termination date. + */ + public enum ConfidenceLevel: String { + case high = "High" + case medium = "Medium" + case low = "Low" + } + + /** + The contract type. + */ + public var text: String? + + /** + The confidence level in the identification of the termination date. + */ + public var confidenceLevel: String? + + /** + The numeric location of the identified element in the document, represented with two integers labeled `begin` and + `end`. + */ + public var location: Location? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case confidenceLevel = "confidence_level" + case location = "location" + } + +} diff --git a/Source/CompareComplyV1/Models/DocCounts.swift b/Source/CompareComplyV1/Models/DocCounts.swift index cef6e8ab4..e23e961fe 100644 --- a/Source/CompareComplyV1/Models/DocCounts.swift +++ b/Source/CompareComplyV1/Models/DocCounts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/DocInfo.swift b/Source/CompareComplyV1/Models/DocInfo.swift index a14d4447a..7c46999f2 100644 --- a/Source/CompareComplyV1/Models/DocInfo.swift +++ b/Source/CompareComplyV1/Models/DocInfo.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/DocStructure.swift b/Source/CompareComplyV1/Models/DocStructure.swift index 224b57443..1319cc89f 100644 --- a/Source/CompareComplyV1/Models/DocStructure.swift +++ b/Source/CompareComplyV1/Models/DocStructure.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Document.swift b/Source/CompareComplyV1/Models/Document.swift index ffee09c89..950f75b07 100644 --- a/Source/CompareComplyV1/Models/Document.swift +++ b/Source/CompareComplyV1/Models/Document.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/EffectiveDates.swift b/Source/CompareComplyV1/Models/EffectiveDates.swift index d36bf72ac..edb779faf 100644 --- a/Source/CompareComplyV1/Models/EffectiveDates.swift +++ b/Source/CompareComplyV1/Models/EffectiveDates.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Element.swift b/Source/CompareComplyV1/Models/Element.swift index 63db58cfe..cbca15919 100644 --- a/Source/CompareComplyV1/Models/Element.swift +++ b/Source/CompareComplyV1/Models/Element.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ElementLocations.swift b/Source/CompareComplyV1/Models/ElementLocations.swift index 46eac9468..507329494 100644 --- a/Source/CompareComplyV1/Models/ElementLocations.swift +++ b/Source/CompareComplyV1/Models/ElementLocations.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ElementPair.swift b/Source/CompareComplyV1/Models/ElementPair.swift index ba1d92985..028b7effa 100644 --- a/Source/CompareComplyV1/Models/ElementPair.swift +++ b/Source/CompareComplyV1/Models/ElementPair.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ public struct ElementPair: Codable, Equatable { public var documentLabel: String? /** - The text of the element. + The contents of the element. */ public var text: String? @@ -39,14 +39,14 @@ public struct ElementPair: Codable, Equatable { public var location: Location? /** - Description of the action specified by the element and whom it affects. + Description of the action specified by the element and whom it affects. */ - public var types: [TypeLabel]? + public var types: [TypeLabelComparison]? /** List of functional categories into which the element falls; in other words, the subject matter of the element. */ - public var categories: [Category]? + public var categories: [CategoryComparison]? /** List of document attributes. diff --git a/Source/CompareComplyV1/Models/FeedbackDataInput.swift b/Source/CompareComplyV1/Models/FeedbackDataInput.swift index 012d2c0fc..7a4542f5f 100644 --- a/Source/CompareComplyV1/Models/FeedbackDataInput.swift +++ b/Source/CompareComplyV1/Models/FeedbackDataInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/FeedbackDataOutput.swift b/Source/CompareComplyV1/Models/FeedbackDataOutput.swift index c5828be6b..7fcaed7ac 100644 --- a/Source/CompareComplyV1/Models/FeedbackDataOutput.swift +++ b/Source/CompareComplyV1/Models/FeedbackDataOutput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/FeedbackDeleted.swift b/Source/CompareComplyV1/Models/FeedbackDeleted.swift index 4d9a6147a..099b8b151 100644 --- a/Source/CompareComplyV1/Models/FeedbackDeleted.swift +++ b/Source/CompareComplyV1/Models/FeedbackDeleted.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/FeedbackInput.swift b/Source/CompareComplyV1/Models/FeedbackInput.swift index 33f5eef48..0476cf658 100644 --- a/Source/CompareComplyV1/Models/FeedbackInput.swift +++ b/Source/CompareComplyV1/Models/FeedbackInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/FeedbackList.swift b/Source/CompareComplyV1/Models/FeedbackList.swift index 2720fa3bf..ae1b2ed8b 100644 --- a/Source/CompareComplyV1/Models/FeedbackList.swift +++ b/Source/CompareComplyV1/Models/FeedbackList.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/FeedbackReturn.swift b/Source/CompareComplyV1/Models/FeedbackReturn.swift index 3ef5b0918..d84bd6dd2 100644 --- a/Source/CompareComplyV1/Models/FeedbackReturn.swift +++ b/Source/CompareComplyV1/Models/FeedbackReturn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/GetFeedback.swift b/Source/CompareComplyV1/Models/GetFeedback.swift index eac0ed6a4..9f008b7e5 100644 --- a/Source/CompareComplyV1/Models/GetFeedback.swift +++ b/Source/CompareComplyV1/Models/GetFeedback.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/HTMLReturn.swift b/Source/CompareComplyV1/Models/HTMLReturn.swift index c63012048..2bf24f111 100644 --- a/Source/CompareComplyV1/Models/HTMLReturn.swift +++ b/Source/CompareComplyV1/Models/HTMLReturn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Key.swift b/Source/CompareComplyV1/Models/Key.swift new file mode 100644 index 000000000..e53f4d36c --- /dev/null +++ b/Source/CompareComplyV1/Models/Key.swift @@ -0,0 +1,47 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + A key in a key-value pair. + */ +public struct Key: Codable, Equatable { + + /** + The unique ID of the key in the table. + */ + public var cellID: String? + + /** + The numeric location of the identified element in the document, represented with two integers labeled `begin` and + `end`. + */ + public var location: Location? + + /** + The text content of the table cell without HTML markup. + */ + public var text: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case cellID = "cell_id" + case location = "location" + case text = "text" + } + +} diff --git a/Source/CompareComplyV1/Models/KeyValuePair.swift b/Source/CompareComplyV1/Models/KeyValuePair.swift new file mode 100644 index 000000000..fa7661942 --- /dev/null +++ b/Source/CompareComplyV1/Models/KeyValuePair.swift @@ -0,0 +1,40 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Key-value pairs detected across cell boundaries. + */ +public struct KeyValuePair: Codable, Equatable { + + /** + A key in a key-value pair. + */ + public var key: Key? + + /** + A value in a key-value pair. + */ + public var value: Value? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case key = "key" + case value = "value" + } + +} diff --git a/Source/CompareComplyV1/Models/Label.swift b/Source/CompareComplyV1/Models/Label.swift index 05e4e4a5d..9b0ecf0a4 100644 --- a/Source/CompareComplyV1/Models/Label.swift +++ b/Source/CompareComplyV1/Models/Label.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/LeadingSentence.swift b/Source/CompareComplyV1/Models/LeadingSentence.swift index f25c9ad69..211863577 100644 --- a/Source/CompareComplyV1/Models/LeadingSentence.swift +++ b/Source/CompareComplyV1/Models/LeadingSentence.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Location.swift b/Source/CompareComplyV1/Models/Location.swift index fefb9f168..e2fef4a16 100644 --- a/Source/CompareComplyV1/Models/Location.swift +++ b/Source/CompareComplyV1/Models/Location.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/OriginalLabelsIn.swift b/Source/CompareComplyV1/Models/OriginalLabelsIn.swift index 0fb233000..fbf6e8130 100644 --- a/Source/CompareComplyV1/Models/OriginalLabelsIn.swift +++ b/Source/CompareComplyV1/Models/OriginalLabelsIn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/OriginalLabelsOut.swift b/Source/CompareComplyV1/Models/OriginalLabelsOut.swift index d1af97a70..784ecf159 100644 --- a/Source/CompareComplyV1/Models/OriginalLabelsOut.swift +++ b/Source/CompareComplyV1/Models/OriginalLabelsOut.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Pagination.swift b/Source/CompareComplyV1/Models/Pagination.swift index 2d71cd52a..1d19f6da0 100644 --- a/Source/CompareComplyV1/Models/Pagination.swift +++ b/Source/CompareComplyV1/Models/Pagination.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Parties.swift b/Source/CompareComplyV1/Models/Parties.swift index ee7b36ebf..41458a569 100644 --- a/Source/CompareComplyV1/Models/Parties.swift +++ b/Source/CompareComplyV1/Models/Parties.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/RowHeaderIds.swift b/Source/CompareComplyV1/Models/RowHeaderIDs.swift similarity index 96% rename from Source/CompareComplyV1/Models/RowHeaderIds.swift rename to Source/CompareComplyV1/Models/RowHeaderIDs.swift index 09707382d..cd6248ec0 100644 --- a/Source/CompareComplyV1/Models/RowHeaderIds.swift +++ b/Source/CompareComplyV1/Models/RowHeaderIDs.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/RowHeaderTexts.swift b/Source/CompareComplyV1/Models/RowHeaderTexts.swift index 81f42dc39..1bff64f2f 100644 --- a/Source/CompareComplyV1/Models/RowHeaderTexts.swift +++ b/Source/CompareComplyV1/Models/RowHeaderTexts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/RowHeaderTextsNormalized.swift b/Source/CompareComplyV1/Models/RowHeaderTextsNormalized.swift index ddfbd7484..ed0a372c4 100644 --- a/Source/CompareComplyV1/Models/RowHeaderTextsNormalized.swift +++ b/Source/CompareComplyV1/Models/RowHeaderTextsNormalized.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/RowHeaders.swift b/Source/CompareComplyV1/Models/RowHeaders.swift index 02190ba16..cd35b873a 100644 --- a/Source/CompareComplyV1/Models/RowHeaders.swift +++ b/Source/CompareComplyV1/Models/RowHeaders.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import Foundation public struct RowHeaders: Codable, Equatable { /** - A string value in the format `rowHeader-x-y`, where `x` and `y` are the begin and end offsets of this row header - cell in the input document. + The unique ID of the cell in the current table. */ public var cellID: String? diff --git a/Source/CompareComplyV1/Models/SectionTitle.swift b/Source/CompareComplyV1/Models/SectionTitle.swift index c278b3ca5..2cb64c908 100644 --- a/Source/CompareComplyV1/Models/SectionTitle.swift +++ b/Source/CompareComplyV1/Models/SectionTitle.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/SectionTitles.swift b/Source/CompareComplyV1/Models/SectionTitles.swift index 9080f137f..52fa9f006 100644 --- a/Source/CompareComplyV1/Models/SectionTitles.swift +++ b/Source/CompareComplyV1/Models/SectionTitles.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/ShortDoc.swift b/Source/CompareComplyV1/Models/ShortDoc.swift index 1eca612b6..e5ea56659 100644 --- a/Source/CompareComplyV1/Models/ShortDoc.swift +++ b/Source/CompareComplyV1/Models/ShortDoc.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/TableHeaders.swift b/Source/CompareComplyV1/Models/TableHeaders.swift index 54a79b2d2..fada40d17 100644 --- a/Source/CompareComplyV1/Models/TableHeaders.swift +++ b/Source/CompareComplyV1/Models/TableHeaders.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,7 @@ import RestKit public struct TableHeaders: Codable, Equatable { /** - String value in the format `tableHeader-x-y` where `x` and `y` are the `begin` and `end` offsets, respectfully, of - the cell value in the input document. + The unique ID of the cell in the current table. */ public var cellID: String? diff --git a/Source/CompareComplyV1/Models/TableReturn.swift b/Source/CompareComplyV1/Models/TableReturn.swift index de4ee57bd..1e5c2d4c4 100644 --- a/Source/CompareComplyV1/Models/TableReturn.swift +++ b/Source/CompareComplyV1/Models/TableReturn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Tables.swift b/Source/CompareComplyV1/Models/Tables.swift index b87385d82..97b799562 100644 --- a/Source/CompareComplyV1/Models/Tables.swift +++ b/Source/CompareComplyV1/Models/Tables.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,11 @@ public struct Tables: Codable, Equatable { */ public var columnHeaders: [ColumnHeaders]? + /** + An array of key-value pairs identified in the current table. + */ + public var keyValuePairs: [KeyValuePair]? + /** An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. @@ -68,6 +73,7 @@ public struct Tables: Codable, Equatable { case tableHeaders = "table_headers" case rowHeaders = "row_headers" case columnHeaders = "column_headers" + case keyValuePairs = "key_value_pairs" case bodyCells = "body_cells" } diff --git a/Source/CompareComplyV1/Models/TerminationDates.swift b/Source/CompareComplyV1/Models/TerminationDates.swift index 4db15fb8c..50932955d 100644 --- a/Source/CompareComplyV1/Models/TerminationDates.swift +++ b/Source/CompareComplyV1/Models/TerminationDates.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/TypeLabel.swift b/Source/CompareComplyV1/Models/TypeLabel.swift index 9e097c82f..fd704aad0 100644 --- a/Source/CompareComplyV1/Models/TypeLabel.swift +++ b/Source/CompareComplyV1/Models/TypeLabel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/TypeLabelComparison.swift b/Source/CompareComplyV1/Models/TypeLabelComparison.swift new file mode 100644 index 000000000..d1e2b7b73 --- /dev/null +++ b/Source/CompareComplyV1/Models/TypeLabelComparison.swift @@ -0,0 +1,35 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Identification of a specific type. + */ +public struct TypeLabelComparison: Codable, Equatable { + + /** + A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified + `party`, and the `party` object identifies the affected party. + */ + public var label: Label? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case label = "label" + } + +} diff --git a/Source/CompareComplyV1/Models/UnalignedElement.swift b/Source/CompareComplyV1/Models/UnalignedElement.swift index ae25ad6d8..497ed4cb8 100644 --- a/Source/CompareComplyV1/Models/UnalignedElement.swift +++ b/Source/CompareComplyV1/Models/UnalignedElement.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import Foundation public struct UnalignedElement: Codable, Equatable { /** - The label assigned to the document by the value of the `file_1_label` or `file_2_label` parameters on the - `/v1/compare` method. + The label assigned to the document by the value of the `file_1_label` or `file_2_label` parameters on the **Compare + two documents** method. */ public var documentLabel: String? @@ -41,12 +41,12 @@ public struct UnalignedElement: Codable, Equatable { /** Description of the action specified by the element and whom it affects. */ - public var types: [TypeLabel]? + public var types: [TypeLabelComparison]? /** List of functional categories into which the element falls; in other words, the subject matter of the element. */ - public var categories: [Category]? + public var categories: [CategoryComparison]? /** List of document attributes. diff --git a/Source/CompareComplyV1/Models/UpdatedLabelsIn.swift b/Source/CompareComplyV1/Models/UpdatedLabelsIn.swift index 8185639a5..115da60a7 100644 --- a/Source/CompareComplyV1/Models/UpdatedLabelsIn.swift +++ b/Source/CompareComplyV1/Models/UpdatedLabelsIn.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/UpdatedLabelsOut.swift b/Source/CompareComplyV1/Models/UpdatedLabelsOut.swift index e522f0930..a14f15e59 100644 --- a/Source/CompareComplyV1/Models/UpdatedLabelsOut.swift +++ b/Source/CompareComplyV1/Models/UpdatedLabelsOut.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/CompareComplyV1/Models/Value.swift b/Source/CompareComplyV1/Models/Value.swift new file mode 100644 index 000000000..70ab52ab7 --- /dev/null +++ b/Source/CompareComplyV1/Models/Value.swift @@ -0,0 +1,47 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + A value in a key-value pair. + */ +public struct Value: Codable, Equatable { + + /** + The unique ID of the value in the table. + */ + public var cellID: String? + + /** + The numeric location of the identified element in the document, represented with two integers labeled `begin` and + `end`. + */ + public var location: Location? + + /** + The text content of the table cell without HTML markup. + */ + public var text: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case cellID = "cell_id" + case location = "location" + case text = "text" + } + +} diff --git a/Source/DiscoveryV1/Discovery.swift b/Source/DiscoveryV1/Discovery.swift index 2501366f3..af36539cd 100644 --- a/Source/DiscoveryV1/Discovery.swift +++ b/Source/DiscoveryV1/Discovery.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,22 +38,23 @@ public class Discovery { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `Discovery` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "discovery") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "discovery") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -63,20 +64,22 @@ public class Discovery { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `Discovery` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -90,6 +93,7 @@ public class Discovery { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -100,8 +104,9 @@ public class Discovery { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -124,19 +129,25 @@ public class Discovery { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(description)) = json["description"] { - metadata["description"] = description - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -165,7 +176,7 @@ public class Discovery { name: name, description: description, size: size) - guard let body = try? JSONEncoder().encode(createEnvironmentRequest) else { + guard let body = try? JSON.encoder.encode(createEnvironmentRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -175,8 +186,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEnvironment") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEnvironment") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -219,8 +230,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listEnvironments") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listEnvironments") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -263,8 +274,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getEnvironment") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getEnvironment") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -318,7 +329,7 @@ public class Discovery { name: name, description: description, size: size) - guard let body = try? JSONEncoder().encode(updateEnvironmentRequest) else { + guard let body = try? JSON.encoder.encode(updateEnvironmentRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -328,8 +339,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateEnvironment") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateEnvironment") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -375,8 +386,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteEnvironment") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteEnvironment") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -424,8 +435,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listFields") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listFields") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -494,7 +505,7 @@ public class Discovery { enrichments: enrichments, normalizations: normalizations, source: source) - guard let body = try? JSONEncoder().encode(createConfigurationRequest) else { + guard let body = try? JSON.encoder.encode(createConfigurationRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -504,8 +515,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createConfiguration") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createConfiguration") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -555,8 +566,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listConfigurations") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listConfigurations") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -606,8 +617,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getConfiguration") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getConfiguration") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -677,7 +688,7 @@ public class Discovery { enrichments: enrichments, normalizations: normalizations, source: source) - guard let body = try? JSONEncoder().encode(updateConfigurationRequest) else { + guard let body = try? JSON.encoder.encode(updateConfigurationRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -687,8 +698,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateConfiguration") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateConfiguration") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -741,8 +752,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteConfiguration") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteConfiguration") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -781,12 +792,11 @@ public class Discovery { present at the same time), then request is rejected. The maximum supported configuration size is 1 MB. Configuration parts larger than 1 MB are rejected. See the `GET /configurations/{configuration_id}` operation for an example configuration. - - parameter step: Specify to only run the input document through the given step instead of running the input - document through the entire ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. - - parameter configurationID: The ID of the configuration to use to process the document. If the **configuration** - form part is also provided (both are present at the same time), then the request will be rejected. - - parameter file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files - larger than 50 megabytes is rejected. + - parameter file: The content of the document to ingest. The maximum supported file size when adding a file to a + collection is 50 megabytes, the maximum supported file size when testing a confiruration is 1 megabyte. Files + larger than the supported size are rejected. + - parameter filename: The filename for file. + - parameter fileContentType: The content type of file. - parameter metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. @@ -794,18 +804,22 @@ public class Discovery { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. - - parameter fileContentType: The content type of file. + - parameter step: Specify to only run the input document through the given step instead of running the input + document through the entire ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. + - parameter configurationID: The ID of the configuration to use to process the document. If the **configuration** + form part is also provided (both are present at the same time), then the request will be rejected. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func testConfigurationInEnvironment( environmentID: String, configuration: String? = nil, + file: Data? = nil, + filename: String? = nil, + fileContentType: String? = nil, + metadata: String? = nil, step: String? = nil, configurationID: String? = nil, - file: URL? = nil, - metadata: String? = nil, - fileContentType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -817,12 +831,7 @@ public class Discovery { } } if let file = file { - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: filename ?? "filename") } if let metadata = metadata { if let metadataData = metadata.data(using: .utf8) { @@ -839,8 +848,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "testConfigurationInEnvironment") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "testConfigurationInEnvironment") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -904,7 +913,7 @@ public class Discovery { description: description, configurationID: configurationID, language: language) - guard let body = try? JSONEncoder().encode(createCollectionRequest) else { + guard let body = try? JSON.encoder.encode(createCollectionRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -914,8 +923,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCollection") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCollection") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -965,8 +974,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCollections") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCollections") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1016,8 +1025,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCollection") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCollection") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1069,7 +1078,7 @@ public class Discovery { name: name, description: description, configurationID: configurationID) - guard let body = try? JSONEncoder().encodeIfPresent(updateCollectionRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(updateCollectionRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1079,8 +1088,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCollection") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCollection") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1128,8 +1137,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCollection") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCollection") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1177,8 +1186,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCollectionFields") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCollectionFields") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1227,8 +1236,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listExpansions") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listExpansions") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1287,7 +1296,7 @@ public class Discovery { // construct body let createExpansionsRequest = Expansions( expansions: expansions) - guard let body = try? JSONEncoder().encode(createExpansionsRequest) else { + guard let body = try? JSON.encoder.encode(createExpansionsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1297,8 +1306,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createExpansions") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createExpansions") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1349,9 +1358,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteExpansions") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteExpansions") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -1398,8 +1406,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTokenizationDictionaryStatus") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTokenizationDictionaryStatus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1448,7 +1456,7 @@ public class Discovery { // construct body let createTokenizationDictionaryRequest = TokenDict( tokenizationRules: tokenizationRules) - guard let body = try? JSONEncoder().encodeIfPresent(createTokenizationDictionaryRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(createTokenizationDictionaryRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1458,8 +1466,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createTokenizationDictionary") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createTokenizationDictionary") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1509,9 +1517,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTokenizationDictionary") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTokenizationDictionary") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -1558,6 +1565,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getStopwordListStatus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1592,24 +1601,21 @@ public class Discovery { - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. - parameter stopwordFile: The content of the stopword list to ingest. + - parameter stopwordFilename: The filename for stopwordFile. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createStopwordList( environmentID: String, collectionID: String, - stopwordFile: URL, + stopwordFile: Data, + stopwordFilename: String, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: stopwordFile, withName: "stopword_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(stopwordFile.path)")) - return - } + multipartFormData.append(stopwordFile, withName: "stopword_file", fileName: stopwordFilename) guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -1620,8 +1626,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createStopwordList") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createStopwordList") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -1672,9 +1678,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteStopwordList") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteStopwordList") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -1714,12 +1719,17 @@ public class Discovery { * The following field names are reserved and will be filtered out if present after normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, `+`, or `-` * Fields with empty name values after normalization are filtered out before indexing. - * Fields containing the following characters after normalization are filtered out before indexing: `#` and `,`. + * Fields containing the following characters after normalization are filtered out before indexing: `#` and `,` + **Note:** Documents can be added with a specific **document_id** by using the + **_/v1/environments/{environment_id}/collections/{collection_id}/documents** method. - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. - - parameter file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files - larger than 50 megabytes is rejected. + - parameter file: The content of the document to ingest. The maximum supported file size when adding a file to a + collection is 50 megabytes, the maximum supported file size when testing a confiruration is 1 megabyte. Files + larger than the supported size are rejected. + - parameter filename: The filename for file. + - parameter fileContentType: The content type of file. - parameter metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. @@ -1727,28 +1737,23 @@ public class Discovery { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. - - parameter fileContentType: The content type of file. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func addDocument( environmentID: String, collectionID: String, - file: URL? = nil, - metadata: String? = nil, + file: Data? = nil, + filename: String? = nil, fileContentType: String? = nil, + metadata: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() if let file = file { - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: filename ?? "filename") } if let metadata = metadata { if let metadataData = metadata.data(using: .utf8) { @@ -1765,8 +1770,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addDocument") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addDocument") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -1820,8 +1825,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getDocumentStatus") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getDocumentStatus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1851,13 +1856,19 @@ public class Discovery { /** Update a document. - Replace an existing document. Starts ingesting a document with optional metadata. + Replace an existing document or add a document with a specified **document_id**. Starts ingesting a document with + optional metadata. + **Note:** When uploading a new document with this method it automatically replaces any document stored with the + same **document_id** if it exists. - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. - parameter documentID: The ID of the document. - - parameter file: The content of the document to ingest. The maximum supported file size is 50 megabytes. Files - larger than 50 megabytes is rejected. + - parameter file: The content of the document to ingest. The maximum supported file size when adding a file to a + collection is 50 megabytes, the maximum supported file size when testing a confiruration is 1 megabyte. Files + larger than the supported size are rejected. + - parameter filename: The filename for file. + - parameter fileContentType: The content type of file. - parameter metadata: If you're using the Data Crawler to upload your documents, you can test a document against the type of metadata that the Data Crawler might send. The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are rejected. @@ -1865,7 +1876,6 @@ public class Discovery { \"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" } ```. - - parameter fileContentType: The content type of file. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -1873,21 +1883,17 @@ public class Discovery { environmentID: String, collectionID: String, documentID: String, - file: URL? = nil, - metadata: String? = nil, + file: Data? = nil, + filename: String? = nil, fileContentType: String? = nil, + metadata: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() if let file = file { - do { - try multipartFormData.append(file: file, withName: "file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(file.path)")) - return - } + multipartFormData.append(file, withName: "file", mimeType: fileContentType, fileName: filename ?? "filename") } if let metadata = metadata { if let metadataData = metadata.data(using: .utf8) { @@ -1904,8 +1910,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateDocument") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateDocument") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -1958,8 +1964,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDocument") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDocument") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1991,7 +1997,8 @@ public class Discovery { Complex queries might be too long for a standard method query. By using this method, you can construct longer queries. However, these queries may take longer to complete than the standard method. For details, see the - [Discovery service documentation](https://cloud.ibm.com/docs/services/discovery/using.html). + [Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. @@ -2021,7 +2028,7 @@ public class Discovery { - parameter passagesCount: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. - parameter passagesCharacters: The approximate number of characters that any one passage will have. - - parameter deduplicate: When `true` and used with a Watson Discovery News collection, duplicate results (based + - parameter deduplicate: When `true`, and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. - parameter deduplicateField: When specified, duplicate results based on the field specified are removed from the @@ -2094,7 +2101,7 @@ public class Discovery { similarDocumentIDs: similarDocumentIDs, similarFields: similarFields, bias: bias) - guard let body = try? JSONEncoder().encodeIfPresent(queryRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(queryRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2104,8 +2111,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "query") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "query") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" if let loggingOptOut = loggingOptOut { @@ -2142,8 +2149,8 @@ public class Discovery { Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/using.html) for more details on the query - language. + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts) for + more details on the query language. - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. @@ -2159,10 +2166,12 @@ public class Discovery { - parameter aggregation: An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. - - parameter count: Number of results to return. + - parameter count: Number of results to return. The maximum for the **count** and **offset** values together in + any one query is **10000**. - parameter returnFields: A comma-separated list of the portion of the document hierarchy to return. - parameter offset: The number of query results to skip at the beginning. For example, if the total number of - results that are returned is 10 and the offset is 8, it returns the last two results. + results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the + **count** and **offset** values together in any one query is **10000**. - parameter sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2215,8 +2224,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryNotices") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryNotices") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2316,7 +2325,8 @@ public class Discovery { Complex queries might be too long for a standard method query. By using this method, you can construct longer queries. However, these queries may take longer to complete than the standard method. For details, see the - [Discovery service documentation](https://cloud.ibm.com/docs/services/discovery/using.html). + [Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). - parameter environmentID: The ID of the environment. - parameter filter: A cacheable query that excludes documents that don't mention the query content. Filter @@ -2345,7 +2355,7 @@ public class Discovery { - parameter passagesCount: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. - parameter passagesCharacters: The approximate number of characters that any one passage will have. - - parameter deduplicate: When `true` and used with a Watson Discovery News collection, duplicate results (based + - parameter deduplicate: When `true`, and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. - parameter deduplicateField: When specified, duplicate results based on the field specified are removed from the @@ -2417,7 +2427,7 @@ public class Discovery { similarDocumentIDs: similarDocumentIDs, similarFields: similarFields, bias: bias) - guard let body = try? JSONEncoder().encodeIfPresent(federatedQueryRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(federatedQueryRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2427,8 +2437,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "federatedQuery") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "federatedQuery") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" if let loggingOptOut = loggingOptOut { @@ -2465,8 +2475,8 @@ public class Discovery { Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/using.html) for more details on the query - language. + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts) for + more details on the query language. - parameter environmentID: The ID of the environment. - parameter collectionIDs: A comma-separated list of collection IDs to be queried against. @@ -2481,10 +2491,12 @@ public class Discovery { - parameter aggregation: An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. - - parameter count: Number of results to return. + - parameter count: Number of results to return. The maximum for the **count** and **offset** values together in + any one query is **10000**. - parameter returnFields: A comma-separated list of the portion of the document hierarchy to return. - parameter offset: The number of query results to skip at the beginning. For example, if the total number of - results that are returned is 10 and the offset is 8, it returns the last two results. + results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the + **count** and **offset** values together in any one query is **10000**. - parameter sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2528,8 +2540,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "federatedQueryNotices") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "federatedQueryNotices") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2612,7 +2624,7 @@ public class Discovery { /** Knowledge Graph entity query. - See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery/building-kg.html) for + See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) for more details. - parameter environmentID: The ID of the environment. @@ -2647,7 +2659,7 @@ public class Discovery { context: context, count: count, evidenceCount: evidenceCount) - guard let body = try? JSONEncoder().encode(queryEntitiesRequest) else { + guard let body = try? JSON.encoder.encode(queryEntitiesRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2657,8 +2669,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryEntities") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryEntities") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2690,7 +2702,7 @@ public class Discovery { /** Knowledge Graph relationship query. - See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery/building-kg.html) for + See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) for more details. - parameter environmentID: The ID of the environment. @@ -2702,7 +2714,7 @@ public class Discovery { - parameter sort: The sorting method for the relationships, can be `score` or `frequency`. `frequency` is the number of unique times each entity is identified. The default is `score`. This parameter cannot be used in the same query as the **bias** parameter. - - parameter filter: Filters to apply to the relationship query. + - parameter filter: - parameter count: The number of results to return. The default is `10`. The maximum is `1000`. - parameter evidenceCount: The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000. @@ -2729,7 +2741,7 @@ public class Discovery { filter: filter, count: count, evidenceCount: evidenceCount) - guard let body = try? JSONEncoder().encode(queryRelationsRequest) else { + guard let body = try? JSON.encoder.encode(queryRelationsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2739,8 +2751,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryRelations") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryRelations") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2790,8 +2802,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listTrainingData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listTrainingData") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2825,9 +2837,9 @@ public class Discovery { - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. - - parameter naturalLanguageQuery: - - parameter filter: - - parameter examples: + - parameter naturalLanguageQuery: The natural text query for the new training query. + - parameter filter: The filter used on the collection before the **natural_language_query** is applied. + - parameter examples: Array of training examples. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -2845,7 +2857,7 @@ public class Discovery { naturalLanguageQuery: naturalLanguageQuery, filter: filter, examples: examples) - guard let body = try? JSONEncoder().encode(addTrainingDataRequest) else { + guard let body = try? JSON.encoder.encode(addTrainingDataRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2855,8 +2867,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addTrainingData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addTrainingData") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2906,9 +2918,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAllTrainingData") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAllTrainingData") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -2957,8 +2968,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTrainingData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTrainingData") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3008,9 +3019,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTrainingData") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTrainingData") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -3059,8 +3069,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listTrainingExamples") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listTrainingExamples") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3095,9 +3105,9 @@ public class Discovery { - parameter environmentID: The ID of the environment. - parameter collectionID: The ID of the collection. - parameter queryID: The ID of the query used for training. - - parameter documentID: - - parameter crossReference: - - parameter relevance: + - parameter documentID: The document ID associated with this training example. + - parameter crossReference: The cross reference associated with this training example. + - parameter relevance: The relevance of the training example. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -3116,7 +3126,7 @@ public class Discovery { documentID: documentID, crossReference: crossReference, relevance: relevance) - guard let body = try? JSONEncoder().encode(createTrainingExampleRequest) else { + guard let body = try? JSON.encoder.encode(createTrainingExampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -3126,8 +3136,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createTrainingExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createTrainingExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -3181,9 +3191,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTrainingExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteTrainingExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -3218,8 +3227,8 @@ public class Discovery { - parameter collectionID: The ID of the collection. - parameter queryID: The ID of the query used for training. - parameter exampleID: The ID of the document as it is indexed. - - parameter crossReference: - - parameter relevance: + - parameter crossReference: The example to add. + - parameter relevance: The relevance value for this example. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -3237,7 +3246,7 @@ public class Discovery { let updateTrainingExampleRequest = TrainingExamplePatch( crossReference: crossReference, relevance: relevance) - guard let body = try? JSONEncoder().encode(updateTrainingExampleRequest) else { + guard let body = try? JSON.encoder.encode(updateTrainingExampleRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -3247,8 +3256,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateTrainingExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateTrainingExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -3302,8 +3311,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTrainingExample") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTrainingExample") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3337,7 +3346,7 @@ public class Discovery { the customer ID. You associate a customer ID with data by passing the **X-Watson-Metadata** header with a request that passes data. For more information about personal data and customer IDs, see [Information - security](https://cloud.ibm.com/docs/services/discovery/information-security.html). + security](https://cloud.ibm.com/docs/services/discovery?topic=discovery-information-security#information-security). - parameter customerID: The customer ID for which all data is to be deleted. - parameter headers: A dictionary of request headers to be sent with this request. @@ -3353,9 +3362,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -3398,7 +3406,7 @@ public class Discovery { let createEventRequest = CreateEventObject( type: type, data: data) - guard let body = try? JSONEncoder().encode(createEventRequest) else { + guard let body = try? JSON.encoder.encode(createEventRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -3408,8 +3416,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEvent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createEvent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -3444,9 +3452,11 @@ public class Discovery { - parameter query: A query search returns all documents in your data set with full enrichments and full text, but with the most relevant documents listed first. Use a query search when you want to find the most relevant search results. You cannot use **natural_language_query** and **query** at the same time. - - parameter count: Number of results to return. + - parameter count: Number of results to return. The maximum for the **count** and **offset** values together in + any one query is **10000**. - parameter offset: The number of query results to skip at the beginning. For example, if the total number of - results that are returned is 10 and the offset is 8, it returns the last two results. + results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the + **count** and **offset** values together in any one query is **10000**. - parameter sort: A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -3467,8 +3477,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryLog") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "queryLog") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3535,8 +3545,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQuery") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQuery") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3597,8 +3607,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryEvent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryEvent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3658,8 +3668,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryNoResults") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryNoResults") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3720,8 +3730,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsEventRate") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsEventRate") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3762,7 +3772,8 @@ public class Discovery { \"click\" event rate within the recording period (queries and events are stored for 30 days). A query token is an individual word or unigram within the query string. - - parameter count: Number of results to return. + - parameter count: Number of results to return. The maximum for the **count** and **offset** values together in + any one query is **10000**. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -3776,8 +3787,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryTokenEvent") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getMetricsQueryTokenEvent") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3823,8 +3834,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCredentials") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCredentials") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3864,6 +3875,7 @@ public class Discovery { - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. - parameter credentialDetails: Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - parameter headers: A dictionary of request headers to be sent with this request. @@ -3880,7 +3892,7 @@ public class Discovery { let createCredentialsRequest = Credentials( sourceType: sourceType, credentialDetails: credentialDetails) - guard let body = try? JSONEncoder().encode(createCredentialsRequest) else { + guard let body = try? JSON.encoder.encode(createCredentialsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -3890,8 +3902,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCredentials") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createCredentials") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -3943,8 +3955,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCredentials") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCredentials") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -3984,6 +3996,7 @@ public class Discovery { - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. - parameter credentialDetails: Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - parameter headers: A dictionary of request headers to be sent with this request. @@ -4001,7 +4014,7 @@ public class Discovery { let updateCredentialsRequest = Credentials( sourceType: sourceType, credentialDetails: credentialDetails) - guard let body = try? JSONEncoder().encode(updateCredentialsRequest) else { + guard let body = try? JSON.encoder.encode(updateCredentialsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -4011,8 +4024,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCredentials") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateCredentials") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -4062,8 +4075,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCredentials") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCredentials") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -4109,8 +4122,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listGateways") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listGateways") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -4156,7 +4169,7 @@ public class Discovery { // construct body let createGatewayRequest = GatewayName( name: name) - guard let body = try? JSONEncoder().encodeIfPresent(createGatewayRequest) else { + guard let body = try? JSON.encoder.encodeIfPresent(createGatewayRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -4166,8 +4179,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createGateway") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createGateway") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -4217,8 +4230,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getGateway") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getGateway") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -4266,8 +4279,8 @@ public class Discovery { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteGateway") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteGateway") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters diff --git a/Source/DiscoveryV1/Models/AggregationResult.swift b/Source/DiscoveryV1/Models/AggregationResult.swift index 406add7a7..0a48e3fb2 100644 --- a/Source/DiscoveryV1/Models/AggregationResult.swift +++ b/Source/DiscoveryV1/Models/AggregationResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,12 +41,4 @@ public struct AggregationResult: Codable, Equatable { case aggregations = "aggregations" } - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - if let keyAsString = try? container.decode(String.self, forKey: .key) { key = keyAsString } - if let keyAsInt = try? container.decode(Int.self, forKey: .key) { key = "\(keyAsInt)" } - matchingResults = try container.decodeIfPresent(Int.self, forKey: .matchingResults) - aggregations = try container.decodeIfPresent([QueryAggregation].self, forKey: .aggregations) - } - } diff --git a/Source/DiscoveryV1/Models/Calculation.swift b/Source/DiscoveryV1/Models/Calculation.swift index 90abd47bd..88f5e0434 100644 --- a/Source/DiscoveryV1/Models/Calculation.swift +++ b/Source/DiscoveryV1/Models/Calculation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Calculation: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/Collection.swift b/Source/DiscoveryV1/Models/Collection.swift index 152d62235..a4d657697 100644 --- a/Source/DiscoveryV1/Models/Collection.swift +++ b/Source/DiscoveryV1/Models/Collection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,10 +71,6 @@ public struct Collection: Codable, Equatable { */ public var language: String? - /** - The object providing information about the documents in the collection. Present only when retrieving details of a - collection. - */ public var documentCounts: DocumentCounts? /** @@ -82,9 +78,6 @@ public struct Collection: Codable, Equatable { */ public var diskUsage: CollectionDiskUsage? - /** - Provides information about the status of relevance training for collection. - */ public var trainingStatus: TrainingStatus? /** diff --git a/Source/DiscoveryV1/Models/CollectionDiskUsage.swift b/Source/DiscoveryV1/Models/CollectionDiskUsage.swift index c02a88338..fe2f5a07d 100644 --- a/Source/DiscoveryV1/Models/CollectionDiskUsage.swift +++ b/Source/DiscoveryV1/Models/CollectionDiskUsage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/CollectionUsage.swift b/Source/DiscoveryV1/Models/CollectionUsage.swift index f4044a9f7..385308d17 100644 --- a/Source/DiscoveryV1/Models/CollectionUsage.swift +++ b/Source/DiscoveryV1/Models/CollectionUsage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Configuration.swift b/Source/DiscoveryV1/Models/Configuration.swift index c4afeaf11..c1fc73479 100644 --- a/Source/DiscoveryV1/Models/Configuration.swift +++ b/Source/DiscoveryV1/Models/Configuration.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Conversions.swift b/Source/DiscoveryV1/Models/Conversions.swift index 8d7dcb722..cf8979d78 100644 --- a/Source/DiscoveryV1/Models/Conversions.swift +++ b/Source/DiscoveryV1/Models/Conversions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/CreateCollectionRequest.swift b/Source/DiscoveryV1/Models/CreateCollectionRequest.swift index 0fb293b8e..ecc0bd3a9 100644 --- a/Source/DiscoveryV1/Models/CreateCollectionRequest.swift +++ b/Source/DiscoveryV1/Models/CreateCollectionRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ internal struct CreateCollectionRequest: Codable, Equatable { case ko = "ko" case pt = "pt" case nl = "nl" + case zhCn = "zh-CN" } /** diff --git a/Source/DiscoveryV1/Models/CreateEnvironmentRequest.swift b/Source/DiscoveryV1/Models/CreateEnvironmentRequest.swift index 044f4b858..3d0b3330d 100644 --- a/Source/DiscoveryV1/Models/CreateEnvironmentRequest.swift +++ b/Source/DiscoveryV1/Models/CreateEnvironmentRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/CreateEventObject.swift b/Source/DiscoveryV1/Models/CreateEventObject.swift index 3b4002d34..a946f2480 100644 --- a/Source/DiscoveryV1/Models/CreateEventObject.swift +++ b/Source/DiscoveryV1/Models/CreateEventObject.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/CreateEventResponse.swift b/Source/DiscoveryV1/Models/CreateEventResponse.swift index 326df7702..206de1f20 100644 --- a/Source/DiscoveryV1/Models/CreateEventResponse.swift +++ b/Source/DiscoveryV1/Models/CreateEventResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/CredentialDetails.swift b/Source/DiscoveryV1/Models/CredentialDetails.swift index 3664b0858..bcc00e71c 100644 --- a/Source/DiscoveryV1/Models/CredentialDetails.swift +++ b/Source/DiscoveryV1/Models/CredentialDetails.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,8 @@ public struct CredentialDetails: Codable, Equatable { - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntml_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`. + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. */ public enum CredentialType: String { case oauth2 = "oauth2" @@ -38,6 +39,7 @@ public struct CredentialDetails: Codable, Equatable { case noauth = "noauth" case basic = "basic" case ntmlV1 = "ntml_v1" + case aws4Hmac = "aws4_hmac" } /** @@ -45,7 +47,6 @@ public struct CredentialDetails: Codable, Equatable { */ public enum SourceVersion: String { case online = "online" - case sp2016 = "2016" } /** @@ -55,7 +56,8 @@ public struct CredentialDetails: Codable, Equatable { - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntml_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`. + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. */ public var credentialType: String? @@ -155,6 +157,27 @@ public struct CredentialDetails: Codable, Equatable { */ public var domain: String? + /** + The endpoint associated with the cloud object store that your are connecting to. Only valid, and required, with a + **credential_type** of `aws4_hmac`. + */ + public var endpoint: String? + + /** + The access key ID associated with the cloud object store. Only valid, and required, with a **credential_type** of + `aws4_hmac`. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + */ + public var accessKeyID: String? + + /** + The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** + of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more + infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + */ + public var secretAccessKey: String? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case credentialType = "credential_type" @@ -173,6 +196,9 @@ public struct CredentialDetails: Codable, Equatable { case sourceVersion = "source_version" case webApplicationURL = "web_application_url" case domain = "domain" + case endpoint = "endpoint" + case accessKeyID = "access_key_id" + case secretAccessKey = "secret_access_key" } /** @@ -184,7 +210,8 @@ public struct CredentialDetails: Codable, Equatable { - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or `ntml_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic`. + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - parameter clientID: The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. - parameter enterpriseID: The **enterprise_id** of the Box site that these credentials connect to. Only valid, @@ -223,6 +250,15 @@ public struct CredentialDetails: Codable, Equatable { **source_version** of `2016`. - parameter domain: The domain used to log in to your OnPrem SharePoint account. Only valid, and required, with a **source_version** of `2016`. + - parameter endpoint: The endpoint associated with the cloud object store that your are connecting to. Only + valid, and required, with a **credential_type** of `aws4_hmac`. + - parameter accessKeyID: The access key ID associated with the cloud object store. Only valid, and required, + with a **credential_type** of `aws4_hmac`. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + - parameter secretAccessKey: The secret access key associated with the cloud object store. Only valid, and + required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating + or modifying **credentials**. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - returns: An initialized `CredentialDetails`. */ @@ -242,7 +278,10 @@ public struct CredentialDetails: Codable, Equatable { gatewayID: String? = nil, sourceVersion: String? = nil, webApplicationURL: String? = nil, - domain: String? = nil + domain: String? = nil, + endpoint: String? = nil, + accessKeyID: String? = nil, + secretAccessKey: String? = nil ) { self.credentialType = credentialType @@ -261,6 +300,9 @@ public struct CredentialDetails: Codable, Equatable { self.sourceVersion = sourceVersion self.webApplicationURL = webApplicationURL self.domain = domain + self.endpoint = endpoint + self.accessKeyID = accessKeyID + self.secretAccessKey = secretAccessKey } } diff --git a/Source/DiscoveryV1/Models/Credentials.swift b/Source/DiscoveryV1/Models/Credentials.swift index 5cb6312fe..92bcf740c 100644 --- a/Source/DiscoveryV1/Models/Credentials.swift +++ b/Source/DiscoveryV1/Models/Credentials.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,12 +27,14 @@ public struct Credentials: Codable, Equatable { - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. */ public enum SourceType: String { case box = "box" case salesforce = "salesforce" case sharepoint = "sharepoint" case webCrawl = "web_crawl" + case cloudObjectStorage = "cloud_object_storage" } /** @@ -46,6 +48,7 @@ public struct Credentials: Codable, Equatable { - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. */ public var sourceType: String? @@ -71,6 +74,7 @@ public struct Credentials: Codable, Equatable { - `salesforce` indicates the credentials are used to connect to Salesforce. - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint Online. - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. - parameter credentialDetails: Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. diff --git a/Source/DiscoveryV1/Models/CredentialsList.swift b/Source/DiscoveryV1/Models/CredentialsList.swift index 654eb82e2..8bbbf4dca 100644 --- a/Source/DiscoveryV1/Models/CredentialsList.swift +++ b/Source/DiscoveryV1/Models/CredentialsList.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DeleteCollectionResponse.swift b/Source/DiscoveryV1/Models/DeleteCollectionResponse.swift index d8eb635b0..3aeee4303 100644 --- a/Source/DiscoveryV1/Models/DeleteCollectionResponse.swift +++ b/Source/DiscoveryV1/Models/DeleteCollectionResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DeleteConfigurationResponse.swift b/Source/DiscoveryV1/Models/DeleteConfigurationResponse.swift index 954641231..a082781ab 100644 --- a/Source/DiscoveryV1/Models/DeleteConfigurationResponse.swift +++ b/Source/DiscoveryV1/Models/DeleteConfigurationResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DeleteCredentials.swift b/Source/DiscoveryV1/Models/DeleteCredentials.swift index 8eb8f3ee0..5afc67405 100644 --- a/Source/DiscoveryV1/Models/DeleteCredentials.swift +++ b/Source/DiscoveryV1/Models/DeleteCredentials.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DeleteDocumentResponse.swift b/Source/DiscoveryV1/Models/DeleteDocumentResponse.swift index 1f465529c..9f5c6dd6f 100644 --- a/Source/DiscoveryV1/Models/DeleteDocumentResponse.swift +++ b/Source/DiscoveryV1/Models/DeleteDocumentResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DeleteEnvironmentResponse.swift b/Source/DiscoveryV1/Models/DeleteEnvironmentResponse.swift index b643628c9..1f6efc365 100644 --- a/Source/DiscoveryV1/Models/DeleteEnvironmentResponse.swift +++ b/Source/DiscoveryV1/Models/DeleteEnvironmentResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DiskUsage.swift b/Source/DiscoveryV1/Models/DiskUsage.swift index 9fb9908c2..1bf01ad4a 100644 --- a/Source/DiscoveryV1/Models/DiskUsage.swift +++ b/Source/DiscoveryV1/Models/DiskUsage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DocumentAccepted.swift b/Source/DiscoveryV1/Models/DocumentAccepted.swift index 5cc3e431c..ea06931d4 100644 --- a/Source/DiscoveryV1/Models/DocumentAccepted.swift +++ b/Source/DiscoveryV1/Models/DocumentAccepted.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DocumentCounts.swift b/Source/DiscoveryV1/Models/DocumentCounts.swift index 03384aebd..e99db1891 100644 --- a/Source/DiscoveryV1/Models/DocumentCounts.swift +++ b/Source/DiscoveryV1/Models/DocumentCounts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/DocumentSnapshot.swift b/Source/DiscoveryV1/Models/DocumentSnapshot.swift index 684153333..7424e0e22 100644 --- a/Source/DiscoveryV1/Models/DocumentSnapshot.swift +++ b/Source/DiscoveryV1/Models/DocumentSnapshot.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,9 @@ import RestKit /** DocumentSnapshot. */ public struct DocumentSnapshot: Codable, Equatable { + /** + The step in the document conversion process that the snapshot object represents. + */ public enum Step: String { case htmlInput = "html_input" case htmlOutput = "html_output" @@ -29,8 +32,14 @@ public struct DocumentSnapshot: Codable, Equatable { case normalizationsOutput = "normalizations_output" } + /** + The step in the document conversion process that the snapshot object represents. + */ public var step: String? + /** + Snapshot of the conversion. + */ public var snapshot: [String: JSON]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/DocumentStatus.swift b/Source/DiscoveryV1/Models/DocumentStatus.swift index 7bc0ae4ad..ec0b4d90a 100644 --- a/Source/DiscoveryV1/Models/DocumentStatus.swift +++ b/Source/DiscoveryV1/Models/DocumentStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,16 +52,6 @@ public struct DocumentStatus: Codable, Equatable { */ public var configurationID: String? - /** - The creation date of the document in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - */ - public var created: Date? - - /** - Date of the most recent document update, in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - */ - public var updated: Date? - /** Status of the document in the ingestion process. */ @@ -96,8 +86,6 @@ public struct DocumentStatus: Codable, Equatable { private enum CodingKeys: String, CodingKey { case documentID = "document_id" case configurationID = "configuration_id" - case created = "created" - case updated = "updated" case status = "status" case statusDescription = "status_description" case filename = "filename" diff --git a/Source/DiscoveryV1/Models/Enrichment.swift b/Source/DiscoveryV1/Models/Enrichment.swift index 9048d87bf..232639e3a 100644 --- a/Source/DiscoveryV1/Models/Enrichment.swift +++ b/Source/DiscoveryV1/Models/Enrichment.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,8 @@ public struct Enrichment: Codable, Equatable { /** Field to be enriched. + Arrays can be specified as the **source_field** if the **enrichment** service for this enrichment is set to + `natural_language_undstanding`. */ public var sourceField: String @@ -47,8 +49,8 @@ public struct Enrichment: Codable, Equatable { options. When using `elements` the **options** object must contain Element Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in - [the documentation](https://cloud.ibm.com/docs/services/discovery/element-classification.html) - Previous API versions also supported `alchemy_language`. + [the + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). */ public var enrichmentName: String @@ -59,7 +61,7 @@ public struct Enrichment: Codable, Equatable { public var ignoreDownstreamErrors: Bool? /** - Options which are specific to a particular enrichment. + An object representing the configuration options to use for the `elements` enrichment. */ public var options: EnrichmentOptions? @@ -81,20 +83,22 @@ public struct Enrichment: Codable, Equatable { most 1 level deeper than an existing field. For example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but `text.foo.bar` is not. - parameter sourceField: Field to be enriched. + Arrays can be specified as the **source_field** if the **enrichment** service for this enrichment is set to + `natural_language_undstanding`. - parameter enrichmentName: Name of the enrichment service to call. Current options are `natural_language_understanding` and `elements`. When using `natual_language_understanding`, the **options** object must contain Natural Language Understanding options. When using `elements` the **options** object must contain Element Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria - specified in [the documentation](https://cloud.ibm.com/docs/services/discovery/element-classification.html) - Previous API versions also supported `alchemy_language`. + specified in [the + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). - parameter description: Describes what the enrichment step does. - parameter overwrite: Indicates that the enrichments will overwrite the destination_field field if it already exists. - parameter ignoreDownstreamErrors: If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. - - parameter options: Options which are specific to a particular enrichment. + - parameter options: An object representing the configuration options to use for the `elements` enrichment. - returns: An initialized `Enrichment`. */ diff --git a/Source/DiscoveryV1/Models/EnrichmentOptions.swift b/Source/DiscoveryV1/Models/EnrichmentOptions.swift index 83bd2f5f7..20c7a5538 100644 --- a/Source/DiscoveryV1/Models/EnrichmentOptions.swift +++ b/Source/DiscoveryV1/Models/EnrichmentOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Foundation /** - Options which are specific to a particular enrichment. + An object representing the configuration options to use for the `elements` enrichment. */ public struct EnrichmentOptions: Codable, Equatable { @@ -39,9 +39,6 @@ public struct EnrichmentOptions: Codable, Equatable { case sv = "sv" } - /** - An object representing the enrichment features that will be applied to the specified field. - */ public var features: NluEnrichmentFeatures? /** @@ -67,8 +64,7 @@ public struct EnrichmentOptions: Codable, Equatable { /** Initialize a `EnrichmentOptions` with member variables. - - parameter features: An object representing the enrichment features that will be applied to the specified - field. + - parameter features: - parameter language: ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). diff --git a/Source/DiscoveryV1/Models/Environment.swift b/Source/DiscoveryV1/Models/Environment.swift index 7f4dcde9d..ca7e55bb2 100644 --- a/Source/DiscoveryV1/Models/Environment.swift +++ b/Source/DiscoveryV1/Models/Environment.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/EnvironmentDocuments.swift b/Source/DiscoveryV1/Models/EnvironmentDocuments.swift index 9d61173cf..0d1355cbd 100644 --- a/Source/DiscoveryV1/Models/EnvironmentDocuments.swift +++ b/Source/DiscoveryV1/Models/EnvironmentDocuments.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/EventData.swift b/Source/DiscoveryV1/Models/EventData.swift index 6bbd69ce5..4e9f1fe78 100644 --- a/Source/DiscoveryV1/Models/EventData.swift +++ b/Source/DiscoveryV1/Models/EventData.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Expansion.swift b/Source/DiscoveryV1/Models/Expansion.swift index d0831604f..61607d26c 100644 --- a/Source/DiscoveryV1/Models/Expansion.swift +++ b/Source/DiscoveryV1/Models/Expansion.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Expansions.swift b/Source/DiscoveryV1/Models/Expansions.swift index ed5000484..75e7a5812 100644 --- a/Source/DiscoveryV1/Models/Expansions.swift +++ b/Source/DiscoveryV1/Models/Expansions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Field.swift b/Source/DiscoveryV1/Models/Field.swift index 6fce052d3..4f8734fc4 100644 --- a/Source/DiscoveryV1/Models/Field.swift +++ b/Source/DiscoveryV1/Models/Field.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Filter.swift b/Source/DiscoveryV1/Models/Filter.swift index 5df121fdc..c27650abd 100644 --- a/Source/DiscoveryV1/Models/Filter.swift +++ b/Source/DiscoveryV1/Models/Filter.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Filter: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/FontSetting.swift b/Source/DiscoveryV1/Models/FontSetting.swift index 1bc071317..387d6c433 100644 --- a/Source/DiscoveryV1/Models/FontSetting.swift +++ b/Source/DiscoveryV1/Models/FontSetting.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,16 +19,34 @@ import Foundation /** FontSetting. */ public struct FontSetting: Codable, Equatable { + /** + The HTML heading level that any content with the matching font will be converted to. + */ public var level: Int? + /** + The minimum size of the font to match. + */ public var minSize: Int? + /** + The maximum size of the font to match. + */ public var maxSize: Int? + /** + When `true`, the font is matched if it is bold. + */ public var bold: Bool? + /** + When `true`, the font is matched if it is italic. + */ public var italic: Bool? + /** + The name of the font. + */ public var name: String? // Map each property name to the key that shall be used for encoding/decoding. @@ -44,12 +62,12 @@ public struct FontSetting: Codable, Equatable { /** Initialize a `FontSetting` with member variables. - - parameter level: - - parameter minSize: - - parameter maxSize: - - parameter bold: - - parameter italic: - - parameter name: + - parameter level: The HTML heading level that any content with the matching font will be converted to. + - parameter minSize: The minimum size of the font to match. + - parameter maxSize: The maximum size of the font to match. + - parameter bold: When `true`, the font is matched if it is bold. + - parameter italic: When `true`, the font is matched if it is italic. + - parameter name: The name of the font. - returns: An initialized `FontSetting`. */ diff --git a/Source/DiscoveryV1/Models/Gateway.swift b/Source/DiscoveryV1/Models/Gateway.swift index 72072b61f..5a3d01a05 100644 --- a/Source/DiscoveryV1/Models/Gateway.swift +++ b/Source/DiscoveryV1/Models/Gateway.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/GatewayDelete.swift b/Source/DiscoveryV1/Models/GatewayDelete.swift index 5b0090dbb..c6b79e5f7 100644 --- a/Source/DiscoveryV1/Models/GatewayDelete.swift +++ b/Source/DiscoveryV1/Models/GatewayDelete.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/GatewayList.swift b/Source/DiscoveryV1/Models/GatewayList.swift index 68b5978b3..a772e4d6a 100644 --- a/Source/DiscoveryV1/Models/GatewayList.swift +++ b/Source/DiscoveryV1/Models/GatewayList.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/GatewayName.swift b/Source/DiscoveryV1/Models/GatewayName.swift index ea7461f43..af63dc79e 100644 --- a/Source/DiscoveryV1/Models/GatewayName.swift +++ b/Source/DiscoveryV1/Models/GatewayName.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/HTMLSettings.swift b/Source/DiscoveryV1/Models/HTMLSettings.swift index 85f9104f0..6b9cd17be 100644 --- a/Source/DiscoveryV1/Models/HTMLSettings.swift +++ b/Source/DiscoveryV1/Models/HTMLSettings.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,16 +21,28 @@ import Foundation */ public struct HTMLSettings: Codable, Equatable { + /** + Array of HTML tags that are excluded completely. + */ public var excludeTagsCompletely: [String]? + /** + Array of HTML tags which are excluded but still retain content. + */ public var excludeTagsKeepContent: [String]? public var keepContent: XPathPatterns? public var excludeContent: XPathPatterns? + /** + An array of HTML tag attributes to keep in the converted document. + */ public var keepTagAttributes: [String]? + /** + Array of HTML tag attributes to exclude. + */ public var excludeTagAttributes: [String]? // Map each property name to the key that shall be used for encoding/decoding. @@ -46,12 +58,12 @@ public struct HTMLSettings: Codable, Equatable { /** Initialize a `HTMLSettings` with member variables. - - parameter excludeTagsCompletely: - - parameter excludeTagsKeepContent: + - parameter excludeTagsCompletely: Array of HTML tags that are excluded completely. + - parameter excludeTagsKeepContent: Array of HTML tags which are excluded but still retain content. - parameter keepContent: - parameter excludeContent: - - parameter keepTagAttributes: - - parameter excludeTagAttributes: + - parameter keepTagAttributes: An array of HTML tag attributes to keep in the converted document. + - parameter excludeTagAttributes: Array of HTML tag attributes to exclude. - returns: An initialized `HTMLSettings`. */ diff --git a/Source/DiscoveryV1/Models/Histogram.swift b/Source/DiscoveryV1/Models/Histogram.swift index 4056831ac..42544fcb3 100644 --- a/Source/DiscoveryV1/Models/Histogram.swift +++ b/Source/DiscoveryV1/Models/Histogram.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Histogram: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/IndexCapacity.swift b/Source/DiscoveryV1/Models/IndexCapacity.swift index b72937ab4..e85bb33d6 100644 --- a/Source/DiscoveryV1/Models/IndexCapacity.swift +++ b/Source/DiscoveryV1/Models/IndexCapacity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/ListCollectionFieldsResponse.swift b/Source/DiscoveryV1/Models/ListCollectionFieldsResponse.swift index 6e6e99fe9..e20bdc903 100644 --- a/Source/DiscoveryV1/Models/ListCollectionFieldsResponse.swift +++ b/Source/DiscoveryV1/Models/ListCollectionFieldsResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/ListCollectionsResponse.swift b/Source/DiscoveryV1/Models/ListCollectionsResponse.swift index 915a0ad29..afa5424b7 100644 --- a/Source/DiscoveryV1/Models/ListCollectionsResponse.swift +++ b/Source/DiscoveryV1/Models/ListCollectionsResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/ListConfigurationsResponse.swift b/Source/DiscoveryV1/Models/ListConfigurationsResponse.swift index a7dddd992..79fd8a3ff 100644 --- a/Source/DiscoveryV1/Models/ListConfigurationsResponse.swift +++ b/Source/DiscoveryV1/Models/ListConfigurationsResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/ListEnvironmentsResponse.swift b/Source/DiscoveryV1/Models/ListEnvironmentsResponse.swift index 7d22290a1..dec3502a6 100644 --- a/Source/DiscoveryV1/Models/ListEnvironmentsResponse.swift +++ b/Source/DiscoveryV1/Models/ListEnvironmentsResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/LogQueryResponse.swift b/Source/DiscoveryV1/Models/LogQueryResponse.swift index 3cfd31a4b..d5bc867d1 100644 --- a/Source/DiscoveryV1/Models/LogQueryResponse.swift +++ b/Source/DiscoveryV1/Models/LogQueryResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,9 @@ public struct LogQueryResponse: Codable, Equatable { */ public var matchingResults: Int? + /** + Array of log query response results. + */ public var results: [LogQueryResponseResult]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/LogQueryResponseResult.swift b/Source/DiscoveryV1/Models/LogQueryResponseResult.swift index 213d59309..2333cddb6 100644 --- a/Source/DiscoveryV1/Models/LogQueryResponseResult.swift +++ b/Source/DiscoveryV1/Models/LogQueryResponseResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/LogQueryResponseResultDocuments.swift b/Source/DiscoveryV1/Models/LogQueryResponseResultDocuments.swift index a460d9048..2541d9ce1 100644 --- a/Source/DiscoveryV1/Models/LogQueryResponseResultDocuments.swift +++ b/Source/DiscoveryV1/Models/LogQueryResponseResultDocuments.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,9 @@ import Foundation */ public struct LogQueryResponseResultDocuments: Codable, Equatable { + /** + Array of log query response results. + */ public var results: [LogQueryResponseResultDocumentsResult]? /** diff --git a/Source/DiscoveryV1/Models/LogQueryResponseResultDocumentsResult.swift b/Source/DiscoveryV1/Models/LogQueryResponseResultDocumentsResult.swift index 03dc57b18..fef1af0b7 100644 --- a/Source/DiscoveryV1/Models/LogQueryResponseResultDocumentsResult.swift +++ b/Source/DiscoveryV1/Models/LogQueryResponseResultDocumentsResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/MemoryUsage.swift b/Source/DiscoveryV1/Models/MemoryUsage.swift new file mode 100644 index 000000000..e6ff29d08 --- /dev/null +++ b/Source/DiscoveryV1/Models/MemoryUsage.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + **Deprecated**: Summary of the memory usage statistics for this environment. + */ +public struct MemoryUsage: Codable, Equatable { + + /** + **Deprecated**: Number of bytes used in the environment's memory capacity. + */ + public var usedBytes: Int? + + /** + **Deprecated**: Total number of bytes available in the environment's memory capacity. + */ + public var totalBytes: Int? + + /** + **Deprecated**: Amount of memory capacity used, in KB or GB format. + */ + public var used: String? + + /** + **Deprecated**: Total amount of the environment's memory capacity, in KB or GB format. + */ + public var total: String? + + /** + **Deprecated**: Percentage of the environment's memory capacity that is being used. + */ + public var percentUsed: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case usedBytes = "used_bytes" + case totalBytes = "total_bytes" + case used = "used" + case total = "total" + case percentUsed = "percent_used" + } + +} diff --git a/Source/DiscoveryV1/Models/MetricAggregation.swift b/Source/DiscoveryV1/Models/MetricAggregation.swift index 069af7fe7..1c0d1826a 100644 --- a/Source/DiscoveryV1/Models/MetricAggregation.swift +++ b/Source/DiscoveryV1/Models/MetricAggregation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,9 @@ public struct MetricAggregation: Codable, Equatable { */ public var eventType: String? + /** + Array of metric aggregation query results. + */ public var results: [MetricAggregationResult]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/MetricAggregationResult.swift b/Source/DiscoveryV1/Models/MetricAggregationResult.swift index 1067d3a01..91dd2e4f8 100644 --- a/Source/DiscoveryV1/Models/MetricAggregationResult.swift +++ b/Source/DiscoveryV1/Models/MetricAggregationResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/MetricResponse.swift b/Source/DiscoveryV1/Models/MetricResponse.swift index fc599923b..864b66e47 100644 --- a/Source/DiscoveryV1/Models/MetricResponse.swift +++ b/Source/DiscoveryV1/Models/MetricResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,9 @@ import Foundation */ public struct MetricResponse: Codable, Equatable { + /** + Array of metric aggregations. + */ public var aggregations: [MetricAggregation]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/MetricTokenAggregation.swift b/Source/DiscoveryV1/Models/MetricTokenAggregation.swift index cb411e8c4..45feca046 100644 --- a/Source/DiscoveryV1/Models/MetricTokenAggregation.swift +++ b/Source/DiscoveryV1/Models/MetricTokenAggregation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,9 @@ public struct MetricTokenAggregation: Codable, Equatable { */ public var eventType: String? + /** + Array of results for the metric token aggregation. + */ public var results: [MetricTokenAggregationResult]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/MetricTokenAggregationResult.swift b/Source/DiscoveryV1/Models/MetricTokenAggregationResult.swift index 2b6f8ff33..5060eaf41 100644 --- a/Source/DiscoveryV1/Models/MetricTokenAggregationResult.swift +++ b/Source/DiscoveryV1/Models/MetricTokenAggregationResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/MetricTokenResponse.swift b/Source/DiscoveryV1/Models/MetricTokenResponse.swift index d32ea9fc5..8afb231a7 100644 --- a/Source/DiscoveryV1/Models/MetricTokenResponse.swift +++ b/Source/DiscoveryV1/Models/MetricTokenResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,9 @@ import Foundation */ public struct MetricTokenResponse: Codable, Equatable { + /** + Array of metric token aggregations. + */ public var aggregations: [MetricTokenAggregation]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/Nested.swift b/Source/DiscoveryV1/Models/Nested.swift index 7c277da5e..f8954a0a0 100644 --- a/Source/DiscoveryV1/Models/Nested.swift +++ b/Source/DiscoveryV1/Models/Nested.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Nested: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/NewTrainingQuery.swift b/Source/DiscoveryV1/Models/NewTrainingQuery.swift index 6f00e9d74..20ea79c78 100644 --- a/Source/DiscoveryV1/Models/NewTrainingQuery.swift +++ b/Source/DiscoveryV1/Models/NewTrainingQuery.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,19 @@ import Foundation /** NewTrainingQuery. */ internal struct NewTrainingQuery: Codable, Equatable { + /** + The natural text query for the new training query. + */ public var naturalLanguageQuery: String? + /** + The filter used on the collection before the **natural_language_query** is applied. + */ public var filter: String? + /** + Array of training examples. + */ public var examples: [TrainingExample]? // Map each property name to the key that shall be used for encoding/decoding. @@ -35,9 +44,9 @@ internal struct NewTrainingQuery: Codable, Equatable { /** Initialize a `NewTrainingQuery` with member variables. - - parameter naturalLanguageQuery: - - parameter filter: - - parameter examples: + - parameter naturalLanguageQuery: The natural text query for the new training query. + - parameter filter: The filter used on the collection before the **natural_language_query** is applied. + - parameter examples: Array of training examples. - returns: An initialized `NewTrainingQuery`. */ diff --git a/Source/DiscoveryV1/Models/NluEnrichmentCategories.swift b/Source/DiscoveryV1/Models/NluEnrichmentCategories.swift index f0a020bfb..8b101edc3 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentCategories.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentCategories.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentConcepts.swift b/Source/DiscoveryV1/Models/NluEnrichmentConcepts.swift index 07740473a..eab3d5b72 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentConcepts.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentConcepts.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentEmotion.swift b/Source/DiscoveryV1/Models/NluEnrichmentEmotion.swift index 67f801d76..9480d18f6 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentEmotion.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentEmotion.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentEntities.swift b/Source/DiscoveryV1/Models/NluEnrichmentEntities.swift index 02f7aba57..f70209d83 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentEntities.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentEntities.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public struct NluEnrichmentEntities: Codable, Equatable { When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. */ - public var sentenceLocation: Bool? + public var sentenceLocations: Bool? /** The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the @@ -65,7 +65,7 @@ public struct NluEnrichmentEntities: Codable, Equatable { case limit = "limit" case mentions = "mentions" case mentionTypes = "mention_types" - case sentenceLocation = "sentence_location" + case sentenceLocations = "sentence_locations" case model = "model" } @@ -79,7 +79,7 @@ public struct NluEnrichmentEntities: Codable, Equatable { `false`. - parameter mentionTypes: When `true`, the types of mentions for each idetifieid entity is recorded. The default is `false`. - - parameter sentenceLocation: When `true`, a list of sentence locations for each instance of each identified + - parameter sentenceLocations: When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. - parameter model: The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. @@ -92,7 +92,7 @@ public struct NluEnrichmentEntities: Codable, Equatable { limit: Int? = nil, mentions: Bool? = nil, mentionTypes: Bool? = nil, - sentenceLocation: Bool? = nil, + sentenceLocations: Bool? = nil, model: String? = nil ) { @@ -101,7 +101,7 @@ public struct NluEnrichmentEntities: Codable, Equatable { self.limit = limit self.mentions = mentions self.mentionTypes = mentionTypes - self.sentenceLocation = sentenceLocation + self.sentenceLocations = sentenceLocations self.model = model } diff --git a/Source/DiscoveryV1/Models/NluEnrichmentFeatures.swift b/Source/DiscoveryV1/Models/NluEnrichmentFeatures.swift index 76991d9c2..e10aeba1f 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentFeatures.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentFeatures.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentKeywords.swift b/Source/DiscoveryV1/Models/NluEnrichmentKeywords.swift index 10f3d1d2b..51632a2d8 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentKeywords.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentKeywords.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentRelations.swift b/Source/DiscoveryV1/Models/NluEnrichmentRelations.swift index 09f827464..8cdcff7be 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentRelations.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentRelations.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentSemanticRoles.swift b/Source/DiscoveryV1/Models/NluEnrichmentSemanticRoles.swift index 08001bc46..b9f8f25b2 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentSemanticRoles.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentSemanticRoles.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NluEnrichmentSentiment.swift b/Source/DiscoveryV1/Models/NluEnrichmentSentiment.swift index 17d7be64e..4bd151e99 100644 --- a/Source/DiscoveryV1/Models/NluEnrichmentSentiment.swift +++ b/Source/DiscoveryV1/Models/NluEnrichmentSentiment.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/NormalizationOperation.swift b/Source/DiscoveryV1/Models/NormalizationOperation.swift index b9f563c4b..76c27e362 100644 --- a/Source/DiscoveryV1/Models/NormalizationOperation.swift +++ b/Source/DiscoveryV1/Models/NormalizationOperation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,10 +35,10 @@ public struct NormalizationOperation: Codable, Equatable { array (if it is not an array already). This conversion ensures the type for **destination_field** is consistent across all documents. **remove** - Deletes the **source_field** field. The **destination_field** is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the JSON tree. **source_field** and - **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire JSON tree. - Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be - time-expensive). + **remove_nulls** - Removes all nested null (blank) field values from the ingested document. **source_field** and + **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire ingested + document. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it + can be time-expensive). */ public enum Operation: String { case copy = "copy" @@ -64,10 +64,10 @@ public struct NormalizationOperation: Codable, Equatable { array (if it is not an array already). This conversion ensures the type for **destination_field** is consistent across all documents. **remove** - Deletes the **source_field** field. The **destination_field** is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the JSON tree. **source_field** and - **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire JSON tree. - Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be - time-expensive). + **remove_nulls** - Removes all nested null (blank) field values from the ingested document. **source_field** and + **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire ingested + document. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it + can be time-expensive). */ public var operation: String? @@ -106,10 +106,10 @@ public struct NormalizationOperation: Codable, Equatable { an array (if it is not an array already). This conversion ensures the type for **destination_field** is consistent across all documents. **remove** - Deletes the **source_field** field. The **destination_field** is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the JSON tree. **source_field** and - **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire JSON tree. - Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be - time-expensive). + **remove_nulls** - Removes all nested null (blank) field values from the ingested document. **source_field** and + **destination_field** are ignored by this operation because _remove_nulls_ operates on the entire ingested + document. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it + can be time-expensive). - parameter sourceField: The source field for the operation. - parameter destinationField: The destination field for the operation. diff --git a/Source/DiscoveryV1/Models/Notice.swift b/Source/DiscoveryV1/Models/Notice.swift index 9c15ffb97..e770ad8ab 100644 --- a/Source/DiscoveryV1/Models/Notice.swift +++ b/Source/DiscoveryV1/Models/Notice.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,13 @@ public struct Notice: Codable, Equatable { /** Identifies the notice. Many notices might have the same ID. This field exists so that user applications can - programmatically identify a notice and take automatic corrective action. + programmatically identify a notice and take automatic corrective action. Typical notice IDs include: + `index_failed`, `index_failed_too_many_requests`, `index_failed_incompatible_field`, + `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, + `missing_model`, `unsupported_model`, `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a complete list, other values might be returned. */ public var noticeID: String? @@ -56,7 +62,9 @@ public struct Notice: Codable, Equatable { public var severity: String? /** - Ingestion or training step in which the notice occurred. + Ingestion or training step in which the notice occurred. Typical step values include: `classify_elements`, + `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list, other + values might be returned. */ public var step: String? diff --git a/Source/DiscoveryV1/Models/PDFHeadingDetection.swift b/Source/DiscoveryV1/Models/PDFHeadingDetection.swift index ea9e5b947..830d7d754 100644 --- a/Source/DiscoveryV1/Models/PDFHeadingDetection.swift +++ b/Source/DiscoveryV1/Models/PDFHeadingDetection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/PDFSettings.swift b/Source/DiscoveryV1/Models/PDFSettings.swift index d49de4c12..0b4fe01ac 100644 --- a/Source/DiscoveryV1/Models/PDFSettings.swift +++ b/Source/DiscoveryV1/Models/PDFSettings.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryAggregation.swift b/Source/DiscoveryV1/Models/QueryAggregation.swift index 199ce4641..523d75a24 100644 --- a/Source/DiscoveryV1/Models/QueryAggregation.swift +++ b/Source/DiscoveryV1/Models/QueryAggregation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,91 +16,37 @@ import Foundation -/** An aggregation produced by the Discovery service to analyze the input provided. */ -public enum QueryAggregation: Codable, Equatable { - - // reference: https://cloud.ibm.com/docs/services/discovery/query-reference.html#aggregations - - case term(Term) - case filter(Filter) - case nested(Nested) - case histogram(Histogram) - case timeslice(Timeslice) - case topHits(TopHits) - case uniqueCount(Calculation) - case max(Calculation) - case min(Calculation) - case average(Calculation) - case sum(Calculation) - case generic(GenericQueryAggregation) - +/** + An aggregation produced by the Discovery service to analyze the input provided. + */ +public struct QueryAggregation: Codable, Equatable { + + /** + The type of aggregation command used. For example: term, filter, max, min, etc. + */ + public var type: String? + + /** + Array of aggregation results. + */ + public var results: [AggregationResult]? + + /** + Number of matching results. + */ + public var matchingResults: Int? + + /** + Aggregations returned by the Discovery service. + */ + public var aggregations: [QueryAggregation]? + + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - guard let type = try container.decodeIfPresent(String.self, forKey: .type) else { - // the specification does not identify `type` as a required field, - // so we need a generic catch-all in case it is not present - self = .generic(try GenericQueryAggregation(from: decoder)) - return - } - switch type { - case "term": self = .term(try Term(from: decoder)) - case "filter": self = .filter(try Filter(from: decoder)) - case "nested": self = .nested(try Nested(from: decoder)) - case "histogram": self = .histogram(try Histogram(from: decoder)) - case "timeslice": self = .timeslice(try Timeslice(from: decoder)) - case "top_hits": self = .topHits(try TopHits(from: decoder)) - case "unique_count": self = .uniqueCount(try Calculation(from: decoder)) - case "max": self = .max(try Calculation(from: decoder)) - case "min": self = .min(try Calculation(from: decoder)) - case "average": self = .average(try Calculation(from: decoder)) - case "sum": self = .sum(try Calculation(from: decoder)) - default: self = .generic(try GenericQueryAggregation(from: decoder)) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - switch self { - case .term(let term): - try container.encode("term", forKey: .type) - try term.encode(to: encoder) - case .filter(let filter): - try container.encode("filter", forKey: .type) - try filter.encode(to: encoder) - case .nested(let nested): - try container.encode("nested", forKey: .type) - try nested.encode(to: encoder) - case .histogram(let histogram): - try container.encode("histogram", forKey: .type) - try histogram.encode(to: encoder) - case .timeslice(let timeslice): - try container.encode("timeslice", forKey: .type) - try timeslice.encode(to: encoder) - case .topHits(let topHits): - try container.encode("top_hits", forKey: .type) - try topHits.encode(to: encoder) - case .uniqueCount(let uniqueCount): - try container.encode("unique_count", forKey: .type) - try uniqueCount.encode(to: encoder) - case .max(let max): - try container.encode("max", forKey: .type) - try max.encode(to: encoder) - case .min(let min): - try container.encode("min", forKey: .type) - try min.encode(to: encoder) - case .average(let average): - try container.encode("average", forKey: .type) - try average.encode(to: encoder) - case .sum(let sum): - try container.encode("sum", forKey: .type) - try sum.encode(to: encoder) - case .generic(let generic): - try generic.encode(to: encoder) - } + case results = "results" + case matchingResults = "matching_results" + case aggregations = "aggregations" } } diff --git a/Source/DiscoveryV1/Models/QueryEntities.swift b/Source/DiscoveryV1/Models/QueryEntities.swift index b63e93d4a..3d7ae3171 100644 --- a/Source/DiscoveryV1/Models/QueryEntities.swift +++ b/Source/DiscoveryV1/Models/QueryEntities.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryEntitiesContext.swift b/Source/DiscoveryV1/Models/QueryEntitiesContext.swift index 6a573367b..465d97b38 100644 --- a/Source/DiscoveryV1/Models/QueryEntitiesContext.swift +++ b/Source/DiscoveryV1/Models/QueryEntitiesContext.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryEntitiesEntity.swift b/Source/DiscoveryV1/Models/QueryEntitiesEntity.swift index 59b284792..b94a66ffc 100644 --- a/Source/DiscoveryV1/Models/QueryEntitiesEntity.swift +++ b/Source/DiscoveryV1/Models/QueryEntitiesEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryEntitiesResponse.swift b/Source/DiscoveryV1/Models/QueryEntitiesResponse.swift index 37687af38..27e2c2b48 100644 --- a/Source/DiscoveryV1/Models/QueryEntitiesResponse.swift +++ b/Source/DiscoveryV1/Models/QueryEntitiesResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ import Foundation /** - An array of entities resulting from the query. + An object that contains an array of entities resulting from the query. */ public struct QueryEntitiesResponse: Codable, Equatable { + /** + Array of entities that results from the query. + */ public var entities: [QueryEntitiesResponseItem]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/QueryEntitiesResponseItem.swift b/Source/DiscoveryV1/Models/QueryEntitiesResponseItem.swift index acbe833d0..7d46ed276 100644 --- a/Source/DiscoveryV1/Models/QueryEntitiesResponseItem.swift +++ b/Source/DiscoveryV1/Models/QueryEntitiesResponseItem.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryEvidence.swift b/Source/DiscoveryV1/Models/QueryEvidence.swift index a64728baa..1f4947df4 100644 --- a/Source/DiscoveryV1/Models/QueryEvidence.swift +++ b/Source/DiscoveryV1/Models/QueryEvidence.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryEvidenceEntity.swift b/Source/DiscoveryV1/Models/QueryEvidenceEntity.swift index 15ad3c339..46984c538 100644 --- a/Source/DiscoveryV1/Models/QueryEvidenceEntity.swift +++ b/Source/DiscoveryV1/Models/QueryEvidenceEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryFilterType.swift b/Source/DiscoveryV1/Models/QueryFilterType.swift index 0eb35cde2..85312d42f 100644 --- a/Source/DiscoveryV1/Models/QueryFilterType.swift +++ b/Source/DiscoveryV1/Models/QueryFilterType.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryLarge.swift b/Source/DiscoveryV1/Models/QueryLarge.swift index 7b48f4d25..d1293be6e 100644 --- a/Source/DiscoveryV1/Models/QueryLarge.swift +++ b/Source/DiscoveryV1/Models/QueryLarge.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -98,7 +98,7 @@ internal struct QueryLarge: Codable, Equatable { public var passagesCharacters: Int? /** - When `true` and used with a Watson Discovery News collection, duplicate results (based on the contents of the + When `true`, and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. */ @@ -198,7 +198,7 @@ internal struct QueryLarge: Codable, Equatable { - parameter passagesCount: The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. The maximum is `100`. - parameter passagesCharacters: The approximate number of characters that any one passage will have. - - parameter deduplicate: When `true` and used with a Watson Discovery News collection, duplicate results (based + - parameter deduplicate: When `true`, and used with a Watson Discovery News collection, duplicate results (based on the contents of the **title** field) are removed. Duplicate comparison is limited to the current query only; **offset** is not considered. This parameter is currently Beta functionality. - parameter deduplicateField: When specified, duplicate results based on the field specified are removed from diff --git a/Source/DiscoveryV1/Models/QueryNoticesResponse.swift b/Source/DiscoveryV1/Models/QueryNoticesResponse.swift index 6d706eb65..b7e3a4bdc 100644 --- a/Source/DiscoveryV1/Models/QueryNoticesResponse.swift +++ b/Source/DiscoveryV1/Models/QueryNoticesResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,14 +19,29 @@ import Foundation /** QueryNoticesResponse. */ public struct QueryNoticesResponse: Codable, Equatable { + /** + The number of matching results. + */ public var matchingResults: Int? + /** + Array of document results that match the query. + */ public var results: [QueryNoticesResult]? + /** + Array of aggregation results that match the query. + */ public var aggregations: [QueryAggregation]? + /** + Array of passage results that match the query. + */ public var passages: [QueryPassages]? + /** + The number of duplicates removed from this notices query. + */ public var duplicatesRemoved: Int? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/QueryNoticesResult.swift b/Source/DiscoveryV1/Models/QueryNoticesResult.swift index 18e4b1b60..42707ad64 100644 --- a/Source/DiscoveryV1/Models/QueryNoticesResult.swift +++ b/Source/DiscoveryV1/Models/QueryNoticesResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,6 +50,11 @@ public struct QueryNoticesResult: Codable, Equatable { */ public var resultMetadata: QueryResultMetadata? + /** + Automatically extracted result title. + */ + public var title: String? + /** The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. @@ -85,12 +90,13 @@ public struct QueryNoticesResult: Codable, Equatable { case metadata = "metadata" case collectionID = "collection_id" case resultMetadata = "result_metadata" + case title = "title" case code = "code" case filename = "filename" case fileType = "file_type" case sha1 = "sha1" case notices = "notices" - static let allValues = [id, metadata, collectionID, resultMetadata, code, filename, fileType, sha1, notices] + static let allValues = [id, metadata, collectionID, resultMetadata, title, code, filename, fileType, sha1, notices] } public init(from decoder: Decoder) throws { @@ -99,6 +105,7 @@ public struct QueryNoticesResult: Codable, Equatable { metadata = try container.decodeIfPresent([String: JSON].self, forKey: .metadata) collectionID = try container.decodeIfPresent(String.self, forKey: .collectionID) resultMetadata = try container.decodeIfPresent(QueryResultMetadata.self, forKey: .resultMetadata) + title = try container.decodeIfPresent(String.self, forKey: .title) code = try container.decodeIfPresent(Int.self, forKey: .code) filename = try container.decodeIfPresent(String.self, forKey: .filename) fileType = try container.decodeIfPresent(String.self, forKey: .fileType) @@ -114,6 +121,7 @@ public struct QueryNoticesResult: Codable, Equatable { try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(collectionID, forKey: .collectionID) try container.encodeIfPresent(resultMetadata, forKey: .resultMetadata) + try container.encodeIfPresent(title, forKey: .title) try container.encodeIfPresent(code, forKey: .code) try container.encodeIfPresent(filename, forKey: .filename) try container.encodeIfPresent(fileType, forKey: .fileType) diff --git a/Source/DiscoveryV1/Models/QueryPassages.swift b/Source/DiscoveryV1/Models/QueryPassages.swift index 27663f54e..3cb96c283 100644 --- a/Source/DiscoveryV1/Models/QueryPassages.swift +++ b/Source/DiscoveryV1/Models/QueryPassages.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryRelations.swift b/Source/DiscoveryV1/Models/QueryRelations.swift index da8c065a3..be60a2488 100644 --- a/Source/DiscoveryV1/Models/QueryRelations.swift +++ b/Source/DiscoveryV1/Models/QueryRelations.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,9 +49,6 @@ internal struct QueryRelations: Codable, Equatable { */ public var sort: String? - /** - Filters to apply to the relationship query. - */ public var filter: QueryRelationsFilter? /** @@ -85,7 +82,7 @@ internal struct QueryRelations: Codable, Equatable { - parameter sort: The sorting method for the relationships, can be `score` or `frequency`. `frequency` is the number of unique times each entity is identified. The default is `score`. This parameter cannot be used in the same query as the **bias** parameter. - - parameter filter: Filters to apply to the relationship query. + - parameter filter: - parameter count: The number of results to return. The default is `10`. The maximum is `1000`. - parameter evidenceCount: The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000. diff --git a/Source/DiscoveryV1/Models/QueryRelationsArgument.swift b/Source/DiscoveryV1/Models/QueryRelationsArgument.swift index f9b6f3ea8..5821db54b 100644 --- a/Source/DiscoveryV1/Models/QueryRelationsArgument.swift +++ b/Source/DiscoveryV1/Models/QueryRelationsArgument.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ import Foundation /** QueryRelationsArgument. */ public struct QueryRelationsArgument: Codable, Equatable { + /** + Array of query entities. + */ public var entities: [QueryEntitiesEntity]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/QueryRelationsEntity.swift b/Source/DiscoveryV1/Models/QueryRelationsEntity.swift index cd2a24908..4bba326e3 100644 --- a/Source/DiscoveryV1/Models/QueryRelationsEntity.swift +++ b/Source/DiscoveryV1/Models/QueryRelationsEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryRelationsFilter.swift b/Source/DiscoveryV1/Models/QueryRelationsFilter.swift index bbcfcd525..bf2e3b2b0 100644 --- a/Source/DiscoveryV1/Models/QueryRelationsFilter.swift +++ b/Source/DiscoveryV1/Models/QueryRelationsFilter.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,14 +19,8 @@ import Foundation /** QueryRelationsFilter. */ public struct QueryRelationsFilter: Codable, Equatable { - /** - A list of relation types to include or exclude from the query. - */ public var relationTypes: QueryFilterType? - /** - A list of entity types to include or exclude from the query. - */ public var entityTypes: QueryFilterType? /** @@ -44,8 +38,8 @@ public struct QueryRelationsFilter: Codable, Equatable { /** Initialize a `QueryRelationsFilter` with member variables. - - parameter relationTypes: A list of relation types to include or exclude from the query. - - parameter entityTypes: A list of entity types to include or exclude from the query. + - parameter relationTypes: + - parameter entityTypes: - parameter documentIDs: A comma-separated list of document IDs to include in the query. - returns: An initialized `QueryRelationsFilter`. diff --git a/Source/DiscoveryV1/Models/QueryRelationsRelationship.swift b/Source/DiscoveryV1/Models/QueryRelationsRelationship.swift index 3405875f1..a67022c10 100644 --- a/Source/DiscoveryV1/Models/QueryRelationsRelationship.swift +++ b/Source/DiscoveryV1/Models/QueryRelationsRelationship.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/QueryRelationsResponse.swift b/Source/DiscoveryV1/Models/QueryRelationsResponse.swift index 4c5f6c1dd..097d096db 100644 --- a/Source/DiscoveryV1/Models/QueryRelationsResponse.swift +++ b/Source/DiscoveryV1/Models/QueryRelationsResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ import Foundation /** QueryRelationsResponse. */ public struct QueryRelationsResponse: Codable, Equatable { + /** + Array of relationships for the relations query. + */ public var relations: [QueryRelationsRelationship]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/QueryResponse.swift b/Source/DiscoveryV1/Models/QueryResponse.swift index 889c3c779..4f35832f3 100644 --- a/Source/DiscoveryV1/Models/QueryResponse.swift +++ b/Source/DiscoveryV1/Models/QueryResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,29 @@ import Foundation */ public struct QueryResponse: Codable, Equatable { + /** + The number of matching results for the query. + */ public var matchingResults: Int? + /** + Array of document results for the query. + */ public var results: [QueryResult]? + /** + Array of aggregation results for the query. + */ public var aggregations: [QueryAggregation]? + /** + Array of passage results for the query. + */ public var passages: [QueryPassages]? + /** + The number of duplicate results removed. + */ public var duplicatesRemoved: Int? /** diff --git a/Source/DiscoveryV1/Models/QueryResult.swift b/Source/DiscoveryV1/Models/QueryResult.swift index ba2f3ee28..f106b3805 100644 --- a/Source/DiscoveryV1/Models/QueryResult.swift +++ b/Source/DiscoveryV1/Models/QueryResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,6 +40,11 @@ public struct QueryResult: Codable, Equatable { */ public var resultMetadata: QueryResultMetadata? + /** + Automatically extracted result title. + */ + public var title: String? + /// Additional properties associated with this model. public var additionalProperties: [String: JSON] @@ -49,7 +54,8 @@ public struct QueryResult: Codable, Equatable { case metadata = "metadata" case collectionID = "collection_id" case resultMetadata = "result_metadata" - static let allValues = [id, metadata, collectionID, resultMetadata] + case title = "title" + static let allValues = [id, metadata, collectionID, resultMetadata, title] } public init(from decoder: Decoder) throws { @@ -58,6 +64,7 @@ public struct QueryResult: Codable, Equatable { metadata = try container.decodeIfPresent([String: JSON].self, forKey: .metadata) collectionID = try container.decodeIfPresent(String.self, forKey: .collectionID) resultMetadata = try container.decodeIfPresent(QueryResultMetadata.self, forKey: .resultMetadata) + title = try container.decodeIfPresent(String.self, forKey: .title) let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self) additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues) } @@ -68,6 +75,7 @@ public struct QueryResult: Codable, Equatable { try container.encodeIfPresent(metadata, forKey: .metadata) try container.encodeIfPresent(collectionID, forKey: .collectionID) try container.encodeIfPresent(resultMetadata, forKey: .resultMetadata) + try container.encodeIfPresent(title, forKey: .title) var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self) try dynamicContainer.encodeIfPresent(additionalProperties) } diff --git a/Source/DiscoveryV1/Models/QueryResultMetadata.swift b/Source/DiscoveryV1/Models/QueryResultMetadata.swift index 6a8cd90ab..7a1a4fac7 100644 --- a/Source/DiscoveryV1/Models/QueryResultMetadata.swift +++ b/Source/DiscoveryV1/Models/QueryResultMetadata.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ public struct QueryResultMetadata: Codable, Equatable { An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. */ - public var score: Double? + public var score: Double /** The confidence score for the given result. Calculated based on how relevant the result is estimated to be. diff --git a/Source/DiscoveryV1/Models/RetrievalDetails.swift b/Source/DiscoveryV1/Models/RetrievalDetails.swift index 2c8e63498..e514bd532 100644 --- a/Source/DiscoveryV1/Models/RetrievalDetails.swift +++ b/Source/DiscoveryV1/Models/RetrievalDetails.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SearchStatus.swift b/Source/DiscoveryV1/Models/SearchStatus.swift index bc5e977d3..9bb9a7572 100644 --- a/Source/DiscoveryV1/Models/SearchStatus.swift +++ b/Source/DiscoveryV1/Models/SearchStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SegmentSettings.swift b/Source/DiscoveryV1/Models/SegmentSettings.swift index 196c126a0..810aa853b 100644 --- a/Source/DiscoveryV1/Models/SegmentSettings.swift +++ b/Source/DiscoveryV1/Models/SegmentSettings.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,8 @@ public struct SegmentSettings: Codable, Equatable { public var enabled: Bool? /** - Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. + Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content + of the header field that the segmentation splits at is used as the **title** field for that segmented result. */ public var selectorTags: [String]? @@ -42,7 +43,8 @@ public struct SegmentSettings: Codable, Equatable { - parameter enabled: Enables/disables the Document Segmentation feature. - parameter selectorTags: Defines the heading level that splits into document segments. Valid values are h1, h2, - h3, h4, h5, h6. + h3, h4, h5, h6. The content of the header field that the segmentation splits at is used as the **title** field + for that segmented result. - returns: An initialized `SegmentSettings`. */ diff --git a/Source/DiscoveryV1/Models/Source.swift b/Source/DiscoveryV1/Models/Source.swift index 71e040948..1bd0bb794 100644 --- a/Source/DiscoveryV1/Models/Source.swift +++ b/Source/DiscoveryV1/Models/Source.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,12 +27,14 @@ public struct Source: Codable, Equatable { - `salesforce` indicates the configuration is to connect to Salesforce. - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint Online. - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. */ public enum TypeEnum: String { case box = "box" case salesforce = "salesforce" case sharepoint = "sharepoint" case webCrawl = "web_crawl" + case cloudObjectStorage = "cloud_object_storage" } /** @@ -41,6 +43,7 @@ public struct Source: Codable, Equatable { - `salesforce` indicates the configuration is to connect to Salesforce. - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint Online. - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. */ public var type: String? @@ -77,6 +80,7 @@ public struct Source: Codable, Equatable { - `salesforce` indicates the configuration is to connect to Salesforce. - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint Online. - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. - parameter credentialID: The **credential_id** of the credentials to use to connect to the source. Credentials are defined using the **credentials** method. The **source_type** of the credentials used must match the **type** field specified in this object. diff --git a/Source/DiscoveryV1/Models/SourceOptions.swift b/Source/DiscoveryV1/Models/SourceOptions.swift index 74ad6e3cd..2b2f6b9cb 100644 --- a/Source/DiscoveryV1/Models/SourceOptions.swift +++ b/Source/DiscoveryV1/Models/SourceOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,12 +45,26 @@ public struct SourceOptions: Codable, Equatable { */ public var urls: [SourceOptionsWebCrawl]? + /** + Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the + **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. + */ + public var buckets: [SourceOptionsBuckets]? + + /** + When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array + must not be specified. + */ + public var crawlAllBuckets: Bool? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case folders = "folders" case objects = "objects" case siteCollections = "site_collections" case urls = "urls" + case buckets = "buckets" + case crawlAllBuckets = "crawl_all_buckets" } /** @@ -65,6 +79,11 @@ public struct SourceOptions: Codable, Equatable { `sharepoint`. - parameter urls: Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. + - parameter buckets: Array of cloud object store buckets to begin crawling. Only valid and required when the + **type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is + `false` or not specified. + - parameter crawlAllBuckets: When `true`, all buckets in the specified cloud object store are crawled. If set to + `true`, the **buckets** array must not be specified. - returns: An initialized `SourceOptions`. */ @@ -72,13 +91,17 @@ public struct SourceOptions: Codable, Equatable { folders: [SourceOptionsFolder]? = nil, objects: [SourceOptionsObject]? = nil, siteCollections: [SourceOptionsSiteColl]? = nil, - urls: [SourceOptionsWebCrawl]? = nil + urls: [SourceOptionsWebCrawl]? = nil, + buckets: [SourceOptionsBuckets]? = nil, + crawlAllBuckets: Bool? = nil ) { self.folders = folders self.objects = objects self.siteCollections = siteCollections self.urls = urls + self.buckets = buckets + self.crawlAllBuckets = crawlAllBuckets } } diff --git a/Source/DiscoveryV1/Models/SourceOptionsBuckets.swift b/Source/DiscoveryV1/Models/SourceOptionsBuckets.swift new file mode 100644 index 000000000..e08facbf4 --- /dev/null +++ b/Source/DiscoveryV1/Models/SourceOptionsBuckets.swift @@ -0,0 +1,59 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Object defining a cloud object store bucket to crawl. + */ +public struct SourceOptionsBuckets: Codable, Equatable { + + /** + The name of the cloud object store bucket to crawl. + */ + public var name: String + + /** + The number of documents to crawl from this cloud object store bucket. If not specified, all documents in the bucket + are crawled. + */ + public var limit: Int? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case name = "name" + case limit = "limit" + } + + /** + Initialize a `SourceOptionsBuckets` with member variables. + + - parameter name: The name of the cloud object store bucket to crawl. + - parameter limit: The number of documents to crawl from this cloud object store bucket. If not specified, all + documents in the bucket are crawled. + + - returns: An initialized `SourceOptionsBuckets`. + */ + public init( + name: String, + limit: Int? = nil + ) + { + self.name = name + self.limit = limit + } + +} diff --git a/Source/DiscoveryV1/Models/SourceOptionsFolder.swift b/Source/DiscoveryV1/Models/SourceOptionsFolder.swift index 994bed7a5..69b02083c 100644 --- a/Source/DiscoveryV1/Models/SourceOptionsFolder.swift +++ b/Source/DiscoveryV1/Models/SourceOptionsFolder.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SourceOptionsObject.swift b/Source/DiscoveryV1/Models/SourceOptionsObject.swift index 1e750cc89..6221917ee 100644 --- a/Source/DiscoveryV1/Models/SourceOptionsObject.swift +++ b/Source/DiscoveryV1/Models/SourceOptionsObject.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SourceOptionsSiteColl.swift b/Source/DiscoveryV1/Models/SourceOptionsSiteColl.swift index bc1acdb0f..22921e506 100644 --- a/Source/DiscoveryV1/Models/SourceOptionsSiteColl.swift +++ b/Source/DiscoveryV1/Models/SourceOptionsSiteColl.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SourceOptionsWebCrawl.swift b/Source/DiscoveryV1/Models/SourceOptionsWebCrawl.swift index 874b9a612..09e1eb876 100644 --- a/Source/DiscoveryV1/Models/SourceOptionsWebCrawl.swift +++ b/Source/DiscoveryV1/Models/SourceOptionsWebCrawl.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SourceSchedule.swift b/Source/DiscoveryV1/Models/SourceSchedule.swift index b95c2452a..15c9c6f4c 100644 --- a/Source/DiscoveryV1/Models/SourceSchedule.swift +++ b/Source/DiscoveryV1/Models/SourceSchedule.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/SourceStatus.swift b/Source/DiscoveryV1/Models/SourceStatus.swift index bc8bfb83d..fb5280954 100644 --- a/Source/DiscoveryV1/Models/SourceStatus.swift +++ b/Source/DiscoveryV1/Models/SourceStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,16 +26,13 @@ public struct SourceStatus: Codable, Equatable { configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. - `complete` indicates that the crawl has completed with no errors. - - `complete_with_notices` indicates that some notices were generated during the crawl. Notices can be checked by - using the **notices** query method. - - `stopped` indicates that the crawl has stopped but is not complete. + - `queued` indicates that the crawl has been paused by the system and will automatically restart when possible. */ public enum Status: String { case running = "running" case complete = "complete" - case completeWithNotices = "complete_with_notices" - case stopped = "stopped" case notConfigured = "not_configured" + case queued = "queued" } /** @@ -43,9 +40,7 @@ public struct SourceStatus: Codable, Equatable { configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. - `complete` indicates that the crawl has completed with no errors. - - `complete_with_notices` indicates that some notices were generated during the crawl. Notices can be checked by - using the **notices** query method. - - `stopped` indicates that the crawl has stopped but is not complete. + - `queued` indicates that the crawl has been paused by the system and will automatically restart when possible. */ public var status: String? diff --git a/Source/DiscoveryV1/Models/Term.swift b/Source/DiscoveryV1/Models/Term.swift index 7facacc82..0e55bad28 100644 --- a/Source/DiscoveryV1/Models/Term.swift +++ b/Source/DiscoveryV1/Models/Term.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Term: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/TestDocument.swift b/Source/DiscoveryV1/Models/TestDocument.swift index b9d0db8e7..bd2eccf1f 100644 --- a/Source/DiscoveryV1/Models/TestDocument.swift +++ b/Source/DiscoveryV1/Models/TestDocument.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/Timeslice.swift b/Source/DiscoveryV1/Models/Timeslice.swift index 14a3e6a67..e0a70f4ef 100644 --- a/Source/DiscoveryV1/Models/Timeslice.swift +++ b/Source/DiscoveryV1/Models/Timeslice.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct Timeslice: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/TokenDict.swift b/Source/DiscoveryV1/Models/TokenDict.swift index 902f72f75..d3b18259c 100644 --- a/Source/DiscoveryV1/Models/TokenDict.swift +++ b/Source/DiscoveryV1/Models/TokenDict.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/TokenDictRule.swift b/Source/DiscoveryV1/Models/TokenDictRule.swift index 5f86fa449..d5eb6537c 100644 --- a/Source/DiscoveryV1/Models/TokenDictRule.swift +++ b/Source/DiscoveryV1/Models/TokenDictRule.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ public struct TokenDictRule: Codable, Equatable { /** The string to tokenize. */ - public var text: String? + public var text: String /** Array of tokens that the `text` field is split into when found. */ - public var tokens: [String]? + public var tokens: [String] /** Array of tokens that represent the content of the `text` field in an alternate character set. @@ -39,7 +39,7 @@ public struct TokenDictRule: Codable, Equatable { /** The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. */ - public var partOfSpeech: String? + public var partOfSpeech: String // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { @@ -54,24 +54,24 @@ public struct TokenDictRule: Codable, Equatable { - parameter text: The string to tokenize. - parameter tokens: Array of tokens that the `text` field is split into when found. - - parameter readings: Array of tokens that represent the content of the `text` field in an alternate character - set. - parameter partOfSpeech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. + - parameter readings: Array of tokens that represent the content of the `text` field in an alternate character + set. - returns: An initialized `TokenDictRule`. */ public init( - text: String? = nil, - tokens: [String]? = nil, - readings: [String]? = nil, - partOfSpeech: String? = nil + text: String, + tokens: [String], + partOfSpeech: String, + readings: [String]? = nil ) { self.text = text self.tokens = tokens - self.readings = readings self.partOfSpeech = partOfSpeech + self.readings = readings } } diff --git a/Source/DiscoveryV1/Models/TokenDictStatusResponse.swift b/Source/DiscoveryV1/Models/TokenDictStatusResponse.swift index 48a721a9b..18fab2312 100644 --- a/Source/DiscoveryV1/Models/TokenDictStatusResponse.swift +++ b/Source/DiscoveryV1/Models/TokenDictStatusResponse.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/TopHits.swift b/Source/DiscoveryV1/Models/TopHits.swift index 51fe0913f..73a615a8a 100644 --- a/Source/DiscoveryV1/Models/TopHits.swift +++ b/Source/DiscoveryV1/Models/TopHits.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,9 @@ public struct TopHits: Codable, Equatable { */ public var type: String? + /** + Array of aggregation results. + */ public var results: [AggregationResult]? /** diff --git a/Source/DiscoveryV1/Models/TopHitsResults.swift b/Source/DiscoveryV1/Models/TopHitsResults.swift index bf21ea8ff..a2689ddbc 100644 --- a/Source/DiscoveryV1/Models/TopHitsResults.swift +++ b/Source/DiscoveryV1/Models/TopHitsResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/TrainingDataSet.swift b/Source/DiscoveryV1/Models/TrainingDataSet.swift index f726e7e81..89407acd0 100644 --- a/Source/DiscoveryV1/Models/TrainingDataSet.swift +++ b/Source/DiscoveryV1/Models/TrainingDataSet.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,19 @@ import Foundation /** TrainingDataSet. */ public struct TrainingDataSet: Codable, Equatable { + /** + The environment id associated with this training data set. + */ public var environmentID: String? + /** + The collection id associated with this training data set. + */ public var collectionID: String? + /** + Array of training queries. + */ public var queries: [TrainingQuery]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/TrainingExample.swift b/Source/DiscoveryV1/Models/TrainingExample.swift index aa549db3b..9b27835d6 100644 --- a/Source/DiscoveryV1/Models/TrainingExample.swift +++ b/Source/DiscoveryV1/Models/TrainingExample.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,19 @@ import Foundation /** TrainingExample. */ public struct TrainingExample: Codable, Equatable { + /** + The document ID associated with this training example. + */ public var documentID: String? + /** + The cross reference associated with this training example. + */ public var crossReference: String? + /** + The relevance of the training example. + */ public var relevance: Int? // Map each property name to the key that shall be used for encoding/decoding. @@ -35,9 +44,9 @@ public struct TrainingExample: Codable, Equatable { /** Initialize a `TrainingExample` with member variables. - - parameter documentID: - - parameter crossReference: - - parameter relevance: + - parameter documentID: The document ID associated with this training example. + - parameter crossReference: The cross reference associated with this training example. + - parameter relevance: The relevance of the training example. - returns: An initialized `TrainingExample`. */ diff --git a/Source/DiscoveryV1/Models/TrainingExampleList.swift b/Source/DiscoveryV1/Models/TrainingExampleList.swift index 769ea38db..1cdddbefe 100644 --- a/Source/DiscoveryV1/Models/TrainingExampleList.swift +++ b/Source/DiscoveryV1/Models/TrainingExampleList.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ import Foundation /** TrainingExampleList. */ public struct TrainingExampleList: Codable, Equatable { + /** + Array of training examples. + */ public var examples: [TrainingExample]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/TrainingExamplePatch.swift b/Source/DiscoveryV1/Models/TrainingExamplePatch.swift index c478f7936..e7ff03fba 100644 --- a/Source/DiscoveryV1/Models/TrainingExamplePatch.swift +++ b/Source/DiscoveryV1/Models/TrainingExamplePatch.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,14 @@ import Foundation /** TrainingExamplePatch. */ internal struct TrainingExamplePatch: Codable, Equatable { + /** + The example to add. + */ public var crossReference: String? + /** + The relevance value for this example. + */ public var relevance: Int? // Map each property name to the key that shall be used for encoding/decoding. @@ -32,8 +38,8 @@ internal struct TrainingExamplePatch: Codable, Equatable { /** Initialize a `TrainingExamplePatch` with member variables. - - parameter crossReference: - - parameter relevance: + - parameter crossReference: The example to add. + - parameter relevance: The relevance value for this example. - returns: An initialized `TrainingExamplePatch`. */ diff --git a/Source/DiscoveryV1/Models/TrainingQuery.swift b/Source/DiscoveryV1/Models/TrainingQuery.swift index 1822bafd5..e7d4e62ac 100644 --- a/Source/DiscoveryV1/Models/TrainingQuery.swift +++ b/Source/DiscoveryV1/Models/TrainingQuery.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,24 @@ import Foundation /** TrainingQuery. */ public struct TrainingQuery: Codable, Equatable { + /** + The query ID associated with the training query. + */ public var queryID: String? + /** + The natural text query for the training query. + */ public var naturalLanguageQuery: String? + /** + The filter used on the collection before the **natural_language_query** is applied. + */ public var filter: String? + /** + Array of training examples. + */ public var examples: [TrainingExample]? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/TrainingStatus.swift b/Source/DiscoveryV1/Models/TrainingStatus.swift index 5e03f5a4f..f6b20dcf1 100644 --- a/Source/DiscoveryV1/Models/TrainingStatus.swift +++ b/Source/DiscoveryV1/Models/TrainingStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,22 +19,49 @@ import Foundation /** TrainingStatus. */ public struct TrainingStatus: Codable, Equatable { + /** + The total number of training examples uploaded to this collection. + */ public var totalExamples: Int? + /** + When `true`, the collection has been successfully trained. + */ public var available: Bool? + /** + When `true`, the collection is currently processing training. + */ public var processing: Bool? + /** + When `true`, the collection has a sufficent amount of queries added for training to occur. + */ public var minimumQueriesAdded: Bool? + /** + When `true`, the collection has a sufficent amount of examples added for training to occur. + */ public var minimumExamplesAdded: Bool? + /** + When `true`, the collection has a sufficent amount of diversity in labeled results for training to occur. + */ public var sufficientLabelDiversity: Bool? + /** + The number of notices associated with this data set. + */ public var notices: Int? + /** + The timestamp of when the collection was successfully trained. + */ public var successfullyTrained: Date? + /** + The timestamp of when the data was uploaded. + */ public var dataUpdated: Date? // Map each property name to the key that shall be used for encoding/decoding. diff --git a/Source/DiscoveryV1/Models/UpdateCollectionRequest.swift b/Source/DiscoveryV1/Models/UpdateCollectionRequest.swift index 13fa00ada..6159b5c6f 100644 --- a/Source/DiscoveryV1/Models/UpdateCollectionRequest.swift +++ b/Source/DiscoveryV1/Models/UpdateCollectionRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/UpdateEnvironmentRequest.swift b/Source/DiscoveryV1/Models/UpdateEnvironmentRequest.swift index 9212c4443..08b0895f9 100644 --- a/Source/DiscoveryV1/Models/UpdateEnvironmentRequest.swift +++ b/Source/DiscoveryV1/Models/UpdateEnvironmentRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/WordHeadingDetection.swift b/Source/DiscoveryV1/Models/WordHeadingDetection.swift index e5bd0e02a..4d3e01e7d 100644 --- a/Source/DiscoveryV1/Models/WordHeadingDetection.swift +++ b/Source/DiscoveryV1/Models/WordHeadingDetection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/WordSettings.swift b/Source/DiscoveryV1/Models/WordSettings.swift index 81d560be1..71e7a41a1 100644 --- a/Source/DiscoveryV1/Models/WordSettings.swift +++ b/Source/DiscoveryV1/Models/WordSettings.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/DiscoveryV1/Models/WordStyle.swift b/Source/DiscoveryV1/Models/WordStyle.swift index 87ec9cf78..da34b9007 100644 --- a/Source/DiscoveryV1/Models/WordStyle.swift +++ b/Source/DiscoveryV1/Models/WordStyle.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,14 @@ import Foundation /** WordStyle. */ public struct WordStyle: Codable, Equatable { + /** + HTML head level that content matching this style is tagged with. + */ public var level: Int? + /** + Array of word style names to convert. + */ public var names: [String]? // Map each property name to the key that shall be used for encoding/decoding. @@ -32,8 +38,8 @@ public struct WordStyle: Codable, Equatable { /** Initialize a `WordStyle` with member variables. - - parameter level: - - parameter names: + - parameter level: HTML head level that content matching this style is tagged with. + - parameter names: Array of word style names to convert. - returns: An initialized `WordStyle`. */ diff --git a/Source/DiscoveryV1/Models/XPathPatterns.swift b/Source/DiscoveryV1/Models/XPathPatterns.swift index e96b19885..770cbb440 100644 --- a/Source/DiscoveryV1/Models/XPathPatterns.swift +++ b/Source/DiscoveryV1/Models/XPathPatterns.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ import Foundation /** XPathPatterns. */ public struct XPathPatterns: Codable, Equatable { + /** + An array to XPaths. + */ public var xpaths: [String]? // Map each property name to the key that shall be used for encoding/decoding. @@ -29,7 +32,7 @@ public struct XPathPatterns: Codable, Equatable { /** Initialize a `XPathPatterns` with member variables. - - parameter xpaths: + - parameter xpaths: An array to XPaths. - returns: An initialized `XPathPatterns`. */ diff --git a/Source/LanguageTranslatorV3/LanguageTranslator.swift b/Source/LanguageTranslatorV3/LanguageTranslator.swift index be5b4ae71..9b3eee932 100644 --- a/Source/LanguageTranslatorV3/LanguageTranslator.swift +++ b/Source/LanguageTranslatorV3/LanguageTranslator.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,22 +38,23 @@ public class LanguageTranslator { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `LanguageTranslator` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "language_translator") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "language_translator") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -63,20 +64,22 @@ public class LanguageTranslator { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `LanguageTranslator` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -90,6 +93,7 @@ public class LanguageTranslator { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -100,8 +104,9 @@ public class LanguageTranslator { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -124,16 +129,25 @@ public class LanguageTranslator { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -163,7 +177,7 @@ public class LanguageTranslator { modelID: modelID, source: source, target: target) - guard let body = try? JSONEncoder().encode(translateRequest) else { + guard let body = try? JSON.encoder.encode(translateRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -173,8 +187,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "translate") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "translate") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -216,8 +230,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listIdentifiableLanguages") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listIdentifiableLanguages") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -266,8 +280,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "identify") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "identify") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "text/plain" @@ -317,8 +331,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -369,8 +383,6 @@ public class LanguageTranslator { - parameter baseModelID: The model ID of the model to use as the base for customization. To see available models, use the `List models` method. Usually all IBM provided models are customizable. In addition, all your models that have been created via parallel corpus customization, can be further customized with a forced glossary. - - parameter name: An optional model name that you can use to identify the model. Valid characters are letters, - numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. - parameter forcedGlossary: A TMX file with your customizations. The customizations in the file completely overwrite the domain translaton data, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain single words @@ -378,34 +390,26 @@ public class LanguageTranslator { - parameter parallelCorpus: A TMX file with parallel sentences for source and target language. You can upload multiple parallel_corpus files in one request. All uploaded parallel_corpus files combined, your parallel corpus must contain at least 5,000 parallel sentences to train successfully. + - parameter name: An optional model name that you can use to identify the model. Valid characters are letters, + numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createModel( baseModelID: String, + forcedGlossary: Data? = nil, + parallelCorpus: Data? = nil, name: String? = nil, - forcedGlossary: URL? = nil, - parallelCorpus: URL? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() if let forcedGlossary = forcedGlossary { - do { - try multipartFormData.append(file: forcedGlossary, withName: "forced_glossary") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(forcedGlossary.path)")) - return - } + multipartFormData.append(forcedGlossary, withName: "forced_glossary", fileName: "filename") } if let parallelCorpus = parallelCorpus { - do { - try multipartFormData.append(file: parallelCorpus, withName: "parallel_corpus") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(parallelCorpus.path)")) - return - } + multipartFormData.append(parallelCorpus, withName: "parallel_corpus", fileName: "filename") } guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) @@ -417,8 +421,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -466,8 +470,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -514,8 +518,8 @@ public class LanguageTranslator { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters diff --git a/Source/LanguageTranslatorV3/Models/DeleteModelResult.swift b/Source/LanguageTranslatorV3/Models/DeleteModelResult.swift index eb101e282..183eccaff 100644 --- a/Source/LanguageTranslatorV3/Models/DeleteModelResult.swift +++ b/Source/LanguageTranslatorV3/Models/DeleteModelResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/IdentifiableLanguage.swift b/Source/LanguageTranslatorV3/Models/IdentifiableLanguage.swift index 19f5bc0eb..d66960fd6 100644 --- a/Source/LanguageTranslatorV3/Models/IdentifiableLanguage.swift +++ b/Source/LanguageTranslatorV3/Models/IdentifiableLanguage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/IdentifiableLanguages.swift b/Source/LanguageTranslatorV3/Models/IdentifiableLanguages.swift index 534ea4ac4..5e69eb2c5 100644 --- a/Source/LanguageTranslatorV3/Models/IdentifiableLanguages.swift +++ b/Source/LanguageTranslatorV3/Models/IdentifiableLanguages.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/IdentifiedLanguage.swift b/Source/LanguageTranslatorV3/Models/IdentifiedLanguage.swift index 3cdb43884..77d9a9ef2 100644 --- a/Source/LanguageTranslatorV3/Models/IdentifiedLanguage.swift +++ b/Source/LanguageTranslatorV3/Models/IdentifiedLanguage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/IdentifiedLanguages.swift b/Source/LanguageTranslatorV3/Models/IdentifiedLanguages.swift index bb0f5cde1..96dc5bd73 100644 --- a/Source/LanguageTranslatorV3/Models/IdentifiedLanguages.swift +++ b/Source/LanguageTranslatorV3/Models/IdentifiedLanguages.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/TranslateRequest.swift b/Source/LanguageTranslatorV3/Models/TranslateRequest.swift index f7b20c116..b71302f5d 100644 --- a/Source/LanguageTranslatorV3/Models/TranslateRequest.swift +++ b/Source/LanguageTranslatorV3/Models/TranslateRequest.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/Translation.swift b/Source/LanguageTranslatorV3/Models/Translation.swift index d38c0b5af..3508f8445 100644 --- a/Source/LanguageTranslatorV3/Models/Translation.swift +++ b/Source/LanguageTranslatorV3/Models/Translation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/TranslationModel.swift b/Source/LanguageTranslatorV3/Models/TranslationModel.swift index e9529ebd6..c8cc6541d 100644 --- a/Source/LanguageTranslatorV3/Models/TranslationModel.swift +++ b/Source/LanguageTranslatorV3/Models/TranslationModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/TranslationModels.swift b/Source/LanguageTranslatorV3/Models/TranslationModels.swift index ceb5d6823..e3a7a6f63 100644 --- a/Source/LanguageTranslatorV3/Models/TranslationModels.swift +++ b/Source/LanguageTranslatorV3/Models/TranslationModels.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/LanguageTranslatorV3/Models/TranslationResult.swift b/Source/LanguageTranslatorV3/Models/TranslationResult.swift index be397af29..e236ce0da 100644 --- a/Source/LanguageTranslatorV3/Models/TranslationResult.swift +++ b/Source/LanguageTranslatorV3/Models/TranslationResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/Classification.swift b/Source/NaturalLanguageClassifierV1/Models/Classification.swift index 206dd823d..b84e7d525 100644 --- a/Source/NaturalLanguageClassifierV1/Models/Classification.swift +++ b/Source/NaturalLanguageClassifierV1/Models/Classification.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/ClassificationCollection.swift b/Source/NaturalLanguageClassifierV1/Models/ClassificationCollection.swift index 8f4623db3..d2b9d91c4 100644 --- a/Source/NaturalLanguageClassifierV1/Models/ClassificationCollection.swift +++ b/Source/NaturalLanguageClassifierV1/Models/ClassificationCollection.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/ClassifiedClass.swift b/Source/NaturalLanguageClassifierV1/Models/ClassifiedClass.swift index 7946413e8..b88840f38 100644 --- a/Source/NaturalLanguageClassifierV1/Models/ClassifiedClass.swift +++ b/Source/NaturalLanguageClassifierV1/Models/ClassifiedClass.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/Classifier.swift b/Source/NaturalLanguageClassifierV1/Models/Classifier.swift index d19e45967..444be9230 100644 --- a/Source/NaturalLanguageClassifierV1/Models/Classifier.swift +++ b/Source/NaturalLanguageClassifierV1/Models/Classifier.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/ClassifierList.swift b/Source/NaturalLanguageClassifierV1/Models/ClassifierList.swift index af36440e9..7b97a8e9d 100644 --- a/Source/NaturalLanguageClassifierV1/Models/ClassifierList.swift +++ b/Source/NaturalLanguageClassifierV1/Models/ClassifierList.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift b/Source/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift index db50a2884..4cacc0b0b 100644 --- a/Source/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift +++ b/Source/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/ClassifyInput.swift b/Source/NaturalLanguageClassifierV1/Models/ClassifyInput.swift index 9e1aff990..0a800fdee 100644 --- a/Source/NaturalLanguageClassifierV1/Models/ClassifyInput.swift +++ b/Source/NaturalLanguageClassifierV1/Models/ClassifyInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/Models/CollectionItem.swift b/Source/NaturalLanguageClassifierV1/Models/CollectionItem.swift index 5f12cc930..02879f40a 100644 --- a/Source/NaturalLanguageClassifierV1/Models/CollectionItem.swift +++ b/Source/NaturalLanguageClassifierV1/Models/CollectionItem.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift b/Source/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift index a32bd98ff..922599713 100644 --- a/Source/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift +++ b/Source/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,20 +36,20 @@ public class NaturalLanguageClassifier { var session = URLSession(configuration: URLSessionConfiguration.default) var authMethod: AuthenticationMethod + #if os(Linux) /** Create a `NaturalLanguageClassifier` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. */ - public init?(credentialsFile: URL) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "natural_language_classifier") else { + public init?() { + guard let credentials = Shared.extractCredentials(serviceName: "natural_language_classifier") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -59,7 +59,9 @@ public class NaturalLanguageClassifier { self.serviceURL = serviceURL } self.authMethod = authMethod + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `NaturalLanguageClassifier` object. @@ -69,6 +71,7 @@ public class NaturalLanguageClassifier { */ public init(username: String, password: String) { self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -79,6 +82,7 @@ public class NaturalLanguageClassifier { */ public init(apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) + RestRequest.userAgent = Shared.userAgent } /** @@ -88,6 +92,7 @@ public class NaturalLanguageClassifier { */ public init(accessToken: String) { self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -110,19 +115,25 @@ public class NaturalLanguageClassifier { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(description)) = json["description"] { - metadata["description"] = description - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -145,7 +156,7 @@ public class NaturalLanguageClassifier { // construct body let classifyRequest = ClassifyInput( text: text) - guard let body = try? JSONEncoder().encode(classifyRequest) else { + guard let body = try? JSON.encoder.encode(classifyRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -155,8 +166,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classify") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classify") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -201,7 +212,7 @@ public class NaturalLanguageClassifier { // construct body let classifyCollectionRequest = ClassifyCollectionInput( collection: collection) - guard let body = try? JSONEncoder().encode(classifyCollectionRequest) else { + guard let body = try? JSON.encoder.encode(classifyCollectionRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -211,8 +222,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classifyCollection") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classifyCollection") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -253,25 +264,15 @@ public class NaturalLanguageClassifier { - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createClassifier( - metadata: URL, - trainingData: URL, + metadata: Data, + trainingData: Data, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: metadata, withName: "training_metadata") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(metadata.path)")) - return - } - do { - try multipartFormData.append(file: trainingData, withName: "training_data") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(trainingData.path)")) - return - } + multipartFormData.append(metadata, withName: "training_metadata", fileName: "filename") + multipartFormData.append(trainingData, withName: "training_data", fileName: "filename") guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -282,8 +283,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -319,8 +320,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassifiers") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassifiers") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -356,8 +357,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -396,8 +397,8 @@ public class NaturalLanguageClassifier { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request diff --git a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift index f172e1c8c..eaf70bd14 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ import Foundation /** - Results of the analysis, organized by feature. + Analysis results for each requested feature. */ public struct AnalysisResults: Codable, Equatable { @@ -37,9 +37,9 @@ public struct AnalysisResults: Codable, Equatable { public var retrievedURL: String? /** - Usage information. + API usage information for the request. */ - public var usage: Usage? + public var usage: AnalysisResultsUsage? /** The general concepts referenced or alluded to in the analyzed text. @@ -62,16 +62,14 @@ public struct AnalysisResults: Codable, Equatable { public var categories: [CategoriesResult]? /** - The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be - returned for detected entities, keywords, or user-specified target phrases found in the text. + The anger, disgust, fear, joy, or sadness conveyed by the content. */ public var emotion: EmotionResult? /** - The authors, publication date, title, prominent page image, and RSS/ATOM feeds of the webpage. Supports URL and - HTML input types. + Webpage metadata, such as the author and the title of the page. */ - public var metadata: MetadataResult? + public var metadata: AnalysisResultsMetadata? /** The relationships between entities in the content. @@ -88,6 +86,11 @@ public struct AnalysisResults: Codable, Equatable { */ public var sentiment: SentimentResult? + /** + Tokens and sentences returned from syntax analysis. + */ + public var syntax: SyntaxResult? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case language = "language" @@ -103,6 +106,7 @@ public struct AnalysisResults: Codable, Equatable { case relations = "relations" case semanticRoles = "semantic_roles" case sentiment = "sentiment" + case syntax = "syntax" } } diff --git a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsEmotion.swift b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsEmotion.swift new file mode 100644 index 000000000..ae067b880 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsEmotion.swift @@ -0,0 +1,37 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + The anger, disgust, fear, joy, or sadness conveyed by the content. + */ +public struct AnalysisResultsEmotion: Codable, Equatable { + + public var document: DocumentEmotionResults? + + /** + Emotion results for specified targets. + */ + public var targets: [TargetedEmotionResults]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case document = "document" + case targets = "targets" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift new file mode 100644 index 000000000..670bebd8a --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Webpage metadata, such as the author and the title of the page. + */ +public struct AnalysisResultsMetadata: Codable, Equatable { + + /** + The authors of the document. + */ + public var authors: [Author]? + + /** + The publication date in the format ISO 8601. + */ + public var publicationDate: String? + + /** + The title of the document. + */ + public var title: String? + + /** + URL of a prominent image on the webpage. + */ + public var image: String? + + /** + RSS/ATOM feeds found on the webpage. + */ + public var feeds: [Feed]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case authors = "authors" + case publicationDate = "publication_date" + case title = "title" + case image = "image" + case feeds = "feeds" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsSentiment.swift b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsSentiment.swift new file mode 100644 index 000000000..d3acebe33 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsSentiment.swift @@ -0,0 +1,37 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + The sentiment of the content. + */ +public struct AnalysisResultsSentiment: Codable, Equatable { + + public var document: DocumentSentimentResults? + + /** + The targeted sentiment to analyze. + */ + public var targets: [TargetedSentimentResults]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case document = "document" + case targets = "targets" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsUsage.swift b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsUsage.swift new file mode 100644 index 000000000..b4625d462 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/AnalysisResultsUsage.swift @@ -0,0 +1,46 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + API usage information for the request. + */ +public struct AnalysisResultsUsage: Codable, Equatable { + + /** + Number of features used in the API call. + */ + public var features: Int? + + /** + Number of text characters processed. + */ + public var textCharacters: Int? + + /** + Number of 10,000-character units processed. + */ + public var textUnits: Int? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case features = "features" + case textCharacters = "text_characters" + case textUnits = "text_units" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/Author.swift b/Source/NaturalLanguageUnderstandingV1/Models/Author.swift index 31e45168a..8a26a05f8 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/Author.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/Author.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/CategoriesOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/CategoriesOptions.swift index 0377b209f..e05527695 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/CategoriesOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/CategoriesOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,23 +27,35 @@ public struct CategoriesOptions: Codable, Equatable { */ public var limit: Int? + /** + Enter a [custom model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to + override the standard categories model. + */ + public var model: String? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case limit = "limit" + case model = "model" } /** Initialize a `CategoriesOptions` with member variables. - parameter limit: Maximum number of categories to return. + - parameter model: Enter a [custom + model](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) ID to override the + standard categories model. - returns: An initialized `CategoriesOptions`. */ public init( - limit: Int? = nil + limit: Int? = nil, + model: String? = nil ) { self.limit = limit + self.model = model } } diff --git a/Source/NaturalLanguageUnderstandingV1/Models/CategoriesResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/CategoriesResult.swift index e4a634e45..5f9a76812 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/CategoriesResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/CategoriesResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/ConceptsOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/ConceptsOptions.swift index d1054e8cd..960b952d0 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/ConceptsOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/ConceptsOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/ConceptsResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/ConceptsResult.swift index 1fba80ae6..1219ecc8c 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/ConceptsResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/ConceptsResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/DeleteModelResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/DeleteModelResults.swift index 5d9c138d3..4b0a692df 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/DeleteModelResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/DeleteModelResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/DisambiguationResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/DisambiguationResult.swift index 7a119a621..b19fb1769 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/DisambiguationResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/DisambiguationResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResults.swift index 1bb262c3c..bb0b0c4d0 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResultsEmotion.swift b/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResultsEmotion.swift new file mode 100644 index 000000000..678b3a01c --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/DocumentEmotionResultsEmotion.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Emotion results for the document as a whole. + */ +public struct DocumentEmotionResultsEmotion: Codable, Equatable { + + /** + Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. + */ + public var anger: Double? + + /** + Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. + */ + public var disgust: Double? + + /** + Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. + */ + public var fear: Double? + + /** + Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. + */ + public var joy: Double? + + /** + Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. + */ + public var sadness: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case anger = "anger" + case disgust = "disgust" + case fear = "fear" + case joy = "joy" + case sadness = "sadness" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/DocumentSentimentResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/DocumentSentimentResults.swift index bb46bb9c3..ada426161 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/DocumentSentimentResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/DocumentSentimentResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift index 142cfc001..a5ea8a166 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EmotionOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift index c663a0eb4..3f301e744 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EmotionScores.swift b/Source/NaturalLanguageUnderstandingV1/Models/EmotionScores.swift index a1e83a2da..4ec5c0566 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EmotionScores.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EmotionScores.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift index cfa0d494c..88c8bfdcd 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResult.swift index cde0083e8..017ec7b45 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/AssistantV1/Models/IntentExport.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultDisambiguation.swift similarity index 54% rename from Source/AssistantV1/Models/IntentExport.swift rename to Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultDisambiguation.swift index 194254f29..056290213 100644 --- a/Source/AssistantV1/Models/IntentExport.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultDisambiguation.swift @@ -15,42 +15,33 @@ **/ import Foundation +import RestKit -/** IntentExport. */ -public struct IntentExport: Codable, Equatable { - - /** - The name of the intent. - */ - public var intentName: String - - /** - The timestamp for creation of the intent. - */ - public var created: Date? +/** + Disambiguation information for the entity. + */ +public struct EntitiesResultDisambiguation: Codable, Equatable { /** - The timestamp for the last update to the intent. + Common entity name. */ - public var updated: Date? + public var name: String? /** - The description of the intent. + Link to the corresponding DBpedia resource. */ - public var description: String? + public var dbpediaResource: [String: JSON]? /** - An array of objects describing the user input examples for the intent. + Entity subtype information. */ - public var examples: [Example]? + public var subtype: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { - case intentName = "intent" - case created = "created" - case updated = "updated" - case description = "description" - case examples = "examples" + case name = "name" + case dbpediaResource = "dbpedia_resource" + case subtype = "subtype" } } diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultEmotion.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultEmotion.swift new file mode 100644 index 000000000..f3948e2e3 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultEmotion.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Emotion analysis results for the entity, enabled with the `emotion` option. + */ +public struct EntitiesResultEmotion: Codable, Equatable { + + /** + Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. + */ + public var anger: Double? + + /** + Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. + */ + public var disgust: Double? + + /** + Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. + */ + public var fear: Double? + + /** + Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. + */ + public var joy: Double? + + /** + Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. + */ + public var sadness: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case anger = "anger" + case disgust = "disgust" + case fear = "fear" + case joy = "joy" + case sadness = "sadness" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultSentiment.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultSentiment.swift new file mode 100644 index 000000000..4157b0b70 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntitiesResultSentiment.swift @@ -0,0 +1,34 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Sentiment analysis results for the entity, enabled with the `sentiment` option. + */ +public struct EntitiesResultSentiment: Codable, Equatable { + + /** + Sentiment score from -1 (negative) to 1 (positive). + */ + public var score: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case score = "score" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/EntityMention.swift b/Source/NaturalLanguageUnderstandingV1/Models/EntityMention.swift index d3dfc260c..f56f27030 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/EntityMention.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/EntityMention.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/FeatureSentimentResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/FeatureSentimentResults.swift index 73e28212a..8b5968357 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/FeatureSentimentResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/FeatureSentimentResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/Features.swift b/Source/NaturalLanguageUnderstandingV1/Models/Features.swift index 35a85b24e..6bbc4551e 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/Features.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/Features.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,6 +84,11 @@ public struct Features: Codable, Equatable { */ public var categories: CategoriesOptions? + /** + Returns tokens and sentences from the input text. + */ + public var syntax: SyntaxOptions? + // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case concepts = "concepts" @@ -95,6 +100,7 @@ public struct Features: Codable, Equatable { case semanticRoles = "semantic_roles" case sentiment = "sentiment" case categories = "categories" + case syntax = "syntax" } /** @@ -128,6 +134,7 @@ public struct Features: Codable, Equatable { Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - parameter categories: Returns a five-level taxonomy of the content. The top three categories are returned. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. + - parameter syntax: Returns tokens and sentences from the input text. - returns: An initialized `Features`. */ @@ -140,7 +147,8 @@ public struct Features: Codable, Equatable { relations: RelationsOptions? = nil, semanticRoles: SemanticRolesOptions? = nil, sentiment: SentimentOptions? = nil, - categories: CategoriesOptions? = nil + categories: CategoriesOptions? = nil, + syntax: SyntaxOptions? = nil ) { self.concepts = concepts @@ -152,6 +160,7 @@ public struct Features: Codable, Equatable { self.semanticRoles = semanticRoles self.sentiment = sentiment self.categories = categories + self.syntax = syntax } } diff --git a/Source/NaturalLanguageUnderstandingV1/Models/Feed.swift b/Source/NaturalLanguageUnderstandingV1/Models/Feed.swift index 9baf2f874..a6321fe9f 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/Feed.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/Feed.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsOptions.swift index 350659829..851008789 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResult.swift index caf41ca75..9b686b009 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultEmotion.swift b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultEmotion.swift new file mode 100644 index 000000000..d68344378 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultEmotion.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Emotion analysis results for the keyword, enabled with the `emotion` option. + */ +public struct KeywordsResultEmotion: Codable, Equatable { + + /** + Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. + */ + public var anger: Double? + + /** + Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. + */ + public var disgust: Double? + + /** + Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. + */ + public var fear: Double? + + /** + Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. + */ + public var joy: Double? + + /** + Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. + */ + public var sadness: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case anger = "anger" + case disgust = "disgust" + case fear = "fear" + case joy = "joy" + case sadness = "sadness" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultSentiment.swift b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultSentiment.swift new file mode 100644 index 000000000..22e08a783 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/KeywordsResultSentiment.swift @@ -0,0 +1,34 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Sentiment analysis results for the keyword, enabled with the `sentiment` option. + */ +public struct KeywordsResultSentiment: Codable, Equatable { + + /** + Sentiment score from -1 (negative) to 1 (positive). + */ + public var score: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case score = "score" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/ListModelsResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/ListModelsResults.swift index 368ceac0a..edd9eddda 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/ListModelsResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/ListModelsResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift index c23eba93b..303ff814f 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,9 @@ **/ import Foundation -import RestKit /** Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. */ -public struct MetadataOptions: Codable, Equatable { - public init() { } -} +public typealias MetadataOptions = JSON diff --git a/Source/NaturalLanguageUnderstandingV1/Models/Model.swift b/Source/NaturalLanguageUnderstandingV1/Models/Model.swift index 2ee4512ac..fe13315f5 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/Model.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/Model.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/Parameters.swift b/Source/NaturalLanguageUnderstandingV1/Models/Parameters.swift index 6c8877527..3fc02b846 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/Parameters.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/Parameters.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ internal struct Parameters: Codable, Equatable { public var url: String? /** - Analysis features and options. + Specific features to analyze the document for. */ public var features: Features @@ -68,7 +68,7 @@ internal struct Parameters: Codable, Equatable { /** ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See [Language - support](https://cloud.ibm.com/docs/services/natural-language-understanding/language-support.html) for more + support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html) for more information. */ public var language: String? @@ -95,7 +95,7 @@ internal struct Parameters: Codable, Equatable { /** Initialize a `Parameters` with member variables. - - parameter features: Analysis features and options. + - parameter features: Specific features to analyze the document for. - parameter text: The plain text to analyze. One of the `text`, `html`, or `url` parameters is required. - parameter html: The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required. - parameter url: The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. @@ -111,7 +111,7 @@ internal struct Parameters: Codable, Equatable { - parameter returnAnalyzedText: Whether or not to return the analyzed text. - parameter language: ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See [Language - support](https://cloud.ibm.com/docs/services/natural-language-understanding/language-support.html) for more + support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html) for more information. - parameter limitTextCharacters: Sets the maximum number of characters that are processed by the service. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/ParametersFeatures.swift b/Source/NaturalLanguageUnderstandingV1/Models/ParametersFeatures.swift new file mode 100644 index 000000000..e35391ad4 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/ParametersFeatures.swift @@ -0,0 +1,106 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Specific features to analyze the document for. + */ +public struct ParametersFeatures: Codable, Equatable { + + /** + Returns high-level concepts in the content. For example, a research paper about deep learning might return the + concept, "Artificial Intelligence" although the term is not mentioned. + Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. + */ + public var concepts: ConceptsOptions? + + /** + Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target + phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` + and for keywords with `keywords.emotion`. + Supported languages: English. + */ + public var emotion: EmotionOptions? + + /** + Identifies people, cities, organizations, and other entities in the content. See [Entity types and + subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding/entity-types.html). + Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. + Arabic, Chinese, and Dutch are supported only through custom models. + */ + public var entities: EntitiesOptions? + + /** + Returns important keywords in the content. + Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. + */ + public var keywords: KeywordsOptions? + + /** + Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. + */ + public var metadata: MetadataOptions? + + /** + Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation + might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation + types](https://cloud.ibm.com/docs/services/natural-language-understanding/relations.html). + Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and + Portuguese custom models are also supported. + */ + public var relations: RelationsOptions? + + /** + Parses sentences into subject, action, and object form. + Supported languages: English, German, Japanese, Korean, Spanish. + */ + public var semanticRoles: SemanticRolesOptions? + + /** + Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze + sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. + */ + public var sentiment: SentimentOptions? + + /** + Returns a five-level taxonomy of the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. + */ + public var categories: CategoriesOptions? + + /** + Returns tokens and sentences from the input text. + */ + public var syntax: SyntaxOptions? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case concepts = "concepts" + case emotion = "emotion" + case entities = "entities" + case keywords = "keywords" + case metadata = "metadata" + case relations = "relations" + case semanticRoles = "semantic_roles" + case sentiment = "sentiment" + case categories = "categories" + case syntax = "syntax" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/RelationArgument.swift b/Source/NaturalLanguageUnderstandingV1/Models/RelationArgument.swift index d47e58635..e031e0251 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/RelationArgument.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/RelationArgument.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/RelationEntity.swift b/Source/NaturalLanguageUnderstandingV1/Models/RelationEntity.swift index 43204eb18..63c441b5c 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/RelationEntity.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/RelationEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/RelationsOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/RelationsOptions.swift index 26a17ce94..7bbcdf605 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/RelationsOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/RelationsOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/RelationsResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/RelationsResult.swift index 24bdee369..b0a204817 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/RelationsResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/RelationsResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesEntity.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesEntity.swift index c5217fb99..63adaac79 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesEntity.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesEntity.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesKeyword.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesKeyword.swift index 159d2485e..a49995646 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesKeyword.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesKeyword.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesOptions.swift index 7a80be32a..9f6d2bd32 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResult.swift index b41dbf8c1..42882a36f 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,17 +29,17 @@ public struct SemanticRolesResult: Codable, Equatable { /** The extracted subject from the sentence. */ - public var subject: SemanticRolesSubject? + public var subject: SemanticRolesResultSubject? /** The extracted action from the sentence. */ - public var action: SemanticRolesAction? + public var action: SemanticRolesResultAction? /** The extracted object from the sentence. */ - public var object: SemanticRolesObject? + public var object: SemanticRolesResultObject? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultAction.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultAction.swift new file mode 100644 index 000000000..0a2e01e14 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultAction.swift @@ -0,0 +1,43 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + The extracted action from the sentence. + */ +public struct SemanticRolesResultAction: Codable, Equatable { + + /** + Analyzed text that corresponds to the action. + */ + public var text: String? + + /** + normalized version of the action. + */ + public var normalized: String? + + public var verb: SemanticRolesVerb? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case normalized = "normalized" + case verb = "verb" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultObject.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultObject.swift new file mode 100644 index 000000000..a2a611c29 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultObject.swift @@ -0,0 +1,40 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + The extracted object from the sentence. + */ +public struct SemanticRolesResultObject: Codable, Equatable { + + /** + Object text. + */ + public var text: String? + + /** + An array of extracted keywords. + */ + public var keywords: [SemanticRolesKeyword]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case keywords = "keywords" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultSubject.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultSubject.swift new file mode 100644 index 000000000..57406374c --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesResultSubject.swift @@ -0,0 +1,46 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + The extracted subject from the sentence. + */ +public struct SemanticRolesResultSubject: Codable, Equatable { + + /** + Text that corresponds to the subject role. + */ + public var text: String? + + /** + An array of extracted entities. + */ + public var entities: [SemanticRolesEntity]? + + /** + An array of extracted keywords. + */ + public var keywords: [SemanticRolesKeyword]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case entities = "entities" + case keywords = "keywords" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesVerb.swift b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesVerb.swift index b6a8b731b..5b33c0ed4 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesVerb.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SemanticRolesVerb.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SentenceResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/SentenceResult.swift new file mode 100644 index 000000000..0d7c306c9 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SentenceResult.swift @@ -0,0 +1,38 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** SentenceResult. */ +public struct SentenceResult: Codable, Equatable { + + /** + The sentence. + */ + public var text: String? + + /** + Character offsets indicating the beginning and end of the sentence in the analyzed text. + */ + public var location: [Int]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case location = "location" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SentimentOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/SentimentOptions.swift index 275516b38..c0d2218e2 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SentimentOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SentimentOptions.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SentimentResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/SentimentResult.swift index cad2b5f95..b11231c35 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/SentimentResult.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/SentimentResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptions.swift new file mode 100644 index 000000000..9ae3cf35b --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptions.swift @@ -0,0 +1,57 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Returns tokens and sentences from the input text. + */ +public struct SyntaxOptions: Codable, Equatable { + + /** + Tokenization options. + */ + public var tokens: SyntaxOptionsTokens? + + /** + Set this to `true` to return sentence information. + */ + public var sentences: Bool? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case tokens = "tokens" + case sentences = "sentences" + } + + /** + Initialize a `SyntaxOptions` with member variables. + + - parameter tokens: Tokenization options. + - parameter sentences: Set this to `true` to return sentence information. + + - returns: An initialized `SyntaxOptions`. + */ + public init( + tokens: SyntaxOptionsTokens? = nil, + sentences: Bool? = nil + ) + { + self.tokens = tokens + self.sentences = sentences + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptionsTokens.swift b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptionsTokens.swift new file mode 100644 index 000000000..a4211f66e --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxOptionsTokens.swift @@ -0,0 +1,40 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Tokenization options. + */ +public struct SyntaxOptionsTokens: Codable, Equatable { + + /** + Set this to `true` to return the lemma for each token. + */ + public var lemma: Bool? + + /** + Set this to `true` to return the part of speech for each token. + */ + public var partOfSpeech: Bool? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case lemma = "lemma" + case partOfSpeech = "part_of_speech" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/SyntaxResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxResult.swift new file mode 100644 index 000000000..72ef40bf3 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/SyntaxResult.swift @@ -0,0 +1,34 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** + Tokens and sentences returned from syntax analysis. + */ +public struct SyntaxResult: Codable, Equatable { + + public var tokens: [TokenResult]? + + public var sentences: [SentenceResult]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case tokens = "tokens" + case sentences = "sentences" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResults.swift index f5b8b33f5..18f61e519 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResultsEmotion.swift b/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResultsEmotion.swift new file mode 100644 index 000000000..efe6e7745 --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/TargetedEmotionResultsEmotion.swift @@ -0,0 +1,58 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + The emotion results for the target. + */ +public struct TargetedEmotionResultsEmotion: Codable, Equatable { + + /** + Anger score from 0 to 1. A higher score means that the text is more likely to convey anger. + */ + public var anger: Double? + + /** + Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. + */ + public var disgust: Double? + + /** + Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. + */ + public var fear: Double? + + /** + Joy score from 0 to 1. A higher score means that the text is more likely to convey joy. + */ + public var joy: Double? + + /** + Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. + */ + public var sadness: Double? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case anger = "anger" + case disgust = "disgust" + case fear = "fear" + case joy = "joy" + case sadness = "sadness" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/Models/TargetedSentimentResults.swift b/Source/NaturalLanguageUnderstandingV1/Models/TargetedSentimentResults.swift index 7ccbf0ca8..ae6d3171a 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/TargetedSentimentResults.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/TargetedSentimentResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/NaturalLanguageUnderstandingV1/Models/TokenResult.swift b/Source/NaturalLanguageUnderstandingV1/Models/TokenResult.swift new file mode 100644 index 000000000..c1ca7c85b --- /dev/null +++ b/Source/NaturalLanguageUnderstandingV1/Models/TokenResult.swift @@ -0,0 +1,75 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +/** TokenResult. */ +public struct TokenResult: Codable, Equatable { + + /** + The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS + tags](https://universaldependencies.org/u/pos/). + */ + public enum PartOfSpeech: String { + case adj = "ADJ" + case adp = "ADP" + case adv = "ADV" + case aux = "AUX" + case cconj = "CCONJ" + case det = "DET" + case intj = "INTJ" + case noun = "NOUN" + case num = "NUM" + case part = "PART" + case pron = "PRON" + case propn = "PROPN" + case punct = "PUNCT" + case sconj = "SCONJ" + case sym = "SYM" + case verb = "VERB" + case x = "X" + } + + /** + The token as it appears in the analyzed text. + */ + public var text: String? + + /** + The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS + tags](https://universaldependencies.org/u/pos/). + */ + public var partOfSpeech: String? + + /** + Character offsets indicating the beginning and end of the token in the analyzed text. + */ + public var location: [Int]? + + /** + The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. + */ + public var lemma: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case text = "text" + case partOfSpeech = "part_of_speech" + case location = "location" + case lemma = "lemma" + } + +} diff --git a/Source/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift b/Source/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift index d9111c421..8b2ebed4d 100644 --- a/Source/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift +++ b/Source/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import RestKit Language Understanding will give you results for the features you request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content. You can create [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding/customizing.html) - with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. + with Watson Knowledge Studio to detect custom entities, relations, and categories in Natural Language Understanding. */ public class NaturalLanguageUnderstanding { @@ -39,22 +39,23 @@ public class NaturalLanguageUnderstanding { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `NaturalLanguageUnderstanding` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "natural_language_understanding") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "natural_language_understanding") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -64,20 +65,22 @@ public class NaturalLanguageUnderstanding { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `NaturalLanguageUnderstanding` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -91,6 +94,7 @@ public class NaturalLanguageUnderstanding { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -101,8 +105,9 @@ public class NaturalLanguageUnderstanding { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -125,19 +130,25 @@ public class NaturalLanguageUnderstanding { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(description)) = json["description"] { - metadata["description"] = description - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -152,9 +163,10 @@ public class NaturalLanguageUnderstanding { - Metadata - Relations - Semantic roles - - Sentiment. + - Sentiment + - Syntax (Experimental). - - parameter features: Analysis features and options. + - parameter features: Specific features to analyze the document for. - parameter text: The plain text to analyze. One of the `text`, `html`, or `url` parameters is required. - parameter html: The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required. - parameter url: The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. @@ -169,7 +181,7 @@ public class NaturalLanguageUnderstanding { - parameter returnAnalyzedText: Whether or not to return the analyzed text. - parameter language: ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See [Language - support](https://cloud.ibm.com/docs/services/natural-language-understanding/language-support.html) for more + support](https://www.bluemix.net/docs/services/natural-language-understanding/language-support.html) for more information. - parameter limitTextCharacters: Sets the maximum number of characters that are processed by the service. - parameter headers: A dictionary of request headers to be sent with this request. @@ -201,7 +213,7 @@ public class NaturalLanguageUnderstanding { returnAnalyzedText: returnAnalyzedText, language: language, limitTextCharacters: limitTextCharacters) - guard let body = try? JSONEncoder().encode(analyzeRequest) else { + guard let body = try? JSON.encoder.encode(analyzeRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -211,8 +223,8 @@ public class NaturalLanguageUnderstanding { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "analyze") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "analyze") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -255,8 +267,8 @@ public class NaturalLanguageUnderstanding { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -297,8 +309,8 @@ public class NaturalLanguageUnderstanding { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters diff --git a/Source/PersonalityInsightsV3/Models/Behavior.swift b/Source/PersonalityInsightsV3/Models/Behavior.swift index 999dc0404..a9abecc10 100644 --- a/Source/PersonalityInsightsV3/Models/Behavior.swift +++ b/Source/PersonalityInsightsV3/Models/Behavior.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/ConsumptionPreferences.swift b/Source/PersonalityInsightsV3/Models/ConsumptionPreferences.swift index 648c09642..63ea348be 100644 --- a/Source/PersonalityInsightsV3/Models/ConsumptionPreferences.swift +++ b/Source/PersonalityInsightsV3/Models/ConsumptionPreferences.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/ConsumptionPreferencesCategory.swift b/Source/PersonalityInsightsV3/Models/ConsumptionPreferencesCategory.swift index 602d82b24..b82c30219 100644 --- a/Source/PersonalityInsightsV3/Models/ConsumptionPreferencesCategory.swift +++ b/Source/PersonalityInsightsV3/Models/ConsumptionPreferencesCategory.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/Content.swift b/Source/PersonalityInsightsV3/Models/Content.swift index 2772adbd7..cfdf2d85c 100644 --- a/Source/PersonalityInsightsV3/Models/Content.swift +++ b/Source/PersonalityInsightsV3/Models/Content.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/ContentItem.swift b/Source/PersonalityInsightsV3/Models/ContentItem.swift index 91e9be5bf..0ef3bc4c7 100644 --- a/Source/PersonalityInsightsV3/Models/ContentItem.swift +++ b/Source/PersonalityInsightsV3/Models/ContentItem.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/Profile.swift b/Source/PersonalityInsightsV3/Models/Profile.swift index 9268bc249..ad595aba7 100644 --- a/Source/PersonalityInsightsV3/Models/Profile.swift +++ b/Source/PersonalityInsightsV3/Models/Profile.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/ProfileContent.swift b/Source/PersonalityInsightsV3/Models/ProfileContent.swift index 601f1178b..5801914eb 100644 --- a/Source/PersonalityInsightsV3/Models/ProfileContent.swift +++ b/Source/PersonalityInsightsV3/Models/ProfileContent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ **/ import Foundation +import RestKit /** A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see @@ -37,7 +38,7 @@ public enum ProfileContent { internal var content: Data? { switch self { - case .content(let content): return try? JSONEncoder().encode(content) + case .content(let content): return try? JSON.encoder.encode(content) case .html(let html): return html.data(using: .utf8) case .text(let text): return text.data(using: .utf8) } diff --git a/Source/PersonalityInsightsV3/Models/Trait.swift b/Source/PersonalityInsightsV3/Models/Trait.swift index ac7575bd5..adfe11116 100644 --- a/Source/PersonalityInsightsV3/Models/Trait.swift +++ b/Source/PersonalityInsightsV3/Models/Trait.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/Models/Warning.swift b/Source/PersonalityInsightsV3/Models/Warning.swift index c48827299..a77c31f68 100644 --- a/Source/PersonalityInsightsV3/Models/Warning.swift +++ b/Source/PersonalityInsightsV3/Models/Warning.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/PersonalityInsightsV3/PersonalityInsights.swift b/Source/PersonalityInsightsV3/PersonalityInsights.swift index 87993cbaa..5a9b30691 100644 --- a/Source/PersonalityInsightsV3/PersonalityInsights.swift +++ b/Source/PersonalityInsightsV3/PersonalityInsights.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,22 +47,23 @@ public class PersonalityInsights { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `PersonalityInsights` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "personality_insights") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "personality_insights") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -72,20 +73,22 @@ public class PersonalityInsights { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `PersonalityInsights` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -99,6 +102,7 @@ public class PersonalityInsights { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -109,8 +113,9 @@ public class PersonalityInsights { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -133,19 +138,25 @@ public class PersonalityInsights { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(help)) = json["help"] { - metadata["help"] = help - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -193,6 +204,8 @@ public class PersonalityInsights { - parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw scores are not compared with a sample population. By default, only normalized percentiles are returned. + - parameter csvHeaders: Indicates whether column labels are returned with a CSV response. By default, no column + labels are returned. Applies only when the response type is CSV (`text/csv`). - parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are returned. - parameter headers: A dictionary of request headers to be sent with this request. @@ -203,6 +216,7 @@ public class PersonalityInsights { contentLanguage: String? = nil, acceptLanguage: String? = nil, rawScores: Bool? = nil, + csvHeaders: Bool? = nil, consumptionPreferences: Bool? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) @@ -218,8 +232,8 @@ public class PersonalityInsights { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profile") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profile") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = profileContent.contentType if let contentLanguage = contentLanguage { @@ -236,6 +250,10 @@ public class PersonalityInsights { let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)") queryParameters.append(queryParameter) } + if let csvHeaders = csvHeaders { + let queryParameter = URLQueryItem(name: "csv_headers", value: "\(csvHeaders)") + queryParameters.append(queryParameter) + } if let consumptionPreferences = consumptionPreferences { let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)") queryParameters.append(queryParameter) @@ -317,7 +335,7 @@ public class PersonalityInsights { csvHeaders: Bool? = nil, consumptionPreferences: Bool? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body guard let body = profileContent.content else { @@ -330,8 +348,8 @@ public class PersonalityInsights { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profileAsCSV") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profileAsCSV") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "text/csv" headerParameters["Content-Type"] = profileContent.contentType if let contentLanguage = contentLanguage { diff --git a/Source/SpeechToTextV1/Models/AcousticModel.swift b/Source/SpeechToTextV1/Models/AcousticModel.swift index 911f20c9d..9a15f9b1f 100644 --- a/Source/SpeechToTextV1/Models/AcousticModel.swift +++ b/Source/SpeechToTextV1/Models/AcousticModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/AcousticModels.swift b/Source/SpeechToTextV1/Models/AcousticModels.swift index c42a80523..3ee90943c 100644 --- a/Source/SpeechToTextV1/Models/AcousticModels.swift +++ b/Source/SpeechToTextV1/Models/AcousticModels.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/AudioDetails.swift b/Source/SpeechToTextV1/Models/AudioDetails.swift index 4cdfe4592..1db826785 100644 --- a/Source/SpeechToTextV1/Models/AudioDetails.swift +++ b/Source/SpeechToTextV1/Models/AudioDetails.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/AudioListing.swift b/Source/SpeechToTextV1/Models/AudioListing.swift index 8469139ab..dc7afd275 100644 --- a/Source/SpeechToTextV1/Models/AudioListing.swift +++ b/Source/SpeechToTextV1/Models/AudioListing.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,10 +35,9 @@ public struct AudioListing: Codable, Equatable { } /** - **For an audio-type resource,** the total seconds of audio in the resource. The value is always a whole number. - Omitted for an archive-type resource. + **For an audio-type resource,** the total seconds of audio in the resource. Omitted for an archive-type resource. */ - public var duration: Double? + public var duration: Int? /** **For an audio-type resource,** the user-specified name of the resource. Omitted for an archive-type resource. diff --git a/Source/SpeechToTextV1/Models/AudioListingContainer.swift b/Source/SpeechToTextV1/Models/AudioListingContainer.swift new file mode 100644 index 000000000..859018caa --- /dev/null +++ b/Source/SpeechToTextV1/Models/AudioListingContainer.swift @@ -0,0 +1,77 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + **For an archive-type resource,** an object of type `AudioResource` that provides information about the resource. + Omitted for an audio-type resource. + */ +public struct AudioListingContainer: Codable, Equatable { + + /** + The status of the audio resource: + * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new + audio resources or to train the custom model until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or + sampling rate, or because it is corrupted). For an archive file, the entire archive is invalid if any of its audio + files are invalid. + */ + public enum Status: String { + case ok = "ok" + case beingProcessed = "being_processed" + case invalid = "invalid" + } + + /** + The total seconds of audio in the audio resource. The value is always a whole number. + */ + public var duration: Double + + /** + **For an archive-type resource,** the user-specified name of the resource. + **For an audio-type resource,** the user-specified name of the resource or the name of the audio file that the user + added for the resource. The value depends on the method that is called. + */ + public var name: String + + /** + An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the + service finishes processing the audio. + */ + public var details: AudioResourceDetails + + /** + The status of the audio resource: + * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service cannot accept requests to add new + audio resources or to train the custom model until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or + sampling rate, or because it is corrupted). For an archive file, the entire archive is invalid if any of its audio + files are invalid. + */ + public var status: String + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case duration = "duration" + case name = "name" + case details = "details" + case status = "status" + } + +} diff --git a/Source/SpeechToTextV1/Models/AudioListingDetails.swift b/Source/SpeechToTextV1/Models/AudioListingDetails.swift new file mode 100644 index 000000000..d08facbdf --- /dev/null +++ b/Source/SpeechToTextV1/Models/AudioListingDetails.swift @@ -0,0 +1,85 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + **For an audio-type resource,** an `AudioDetails` object that provides detailed information about the resource. The + object is empty until the service finishes processing the audio. Omitted for an archive-type resource. + */ +public struct AudioListingDetails: Codable, Equatable { + + /** + The type of the audio resource: + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files + * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file + that does not contain audio, such as a JPEG file). + */ + public enum TypeEnum: String { + case audio = "audio" + case archive = "archive" + case undetermined = "undetermined" + } + + /** + **For an archive-type resource,** the format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. + */ + public enum Compression: String { + case zip = "zip" + case gzip = "gzip" + } + + /** + The type of the audio resource: + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files + * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file + that does not contain audio, such as a JPEG file). + */ + public var type: String? + + /** + **For an audio-type resource,** the codec in which the audio is encoded. Omitted for an archive-type resource. + */ + public var codec: String? + + /** + **For an audio-type resource,** the sampling rate of the audio in Hertz (samples per second). Omitted for an + archive-type resource. + */ + public var frequency: Int? + + /** + **For an archive-type resource,** the format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. + */ + public var compression: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case type = "type" + case codec = "codec" + case frequency = "frequency" + case compression = "compression" + } + +} diff --git a/Source/SpeechToTextV1/Models/AudioResource.swift b/Source/SpeechToTextV1/Models/AudioResource.swift index b9982d0eb..767168fa8 100644 --- a/Source/SpeechToTextV1/Models/AudioResource.swift +++ b/Source/SpeechToTextV1/Models/AudioResource.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,9 @@ public struct AudioResource: Codable, Equatable { } /** - The total seconds of audio in the audio resource. The value is always a whole number. + The total seconds of audio in the audio resource. */ - public var duration: Double + public var duration: Int /** **For an archive-type resource,** the user-specified name of the resource. diff --git a/Source/SpeechToTextV1/Models/AudioResourceDetails.swift b/Source/SpeechToTextV1/Models/AudioResourceDetails.swift new file mode 100644 index 000000000..86f724b8d --- /dev/null +++ b/Source/SpeechToTextV1/Models/AudioResourceDetails.swift @@ -0,0 +1,85 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the + service finishes processing the audio. + */ +public struct AudioResourceDetails: Codable, Equatable { + + /** + The type of the audio resource: + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files + * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file + that does not contain audio, such as a JPEG file). + */ + public enum TypeEnum: String { + case audio = "audio" + case archive = "archive" + case undetermined = "undetermined" + } + + /** + **For an archive-type resource,** the format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. + */ + public enum Compression: String { + case zip = "zip" + case gzip = "gzip" + } + + /** + The type of the audio resource: + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files + * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file + that does not contain audio, such as a JPEG file). + */ + public var type: String? + + /** + **For an audio-type resource,** the codec in which the audio is encoded. Omitted for an archive-type resource. + */ + public var codec: String? + + /** + **For an audio-type resource,** the sampling rate of the audio in Hertz (samples per second). Omitted for an + archive-type resource. + */ + public var frequency: Int? + + /** + **For an archive-type resource,** the format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. + */ + public var compression: String? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case type = "type" + case codec = "codec" + case frequency = "frequency" + case compression = "compression" + } + +} diff --git a/Source/SpeechToTextV1/Models/AudioResources.swift b/Source/SpeechToTextV1/Models/AudioResources.swift index a4c2b8d81..a986b0e28 100644 --- a/Source/SpeechToTextV1/Models/AudioResources.swift +++ b/Source/SpeechToTextV1/Models/AudioResources.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Corpora.swift b/Source/SpeechToTextV1/Models/Corpora.swift index 1d4c04c83..d1b1e1b93 100644 --- a/Source/SpeechToTextV1/Models/Corpora.swift +++ b/Source/SpeechToTextV1/Models/Corpora.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Corpus.swift b/Source/SpeechToTextV1/Models/Corpus.swift index f07fe8648..5ee637d8a 100644 --- a/Source/SpeechToTextV1/Models/Corpus.swift +++ b/Source/SpeechToTextV1/Models/Corpus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/CreateAcousticModel.swift b/Source/SpeechToTextV1/Models/CreateAcousticModel.swift index 244960d97..a90e2fe02 100644 --- a/Source/SpeechToTextV1/Models/CreateAcousticModel.swift +++ b/Source/SpeechToTextV1/Models/CreateAcousticModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/CreateLanguageModel.swift b/Source/SpeechToTextV1/Models/CreateLanguageModel.swift index 48621d2f9..6523d68b2 100644 --- a/Source/SpeechToTextV1/Models/CreateLanguageModel.swift +++ b/Source/SpeechToTextV1/Models/CreateLanguageModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/CustomWord.swift b/Source/SpeechToTextV1/Models/CustomWord.swift index b990fca3c..ca61bcee5 100644 --- a/Source/SpeechToTextV1/Models/CustomWord.swift +++ b/Source/SpeechToTextV1/Models/CustomWord.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/CustomWords.swift b/Source/SpeechToTextV1/Models/CustomWords.swift index 70935234d..876123223 100644 --- a/Source/SpeechToTextV1/Models/CustomWords.swift +++ b/Source/SpeechToTextV1/Models/CustomWords.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Grammar.swift b/Source/SpeechToTextV1/Models/Grammar.swift index 251633706..52068b25a 100644 --- a/Source/SpeechToTextV1/Models/Grammar.swift +++ b/Source/SpeechToTextV1/Models/Grammar.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Grammars.swift b/Source/SpeechToTextV1/Models/Grammars.swift index c9f816545..e6515181b 100644 --- a/Source/SpeechToTextV1/Models/Grammars.swift +++ b/Source/SpeechToTextV1/Models/Grammars.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/KeywordResult.swift b/Source/SpeechToTextV1/Models/KeywordResult.swift index eb8179df6..aa8e86e06 100644 --- a/Source/SpeechToTextV1/Models/KeywordResult.swift +++ b/Source/SpeechToTextV1/Models/KeywordResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/LanguageModel.swift b/Source/SpeechToTextV1/Models/LanguageModel.swift index af7f34dd7..8c21d7c20 100644 --- a/Source/SpeechToTextV1/Models/LanguageModel.swift +++ b/Source/SpeechToTextV1/Models/LanguageModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/LanguageModels.swift b/Source/SpeechToTextV1/Models/LanguageModels.swift index d1159e150..f4b423fc8 100644 --- a/Source/SpeechToTextV1/Models/LanguageModels.swift +++ b/Source/SpeechToTextV1/Models/LanguageModels.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/RecognitionJob.swift b/Source/SpeechToTextV1/Models/RecognitionJob.swift index bc08c9177..d7d27e37d 100644 --- a/Source/SpeechToTextV1/Models/RecognitionJob.swift +++ b/Source/SpeechToTextV1/Models/RecognitionJob.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/RecognitionJobs.swift b/Source/SpeechToTextV1/Models/RecognitionJobs.swift index e719e8b2b..4f63ec0cd 100644 --- a/Source/SpeechToTextV1/Models/RecognitionJobs.swift +++ b/Source/SpeechToTextV1/Models/RecognitionJobs.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/RegisterStatus.swift b/Source/SpeechToTextV1/Models/RegisterStatus.swift index 9e5704a10..4bb2c7636 100644 --- a/Source/SpeechToTextV1/Models/RegisterStatus.swift +++ b/Source/SpeechToTextV1/Models/RegisterStatus.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift b/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift index 74edcceba..29da36e55 100644 --- a/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift +++ b/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SpeechModel.swift b/Source/SpeechToTextV1/Models/SpeechModel.swift index 8639d0578..fc2142934 100644 --- a/Source/SpeechToTextV1/Models/SpeechModel.swift +++ b/Source/SpeechToTextV1/Models/SpeechModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SpeechModels.swift b/Source/SpeechToTextV1/Models/SpeechModels.swift index bb362ed4f..fab2bc230 100644 --- a/Source/SpeechToTextV1/Models/SpeechModels.swift +++ b/Source/SpeechToTextV1/Models/SpeechModels.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift b/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift index 4cc1bf5c9..1de4a53b6 100644 --- a/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift +++ b/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,14 +35,14 @@ public struct SpeechRecognitionAlternative: Codable, Equatable { the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. */ - public var timestamps: [WordTimestamp]? + public var timestamps: [String]? /** A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best alternative and only with results marked as final. */ - public var wordConfidence: [WordConfidence]? + public var wordConfidence: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { diff --git a/Source/SpeechToTextV1/Models/SpeechRecognitionResult.swift b/Source/SpeechToTextV1/Models/SpeechRecognitionResult.swift index 2fd9b10d8..cffb9f8ab 100644 --- a/Source/SpeechToTextV1/Models/SpeechRecognitionResult.swift +++ b/Source/SpeechToTextV1/Models/SpeechRecognitionResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SpeechRecognitionResults.swift b/Source/SpeechToTextV1/Models/SpeechRecognitionResults.swift index d9799cf41..49c116d33 100644 --- a/Source/SpeechToTextV1/Models/SpeechRecognitionResults.swift +++ b/Source/SpeechToTextV1/Models/SpeechRecognitionResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/SupportedFeatures.swift b/Source/SpeechToTextV1/Models/SupportedFeatures.swift index 6eeeead7b..c93c61df4 100644 --- a/Source/SpeechToTextV1/Models/SupportedFeatures.swift +++ b/Source/SpeechToTextV1/Models/SupportedFeatures.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Word.swift b/Source/SpeechToTextV1/Models/Word.swift index e7ccd6dcb..f1c9d51e3 100644 --- a/Source/SpeechToTextV1/Models/Word.swift +++ b/Source/SpeechToTextV1/Models/Word.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/WordAlternativeResult.swift b/Source/SpeechToTextV1/Models/WordAlternativeResult.swift index 4ad86b6e9..4f17cacae 100644 --- a/Source/SpeechToTextV1/Models/WordAlternativeResult.swift +++ b/Source/SpeechToTextV1/Models/WordAlternativeResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/WordAlternativeResults.swift b/Source/SpeechToTextV1/Models/WordAlternativeResults.swift index b0a45a136..ef4ea77ef 100644 --- a/Source/SpeechToTextV1/Models/WordAlternativeResults.swift +++ b/Source/SpeechToTextV1/Models/WordAlternativeResults.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/WordError.swift b/Source/SpeechToTextV1/Models/WordError.swift index 2883346de..e63747aa1 100644 --- a/Source/SpeechToTextV1/Models/WordError.swift +++ b/Source/SpeechToTextV1/Models/WordError.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/Models/Words.swift b/Source/SpeechToTextV1/Models/Words.swift index 0eecb5a6c..d9e3952f4 100644 --- a/Source/SpeechToTextV1/Models/Words.swift +++ b/Source/SpeechToTextV1/Models/Words.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/SpeechToTextV1/SpeechToText.swift b/Source/SpeechToTextV1/SpeechToText.swift index 97f97ae65..8e5494404 100644 --- a/Source/SpeechToTextV1/SpeechToText.swift +++ b/Source/SpeechToTextV1/SpeechToText.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,14 +37,7 @@ import RestKit public class SpeechToText { /// The base URL to use when contacting the service. - public var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" { - didSet { - if serviceURL.last == "/" { - serviceURL.removeLast() - } - } - } - + public var serviceURL = "https://stream.watsonplatform.net/speech-to-text/api" internal let serviceName = "SpeechToText" internal let serviceVersion = "v1" @@ -54,20 +47,20 @@ public class SpeechToText { var session = URLSession(configuration: URLSessionConfiguration.default) var authMethod: AuthenticationMethod + #if os(Linux) /** Create a `SpeechToText` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. */ - public init?(credentialsFile: URL) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "speech_to_text") else { + public init?() { + guard let credentials = Shared.extractCredentials(serviceName: "speech_to_text") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -77,7 +70,9 @@ public class SpeechToText { self.serviceURL = serviceURL } self.authMethod = authMethod + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `SpeechToText` object. @@ -87,6 +82,7 @@ public class SpeechToText { */ public init(username: String, password: String) { self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -97,6 +93,7 @@ public class SpeechToText { */ public init(apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) + RestRequest.userAgent = Shared.userAgent } /** @@ -106,6 +103,7 @@ public class SpeechToText { */ public init(accessToken: String) { self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -128,19 +126,25 @@ public class SpeechToText { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(description)) = json["code_description"] { - metadata["codeDescription"] = description - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -162,8 +166,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -202,8 +206,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -236,10 +240,10 @@ public class SpeechToText { request](https://cloud.ibm.com/docs/services/speech-to-text/http.html#HTTP-basic). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to - `chunked` to use streaming mode. In streaming mode, the server closes the connection (status code 408) if the - service receives no data chunk for 30 seconds and it has no audio to transcribe for 30 seconds. The server also - closes the connection (status code 400) if no speech is detected for `inactivity_timeout` seconds of audio (not - processing time); use the `inactivity_timeout` parameter to change the default of 30 seconds. + `chunked` to use streaming mode. In streaming mode, the service closes the connection (status code 408) if it does + not receive at least 15 seconds of audio (including silence) in any 30-second period. The service also closes the + connection (status code 400) if it detects no speech for `inactivity_timeout` seconds of streaming audio; use the + `inactivity_timeout` parameter to change the default of 30 seconds. **See also:** * [Audio transmission](https://cloud.ibm.com/docs/services/speech-to-text/input.html#transmission) * [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts) @@ -252,6 +256,7 @@ public class SpeechToText { either `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. + * `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) * `audio/basic` (**Required.** Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) @@ -284,21 +289,19 @@ public class SpeechToText { request](https://cloud.ibm.com/docs/services/speech-to-text/http.html#HTTP-multi). - parameter audio: The audio to transcribe. - - parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio - format, see **Audio formats (content types)** in the method description. - parameter model: The identifier of the model that is to be used for the recognition request. See [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). - parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. - parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model that is to be used with the recognition request. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). - parameter baseModelVersion: The version of the specified base model that is to be used with recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The @@ -313,11 +316,11 @@ public class SpeechToText { The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. - See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). - parameter inactivityTimeout: The time in seconds after which, if only silence (no speech) is detected in - submitted audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission - from a live microphone when a user simply walks away. Use `-1` for infinity. See - [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts). + streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission + from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity + timeout](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts-inactivity). - parameter keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter @@ -329,7 +332,8 @@ public class SpeechToText { no keyword spotting if you omit either parameter. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). - parameter maxAlternatives: The maximum number of alternative transcripts that the service is to return. By - default, the service returns a single transcript. See [Maximum + default, the service returns a single transcript. If you specify a value of `0`, the service uses the default + value, `1`. See [Maximum alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#max_alternatives). - parameter wordAlternativesThreshold: A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its @@ -360,11 +364,14 @@ public class SpeechToText { supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). + - parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the + customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not + specify both parameters with a request. - parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See - [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html). + [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/input.html#grammars-input). - parameter redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no @@ -375,12 +382,13 @@ public class SpeechToText { `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). + - parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio + format, see **Audio formats (content types)** in the method description. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func recognize( audio: Data, - contentType: String? = nil, model: String? = nil, languageCustomizationID: String? = nil, acousticCustomizationID: String? = nil, @@ -396,8 +404,10 @@ public class SpeechToText { profanityFilter: Bool? = nil, smartFormatting: Bool? = nil, speakerLabels: Bool? = nil, + customizationID: String? = nil, grammarName: String? = nil, redaction: Bool? = nil, + contentType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -409,8 +419,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognize") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognize") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" if let contentType = contentType { headerParameters["Content-Type"] = contentType @@ -478,6 +488,10 @@ public class SpeechToText { let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)") queryParameters.append(queryParameter) } + if let customizationID = customizationID { + let queryParameter = URLQueryItem(name: "customization_id", value: customizationID) + queryParameters.append(queryParameter) + } if let grammarName = grammarName { let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName) queryParameters.append(queryParameter) @@ -550,8 +564,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "registerCallback") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "registerCallback") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -599,9 +613,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "unregisterCallback") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "unregisterCallback") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -646,17 +659,17 @@ public class SpeechToText { * `events` * `user_token` * `results_ttl` - You can pass a maximum of 100 MB and a minimum of 100 bytes of audio with a request. The service automatically + You can pass a maximum of 1 GB and a minimum of 100 bytes of audio with a request. The service automatically detects the endianness of the incoming audio and, for audio that includes multiple channels, downmixes the audio to one-channel mono during transcoding. The method returns only final results; to enable interim results, use the WebSocket API. **See also:** [Creating a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#create). ### Streaming mode For requests to transcribe live audio as it becomes available, you must set the `Transfer-Encoding` header to - `chunked` to use streaming mode. In streaming mode, the server closes the connection (status code 408) if the - service receives no data chunk for 30 seconds and it has no audio to transcribe for 30 seconds. The server also - closes the connection (status code 400) if no speech is detected for `inactivity_timeout` seconds of audio (not - processing time); use the `inactivity_timeout` parameter to change the default of 30 seconds. + `chunked` to use streaming mode. In streaming mode, the service closes the connection (status code 408) if it does + not receive at least 15 seconds of audio (including silence) in any 30-second period. The service also closes the + connection (status code 400) if it detects no speech for `inactivity_timeout` seconds of streaming audio; use the + `inactivity_timeout` parameter to change the default of 30 seconds. **See also:** * [Audio transmission](https://cloud.ibm.com/docs/services/speech-to-text/input.html#transmission) * [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts) @@ -669,6 +682,7 @@ public class SpeechToText { either `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. + * `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) * `audio/basic` (**Required.** Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) @@ -691,8 +705,6 @@ public class SpeechToText { **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text/audio-formats.html). - parameter audio: The audio to transcribe. - - parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio - format, see **Audio formats (content types)** in the method description. - parameter model: The identifier of the model that is to be used for the recognition request. See [Languages and models](https://cloud.ibm.com/docs/services/speech-to-text/models.html). - parameter callbackURL: A URL to which callback notifications are to be sent. The URL must already be @@ -724,13 +736,13 @@ public class SpeechToText { with the recognition request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom language model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. - parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model that is to be used with the recognition request. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with credentials for the instance of the service that owns the custom model. By default, no custom acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). - parameter baseModelVersion: The version of the specified base model that is to be used with recognition request. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The @@ -745,11 +757,11 @@ public class SpeechToText { The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. - See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). + See [Custom models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom-input). - parameter inactivityTimeout: The time in seconds after which, if only silence (no speech) is detected in - submitted audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission - from a live microphone when a user simply walks away. Use `-1` for infinity. See - [Timeouts](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts). + streaming audio, the connection is closed with a 400 error. The parameter is useful for stopping audio submission + from a live microphone when a user simply walks away. Use `-1` for infinity. See [Inactivity + timeout](https://cloud.ibm.com/docs/services/speech-to-text/input.html#timeouts-inactivity). - parameter keywords: An array of keyword strings to spot in the audio. Each keyword string can include one or more string tokens. Keywords are spotted only in the final results, not in interim hypotheses. If you specify any keywords, you must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter @@ -761,7 +773,8 @@ public class SpeechToText { no keyword spotting if you omit either parameter. See [Keyword spotting](https://cloud.ibm.com/docs/services/speech-to-text/output.html#keyword_spotting). - parameter maxAlternatives: The maximum number of alternative transcripts that the service is to return. By - default, the service returns a single transcript. See [Maximum + default, the service returns a single transcript. If you specify a value of `0`, the service uses the default + value, `1`. See [Maximum alternatives](https://cloud.ibm.com/docs/services/speech-to-text/output.html#max_alternatives). - parameter wordAlternativesThreshold: A confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its @@ -792,11 +805,14 @@ public class SpeechToText { supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). + - parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the + customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not + specify both parameters with a request. - parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified grammar; it does not recognize other custom words from the model's words resource. See - [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/output.html). + [Grammars](https://cloud.ibm.com/docs/services/speech-to-text/input.html#grammars-input). - parameter redaction: If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that has three or more consecutive digits by replacing each digit with an `X` character. It is intended to redact sensitive numeric data, such as credit card numbers. By default, the service performs no @@ -807,12 +823,13 @@ public class SpeechToText { `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). + - parameter contentType: The format (MIME type) of the audio. For more information about specifying an audio + format, see **Audio formats (content types)** in the method description. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createJob( audio: Data, - contentType: String? = nil, model: String? = nil, callbackURL: String? = nil, events: String? = nil, @@ -832,8 +849,10 @@ public class SpeechToText { profanityFilter: Bool? = nil, smartFormatting: Bool? = nil, speakerLabels: Bool? = nil, + customizationID: String? = nil, grammarName: String? = nil, redaction: Bool? = nil, + contentType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -845,8 +864,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createJob") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createJob") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" if let contentType = contentType { headerParameters["Content-Type"] = contentType @@ -930,6 +949,10 @@ public class SpeechToText { let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)") queryParameters.append(queryParameter) } + if let customizationID = customizationID { + let queryParameter = URLQueryItem(name: "customization_id", value: customizationID) + queryParameters.append(queryParameter) + } if let grammarName = grammarName { let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName) queryParameters.append(queryParameter) @@ -979,8 +1002,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJobs") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJobs") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1025,8 +1048,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJob") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "checkJob") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1054,7 +1077,7 @@ public class SpeechToText { Deletes the specified job. You cannot delete a job that the service is actively processing. Once you delete a job, its results are no longer available. The service automatically deletes a job and its results when the time to live for the results expires. You must use credentials for the instance of the service that owns a job to delete it. - **See also:** [Deleting a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#delete). + **See also:** [Deleting a job](https://cloud.ibm.com/docs/services/speech-to-text/async.html#delete-async). - parameter id: The identifier of the asynchronous job that is to be used for the request. You must make the request with credentials for the instance of the service that owns the job. @@ -1071,9 +1094,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteJob") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteJob") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct REST request let path = "/v1/recognitions/\(id)" @@ -1101,7 +1123,7 @@ public class SpeechToText { base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. **See also:** [Create a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#createModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#createModel-language). - parameter name: A user-defined name for the new custom language model. Use a name that is unique among all custom language models that you own. Use a localized name that matches the language of the custom model. Use a @@ -1138,7 +1160,7 @@ public class SpeechToText { baseModelName: baseModelName, dialect: dialect, description: description) - guard let body = try? JSONEncoder().encode(createLanguageModelRequest) else { + guard let body = try? JSON.encoder.encode(createLanguageModelRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1148,8 +1170,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1176,7 +1198,7 @@ public class SpeechToText { language models for all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language - models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels). + models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels-language). - parameter language: The identifier of the language for which custom language or custom acoustic models are to be returned (for example, `en-US`). Omit the parameter to see all custom language or custom acoustic models that @@ -1194,8 +1216,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLanguageModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLanguageModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1226,7 +1248,7 @@ public class SpeechToText { Gets information about a specified custom language model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom language - models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels). + models](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#listModels-language). - parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -1243,8 +1265,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1273,7 +1295,7 @@ public class SpeechToText { corpus or grammar to the model, is currently being processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#deleteModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#deleteModel-language). - parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -1290,8 +1312,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1335,7 +1357,7 @@ public class SpeechToText { * No training data have been added to the custom model. * One or more words that were added to the custom model have invalid sounds-like pronunciations that you must fix. **See also:** [Train the custom language - model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#trainModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/language-create.html#trainModel-language). - parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -1368,8 +1390,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1411,7 +1433,7 @@ public class SpeechToText { of the model are preserved, but the model's words resource is removed and must be re-created. You must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom language - model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#resetModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/language-models.html#resetModel-language). - parameter customizationID: The customization ID (GUID) of the custom language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -1428,8 +1450,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1482,8 +1504,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeLanguageModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeLanguageModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1529,8 +1551,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCorpora") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listCorpora") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1610,19 +1632,14 @@ public class SpeechToText { public func addCorpus( customizationID: String, corpusName: String, - corpusFile: URL, + corpusFile: Data, allowOverwrite: Bool? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() - do { - try multipartFormData.append(file: corpusFile, withName: "corpus_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(corpusFile.path)")) - return - } + multipartFormData.append(corpusFile, withName: "corpus_file", fileName: "filename") guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) return @@ -1633,8 +1650,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addCorpus") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addCorpus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -1692,8 +1709,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCorpus") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCorpus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1743,8 +1760,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCorpus") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteCorpus") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1805,8 +1822,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -1896,7 +1913,7 @@ public class SpeechToText { // construct body let addWordsRequest = CustomWords( words: words) - guard let body = try? JSONEncoder().encode(addWordsRequest) else { + guard let body = try? JSON.encoder.encode(addWordsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -1906,8 +1923,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -1999,7 +2016,7 @@ public class SpeechToText { word: word, soundsLike: soundsLike, displayAs: displayAs) - guard let body = try? JSONEncoder().encode(addWordRequest) else { + guard let body = try? JSON.encoder.encode(addWordRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2009,8 +2026,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2061,8 +2078,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2114,8 +2131,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2160,8 +2177,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listGrammars") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listGrammars") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2256,8 +2273,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addGrammar") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addGrammar") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = contentType @@ -2314,8 +2331,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getGrammar") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getGrammar") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2365,8 +2382,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteGrammar") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteGrammar") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2395,7 +2412,7 @@ public class SpeechToText { base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. **See also:** [Create a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#createModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#createModel-acoustic). - parameter name: A user-defined name for the new custom acoustic model. Use a name that is unique among all custom acoustic models that you own. Use a localized name that matches the language of the custom model. Use a @@ -2422,7 +2439,7 @@ public class SpeechToText { name: name, baseModelName: baseModelName, description: description) - guard let body = try? JSONEncoder().encode(createAcousticModelRequest) else { + guard let body = try? JSON.encoder.encode(createAcousticModelRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -2432,8 +2449,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -2460,7 +2477,7 @@ public class SpeechToText { acoustic models for all languages. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic - models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels). + models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels-acoustic). - parameter language: The identifier of the language for which custom language or custom acoustic models are to be returned (for example, `en-US`). Omit the parameter to see all custom language or custom acoustic models that @@ -2478,8 +2495,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAcousticModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAcousticModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2510,7 +2527,7 @@ public class SpeechToText { Gets information about a specified custom acoustic model. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Listing custom acoustic - models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels). + models](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#listModels-acoustic). - parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -2527,8 +2544,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2557,7 +2574,7 @@ public class SpeechToText { audio resource to the model, is currently being processed. You must use credentials for the instance of the service that owns a model to delete it. **See also:** [Deleting a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#deleteModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#deleteModel-acoustic). - parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -2574,8 +2591,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2627,7 +2644,7 @@ public class SpeechToText { * You passed an incompatible custom language model with the `custom_language_model_id` query parameter. Both custom models must be based on the same version of the same base model. **See also:** [Train the custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#trainModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-create.html#trainModel-acoustic). - parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -2650,8 +2667,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "trainAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2689,7 +2706,7 @@ public class SpeechToText { are preserved, but the model's audio resources are removed and must be re-created. You must use credentials for the instance of the service that owns a model to reset it. **See also:** [Resetting a custom acoustic - model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#resetModel). + model](https://cloud.ibm.com/docs/services/speech-to-text/acoustic-models.html#resetModel-acoustic). - parameter customizationID: The customization ID (GUID) of the custom acoustic model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. @@ -2706,8 +2723,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "resetAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2775,8 +2792,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeAcousticModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "upgradeAcousticModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -2836,8 +2853,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAudio") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listAudio") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -2891,6 +2908,7 @@ public class SpeechToText { You can add an individual audio file in any format that the service supports for speech recognition. For an audio-type resource, use the `Content-Type` parameter to specify the audio format (MIME type) of the audio file, including specifying the sampling rate, channels, and endianness where indicated. + * `audio/alaw` (Specify the sampling rate (`rate`) of the audio.) * `audio/basic` (Use only with narrowband models.) * `audio/flac` * `audio/g729` (Use only with narrowband models.) @@ -2917,10 +2935,16 @@ public class SpeechToText { the media type of the archive file: * `application/zip` for a **.zip** file * `application/gzip` for a **.tar.gz** file. - All audio files contained in the archive must have the same audio format. Use the `Contained-Content-Type` - parameter to specify the format of the contained audio files. The parameter accepts all of the audio formats - supported for use with speech recognition and with the `Content-Type` header, including the `rate`, `channels`, and - `endianness` parameters that are used with some formats. The default contained audio format is `audio/wav`. + When you add an archive-type resource, the `Contained-Content-Type` header is optional depending on the format of + the files that you are adding: + * For audio files of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`, you must use the + `Contained-Content-Type` header to specify the format of the contained audio files. Include the `rate`, `channels`, + and `endianness` parameters where necessary. In this case, all audio files contained in the archive file must have + the same audio format. + * For audio files of all other types, you can omit the `Contained-Content-Type` header. In this case, the audio + files contained in the archive file can have any of the formats not listed in the previous bullet. The audio files + do not need to have the same format. + Do not use the `Contained-Content-Type` header when adding an audio-type resource. ### Naming restrictions for embedded audio files The name of an audio file that is embedded within an archive-type resource must meet the following restrictions: * Include a maximum of 128 characters in the file name; this includes the file extension. @@ -2937,17 +2961,22 @@ public class SpeechToText { * Do not use the name of an audio resource that has already been added to the custom model. - parameter audioResource: The audio resource that is to be added to the custom acoustic model, an individual audio file or an archive file. + - parameter containedContentType: **For an archive-type resource,** specify the format of the audio files that + are contained in the archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`. + Include the `rate`, `channels`, and `endianness` parameters where necessary. In this case, all audio files that + are contained in the archive file must be of the indicated type. + For all other audio formats, you can omit the header. In this case, the audio files can be of multiple types as + long as they are not of the types listed in the previous paragraph. + The parameter accepts all of the audio formats that are supported for use with speech recognition. For more + information, see **Content types for audio-type resources** in the method description. + **For an audio-type resource,** omit the header. + - parameter allowOverwrite: If `true`, the specified audio resource overwrites an existing audio resource with + the same name. If `false`, the request fails if an audio resource with the same name already exists. The + parameter has no effect if an audio resource with the same name does not already exist. - parameter contentType: For an audio-type resource, the format (MIME type) of the audio. For more information, see **Content types for audio-type resources** in the method description. For an archive-type resource, the media type of the archive file. For more information, see **Content types for archive-type resources** in the method description. - - parameter containedContentType: For an archive-type resource, specifies the format of the audio files that are - contained in the archive file. The parameter accepts all of the audio formats that are supported for use with - speech recognition, including the `rate`, `channels`, and `endianness` parameters that are used with some - formats. For more information, see **Content types for audio-type resources** in the method description. - - parameter allowOverwrite: If `true`, the specified audio resource overwrites an existing audio resource with - the same name. If `false`, the request fails if an audio resource with the same name already exists. The - parameter has no effect if an audio resource with the same name does not already exist. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ @@ -2955,9 +2984,9 @@ public class SpeechToText { customizationID: String, audioName: String, audioResource: Data, - contentType: String? = nil, containedContentType: String? = nil, allowOverwrite: Bool? = nil, + contentType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -2969,15 +2998,15 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addAudio") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addAudio") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" - if let contentType = contentType { - headerParameters["Content-Type"] = contentType - } if let containedContentType = containedContentType { headerParameters["Contained-Content-Type"] = containedContentType } + if let contentType = contentType { + headerParameters["Content-Type"] = contentType + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -3043,8 +3072,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAudio") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getAudio") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -3094,8 +3123,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAudio") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteAudio") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -3142,9 +3171,8 @@ public class SpeechToText { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") - headerParameters.merge(metadataHeaders) { (_, new) in new } - headerParameters["Accept"] = "application/json" + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() diff --git a/Source/TextToSpeechV1/Models/CreateVoiceModel.swift b/Source/TextToSpeechV1/Models/CreateVoiceModel.swift index 2b69edb5f..87bd86a4d 100644 --- a/Source/TextToSpeechV1/Models/CreateVoiceModel.swift +++ b/Source/TextToSpeechV1/Models/CreateVoiceModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Pronunciation.swift b/Source/TextToSpeechV1/Models/Pronunciation.swift index a22a2002e..79ab883ac 100644 --- a/Source/TextToSpeechV1/Models/Pronunciation.swift +++ b/Source/TextToSpeechV1/Models/Pronunciation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/SupportedFeatures.swift b/Source/TextToSpeechV1/Models/SupportedFeatures.swift index 88fe85b9c..a9fc2ce67 100644 --- a/Source/TextToSpeechV1/Models/SupportedFeatures.swift +++ b/Source/TextToSpeechV1/Models/SupportedFeatures.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Text.swift b/Source/TextToSpeechV1/Models/Text.swift index 3bddd093a..b18d82d73 100644 --- a/Source/TextToSpeechV1/Models/Text.swift +++ b/Source/TextToSpeechV1/Models/Text.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Translation.swift b/Source/TextToSpeechV1/Models/Translation.swift index 5ba0d12ba..c20849aac 100644 --- a/Source/TextToSpeechV1/Models/Translation.swift +++ b/Source/TextToSpeechV1/Models/Translation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/UpdateVoiceModel.swift b/Source/TextToSpeechV1/Models/UpdateVoiceModel.swift index 539e89983..deb88f73b 100644 --- a/Source/TextToSpeechV1/Models/UpdateVoiceModel.swift +++ b/Source/TextToSpeechV1/Models/UpdateVoiceModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Voice.swift b/Source/TextToSpeechV1/Models/Voice.swift index 13b5e25d4..052a72091 100644 --- a/Source/TextToSpeechV1/Models/Voice.swift +++ b/Source/TextToSpeechV1/Models/Voice.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/VoiceCustomization.swift b/Source/TextToSpeechV1/Models/VoiceCustomization.swift new file mode 100644 index 000000000..fd6a4912f --- /dev/null +++ b/Source/TextToSpeechV1/Models/VoiceCustomization.swift @@ -0,0 +1,84 @@ +/** + * Copyright IBM Corporation 2018 + * + * 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. + **/ + +import Foundation + +/** + Returns information about a specified custom voice model. This field is returned only by the **Get a voice** method and + only when you specify the customization ID of a custom voice model. + */ +public struct VoiceCustomization: Codable, Equatable { + + /** + The customization ID (GUID) of the custom voice model. The **Create a custom model** method returns only this + field. It does not not return the other fields of this object. + */ + public var customizationID: String + + /** + The name of the custom voice model. + */ + public var name: String? + + /** + The language identifier of the custom voice model (for example, `en-US`). + */ + public var language: String? + + /** + The GUID of the service credentials for the instance of the service that owns the custom voice model. + */ + public var owner: String? + + /** + The date and time in Coordinated Universal Time (UTC) at which the custom voice model was created. The value is + provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + */ + public var created: String? + + /** + The date and time in Coordinated Universal Time (UTC) at which the custom voice model was last modified. Equals + `created` when a new voice model is first added but has yet to be updated. The value is provided in full ISO 8601 + format (`YYYY-MM-DDThh:mm:ss.sTZD`). + */ + public var lastModified: String? + + /** + The description of the custom voice model. + */ + public var description: String? + + /** + An array of `Word` objects that lists the words and their translations from the custom voice model. The words are + listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the + custom model contains no words. This field is returned only by the **Get a voice** method and only when you specify + the customization ID of a custom voice model. + */ + public var words: [Word]? + + // Map each property name to the key that shall be used for encoding/decoding. + private enum CodingKeys: String, CodingKey { + case customizationID = "customization_id" + case name = "name" + case language = "language" + case owner = "owner" + case created = "created" + case lastModified = "last_modified" + case description = "description" + case words = "words" + } + +} diff --git a/Source/TextToSpeechV1/Models/VoiceModel.swift b/Source/TextToSpeechV1/Models/VoiceModel.swift index 663e05db2..a41f833c8 100644 --- a/Source/TextToSpeechV1/Models/VoiceModel.swift +++ b/Source/TextToSpeechV1/Models/VoiceModel.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/VoiceModels.swift b/Source/TextToSpeechV1/Models/VoiceModels.swift index a12cf4d09..4dd836c74 100644 --- a/Source/TextToSpeechV1/Models/VoiceModels.swift +++ b/Source/TextToSpeechV1/Models/VoiceModels.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Voices.swift b/Source/TextToSpeechV1/Models/Voices.swift index 3bf9feb1c..a22e79375 100644 --- a/Source/TextToSpeechV1/Models/Voices.swift +++ b/Source/TextToSpeechV1/Models/Voices.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Word.swift b/Source/TextToSpeechV1/Models/Word.swift index 37fc5897a..818da38df 100644 --- a/Source/TextToSpeechV1/Models/Word.swift +++ b/Source/TextToSpeechV1/Models/Word.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/Models/Words.swift b/Source/TextToSpeechV1/Models/Words.swift index 367f3f7ea..4fc8dfb8b 100644 --- a/Source/TextToSpeechV1/Models/Words.swift +++ b/Source/TextToSpeechV1/Models/Words.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/TextToSpeechV1/TextToSpeech.swift b/Source/TextToSpeechV1/TextToSpeech.swift index 08c789af9..282030ab1 100644 --- a/Source/TextToSpeechV1/TextToSpeech.swift +++ b/Source/TextToSpeechV1/TextToSpeech.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,20 +45,20 @@ public class TextToSpeech { var session = URLSession(configuration: URLSessionConfiguration.default) var authMethod: AuthenticationMethod + #if os(Linux) /** Create a `TextToSpeech` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. */ - public init?(credentialsFile: URL) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "text_to_speech") else { + public init?() { + guard let credentials = Shared.extractCredentials(serviceName: "text_to_speech") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -68,7 +68,9 @@ public class TextToSpeech { self.serviceURL = serviceURL } self.authMethod = authMethod + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `TextToSpeech` object. @@ -78,6 +80,7 @@ public class TextToSpeech { */ public init(username: String, password: String) { self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -88,6 +91,7 @@ public class TextToSpeech { */ public init(apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) + RestRequest.userAgent = Shared.userAgent } /** @@ -97,6 +101,7 @@ public class TextToSpeech { */ public init(accessToken: String) { self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -119,19 +124,25 @@ public class TextToSpeech { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - if case let .some(.string(description)) = json["code_description"] { - metadata["codeDescription"] = description - } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -139,7 +150,8 @@ public class TextToSpeech { Lists all voices available for use with the service. The information includes the name, language, gender, and other details about the voice. To see information about a specific voice, use the **Get a voice** method. - **See also:** [Specifying a voice](https://cloud.ibm.com/docs/services/text-to-speech/http.html#voices). + **See also:** [Listing all available + voices](https://cloud.ibm.com/docs/services/text-to-speech/voices.html#listVoices). - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error @@ -153,8 +165,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoices") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoices") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -177,7 +189,7 @@ public class TextToSpeech { Gets information about the specified voice. The information includes the name, language, gender, and other details about the voice. Specify a customization ID to obtain information for that custom voice model of the specified voice. To list information about all available voices, use the **List voices** method. - **See also:** [Specifying a voice](https://cloud.ibm.com/docs/services/text-to-speech/http.html#voices). + **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/services/text-to-speech/voices.html#listVoice). - parameter voice: The voice for which information is to be returned. - parameter customizationID: The customization ID (GUID) of a custom voice model for which information is to be @@ -197,8 +209,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoice") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoice") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -233,10 +245,10 @@ public class TextToSpeech { Synthesizes text to audio that is spoken in the specified voice. The service bases its understanding of the language for the input text on the specified voice. Use a voice that matches the language of the input text. - The service returns the synthesized audio stream as an array of bytes. You can pass a maximum of 5 KB of text to - the service. - **See also:** [Synthesizing text to - audio](https://cloud.ibm.com/docs/services/text-to-speech/http.html#synthesize). + The method accepts a maximum of 5 KB of input text in the body of the request, and 8 KB for the URL and headers. + The 5 KB limit includes any SSML tags that you specify. The service returns the synthesized audio stream as an + array of bytes. + **See also:** [The HTTP interface](https://cloud.ibm.com/docs/services/text-to-speech/http.html). ### Audio formats (accept types) The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the audio. You must specify a sampling @@ -276,7 +288,7 @@ public class TextToSpeech { * `audio/webm;codecs=vorbis` You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. For more information about specifying an audio format, including additional details about some of the formats, see - [Specifying an audio format](https://cloud.ibm.com/docs/services/text-to-speech/http.html#format). + [Audio formats](https://cloud.ibm.com/docs/services/text-to-speech/audio-formats.html). ### Warning messages If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning includes a descriptive message and a list of invalid argument @@ -284,30 +296,30 @@ public class TextToSpeech { a list of the form `\"{invalid_arg_1}, {invalid_arg_2}.\"` The request succeeds despite the warnings. - parameter text: The text to synthesize. - - parameter accept: The requested format (MIME type) of the audio. You can use the `Accept` header or the - `accept` parameter to specify the audio format. For more information about specifying an audio format, see - **Audio formats (accept types)** in the method description. - Default: `audio/ogg;codecs=opus`. - parameter voice: The voice to use for synthesis. - parameter customizationID: The customization ID (GUID) of a custom voice model to use for the synthesis. If a custom voice model is specified, it is guaranteed to work only if it matches the language of the indicated voice. You must make the request with service credentials created for the instance of the service that owns the custom model. Omit the parameter to use the specified voice with no customization. + - parameter accept: The requested format (MIME type) of the audio. You can use the `Accept` header or the + `accept` parameter to specify the audio format. For more information about specifying an audio format, see + **Audio formats (accept types)** in the method description. + Default: `audio/ogg;codecs=opus`. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func synthesize( text: String, - accept: String? = nil, voice: String? = nil, customizationID: String? = nil, + accept: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let synthesizeRequest = Text( text: text) - guard let body = try? JSONEncoder().encode(synthesizeRequest) else { + guard let body = try? JSON.encoder.encode(synthesizeRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -317,8 +329,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "synthesize") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "synthesize") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Content-Type"] = "application/json" if let accept = accept { headerParameters["Accept"] = accept @@ -348,37 +360,7 @@ public class TextToSpeech { ) // execute REST request - request.response { (response: WatsonResponse?, error: WatsonError?) in - var response = response - guard let data = response?.result else { - completionHandler(response, error) - return - } - if accept?.lowercased().contains("audio/wav") == true { - // repair the WAV header - var wav = data - guard WAVRepair.isWAVFile(data: wav) else { - let error = WatsonError.other(message: "Expected returned audio to be in WAV format") - completionHandler(nil, error) - return - } - WAVRepair.repairWAVHeader(data: &wav) - response?.result = wav - completionHandler(response, nil) - } else if accept?.lowercased().contains("ogg") == true && accept?.lowercased().contains("opus") == true { - do { - let decodedAudio = try TextToSpeechDecoder(audioData: data) - response?.result = decodedAudio.pcmDataWithHeaders - completionHandler(response, nil) - } catch { - let error = WatsonError.serialization(values: "returned audio") - completionHandler(nil, error) - return - } - } else { - completionHandler(response, nil) - } - } + request.response(completionHandler: completionHandler) } /** @@ -417,8 +399,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getPronunciation") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getPronunciation") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -481,7 +463,7 @@ public class TextToSpeech { name: name, language: language, description: description) - guard let body = try? JSONEncoder().encode(createVoiceModelRequest) else { + guard let body = try? JSON.encoder.encode(createVoiceModelRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -491,8 +473,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createVoiceModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createVoiceModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -538,8 +520,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoiceModels") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listVoiceModels") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -607,7 +589,7 @@ public class TextToSpeech { name: name, description: description, words: words) - guard let body = try? JSONEncoder().encode(updateVoiceModelRequest) else { + guard let body = try? JSON.encoder.encode(updateVoiceModelRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -617,8 +599,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateVoiceModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateVoiceModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -667,8 +649,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoiceModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getVoiceModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -714,8 +696,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteVoiceModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteVoiceModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct REST request let path = "/v1/customizations/\(customizationID)" @@ -776,7 +758,7 @@ public class TextToSpeech { // construct body let addWordsRequest = Words( words: words) - guard let body = try? JSONEncoder().encode(addWordsRequest) else { + guard let body = try? JSON.encoder.encode(addWordsRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -786,8 +768,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWords") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" @@ -836,8 +818,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listWords") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -906,7 +888,7 @@ public class TextToSpeech { let addWordRequest = Translation( translation: translation, partOfSpeech: partOfSpeech) - guard let body = try? JSONEncoder().encode(addWordRequest) else { + guard let body = try? JSON.encoder.encode(addWordRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -916,8 +898,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "addWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Content-Type"] = "application/json" // construct REST request @@ -966,8 +948,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct REST request @@ -1015,8 +997,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteWord") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct REST request let path = "/v1/customizations/\(customizationID)/words/\(word)" @@ -1062,8 +1044,8 @@ public class TextToSpeech { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") + headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() diff --git a/Source/ToneAnalyzerV3/Models/DocumentAnalysis.swift b/Source/ToneAnalyzerV3/Models/DocumentAnalysis.swift index 1367d8d83..2a5e67f9d 100644 --- a/Source/ToneAnalyzerV3/Models/DocumentAnalysis.swift +++ b/Source/ToneAnalyzerV3/Models/DocumentAnalysis.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/SentenceAnalysis.swift b/Source/ToneAnalyzerV3/Models/SentenceAnalysis.swift index ceeb62884..b8ed3de78 100644 --- a/Source/ToneAnalyzerV3/Models/SentenceAnalysis.swift +++ b/Source/ToneAnalyzerV3/Models/SentenceAnalysis.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneAnalysis.swift b/Source/ToneAnalyzerV3/Models/ToneAnalysis.swift index a5696d7d5..467bffe62 100644 --- a/Source/ToneAnalyzerV3/Models/ToneAnalysis.swift +++ b/Source/ToneAnalyzerV3/Models/ToneAnalysis.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneCategory.swift b/Source/ToneAnalyzerV3/Models/ToneCategory.swift index 0e0a137a0..7c4818399 100644 --- a/Source/ToneAnalyzerV3/Models/ToneCategory.swift +++ b/Source/ToneAnalyzerV3/Models/ToneCategory.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneChatInput.swift b/Source/ToneAnalyzerV3/Models/ToneChatInput.swift index 6d91be65d..5a59a51fd 100644 --- a/Source/ToneAnalyzerV3/Models/ToneChatInput.swift +++ b/Source/ToneAnalyzerV3/Models/ToneChatInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneChatScore.swift b/Source/ToneAnalyzerV3/Models/ToneChatScore.swift index daf88a197..e51b75b90 100644 --- a/Source/ToneAnalyzerV3/Models/ToneChatScore.swift +++ b/Source/ToneAnalyzerV3/Models/ToneChatScore.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneContent.swift b/Source/ToneAnalyzerV3/Models/ToneContent.swift index 53547648f..17a59194e 100644 --- a/Source/ToneAnalyzerV3/Models/ToneContent.swift +++ b/Source/ToneAnalyzerV3/Models/ToneContent.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ **/ import Foundation +import RestKit /** JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type @@ -36,7 +37,7 @@ public enum ToneContent { internal var content: Data? { switch self { - case .toneInput(let toneInput): return try? JSONEncoder().encode(toneInput) + case .toneInput(let toneInput): return try? JSON.encoder.encode(toneInput) case .text(let text): return text.data(using: .utf8) case .html(let html): return html.data(using: .utf8) } diff --git a/Source/ToneAnalyzerV3/Models/ToneInput.swift b/Source/ToneAnalyzerV3/Models/ToneInput.swift index ae75fde7c..9f780fb18 100644 --- a/Source/ToneAnalyzerV3/Models/ToneInput.swift +++ b/Source/ToneAnalyzerV3/Models/ToneInput.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/ToneScore.swift b/Source/ToneAnalyzerV3/Models/ToneScore.swift index 8861bafbf..1edb429af 100644 --- a/Source/ToneAnalyzerV3/Models/ToneScore.swift +++ b/Source/ToneAnalyzerV3/Models/ToneScore.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/Utterance.swift b/Source/ToneAnalyzerV3/Models/Utterance.swift index c6ed83cb3..81d2fb68b 100644 --- a/Source/ToneAnalyzerV3/Models/Utterance.swift +++ b/Source/ToneAnalyzerV3/Models/Utterance.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/UtteranceAnalyses.swift b/Source/ToneAnalyzerV3/Models/UtteranceAnalyses.swift index 57245c592..f208b8f60 100644 --- a/Source/ToneAnalyzerV3/Models/UtteranceAnalyses.swift +++ b/Source/ToneAnalyzerV3/Models/UtteranceAnalyses.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/Models/UtteranceAnalysis.swift b/Source/ToneAnalyzerV3/Models/UtteranceAnalysis.swift index 38ee0820e..9e1ce73e2 100644 --- a/Source/ToneAnalyzerV3/Models/UtteranceAnalysis.swift +++ b/Source/ToneAnalyzerV3/Models/UtteranceAnalysis.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/ToneAnalyzerV3/ToneAnalyzer.swift b/Source/ToneAnalyzerV3/ToneAnalyzer.swift index 253952334..5adf1c869 100644 --- a/Source/ToneAnalyzerV3/ToneAnalyzer.swift +++ b/Source/ToneAnalyzerV3/ToneAnalyzer.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,22 +41,23 @@ public class ToneAnalyzer { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `ToneAnalyzer` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "tone_analyzer") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "tone_analyzer") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -66,20 +67,22 @@ public class ToneAnalyzer { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `ToneAnalyzer` object. - - parameter username: The username used to authenticate with the service. - - parameter password: The password used to authenticate with the service. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. + - parameter username: The username used to authenticate with the service. + - parameter password: The password used to authenticate with the service. */ - public init(username: String, password: String, version: String) { - self.authMethod = Shared.getAuthMethod(username: username, password: password) + public init(version: String, username: String, password: String) { self.version = version + self.authMethod = Shared.getAuthMethod(username: username, password: password) + RestRequest.userAgent = Shared.userAgent } /** @@ -93,6 +96,7 @@ public class ToneAnalyzer { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -103,8 +107,9 @@ public class ToneAnalyzer { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -127,16 +132,25 @@ public class ToneAnalyzer { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - if case let .some(.string(message)) = json["error"] { + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { + errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -161,6 +175,11 @@ public class ToneAnalyzer { - parameter sentences: Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If `true` (the default), the service returns results for each sentence. + - parameter tones: **`2017-09-21`:** Deprecated. The service continues to accept the parameter for + backward-compatibility, but the parameter no longer affects the response. + **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the input; + the indicated tones apply both to the full document and to individual sentences of the document. You can specify + one or more of the valid values. Omit the parameter to request results for all three tones. - parameter contentLanguage: The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for @@ -176,6 +195,7 @@ public class ToneAnalyzer { public func tone( toneContent: ToneContent, sentences: Bool? = nil, + tones: [String]? = nil, contentLanguage: String? = nil, acceptLanguage: String? = nil, headers: [String: String]? = nil, @@ -192,8 +212,8 @@ public class ToneAnalyzer { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "tone") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "tone") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = toneContent.contentType if let contentLanguage = contentLanguage { @@ -210,6 +230,10 @@ public class ToneAnalyzer { let queryParameter = URLQueryItem(name: "sentences", value: "\(sentences)") queryParameters.append(queryParameter) } + if let tones = tones { + let queryParameter = URLQueryItem(name: "tones", value: tones.joined(separator: ",")) + queryParameters.append(queryParameter) + } // construct REST request let request = RestRequest( @@ -265,7 +289,7 @@ public class ToneAnalyzer { // construct body let toneChatRequest = ToneChatInput( utterances: utterances) - guard let body = try? JSONEncoder().encode(toneChatRequest) else { + guard let body = try? JSON.encoder.encode(toneChatRequest) else { completionHandler(nil, WatsonError.serialization(values: "request body")) return } @@ -275,8 +299,8 @@ public class ToneAnalyzer { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "toneChat") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "toneChat") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = "application/json" if let contentLanguage = contentLanguage { diff --git a/Source/VisualRecognitionV3/Models/Class.swift b/Source/VisualRecognitionV3/Models/Class.swift index c7be448f5..c539a7fc3 100644 --- a/Source/VisualRecognitionV3/Models/Class.swift +++ b/Source/VisualRecognitionV3/Models/Class.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ClassResult.swift b/Source/VisualRecognitionV3/Models/ClassResult.swift index 3a64c010d..0cca830ee 100644 --- a/Source/VisualRecognitionV3/Models/ClassResult.swift +++ b/Source/VisualRecognitionV3/Models/ClassResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ClassifiedImage.swift b/Source/VisualRecognitionV3/Models/ClassifiedImage.swift index 2d83a0163..32c431777 100644 --- a/Source/VisualRecognitionV3/Models/ClassifiedImage.swift +++ b/Source/VisualRecognitionV3/Models/ClassifiedImage.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ClassifiedImages.swift b/Source/VisualRecognitionV3/Models/ClassifiedImages.swift index 419a59901..dce64e8b5 100644 --- a/Source/VisualRecognitionV3/Models/ClassifiedImages.swift +++ b/Source/VisualRecognitionV3/Models/ClassifiedImages.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/Classifier.swift b/Source/VisualRecognitionV3/Models/Classifier.swift index 54787f6aa..b7c9cf1a0 100644 --- a/Source/VisualRecognitionV3/Models/Classifier.swift +++ b/Source/VisualRecognitionV3/Models/Classifier.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ClassifierResult.swift b/Source/VisualRecognitionV3/Models/ClassifierResult.swift index cc8f87435..3f3d902fd 100644 --- a/Source/VisualRecognitionV3/Models/ClassifierResult.swift +++ b/Source/VisualRecognitionV3/Models/ClassifierResult.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/Classifiers.swift b/Source/VisualRecognitionV3/Models/Classifiers.swift index cda47ad5c..dc9aa0b61 100644 --- a/Source/VisualRecognitionV3/Models/Classifiers.swift +++ b/Source/VisualRecognitionV3/Models/Classifiers.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/DetectedFaces.swift b/Source/VisualRecognitionV3/Models/DetectedFaces.swift index b54cdd9c9..c580d2c6a 100644 --- a/Source/VisualRecognitionV3/Models/DetectedFaces.swift +++ b/Source/VisualRecognitionV3/Models/DetectedFaces.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ErrorInfo.swift b/Source/VisualRecognitionV3/Models/ErrorInfo.swift index 7b3f981d1..955e8334d 100644 --- a/Source/VisualRecognitionV3/Models/ErrorInfo.swift +++ b/Source/VisualRecognitionV3/Models/ErrorInfo.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/Face.swift b/Source/VisualRecognitionV3/Models/Face.swift index 600e532c5..fb9c5812b 100644 --- a/Source/VisualRecognitionV3/Models/Face.swift +++ b/Source/VisualRecognitionV3/Models/Face.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/FaceAge.swift b/Source/VisualRecognitionV3/Models/FaceAge.swift index 634e8eae4..a29ec9275 100644 --- a/Source/VisualRecognitionV3/Models/FaceAge.swift +++ b/Source/VisualRecognitionV3/Models/FaceAge.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/FaceGender.swift b/Source/VisualRecognitionV3/Models/FaceGender.swift index 454bcd2ee..5e69a07d9 100644 --- a/Source/VisualRecognitionV3/Models/FaceGender.swift +++ b/Source/VisualRecognitionV3/Models/FaceGender.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/FaceLocation.swift b/Source/VisualRecognitionV3/Models/FaceLocation.swift index 80032066a..e87427fc4 100644 --- a/Source/VisualRecognitionV3/Models/FaceLocation.swift +++ b/Source/VisualRecognitionV3/Models/FaceLocation.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/ImageWithFaces.swift b/Source/VisualRecognitionV3/Models/ImageWithFaces.swift index d933ec7f0..9c572757a 100644 --- a/Source/VisualRecognitionV3/Models/ImageWithFaces.swift +++ b/Source/VisualRecognitionV3/Models/ImageWithFaces.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/Models/WarningInfo.swift b/Source/VisualRecognitionV3/Models/WarningInfo.swift index fdcc8ec10..36690249d 100644 --- a/Source/VisualRecognitionV3/Models/WarningInfo.swift +++ b/Source/VisualRecognitionV3/Models/WarningInfo.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/Source/VisualRecognitionV3/VisualRecognition.swift b/Source/VisualRecognitionV3/VisualRecognition.swift index 5a1710cc1..aaf7f2bde 100644 --- a/Source/VisualRecognitionV3/VisualRecognition.swift +++ b/Source/VisualRecognitionV3/VisualRecognition.swift @@ -1,5 +1,5 @@ /** - * Copyright IBM Corporation 2018 + * Copyright IBM Corporation 2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,22 +37,23 @@ public class VisualRecognition { var authMethod: AuthenticationMethod let version: String + #if os(Linux) /** Create a `VisualRecognition` object. - Use this initializer to automatically pull service credentials from your credentials file. - This file is downloaded from your service instance on IBM Cloud as ibm-credentials.env. + This initializer will retrieve credentials from the environment or a local credentials file. + The credentials file can be downloaded from your service instance on IBM Cloud as ibm-credentials.env. Make sure to add the credentials file to your project so that it can be loaded at runtime. - If the credentials cannot be loaded from the file, or the file is not found, initialization will fail. + If credentials are not available in the environment or a local credentials file, initialization will fail. In that case, try another initializer that directly passes in the credentials. - - parameter credentialsFile: The URL of the credentials file. - parameter version: The release date of the version of the API to use. Specify the date in "YYYY-MM-DD" format. */ - public init?(credentialsFile: URL, version: String) { - guard let credentials = Shared.extractCredentials(from: credentialsFile, serviceName: "visual_recognition") else { + public init?(version: String) { + self.version = version + guard let credentials = Shared.extractCredentials(serviceName: "visual_recognition") else { return nil } guard let authMethod = Shared.getAuthMethod(from: credentials) else { @@ -62,8 +63,9 @@ public class VisualRecognition { self.serviceURL = serviceURL } self.authMethod = authMethod - self.version = version + RestRequest.userAgent = Shared.userAgent } + #endif /** Create a `VisualRecognition` object. @@ -76,6 +78,7 @@ public class VisualRecognition { public init(version: String, apiKey: String, iamUrl: String? = nil) { self.authMethod = Shared.getAuthMethod(apiKey: apiKey, iamURL: iamUrl) self.version = version + RestRequest.userAgent = Shared.userAgent } /** @@ -86,8 +89,9 @@ public class VisualRecognition { - parameter accessToken: An access token for the service. */ public init(version: String, accessToken: String) { - self.authMethod = IAMAccessToken(accessToken: accessToken) self.version = version + self.authMethod = IAMAccessToken(accessToken: accessToken) + RestRequest.userAgent = Shared.userAgent } public func accessToken(_ newToken: String) { @@ -110,42 +114,25 @@ public class VisualRecognition { var metadata = [String: Any]() do { - let json = try JSONDecoder().decode([String: JSON].self, from: data) - metadata = [:] - switch statusCode { - case 403: - // ErrorAuthentication - if case let .some(.string(status)) = json["status"], - case let .some(.string(statusInfo)) = json["statusInfo"] { - errorMessage = statusInfo - metadata["status"] = status - metadata["statusInfo"] = statusInfo - } - case 404: - // "error": ErrorInfo - if case let .some(.object(errorObj)) = json["error"], - case let .some(.string(message)) = errorObj["description"], - case let .some(.string(errorID)) = errorObj["error_id"] { - errorMessage = message - metadata["description"] = message - metadata["errorID"] = errorID - } - case 413: - // ErrorHTML - if case let .some(.string(message)) = json["Error"] { - errorMessage = message - } - default: - // ErrorResponse - if case let .some(.string(message)) = json["error"] { - errorMessage = message - } + let json = try JSON.decoder.decode([String: JSON].self, from: data) + metadata["response"] = json + if case let .some(.array(errors)) = json["errors"], + case let .some(.object(error)) = errors.first, + case let .some(.string(message)) = error["message"] { + errorMessage = message + } else if case let .some(.string(message)) = json["error"] { + errorMessage = message + } else if case let .some(.string(message)) = json["message"] { + errorMessage = message + } else { + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - // If metadata is empty, it should show up as nil in the WatsonError - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: !metadata.isEmpty ? metadata : nil) } catch { - return WatsonError.http(statusCode: statusCode, message: nil, metadata: nil) + metadata["response"] = data + errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } + + return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -158,7 +145,8 @@ public class VisualRecognition { UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. - - parameter acceptLanguage: The desired language of parts of the response. See the response for details. + - parameter imagesFilename: The filename for imagesFile. + - parameter imagesFileContentType: The content type of imagesFile. - parameter url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. The maximum image size is 10 MB. @@ -179,30 +167,26 @@ public class VisualRecognition { - `default`: Returns classes from thousands of general tags. - `food`: Enhances specificity and accuracy for images of food items. - `explicit`: Evaluates whether the image might be pornographic. - - parameter imagesFileContentType: The content type of imagesFile. + - parameter acceptLanguage: The desired language of parts of the response. See the response for details. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func classify( - imagesFile: URL? = nil, - acceptLanguage: String? = nil, + imagesFile: Data? = nil, + imagesFilename: String? = nil, + imagesFileContentType: String? = nil, url: String? = nil, threshold: Double? = nil, owners: [String]? = nil, classifierIDs: [String]? = nil, - imagesFileContentType: String? = nil, + acceptLanguage: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() if let imagesFile = imagesFile { - do { - try multipartFormData.append(file: imagesFile, withName: "images_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(imagesFile.path)")) - return - } + multipartFormData.append(imagesFile, withName: "images_file", mimeType: imagesFileContentType, fileName: imagesFilename ?? "filename") } if let url = url { if let urlData = url.data(using: .utf8) { @@ -234,8 +218,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classify") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "classify") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType if let acceptLanguage = acceptLanguage { @@ -281,32 +265,29 @@ public class VisualRecognition { Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. + - parameter imagesFilename: The filename for imagesFile. + - parameter imagesFileContentType: The content type of imagesFile. - parameter url: The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. The maximum image size is 10 MB. Redirects are followed, so you can use a shortened URL. You can also include images with the **images_file** parameter. - parameter acceptLanguage: The desired language of parts of the response. See the response for details. - - parameter imagesFileContentType: The content type of imagesFile. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func detectFaces( - imagesFile: URL? = nil, + imagesFile: Data? = nil, + imagesFilename: String? = nil, + imagesFileContentType: String? = nil, url: String? = nil, acceptLanguage: String? = nil, - imagesFileContentType: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body let multipartFormData = MultipartFormData() if let imagesFile = imagesFile { - do { - try multipartFormData.append(file: imagesFile, withName: "images_file") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(imagesFile.path)")) - return - } + multipartFormData.append(imagesFile, withName: "images_file", mimeType: imagesFileContentType, fileName: imagesFilename ?? "filename") } if let url = url { if let urlData = url.data(using: .utf8) { @@ -323,8 +304,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "detectFaces") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "detectFaces") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType if let acceptLanguage = acceptLanguage { @@ -361,7 +342,7 @@ public class VisualRecognition { names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. - parameter name: The name of the new classifier. Encode special characters in UTF-8. - - parameter positiveExamples: A dictionary that contains the value for each classname. The value are a .zip file + - parameter positiveExamples: A dictionary that contains the value for each classname. The value is a .zip file of images that depict the visual subject of a class in the new classifier. You can include more than one positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, @@ -372,13 +353,15 @@ public class VisualRecognition { - parameter negativeExamples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. + - parameter negativeExamplesFilename: The filename for negativeExamples. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func createClassifier( name: String, - positiveExamples: [String: URL], - negativeExamples: URL? = nil, + positiveExamples: [String: Data], + negativeExamples: Data? = nil, + negativeExamplesFilename: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -389,20 +372,10 @@ public class VisualRecognition { } positiveExamples.forEach { (classname, value) in let partName = "\(classname)_positive_examples" - do { - try multipartFormData.append(file: value, withName: partName) - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(value)")) - return - } + multipartFormData.append(value, withName: partName, fileName: classname) } if let negativeExamples = negativeExamples { - do { - try multipartFormData.append(file: negativeExamples, withName: "negative_examples") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(negativeExamples.path)")) - return - } + multipartFormData.append(negativeExamples, withName: "negative_examples", fileName: negativeExamplesFilename ?? "filename") } guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) @@ -414,8 +387,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -457,8 +430,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassifiers") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassifiers") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -503,8 +476,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -544,7 +517,7 @@ public class VisualRecognition { classifier retraining finished. - parameter classifierID: The ID of the classifier. - - parameter positiveExamples: A dictionary that contains the value for each classname. The value are a .zip file + - parameter positiveExamples: A dictionary that contains the value for each classname. The value is a .zip file of images that depict the visual subject of a class in the classifier. The positive examples create or update classes in the classifier. You can include more than one positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, @@ -555,13 +528,15 @@ public class VisualRecognition { - parameter negativeExamples: A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. + - parameter negativeExamplesFilename: The filename for negativeExamples. - parameter headers: A dictionary of request headers to be sent with this request. - parameter completionHandler: A function executed when the request completes with a successful result or error */ public func updateClassifier( classifierID: String, - positiveExamples: [String: URL]? = nil, - negativeExamples: URL? = nil, + positiveExamples: [String: Data]? = nil, + negativeExamples: Data? = nil, + negativeExamplesFilename: String? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { @@ -570,21 +545,11 @@ public class VisualRecognition { if let positiveExamples = positiveExamples { positiveExamples.forEach { (classname, value) in let partName = "\(classname)_positive_examples" - do { - try multipartFormData.append(file: value, withName: partName) - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(value)")) - return - } + multipartFormData.append(value, withName: partName, fileName: classname) } } if let negativeExamples = negativeExamples { - do { - try multipartFormData.append(file: negativeExamples, withName: "negative_examples") - } catch { - completionHandler(nil, WatsonError.serialization(values: "file \(negativeExamples.path)")) - return - } + multipartFormData.append(negativeExamples, withName: "negative_examples", fileName: negativeExamplesFilename ?? "filename") } guard let body = try? multipartFormData.toData() else { completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) @@ -596,8 +561,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "updateClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType @@ -643,8 +608,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassifier") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassifier") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters @@ -691,8 +656,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCoreMLModel") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getCoreMLModel") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/octet-stream" // construct query parameters @@ -742,8 +707,8 @@ public class VisualRecognition { if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") - headerParameters.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteUserData") + headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" // construct query parameters diff --git a/WatsonDeveloperCloud.xcodeproj/project.pbxproj b/WatsonDeveloperCloud.xcodeproj/project.pbxproj index 2ba12b769..624084348 100644 --- a/WatsonDeveloperCloud.xcodeproj/project.pbxproj +++ b/WatsonDeveloperCloud.xcodeproj/project.pbxproj @@ -32,12 +32,8 @@ 6800FCA12056D8D50078788A /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC3E2056D6830078788A /* Context.swift */; }; 6800FCA22056D8D50078788A /* Counterexample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC372056D6830078788A /* Counterexample.swift */; }; 6800FCA32056D8D50078788A /* CounterexampleCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC242056D6830078788A /* CounterexampleCollection.swift */; }; - 6800FCA42056D8D50078788A /* CreateCounterexample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC232056D6830078788A /* CreateCounterexample.swift */; }; - 6800FCA52056D8D50078788A /* CreateDialogNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC392056D6830078788A /* CreateDialogNode.swift */; }; 6800FCA62056D8D50078788A /* CreateEntity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC332056D6830078788A /* CreateEntity.swift */; }; - 6800FCA72056D8D50078788A /* CreateExample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC252056D6830078788A /* CreateExample.swift */; }; 6800FCA82056D8D50078788A /* CreateIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC402056D6830078788A /* CreateIntent.swift */; }; - 6800FCA92056D8D50078788A /* CreateSynonym.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC462056D6830078788A /* CreateSynonym.swift */; }; 6800FCAA2056D8D50078788A /* CreateValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC4E2056D6830078788A /* CreateValue.swift */; }; 6800FCAB2056D8D50078788A /* CreateWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC222056D6830078788A /* CreateWorkspace.swift */; }; 6800FCAC2056D8D50078788A /* DialogNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC312056D6830078788A /* DialogNode.swift */; }; @@ -47,15 +43,11 @@ 6800FCB02056D8D50078788A /* DialogNodeVisitedDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC382056D6830078788A /* DialogNodeVisitedDetails.swift */; }; 6800FCB12056D8D50078788A /* Entity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC2D2056D6830078788A /* Entity.swift */; }; 6800FCB22056D8D50078788A /* EntityCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC352056D6830078788A /* EntityCollection.swift */; }; - 6800FCB32056D8D50078788A /* EntityExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC472056D6830078788A /* EntityExport.swift */; }; 6800FCB42056D8D50078788A /* Example.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC302056D6830078788A /* Example.swift */; }; 6800FCB52056D8D50078788A /* ExampleCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC3C2056D6830078788A /* ExampleCollection.swift */; }; - 6800FCB62056D8D50078788A /* InputData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC492056D6830078788A /* InputData.swift */; }; 6800FCB72056D8D50078788A /* Intent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC512056D6830078788A /* Intent.swift */; }; 6800FCB82056D8D50078788A /* IntentCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC4B2056D6830078788A /* IntentCollection.swift */; }; - 6800FCB92056D8D50078788A /* IntentExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC3D2056D6830078788A /* IntentExport.swift */; }; 6800FCBA2056D8D50078788A /* LogCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC412056D6830078788A /* LogCollection.swift */; }; - 6800FCBB2056D8D50078788A /* LogExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC202056D6830078788A /* LogExport.swift */; }; 6800FCBC2056D8D50078788A /* LogMessage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC3F2056D6830078788A /* LogMessage.swift */; }; 6800FCBD2056D8D50078788A /* LogPagination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC292056D6830078788A /* LogPagination.swift */; }; 6800FCBE2056D8D50078788A /* MessageInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC442056D6830078788A /* MessageInput.swift */; }; @@ -78,10 +70,8 @@ 6800FCCF2056D8D50078788A /* UpdateWorkspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC4A2056D6830078788A /* UpdateWorkspace.swift */; }; 6800FCD02056D8D50078788A /* Value.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC4F2056D6830078788A /* Value.swift */; }; 6800FCD12056D8D50078788A /* ValueCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC432056D6830078788A /* ValueCollection.swift */; }; - 6800FCD22056D8D50078788A /* ValueExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC3A2056D6830078788A /* ValueExport.swift */; }; 6800FCD32056D8D50078788A /* Workspace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC362056D6830078788A /* Workspace.swift */; }; 6800FCD42056D8D50078788A /* WorkspaceCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC482056D6830078788A /* WorkspaceCollection.swift */; }; - 6800FCD52056D8D50078788A /* WorkspaceExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC2F2056D6830078788A /* WorkspaceExport.swift */; }; 6800FCD62056D8EC0078788A /* AssistantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6800FC962056D6AF0078788A /* AssistantTests.swift */; }; 682CBD2C209051BA0049EE9F /* SegmentSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 682CBD2B209051B90049EE9F /* SegmentSettings.swift */; }; 682ED52F204F348100B17B06 /* WAVRepair.swift in Sources */ = {isa = PBXBuildFile; fileRef = 682ED52E204F348100B17B06 /* WAVRepair.swift */; }; @@ -451,9 +441,7 @@ 920F0AB6219CC1E900070C5B /* UpdatedLabelsOut.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0A87219CC1E900070C5B /* UpdatedLabelsOut.swift */; }; 920F0AB7219CC1E900070C5B /* Contact.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0A88219CC1E900070C5B /* Contact.swift */; }; 920F0AB8219CC1E900070C5B /* CompareComply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0A89219CC1E900070C5B /* CompareComply.swift */; }; - 920F0AC4219CEE8C00070C5B /* RowHeaderIds.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0ABC219CEE8A00070C5B /* RowHeaderIds.swift */; }; 920F0AC6219CEE8C00070C5B /* ColumnHeaderTextsNormalized.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0ABD219CEE8B00070C5B /* ColumnHeaderTextsNormalized.swift */; }; - 920F0AC8219CEE8C00070C5B /* ColumnHeaderIds.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0ABE219CEE8B00070C5B /* ColumnHeaderIds.swift */; }; 920F0ACA219CEE8C00070C5B /* ColumnHeaderTexts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0ABF219CEE8B00070C5B /* ColumnHeaderTexts.swift */; }; 920F0ACC219CEE8C00070C5B /* Batches.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0AC0219CEE8B00070C5B /* Batches.swift */; }; 920F0ACE219CEE8C00070C5B /* RowHeaderTextsNormalized.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920F0AC1219CEE8B00070C5B /* RowHeaderTextsNormalized.swift */; }; @@ -605,8 +593,43 @@ CA28818020CB099D00FC992C /* TranslationModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA28816620CB090700FC992C /* TranslationModels.swift */; }; CA28818120CB099D00FC992C /* TranslateRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA28816720CB090700FC992C /* TranslateRequest.swift */; }; CA28818220CB099D00FC992C /* IdentifiableLanguages.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA28816820CB090700FC992C /* IdentifiableLanguages.swift */; }; + CA29B86E222E0AE700626030 /* SyntaxOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B869222E0AE700626030 /* SyntaxOptions.swift */; }; + CA29B86F222E0AE700626030 /* TokenResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86A222E0AE700626030 /* TokenResult.swift */; }; + CA29B870222E0AE700626030 /* SentenceResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86B222E0AE700626030 /* SentenceResult.swift */; }; + CA29B871222E0AE700626030 /* SyntaxOptionsTokens.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86C222E0AE700626030 /* SyntaxOptionsTokens.swift */; }; + CA29B872222E0AE700626030 /* SyntaxResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86D222E0AE700626030 /* SyntaxResult.swift */; }; + CA29B874222E100A00626030 /* MemoryUsage.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B873222E100A00626030 /* MemoryUsage.swift */; }; CA35CD4720E3234900FACB2B /* ToneContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35CD4620E3234800FACB2B /* ToneContent.swift */; }; CA35CD4920E3237400FACB2B /* ProfileContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35CD4820E3237400FACB2B /* ProfileContent.swift */; }; + CA59FDA1224AA0E000E152AE /* RowHeaderIDs.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9A224AA0DE00E152AE /* RowHeaderIDs.swift */; }; + CA59FDA2224AA0E000E152AE /* TypeLabelComparison.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9B224AA0DF00E152AE /* TypeLabelComparison.swift */; }; + CA59FDA3224AA0E000E152AE /* Value.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9C224AA0DF00E152AE /* Value.swift */; }; + CA59FDA4224AA0E000E152AE /* KeyValuePair.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9D224AA0DF00E152AE /* KeyValuePair.swift */; }; + CA59FDA5224AA0E000E152AE /* CategoryComparison.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9E224AA0DF00E152AE /* CategoryComparison.swift */; }; + CA59FDA6224AA0E000E152AE /* Key.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9F224AA0DF00E152AE /* Key.swift */; }; + CA59FDA7224AA0E000E152AE /* ColumnHeaderIDs.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FDA0224AA0E000E152AE /* ColumnHeaderIDs.swift */; }; + CA59FDA9224AB66E00E152AE /* ContractType.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FDA8224AB66E00E152AE /* ContractType.swift */; }; + CA8E9264223406C4001BFABF /* Mention.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9262223406C4001BFABF /* Mention.swift */; }; + CA8E9265223406C4001BFABF /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9263223406C4001BFABF /* Log.swift */; }; + CA8E9268223406E2001BFABF /* MessageRequestContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9266223406E2001BFABF /* MessageRequestContext.swift */; }; + CA8E9269223406E2001BFABF /* MessageResponseContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9267223406E2001BFABF /* MessageResponseContext.swift */; }; + CA8E926D22343585001BFABF /* SemanticRolesResultAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E926A22343584001BFABF /* SemanticRolesResultAction.swift */; }; + CA8E926E22343585001BFABF /* SemanticRolesResultSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E926B22343584001BFABF /* SemanticRolesResultSubject.swift */; }; + CA8E926F22343585001BFABF /* SemanticRolesResultObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E926C22343584001BFABF /* SemanticRolesResultObject.swift */; }; + CA8E9272223435F7001BFABF /* AnalysisResultsUsage.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9270223435F7001BFABF /* AnalysisResultsUsage.swift */; }; + CA8E9273223435F7001BFABF /* AnalysisResultsMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E9271223435F7001BFABF /* AnalysisResultsMetadata.swift */; }; + CA8E927E22343610001BFABF /* EntitiesResultEmotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E92742234360F001BFABF /* EntitiesResultEmotion.swift */; }; + CA8E927F22343610001BFABF /* TargetedEmotionResultsEmotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E92752234360F001BFABF /* TargetedEmotionResultsEmotion.swift */; }; + CA8E928022343610001BFABF /* KeywordsResultSentiment.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E92762234360F001BFABF /* KeywordsResultSentiment.swift */; }; + CA8E928122343610001BFABF /* EntitiesResultSentiment.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927722343610001BFABF /* EntitiesResultSentiment.swift */; }; + CA8E928222343610001BFABF /* DocumentEmotionResultsEmotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927822343610001BFABF /* DocumentEmotionResultsEmotion.swift */; }; + CA8E928322343610001BFABF /* AnalysisResultsSentiment.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927922343610001BFABF /* AnalysisResultsSentiment.swift */; }; + CA8E928422343610001BFABF /* KeywordsResultEmotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927A22343610001BFABF /* KeywordsResultEmotion.swift */; }; + CA8E928522343610001BFABF /* AnalysisResultsEmotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927B22343610001BFABF /* AnalysisResultsEmotion.swift */; }; + CA8E928622343610001BFABF /* EntitiesResultDisambiguation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927C22343610001BFABF /* EntitiesResultDisambiguation.swift */; }; + CA8E928722343610001BFABF /* ParametersFeatures.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E927D22343610001BFABF /* ParametersFeatures.swift */; }; + CA8E92892236C638001BFABF /* MessageContextSkill.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E92882236C638001BFABF /* MessageContextSkill.swift */; }; + CA8E928C223D7BFA001BFABF /* SourceOptionsBuckets.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8E928A2239E9A7001BFABF /* SourceOptionsBuckets.swift */; }; CAD2685B20CAF28B002BA2C4 /* LanguageTranslatorV3.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CAD2685220CAF28A002BA2C4 /* LanguageTranslatorV3.framework */; }; CAD2686E20CAF919002BA2C4 /* LanguageTranslator.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAD2686A20CAF919002BA2C4 /* LanguageTranslator.swift */; }; CAD2687D20CB0196002BA2C4 /* LanguageTranslatorV3.h in Headers */ = {isa = PBXBuildFile; fileRef = CAD2687B20CB0195002BA2C4 /* LanguageTranslatorV3.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -634,7 +657,6 @@ CADA96992110ABB500B5BD84 /* DialogNodeOutputTextValuesElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADA968A2110ABB400B5BD84 /* DialogNodeOutputTextValuesElement.swift */; }; CADA969A2110ABB500B5BD84 /* EntityMention.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADA968B2110ABB400B5BD84 /* EntityMention.swift */; }; CADA969B2110ABB500B5BD84 /* EntityMentionCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADA968C2110ABB500B5BD84 /* EntityMentionCollection.swift */; }; - CADA969C2110ABB500B5BD84 /* Mentions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADA968D2110ABB500B5BD84 /* Mentions.swift */; }; CADA969D2110ABB500B5BD84 /* WorkspaceSystemSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADA968E2110ABB500B5BD84 /* WorkspaceSystemSettings.swift */; }; CADC4B8F214216FC00C76DE6 /* VisualRecognitionUnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADC4B8D2141BC9A00C76DE6 /* VisualRecognitionUnitTests.swift */; }; CAF9A5C420ACED3E006C86B7 /* CHANGELOG.md in Resources */ = {isa = PBXBuildFile; fileRef = CAF9A5C320ACED3E006C86B7 /* CHANGELOG.md */; }; @@ -827,12 +849,9 @@ 12F8005B1DF71BA1006851D6 /* Discovery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Discovery.swift; sourceTree = ""; }; 12F8005D1DF71BED006851D6 /* DiscoveryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DiscoveryTests.swift; sourceTree = ""; }; 6800FC1F2056D6830078788A /* UpdateDialogNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateDialogNode.swift; sourceTree = ""; }; - 6800FC202056D6830078788A /* LogExport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LogExport.swift; sourceTree = ""; }; 6800FC212056D6830078788A /* DialogNodeAction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNodeAction.swift; sourceTree = ""; }; 6800FC222056D6830078788A /* CreateWorkspace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateWorkspace.swift; sourceTree = ""; }; - 6800FC232056D6830078788A /* CreateCounterexample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateCounterexample.swift; sourceTree = ""; }; 6800FC242056D6830078788A /* CounterexampleCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CounterexampleCollection.swift; sourceTree = ""; }; - 6800FC252056D6830078788A /* CreateExample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateExample.swift; sourceTree = ""; }; 6800FC262056D6830078788A /* DialogNodeCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNodeCollection.swift; sourceTree = ""; }; 6800FC272056D6830078788A /* OutputData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OutputData.swift; sourceTree = ""; }; 6800FC282056D6830078788A /* MessageRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageRequest.swift; sourceTree = ""; }; @@ -842,7 +861,6 @@ 6800FC2C2056D6830078788A /* UpdateEntity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateEntity.swift; sourceTree = ""; }; 6800FC2D2056D6830078788A /* Entity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Entity.swift; sourceTree = ""; }; 6800FC2E2056D6830078788A /* DialogNodeNextStep.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNodeNextStep.swift; sourceTree = ""; }; - 6800FC2F2056D6830078788A /* WorkspaceExport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WorkspaceExport.swift; sourceTree = ""; }; 6800FC302056D6830078788A /* Example.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Example.swift; sourceTree = ""; }; 6800FC312056D6830078788A /* DialogNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNode.swift; sourceTree = ""; }; 6800FC322056D6830078788A /* UpdateCounterexample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateCounterexample.swift; sourceTree = ""; }; @@ -852,11 +870,8 @@ 6800FC362056D6830078788A /* Workspace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Workspace.swift; sourceTree = ""; }; 6800FC372056D6830078788A /* Counterexample.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Counterexample.swift; sourceTree = ""; }; 6800FC382056D6830078788A /* DialogNodeVisitedDetails.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNodeVisitedDetails.swift; sourceTree = ""; }; - 6800FC392056D6830078788A /* CreateDialogNode.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateDialogNode.swift; sourceTree = ""; }; - 6800FC3A2056D6830078788A /* ValueExport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueExport.swift; sourceTree = ""; }; 6800FC3B2056D6830078788A /* UpdateSynonym.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateSynonym.swift; sourceTree = ""; }; 6800FC3C2056D6830078788A /* ExampleCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ExampleCollection.swift; sourceTree = ""; }; - 6800FC3D2056D6830078788A /* IntentExport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IntentExport.swift; sourceTree = ""; }; 6800FC3E2056D6830078788A /* Context.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Context.swift; sourceTree = ""; }; 6800FC3F2056D6830078788A /* LogMessage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LogMessage.swift; sourceTree = ""; }; 6800FC402056D6830078788A /* CreateIntent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateIntent.swift; sourceTree = ""; }; @@ -865,10 +880,7 @@ 6800FC432056D6830078788A /* ValueCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueCollection.swift; sourceTree = ""; }; 6800FC442056D6830078788A /* MessageInput.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageInput.swift; sourceTree = ""; }; 6800FC452056D6830078788A /* RuntimeEntity.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RuntimeEntity.swift; sourceTree = ""; }; - 6800FC462056D6830078788A /* CreateSynonym.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CreateSynonym.swift; sourceTree = ""; }; - 6800FC472056D6830078788A /* EntityExport.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntityExport.swift; sourceTree = ""; }; 6800FC482056D6830078788A /* WorkspaceCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WorkspaceCollection.swift; sourceTree = ""; }; - 6800FC492056D6830078788A /* InputData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InputData.swift; sourceTree = ""; }; 6800FC4A2056D6830078788A /* UpdateWorkspace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateWorkspace.swift; sourceTree = ""; }; 6800FC4B2056D6830078788A /* IntentCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IntentCollection.swift; sourceTree = ""; }; 6800FC4C2056D6830078788A /* SystemResponse.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SystemResponse.swift; sourceTree = ""; }; @@ -1214,9 +1226,7 @@ 920F0A87219CC1E900070C5B /* UpdatedLabelsOut.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdatedLabelsOut.swift; sourceTree = ""; }; 920F0A88219CC1E900070C5B /* Contact.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Contact.swift; sourceTree = ""; }; 920F0A89219CC1E900070C5B /* CompareComply.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompareComply.swift; sourceTree = ""; }; - 920F0ABC219CEE8A00070C5B /* RowHeaderIds.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowHeaderIds.swift; sourceTree = ""; }; 920F0ABD219CEE8B00070C5B /* ColumnHeaderTextsNormalized.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnHeaderTextsNormalized.swift; sourceTree = ""; }; - 920F0ABE219CEE8B00070C5B /* ColumnHeaderIds.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnHeaderIds.swift; sourceTree = ""; }; 920F0ABF219CEE8B00070C5B /* ColumnHeaderTexts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnHeaderTexts.swift; sourceTree = ""; }; 920F0AC0219CEE8B00070C5B /* Batches.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Batches.swift; sourceTree = ""; }; 920F0AC1219CEE8B00070C5B /* RowHeaderTextsNormalized.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowHeaderTextsNormalized.swift; sourceTree = ""; }; @@ -1314,10 +1324,45 @@ CA28816820CB090700FC992C /* IdentifiableLanguages.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IdentifiableLanguages.swift; sourceTree = ""; }; CA28817420CB095100FC992C /* glossary.tmx */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; name = glossary.tmx; path = Tests/LanguageTranslatorV3Tests/glossary.tmx; sourceTree = SOURCE_ROOT; }; CA28817520CB095100FC992C /* LanguageTranslatorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = LanguageTranslatorTests.swift; path = Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift; sourceTree = SOURCE_ROOT; }; + CA29B869222E0AE700626030 /* SyntaxOptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyntaxOptions.swift; sourceTree = ""; }; + CA29B86A222E0AE700626030 /* TokenResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TokenResult.swift; sourceTree = ""; }; + CA29B86B222E0AE700626030 /* SentenceResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SentenceResult.swift; sourceTree = ""; }; + CA29B86C222E0AE700626030 /* SyntaxOptionsTokens.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyntaxOptionsTokens.swift; sourceTree = ""; }; + CA29B86D222E0AE700626030 /* SyntaxResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyntaxResult.swift; sourceTree = ""; }; + CA29B873222E100A00626030 /* MemoryUsage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MemoryUsage.swift; sourceTree = ""; }; CA35CD4620E3234800FACB2B /* ToneContent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToneContent.swift; sourceTree = ""; }; CA35CD4820E3237400FACB2B /* ProfileContent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileContent.swift; sourceTree = ""; }; CA45954820A62FBE0060BF9B /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; CA45954920A630080060BF9B /* CONTRIBUTING.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; name = CONTRIBUTING.md; path = .github/CONTRIBUTING.md; sourceTree = ""; }; + CA59FD9A224AA0DE00E152AE /* RowHeaderIDs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowHeaderIDs.swift; sourceTree = ""; }; + CA59FD9B224AA0DF00E152AE /* TypeLabelComparison.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TypeLabelComparison.swift; sourceTree = ""; }; + CA59FD9C224AA0DF00E152AE /* Value.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Value.swift; sourceTree = ""; }; + CA59FD9D224AA0DF00E152AE /* KeyValuePair.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyValuePair.swift; sourceTree = ""; }; + CA59FD9E224AA0DF00E152AE /* CategoryComparison.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CategoryComparison.swift; sourceTree = ""; }; + CA59FD9F224AA0DF00E152AE /* Key.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Key.swift; sourceTree = ""; }; + CA59FDA0224AA0E000E152AE /* ColumnHeaderIDs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnHeaderIDs.swift; sourceTree = ""; }; + CA59FDA8224AB66E00E152AE /* ContractType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContractType.swift; sourceTree = ""; }; + CA8E9262223406C4001BFABF /* Mention.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mention.swift; sourceTree = ""; }; + CA8E9263223406C4001BFABF /* Log.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = ""; }; + CA8E9266223406E2001BFABF /* MessageRequestContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageRequestContext.swift; sourceTree = ""; }; + CA8E9267223406E2001BFABF /* MessageResponseContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageResponseContext.swift; sourceTree = ""; }; + CA8E926A22343584001BFABF /* SemanticRolesResultAction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SemanticRolesResultAction.swift; sourceTree = ""; }; + CA8E926B22343584001BFABF /* SemanticRolesResultSubject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SemanticRolesResultSubject.swift; sourceTree = ""; }; + CA8E926C22343584001BFABF /* SemanticRolesResultObject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SemanticRolesResultObject.swift; sourceTree = ""; }; + CA8E9270223435F7001BFABF /* AnalysisResultsUsage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnalysisResultsUsage.swift; sourceTree = ""; }; + CA8E9271223435F7001BFABF /* AnalysisResultsMetadata.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnalysisResultsMetadata.swift; sourceTree = ""; }; + CA8E92742234360F001BFABF /* EntitiesResultEmotion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntitiesResultEmotion.swift; sourceTree = ""; }; + CA8E92752234360F001BFABF /* TargetedEmotionResultsEmotion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TargetedEmotionResultsEmotion.swift; sourceTree = ""; }; + CA8E92762234360F001BFABF /* KeywordsResultSentiment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeywordsResultSentiment.swift; sourceTree = ""; }; + CA8E927722343610001BFABF /* EntitiesResultSentiment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntitiesResultSentiment.swift; sourceTree = ""; }; + CA8E927822343610001BFABF /* DocumentEmotionResultsEmotion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DocumentEmotionResultsEmotion.swift; sourceTree = ""; }; + CA8E927922343610001BFABF /* AnalysisResultsSentiment.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnalysisResultsSentiment.swift; sourceTree = ""; }; + CA8E927A22343610001BFABF /* KeywordsResultEmotion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeywordsResultEmotion.swift; sourceTree = ""; }; + CA8E927B22343610001BFABF /* AnalysisResultsEmotion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnalysisResultsEmotion.swift; sourceTree = ""; }; + CA8E927C22343610001BFABF /* EntitiesResultDisambiguation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntitiesResultDisambiguation.swift; sourceTree = ""; }; + CA8E927D22343610001BFABF /* ParametersFeatures.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ParametersFeatures.swift; sourceTree = ""; }; + CA8E92882236C638001BFABF /* MessageContextSkill.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MessageContextSkill.swift; sourceTree = ""; }; + CA8E928A2239E9A7001BFABF /* SourceOptionsBuckets.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SourceOptionsBuckets.swift; sourceTree = ""; }; CAD2685220CAF28A002BA2C4 /* LanguageTranslatorV3.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = LanguageTranslatorV3.framework; sourceTree = BUILT_PRODUCTS_DIR; }; CAD2685A20CAF28A002BA2C4 /* LanguageTranslatorV3Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = LanguageTranslatorV3Tests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; CAD2686A20CAF919002BA2C4 /* LanguageTranslator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LanguageTranslator.swift; sourceTree = ""; }; @@ -1346,7 +1391,6 @@ CADA968A2110ABB400B5BD84 /* DialogNodeOutputTextValuesElement.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DialogNodeOutputTextValuesElement.swift; sourceTree = ""; }; CADA968B2110ABB400B5BD84 /* EntityMention.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntityMention.swift; sourceTree = ""; }; CADA968C2110ABB500B5BD84 /* EntityMentionCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EntityMentionCollection.swift; sourceTree = ""; }; - CADA968D2110ABB500B5BD84 /* Mentions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mentions.swift; sourceTree = ""; }; CADA968E2110ABB500B5BD84 /* WorkspaceSystemSettings.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WorkspaceSystemSettings.swift; sourceTree = ""; }; CADC4B8D2141BC9A00C76DE6 /* VisualRecognitionUnitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VisualRecognitionUnitTests.swift; sourceTree = ""; }; CAF9A5C320ACED3E006C86B7 /* CHANGELOG.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; @@ -1643,6 +1687,10 @@ isa = PBXGroup; children = ( 683947CE202CF4F6007E3CF3 /* AnalysisResults.swift */, + CA8E927B22343610001BFABF /* AnalysisResultsEmotion.swift */, + CA8E9271223435F7001BFABF /* AnalysisResultsMetadata.swift */, + CA8E927922343610001BFABF /* AnalysisResultsSentiment.swift */, + CA8E9270223435F7001BFABF /* AnalysisResultsUsage.swift */, 683947C0202CF4F4007E3CF3 /* Author.swift */, 683947AF202CF4F3007E3CF3 /* CategoriesOptions.swift */, 683947BE202CF4F4007E3CF3 /* CategoriesResult.swift */, @@ -1651,23 +1699,30 @@ 68394800202D141E007E3CF3 /* DeleteModelResults.swift */, 683947B5202CF4F4007E3CF3 /* DisambiguationResult.swift */, 683947CF202CF4F6007E3CF3 /* DocumentEmotionResults.swift */, + CA8E927822343610001BFABF /* DocumentEmotionResultsEmotion.swift */, 683947BB202CF4F4007E3CF3 /* DocumentSentimentResults.swift */, 683947BF202CF4F4007E3CF3 /* EmotionOptions.swift */, 683947C3202CF4F5007E3CF3 /* EmotionResult.swift */, 683947C6202CF4F5007E3CF3 /* EmotionScores.swift */, 683947D4202CF4F7007E3CF3 /* EntitiesOptions.swift */, 683947C4202CF4F5007E3CF3 /* EntitiesResult.swift */, + CA8E927C22343610001BFABF /* EntitiesResultDisambiguation.swift */, + CA8E92742234360F001BFABF /* EntitiesResultEmotion.swift */, + CA8E927722343610001BFABF /* EntitiesResultSentiment.swift */, 683947B7202CF4F4007E3CF3 /* EntityMention.swift */, 683947B0202CF4F3007E3CF3 /* Features.swift */, 683947D1202CF4F6007E3CF3 /* FeatureSentimentResults.swift */, 683947B1202CF4F3007E3CF3 /* Feed.swift */, 683947B2202CF4F3007E3CF3 /* KeywordsOptions.swift */, 683947C5202CF4F5007E3CF3 /* KeywordsResult.swift */, + CA8E927A22343610001BFABF /* KeywordsResultEmotion.swift */, + CA8E92762234360F001BFABF /* KeywordsResultSentiment.swift */, 683947C2202CF4F5007E3CF3 /* ListModelsResults.swift */, 683947B4202CF4F3007E3CF3 /* MetadataOptions.swift */, 683947B3202CF4F3007E3CF3 /* MetadataResult.swift */, 683947BA202CF4F4007E3CF3 /* Model.swift */, 683947D3202CF4F6007E3CF3 /* Parameters.swift */, + CA8E927D22343610001BFABF /* ParametersFeatures.swift */, 683947AA202CF4F3007E3CF3 /* RelationArgument.swift */, 683947B6202CF4F4007E3CF3 /* RelationEntity.swift */, 683947C7202CF4F5007E3CF3 /* RelationsOptions.swift */, @@ -1678,12 +1733,21 @@ 683947AC202CF4F3007E3CF3 /* SemanticRolesObject.swift */, 683947AD202CF4F3007E3CF3 /* SemanticRolesOptions.swift */, 683947C8202CF4F5007E3CF3 /* SemanticRolesResult.swift */, + CA8E926A22343584001BFABF /* SemanticRolesResultAction.swift */, + CA8E926C22343584001BFABF /* SemanticRolesResultObject.swift */, + CA8E926B22343584001BFABF /* SemanticRolesResultSubject.swift */, 683947D2202CF4F6007E3CF3 /* SemanticRolesSubject.swift */, 683947BC202CF4F4007E3CF3 /* SemanticRolesVerb.swift */, + CA29B86B222E0AE700626030 /* SentenceResult.swift */, 683947CB202CF4F6007E3CF3 /* SentimentOptions.swift */, 683947BD202CF4F4007E3CF3 /* SentimentResult.swift */, + CA29B869222E0AE700626030 /* SyntaxOptions.swift */, + CA29B86C222E0AE700626030 /* SyntaxOptionsTokens.swift */, + CA29B86D222E0AE700626030 /* SyntaxResult.swift */, 683947C9202CF4F5007E3CF3 /* TargetedEmotionResults.swift */, + CA8E92752234360F001BFABF /* TargetedEmotionResultsEmotion.swift */, 683947CA202CF4F5007E3CF3 /* TargetedSentimentResults.swift */, + CA29B86A222E0AE700626030 /* TokenResult.swift */, 683947AE202CF4F3007E3CF3 /* Usage.swift */, ); path = Models; @@ -1767,12 +1831,8 @@ 6800FC3E2056D6830078788A /* Context.swift */, 6800FC372056D6830078788A /* Counterexample.swift */, 6800FC242056D6830078788A /* CounterexampleCollection.swift */, - 6800FC232056D6830078788A /* CreateCounterexample.swift */, - 6800FC392056D6830078788A /* CreateDialogNode.swift */, 6800FC332056D6830078788A /* CreateEntity.swift */, - 6800FC252056D6830078788A /* CreateExample.swift */, 6800FC402056D6830078788A /* CreateIntent.swift */, - 6800FC462056D6830078788A /* CreateSynonym.swift */, 6800FC4E2056D6830078788A /* CreateValue.swift */, 6800FC222056D6830078788A /* CreateWorkspace.swift */, 6800FC312056D6830078788A /* DialogNode.swift */, @@ -1791,20 +1851,17 @@ CADA96832110ABB300B5BD84 /* DialogSuggestionValue.swift */, 6800FC2D2056D6830078788A /* Entity.swift */, 6800FC352056D6830078788A /* EntityCollection.swift */, - 6800FC472056D6830078788A /* EntityExport.swift */, CADA968B2110ABB400B5BD84 /* EntityMention.swift */, CADA968C2110ABB500B5BD84 /* EntityMentionCollection.swift */, 6800FC302056D6830078788A /* Example.swift */, 6800FC3C2056D6830078788A /* ExampleCollection.swift */, - 6800FC492056D6830078788A /* InputData.swift */, 6800FC512056D6830078788A /* Intent.swift */, 6800FC4B2056D6830078788A /* IntentCollection.swift */, - 6800FC3D2056D6830078788A /* IntentExport.swift */, + CA8E9263223406C4001BFABF /* Log.swift */, 6800FC412056D6830078788A /* LogCollection.swift */, - 6800FC202056D6830078788A /* LogExport.swift */, 6800FC3F2056D6830078788A /* LogMessage.swift */, 6800FC292056D6830078788A /* LogPagination.swift */, - CADA968D2110ABB500B5BD84 /* Mentions.swift */, + CA8E9262223406C4001BFABF /* Mention.swift */, 92EAA86721BF053600A4714C /* MessageContextMetadata.swift */, 6800FC442056D6830078788A /* MessageInput.swift */, 6800FC282056D6830078788A /* MessageRequest.swift */, @@ -1826,10 +1883,8 @@ 6800FC4A2056D6830078788A /* UpdateWorkspace.swift */, 6800FC4F2056D6830078788A /* Value.swift */, 6800FC432056D6830078788A /* ValueCollection.swift */, - 6800FC3A2056D6830078788A /* ValueExport.swift */, 6800FC362056D6830078788A /* Workspace.swift */, 6800FC482056D6830078788A /* WorkspaceCollection.swift */, - 6800FC2F2056D6830078788A /* WorkspaceExport.swift */, CADA968E2110ABB500B5BD84 /* WorkspaceSystemSettings.swift */, CADA96802110ABB300B5BD84 /* WorkspaceSystemSettingsDisambiguation.swift */, CADA96812110ABB300B5BD84 /* WorkspaceSystemSettingsTooling.swift */, @@ -1866,7 +1921,6 @@ 68AF8EAA206968CC00D552E3 /* Models */ = { isa = PBXGroup; children = ( - 92261EA721F1007500A1A620 /* SourceOptionsWebCrawl.swift */, 68AF8EE8206968CC00D552E3 /* AggregationResult.swift */, 68AF8ED5206968CC00D552E3 /* Calculation.swift */, 68AF8EBA206968CC00D552E3 /* Collection.swift */, @@ -1917,6 +1971,7 @@ 928204C62124BC200013315B /* LogQueryResponseResult.swift */, 928204C02124BC1E0013315B /* LogQueryResponseResultDocuments.swift */, 928204C12124BC1E0013315B /* LogQueryResponseResultDocumentsResult.swift */, + CA29B873222E100A00626030 /* MemoryUsage.swift */, 928204C42124BC1F0013315B /* MetricAggregation.swift */, 928204BB2124BC1C0013315B /* MetricAggregationResult.swift */, 928204C22124BC1F0013315B /* MetricResponse.swift */, @@ -1965,9 +2020,11 @@ 682CBD2B209051B90049EE9F /* SegmentSettings.swift */, CADA958F20FCD66500B5BD84 /* Source.swift */, CADA959120FCD66500B5BD84 /* SourceOptions.swift */, + CA8E928A2239E9A7001BFABF /* SourceOptionsBuckets.swift */, CADA959720FCD66600B5BD84 /* SourceOptionsFolder.swift */, CADA959620FCD66600B5BD84 /* SourceOptionsObject.swift */, CADA959320FCD66500B5BD84 /* SourceOptionsSiteColl.swift */, + 92261EA721F1007500A1A620 /* SourceOptionsWebCrawl.swift */, CADA958D20FCD66400B5BD84 /* SourceSchedule.swift */, CADA959220FCD66500B5BD84 /* SourceStatus.swift */, 68AF8EE7206968CC00D552E3 /* Term.swift */, @@ -2335,14 +2392,16 @@ 920F0A69219CC1E900070C5B /* BatchStatus.swift */, 920F0A7F219CC1E900070C5B /* BodyCells.swift */, 920F0A7C219CC1E900070C5B /* Category.swift */, + CA59FD9E224AA0DF00E152AE /* CategoryComparison.swift */, 920F0A5B219CC1E900070C5B /* ClassifyReturn.swift */, - 920F0ABE219CEE8B00070C5B /* ColumnHeaderIds.swift */, + CA59FDA0224AA0E000E152AE /* ColumnHeaderIDs.swift */, 920F0A82219CC1E900070C5B /* ColumnHeaders.swift */, 920F0ABF219CEE8B00070C5B /* ColumnHeaderTexts.swift */, 920F0ABD219CEE8B00070C5B /* ColumnHeaderTextsNormalized.swift */, 920F0A5C219CC1E900070C5B /* CompareReturn.swift */, 920F0A88219CC1E900070C5B /* Contact.swift */, 920F0A86219CC1E900070C5B /* ContractAmts.swift */, + CA59FDA8224AB66E00E152AE /* ContractType.swift */, 920F0A76219CC1E900070C5B /* DocCounts.swift */, 920F0A80219CC1E900070C5B /* DocInfo.swift */, 920F0A83219CC1E900070C5B /* DocStructure.swift */, @@ -2359,6 +2418,8 @@ 920F0A5E219CC1E900070C5B /* FeedbackReturn.swift */, 920F0A84219CC1E900070C5B /* GetFeedback.swift */, 920F0A6E219CC1E900070C5B /* HTMLReturn.swift */, + CA59FD9F224AA0DF00E152AE /* Key.swift */, + CA59FD9D224AA0DF00E152AE /* KeyValuePair.swift */, 920F0A61219CC1E900070C5B /* Label.swift */, 920F0A63219CC1E900070C5B /* LeadingSentence.swift */, 920F0A5D219CC1E900070C5B /* Location.swift */, @@ -2366,7 +2427,7 @@ 920F0A7D219CC1E900070C5B /* OriginalLabelsOut.swift */, 920F0A73219CC1E900070C5B /* Pagination.swift */, 920F0A75219CC1E900070C5B /* Parties.swift */, - 920F0ABC219CEE8A00070C5B /* RowHeaderIds.swift */, + CA59FD9A224AA0DE00E152AE /* RowHeaderIDs.swift */, 920F0A77219CC1E900070C5B /* RowHeaders.swift */, 920F0AC2219CEE8C00070C5B /* RowHeaderTexts.swift */, 920F0AC1219CEE8B00070C5B /* RowHeaderTextsNormalized.swift */, @@ -2378,9 +2439,11 @@ 920F0A7B219CC1E900070C5B /* Tables.swift */, 920F0A6C219CC1E900070C5B /* TerminationDates.swift */, 920F0A7E219CC1E900070C5B /* TypeLabel.swift */, + CA59FD9B224AA0DF00E152AE /* TypeLabelComparison.swift */, 920F0A74219CC1E900070C5B /* UnalignedElement.swift */, 920F0A71219CC1E900070C5B /* UpdatedLabelsIn.swift */, 920F0A87219CC1E900070C5B /* UpdatedLabelsOut.swift */, + CA59FD9C224AA0DF00E152AE /* Value.swift */, ); path = Models; sourceTree = ""; @@ -2411,13 +2474,16 @@ 922077842152FC5900C8C7E4 /* MessageContext.swift */, 922077952152FC5900C8C7E4 /* MessageContextGlobal.swift */, 9220778C2152FC5900C8C7E4 /* MessageContextGlobalSystem.swift */, + CA8E92882236C638001BFABF /* MessageContextSkill.swift */, 922077932152FC5900C8C7E4 /* MessageContextSkills.swift */, 922077912152FC5900C8C7E4 /* MessageInput.swift */, 922077962152FC5900C8C7E4 /* MessageInputOptions.swift */, 922077892152FC5900C8C7E4 /* MessageOutput.swift */, 9220778B2152FC5900C8C7E4 /* MessageOutputDebug.swift */, 922077872152FC5900C8C7E4 /* MessageRequest.swift */, + CA8E9266223406E2001BFABF /* MessageRequestContext.swift */, 922077982152FC5900C8C7E4 /* MessageResponse.swift */, + CA8E9267223406E2001BFABF /* MessageResponseContext.swift */, 922077922152FC5900C8C7E4 /* RuntimeEntity.swift */, 9220778E2152FC5900C8C7E4 /* RuntimeIntent.swift */, 922077862152FC5900C8C7E4 /* SessionResponse.swift */, @@ -3864,44 +3930,64 @@ files = ( 683947E7202CF4F7007E3CF3 /* SemanticRolesVerb.swift in Sources */, 683947EF202CF4F7007E3CF3 /* EntitiesResult.swift in Sources */, + CA8E9272223435F7001BFABF /* AnalysisResultsUsage.swift in Sources */, + CA8E928722343610001BFABF /* ParametersFeatures.swift in Sources */, 683947FD202CF4F7007E3CF3 /* SemanticRolesSubject.swift in Sources */, + CA29B870222E0AE700626030 /* SentenceResult.swift in Sources */, 683947F3202CF4F7007E3CF3 /* SemanticRolesResult.swift in Sources */, 683947E3202CF4F7007E3CF3 /* SemanticRolesEntity.swift in Sources */, 683947ED202CF4F7007E3CF3 /* ListModelsResults.swift in Sources */, 683947FE202CF4F7007E3CF3 /* Parameters.swift in Sources */, + CA8E928222343610001BFABF /* DocumentEmotionResultsEmotion.swift in Sources */, 683947E0202CF4F7007E3CF3 /* DisambiguationResult.swift in Sources */, 683947F1202CF4F7007E3CF3 /* EmotionScores.swift in Sources */, 683947F9202CF4F7007E3CF3 /* AnalysisResults.swift in Sources */, 683947E1202CF4F7007E3CF3 /* RelationEntity.swift in Sources */, + CA8E926F22343585001BFABF /* SemanticRolesResultObject.swift in Sources */, 68AC590D1F8DCA0000012CCB /* NaturalLanguageUnderstanding.swift in Sources */, 683947E2202CF4F7007E3CF3 /* EntityMention.swift in Sources */, 683947DD202CF4F7007E3CF3 /* KeywordsOptions.swift in Sources */, + CA8E928522343610001BFABF /* AnalysisResultsEmotion.swift in Sources */, 68394801202D141F007E3CF3 /* DeleteModelResults.swift in Sources */, + CA8E928322343610001BFABF /* AnalysisResultsSentiment.swift in Sources */, 92BF69B4213F129A00FE6325 /* Shared.swift in Sources */, 683947F6202CF4F7007E3CF3 /* SentimentOptions.swift in Sources */, + CA8E927F22343610001BFABF /* TargetedEmotionResultsEmotion.swift in Sources */, 683947F7202CF4F7007E3CF3 /* ConceptsOptions.swift in Sources */, 683947DC202CF4F7007E3CF3 /* Feed.swift in Sources */, 683947DB202CF4F7007E3CF3 /* Features.swift in Sources */, 683947EE202CF4F7007E3CF3 /* EmotionResult.swift in Sources */, + CA8E926D22343585001BFABF /* SemanticRolesResultAction.swift in Sources */, 683947F2202CF4F7007E3CF3 /* RelationsOptions.swift in Sources */, 683947E4202CF4F7007E3CF3 /* SemanticRolesKeyword.swift in Sources */, 683947DE202CF4F7007E3CF3 /* MetadataResult.swift in Sources */, 683947E8202CF4F7007E3CF3 /* SentimentResult.swift in Sources */, 683947DA202CF4F7007E3CF3 /* CategoriesOptions.swift in Sources */, + CA29B871222E0AE700626030 /* SyntaxOptionsTokens.swift in Sources */, 683947DF202CF4F7007E3CF3 /* MetadataOptions.swift in Sources */, 683947E5202CF4F7007E3CF3 /* Model.swift in Sources */, 683947F5202CF4F7007E3CF3 /* TargetedSentimentResults.swift in Sources */, 683947E9202CF4F7007E3CF3 /* CategoriesResult.swift in Sources */, 683947F0202CF4F7007E3CF3 /* KeywordsResult.swift in Sources */, + CA8E926E22343585001BFABF /* SemanticRolesResultSubject.swift in Sources */, 683947FF202CF4F7007E3CF3 /* EntitiesOptions.swift in Sources */, + CA29B86F222E0AE700626030 /* TokenResult.swift in Sources */, 683947EC202CF4F7007E3CF3 /* SemanticRolesAction.swift in Sources */, 683947FC202CF4F7007E3CF3 /* FeatureSentimentResults.swift in Sources */, + CA8E928022343610001BFABF /* KeywordsResultSentiment.swift in Sources */, 683947D7202CF4F7007E3CF3 /* SemanticRolesObject.swift in Sources */, + CA8E9273223435F7001BFABF /* AnalysisResultsMetadata.swift in Sources */, 683947F4202CF4F7007E3CF3 /* TargetedEmotionResults.swift in Sources */, 683947D8202CF4F7007E3CF3 /* SemanticRolesOptions.swift in Sources */, + CA8E927E22343610001BFABF /* EntitiesResultEmotion.swift in Sources */, + CA29B86E222E0AE700626030 /* SyntaxOptions.swift in Sources */, 683947D5202CF4F7007E3CF3 /* RelationArgument.swift in Sources */, + CA8E928622343610001BFABF /* EntitiesResultDisambiguation.swift in Sources */, + CA8E928122343610001BFABF /* EntitiesResultSentiment.swift in Sources */, 683947EB202CF4F7007E3CF3 /* Author.swift in Sources */, + CA29B872222E0AE700626030 /* SyntaxResult.swift in Sources */, 683947E6202CF4F7007E3CF3 /* DocumentSentimentResults.swift in Sources */, + CA8E928422343610001BFABF /* KeywordsResultEmotion.swift in Sources */, 683947D9202CF4F7007E3CF3 /* Usage.swift in Sources */, 683947FA202CF4F7007E3CF3 /* DocumentEmotionResults.swift in Sources */, 683947D6202CF4F7007E3CF3 /* RelationsResult.swift in Sources */, @@ -3998,6 +4084,7 @@ 68AF8F772069690300D552E3 /* CollectionDiskUsage.swift in Sources */, 68AF8F642069690300D552E3 /* QueryEntitiesResponse.swift in Sources */, 92ED234C2187C57C00C049A2 /* TokenDict.swift in Sources */, + CA8E928C223D7BFA001BFABF /* SourceOptionsBuckets.swift in Sources */, 928204D32124BC200013315B /* LogQueryResponseResult.swift in Sources */, 68AF8F862069690300D552E3 /* Expansion.swift in Sources */, 68AF8F5E2069690300D552E3 /* Collection.swift in Sources */, @@ -4038,6 +4125,7 @@ CADA959B20FCD66600B5BD84 /* CredentialsList.swift in Sources */, 9254773B216D4710003C2829 /* SearchStatus.swift in Sources */, 68AF8F852069690300D552E3 /* XPathPatterns.swift in Sources */, + CA29B874222E100A00626030 /* MemoryUsage.swift in Sources */, 683955072077E613009E1C8A /* Filter.swift in Sources */, 68AF8F872069690300D552E3 /* DeleteConfigurationResponse.swift in Sources */, 68AF8F7A2069690300D552E3 /* Field.swift in Sources */, @@ -4108,9 +4196,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + CA8E9265223406C4001BFABF /* Log.swift in Sources */, 6800FCBF2056D8D50078788A /* MessageRequest.swift in Sources */, 6800FCCA2056D8D50078788A /* UpdateEntity.swift in Sources */, - 6800FCA72056D8D50078788A /* CreateExample.swift in Sources */, 6800FCBD2056D8D50078788A /* LogPagination.swift in Sources */, 6800FCAA2056D8D50078788A /* CreateValue.swift in Sources */, 6800FCAB2056D8D50078788A /* CreateWorkspace.swift in Sources */, @@ -4118,7 +4206,6 @@ 6800FCD32056D8D50078788A /* Workspace.swift in Sources */, CADA969B2110ABB500B5BD84 /* EntityMentionCollection.swift in Sources */, 6800FCC82056D8D50078788A /* UpdateCounterexample.swift in Sources */, - 6800FCB92056D8D50078788A /* IntentExport.swift in Sources */, 6800FCC52056D8D50078788A /* Synonym.swift in Sources */, 6800FCC42056D8D50078788A /* RuntimeIntent.swift in Sources */, 6800FCCF2056D8D50078788A /* UpdateWorkspace.swift in Sources */, @@ -4129,7 +4216,6 @@ 92EAA86821BF053600A4714C /* MessageContextMetadata.swift in Sources */, CADA96982110ABB500B5BD84 /* DialogNodeOutputModifiers.swift in Sources */, 6800FCC12056D8D50078788A /* OutputData.swift in Sources */, - CADA969C2110ABB500B5BD84 /* Mentions.swift in Sources */, 6800FCB52056D8D50078788A /* ExampleCollection.swift in Sources */, 6800FCD42056D8D50078788A /* WorkspaceCollection.swift in Sources */, CADA96972110ABB500B5BD84 /* DialogRuntimeResponseGeneric.swift in Sources */, @@ -4139,7 +4225,6 @@ CADA96952110ABB500B5BD84 /* DialogNodeOutputOptionsElementValue.swift in Sources */, 6800FCA32056D8D50078788A /* CounterexampleCollection.swift in Sources */, CADA968F2110ABB500B5BD84 /* WorkspaceSystemSettingsDisambiguation.swift in Sources */, - 6800FCD22056D8D50078788A /* ValueExport.swift in Sources */, 6800FCA12056D8D50078788A /* Context.swift in Sources */, 6800FCCB2056D8D50078788A /* UpdateExample.swift in Sources */, CADA96912110ABB500B5BD84 /* DialogNodeOutput.swift in Sources */, @@ -4150,12 +4235,7 @@ 6800FCAD2056D8D50078788A /* DialogNodeAction.swift in Sources */, 6800FCB82056D8D50078788A /* IntentCollection.swift in Sources */, 6800FCC62056D8D50078788A /* SynonymCollection.swift in Sources */, - 6800FCA92056D8D50078788A /* CreateSynonym.swift in Sources */, - 6800FCBB2056D8D50078788A /* LogExport.swift in Sources */, 6800FCC92056D8D50078788A /* UpdateDialogNode.swift in Sources */, - 6800FCB62056D8D50078788A /* InputData.swift in Sources */, - 6800FCA52056D8D50078788A /* CreateDialogNode.swift in Sources */, - 6800FCB32056D8D50078788A /* EntityExport.swift in Sources */, 6800FCC22056D8D50078788A /* Pagination.swift in Sources */, 6800FCB72056D8D50078788A /* Intent.swift in Sources */, 6800FCB02056D8D50078788A /* DialogNodeVisitedDetails.swift in Sources */, @@ -4163,7 +4243,7 @@ 6800FCBC2056D8D50078788A /* LogMessage.swift in Sources */, CADA96962110ABB500B5BD84 /* DialogSuggestion.swift in Sources */, 6800FC9F2056D8CB0078788A /* Assistant.swift in Sources */, - 6800FCD52056D8D50078788A /* WorkspaceExport.swift in Sources */, + CA8E9264223406C4001BFABF /* Mention.swift in Sources */, 6800FCC72056D8D50078788A /* SystemResponse.swift in Sources */, 92BF69AE213F129A00FE6325 /* Shared.swift in Sources */, 6800FCB22056D8D50078788A /* EntityCollection.swift in Sources */, @@ -4174,7 +4254,6 @@ 6800FCBA2056D8D50078788A /* LogCollection.swift in Sources */, CADA96942110ABB500B5BD84 /* DialogNodeOutputGeneric.swift in Sources */, 6800FCA62056D8D50078788A /* CreateEntity.swift in Sources */, - 6800FCA42056D8D50078788A /* CreateCounterexample.swift in Sources */, 6800FCCE2056D8D50078788A /* UpdateValue.swift in Sources */, 6800FCC02056D8D50078788A /* MessageResponse.swift in Sources */, 6800FCD02056D8D50078788A /* Value.swift in Sources */, @@ -4411,8 +4490,10 @@ 922078572152FCE400C8C7E4 /* MessageResponse.swift in Sources */, 9220784F2152FCE400C8C7E4 /* DialogRuntimeResponseGeneric.swift in Sources */, 922078442152FCE400C8C7E4 /* DialogSuggestion.swift in Sources */, + CA8E9268223406E2001BFABF /* MessageRequestContext.swift in Sources */, 922078512152FCE400C8C7E4 /* RuntimeEntity.swift in Sources */, 922078492152FCE400C8C7E4 /* DialogNodeOutputOptionsElement.swift in Sources */, + CA8E9269223406E2001BFABF /* MessageResponseContext.swift in Sources */, 922078522152FCE400C8C7E4 /* MessageContextSkills.swift in Sources */, 922078432152FCE400C8C7E4 /* MessageContext.swift in Sources */, 922078562152FCE400C8C7E4 /* DialogNodesVisited.swift in Sources */, @@ -4425,6 +4506,7 @@ 922078482152FCE400C8C7E4 /* MessageOutput.swift in Sources */, 9220784D2152FCE400C8C7E4 /* RuntimeIntent.swift in Sources */, 9220784B2152FCE400C8C7E4 /* MessageContextGlobalSystem.swift in Sources */, + CA8E92892236C638001BFABF /* MessageContextSkill.swift in Sources */, 9220784C2152FCE400C8C7E4 /* DialogSuggestionValue.swift in Sources */, 9220784E2152FCE400C8C7E4 /* DialogNodeOutputOptionsElementValue.swift in Sources */, 922078462152FCE400C8C7E4 /* MessageRequest.swift in Sources */, @@ -4457,12 +4539,12 @@ 920F0AA4219CC1E900070C5B /* Parties.swift in Sources */, 920F0A91219CC1E900070C5B /* AlignedElement.swift in Sources */, 920F0ACE219CEE8C00070C5B /* RowHeaderTextsNormalized.swift in Sources */, + CA59FDA4224AA0E000E152AE /* KeyValuePair.swift in Sources */, 920F0AAB219CC1E900070C5B /* Category.swift in Sources */, 920F0A9C219CC1E900070C5B /* FeedbackDataOutput.swift in Sources */, 920F0A98219CC1E900070C5B /* BatchStatus.swift in Sources */, 920F0AB0219CC1E900070C5B /* FeedbackDataInput.swift in Sources */, 920F0A8F219CC1E900070C5B /* ShortDoc.swift in Sources */, - 920F0AC4219CEE8C00070C5B /* RowHeaderIds.swift in Sources */, 920F0A9E219CC1E900070C5B /* Element.swift in Sources */, 920F0A8E219CC1E900070C5B /* FeedbackInput.swift in Sources */, 920F0AA0219CC1E900070C5B /* UpdatedLabelsIn.swift in Sources */, @@ -4478,28 +4560,34 @@ 920F0A96219CC1E900070C5B /* Address.swift in Sources */, 920F0A8D219CC1E900070C5B /* FeedbackReturn.swift in Sources */, 920F0AA8219CC1E900070C5B /* TableHeaders.swift in Sources */, + CA59FDA5224AA0E000E152AE /* CategoryComparison.swift in Sources */, 920F0A92219CC1E900070C5B /* LeadingSentence.swift in Sources */, 920F0A90219CC1E900070C5B /* Label.swift in Sources */, 920F0AA5219CC1E900070C5B /* DocCounts.swift in Sources */, - 920F0AC8219CEE8C00070C5B /* ColumnHeaderIds.swift in Sources */, 920F0AB2219CC1E900070C5B /* DocStructure.swift in Sources */, 920F0AD0219CEE8C00070C5B /* RowHeaderTexts.swift in Sources */, 920F0A97219CC1E900070C5B /* FeedbackDeleted.swift in Sources */, + CA59FDA1224AA0E000E152AE /* RowHeaderIDs.swift in Sources */, 920F0AB3219CC1E900070C5B /* GetFeedback.swift in Sources */, 920F0A8B219CC1E900070C5B /* CompareReturn.swift in Sources */, 920F0A9B219CC1E900070C5B /* TerminationDates.swift in Sources */, 920F0AB6219CC1E900070C5B /* UpdatedLabelsOut.swift in Sources */, 920F0AAE219CC1E900070C5B /* BodyCells.swift in Sources */, + CA59FDA6224AA0E000E152AE /* Key.swift in Sources */, 920F0ACA219CEE8C00070C5B /* ColumnHeaderTexts.swift in Sources */, 920F0AA7219CC1E900070C5B /* Document.swift in Sources */, 920F0A9D219CC1E900070C5B /* HTMLReturn.swift in Sources */, 920F0A95219CC1E900070C5B /* EffectiveDates.swift in Sources */, + CA59FDA7224AA0E000E152AE /* ColumnHeaderIDs.swift in Sources */, 920F0AB8219CC1E900070C5B /* CompareComply.swift in Sources */, 920F0A94219CC1E900070C5B /* FeedbackList.swift in Sources */, 920F0A99219CC1E900070C5B /* TableReturn.swift in Sources */, 920F0A93219CC1E900070C5B /* ElementLocations.swift in Sources */, + CA59FDA2224AA0E000E152AE /* TypeLabelComparison.swift in Sources */, + CA59FDA9224AB66E00E152AE /* ContractType.swift in Sources */, 920F0AAF219CC1E900070C5B /* DocInfo.swift in Sources */, 920F0AA2219CC1E900070C5B /* Pagination.swift in Sources */, + CA59FDA3224AA0E000E152AE /* Value.swift in Sources */, 920F0ACC219CEE8C00070C5B /* Batches.swift in Sources */, 920F0AA6219CC1E900070C5B /* RowHeaders.swift in Sources */, ); From 2f47ab94a003d313d95317f3e4764cce21da831f Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Thu, 7 Mar 2019 07:55:19 -0600 Subject: [PATCH 04/13] feat: Apply hand-edits to generated files --- Source/AssistantV2/Assistant.swift | 1 + .../Models/AggregationResult.swift | 8 ++ Source/DiscoveryV1/Models/MemoryUsage.swift | 58 --------- .../DiscoveryV1/Models/QueryAggregation.swift | 112 +++++++++++++----- .../Models/MetadataOptions.swift | 4 +- .../PersonalityInsights.swift | 9 +- .../Models/SpeechRecognitionAlternative.swift | 4 +- Source/SpeechToTextV1/SpeechToText.swift | 16 --- Source/TextToSpeechV1/TextToSpeech.swift | 33 +++++- Source/ToneAnalyzerV3/ToneAnalyzer.swift | 10 -- .../VisualRecognition.swift | 10 ++ .../project.pbxproj | 4 - 12 files changed, 140 insertions(+), 129 deletions(-) delete mode 100644 Source/DiscoveryV1/Models/MemoryUsage.swift diff --git a/Source/AssistantV2/Assistant.swift b/Source/AssistantV2/Assistant.swift index d45054b9e..f595be99c 100644 --- a/Source/AssistantV2/Assistant.swift +++ b/Source/AssistantV2/Assistant.swift @@ -174,6 +174,7 @@ public class Assistant { let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "createSession") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + headerParameters["Content-Type"] = "application/json" // construct query parameters var queryParameters = [URLQueryItem]() diff --git a/Source/DiscoveryV1/Models/AggregationResult.swift b/Source/DiscoveryV1/Models/AggregationResult.swift index 0a48e3fb2..2ba72aba8 100644 --- a/Source/DiscoveryV1/Models/AggregationResult.swift +++ b/Source/DiscoveryV1/Models/AggregationResult.swift @@ -41,4 +41,12 @@ public struct AggregationResult: Codable, Equatable { case aggregations = "aggregations" } + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if let keyAsString = try? container.decode(String.self, forKey: .key) { key = keyAsString } + if let keyAsInt = try? container.decode(Int.self, forKey: .key) { key = "\(keyAsInt)" } + matchingResults = try container.decodeIfPresent(Int.self, forKey: .matchingResults) + aggregations = try container.decodeIfPresent([QueryAggregation].self, forKey: .aggregations) + } + } diff --git a/Source/DiscoveryV1/Models/MemoryUsage.swift b/Source/DiscoveryV1/Models/MemoryUsage.swift deleted file mode 100644 index e6ff29d08..000000000 --- a/Source/DiscoveryV1/Models/MemoryUsage.swift +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright IBM Corporation 2019 - * - * 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. - **/ - -import Foundation - -/** - **Deprecated**: Summary of the memory usage statistics for this environment. - */ -public struct MemoryUsage: Codable, Equatable { - - /** - **Deprecated**: Number of bytes used in the environment's memory capacity. - */ - public var usedBytes: Int? - - /** - **Deprecated**: Total number of bytes available in the environment's memory capacity. - */ - public var totalBytes: Int? - - /** - **Deprecated**: Amount of memory capacity used, in KB or GB format. - */ - public var used: String? - - /** - **Deprecated**: Total amount of the environment's memory capacity, in KB or GB format. - */ - public var total: String? - - /** - **Deprecated**: Percentage of the environment's memory capacity that is being used. - */ - public var percentUsed: Double? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case usedBytes = "used_bytes" - case totalBytes = "total_bytes" - case used = "used" - case total = "total" - case percentUsed = "percent_used" - } - -} diff --git a/Source/DiscoveryV1/Models/QueryAggregation.swift b/Source/DiscoveryV1/Models/QueryAggregation.swift index 523d75a24..2c17dae19 100644 --- a/Source/DiscoveryV1/Models/QueryAggregation.swift +++ b/Source/DiscoveryV1/Models/QueryAggregation.swift @@ -16,37 +16,91 @@ import Foundation -/** - An aggregation produced by the Discovery service to analyze the input provided. - */ -public struct QueryAggregation: Codable, Equatable { - - /** - The type of aggregation command used. For example: term, filter, max, min, etc. - */ - public var type: String? - - /** - Array of aggregation results. - */ - public var results: [AggregationResult]? - - /** - Number of matching results. - */ - public var matchingResults: Int? - - /** - Aggregations returned by the Discovery service. - */ - public var aggregations: [QueryAggregation]? - - // Map each property name to the key that shall be used for encoding/decoding. +/** An aggregation produced by the Discovery service to analyze the input provided. */ +public enum QueryAggregation: Codable, Equatable { + + // reference: https://cloud.ibm.com/docs/services/discovery/query-reference.html#aggregations + + case term(Term) + case filter(Filter) + case nested(Nested) + case histogram(Histogram) + case timeslice(Timeslice) + case topHits(TopHits) + case uniqueCount(Calculation) + case max(Calculation) + case min(Calculation) + case average(Calculation) + case sum(Calculation) + case generic(GenericQueryAggregation) + private enum CodingKeys: String, CodingKey { case type = "type" - case results = "results" - case matchingResults = "matching_results" - case aggregations = "aggregations" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let type = try container.decodeIfPresent(String.self, forKey: .type) else { + // the specification does not identify `type` as a required field, + // so we need a generic catch-all in case it is not present + self = .generic(try GenericQueryAggregation(from: decoder)) + return + } + switch type { + case "term": self = .term(try Term(from: decoder)) + case "filter": self = .filter(try Filter(from: decoder)) + case "nested": self = .nested(try Nested(from: decoder)) + case "histogram": self = .histogram(try Histogram(from: decoder)) + case "timeslice": self = .timeslice(try Timeslice(from: decoder)) + case "top_hits": self = .topHits(try TopHits(from: decoder)) + case "unique_count": self = .uniqueCount(try Calculation(from: decoder)) + case "max": self = .max(try Calculation(from: decoder)) + case "min": self = .min(try Calculation(from: decoder)) + case "average": self = .average(try Calculation(from: decoder)) + case "sum": self = .sum(try Calculation(from: decoder)) + default: self = .generic(try GenericQueryAggregation(from: decoder)) + } + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + switch self { + case .term(let term): + try container.encode("term", forKey: .type) + try term.encode(to: encoder) + case .filter(let filter): + try container.encode("filter", forKey: .type) + try filter.encode(to: encoder) + case .nested(let nested): + try container.encode("nested", forKey: .type) + try nested.encode(to: encoder) + case .histogram(let histogram): + try container.encode("histogram", forKey: .type) + try histogram.encode(to: encoder) + case .timeslice(let timeslice): + try container.encode("timeslice", forKey: .type) + try timeslice.encode(to: encoder) + case .topHits(let topHits): + try container.encode("top_hits", forKey: .type) + try topHits.encode(to: encoder) + case .uniqueCount(let uniqueCount): + try container.encode("unique_count", forKey: .type) + try uniqueCount.encode(to: encoder) + case .max(let max): + try container.encode("max", forKey: .type) + try max.encode(to: encoder) + case .min(let min): + try container.encode("min", forKey: .type) + try min.encode(to: encoder) + case .average(let average): + try container.encode("average", forKey: .type) + try average.encode(to: encoder) + case .sum(let sum): + try container.encode("sum", forKey: .type) + try sum.encode(to: encoder) + case .generic(let generic): + try generic.encode(to: encoder) + } } } diff --git a/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift b/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift index 303ff814f..b765c8f56 100644 --- a/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift +++ b/Source/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift @@ -20,4 +20,6 @@ import Foundation Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. */ -public typealias MetadataOptions = JSON +public struct MetadataOptions: Codable, Equatable { + public init() { } +} diff --git a/Source/PersonalityInsightsV3/PersonalityInsights.swift b/Source/PersonalityInsightsV3/PersonalityInsights.swift index 5a9b30691..e9b7383b1 100644 --- a/Source/PersonalityInsightsV3/PersonalityInsights.swift +++ b/Source/PersonalityInsightsV3/PersonalityInsights.swift @@ -204,8 +204,6 @@ public class PersonalityInsights { - parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw scores are not compared with a sample population. By default, only normalized percentiles are returned. - - parameter csvHeaders: Indicates whether column labels are returned with a CSV response. By default, no column - labels are returned. Applies only when the response type is CSV (`text/csv`). - parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are returned. - parameter headers: A dictionary of request headers to be sent with this request. @@ -216,7 +214,6 @@ public class PersonalityInsights { contentLanguage: String? = nil, acceptLanguage: String? = nil, rawScores: Bool? = nil, - csvHeaders: Bool? = nil, consumptionPreferences: Bool? = nil, headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) @@ -250,10 +247,6 @@ public class PersonalityInsights { let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)") queryParameters.append(queryParameter) } - if let csvHeaders = csvHeaders { - let queryParameter = URLQueryItem(name: "csv_headers", value: "\(csvHeaders)") - queryParameters.append(queryParameter) - } if let consumptionPreferences = consumptionPreferences { let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)") queryParameters.append(queryParameter) @@ -335,7 +328,7 @@ public class PersonalityInsights { csvHeaders: Bool? = nil, consumptionPreferences: Bool? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body guard let body = profileContent.content else { diff --git a/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift b/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift index 1de4a53b6..4c34b4b04 100644 --- a/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift +++ b/Source/SpeechToTextV1/Models/SpeechRecognitionAlternative.swift @@ -35,14 +35,14 @@ public struct SpeechRecognitionAlternative: Codable, Equatable { the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. */ - public var timestamps: [String]? + public var timestamps: [WordTimestamp]? /** A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best alternative and only with results marked as final. */ - public var wordConfidence: [String]? + public var wordConfidence: [WordConfidence]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { diff --git a/Source/SpeechToTextV1/SpeechToText.swift b/Source/SpeechToTextV1/SpeechToText.swift index 8e5494404..bc706a414 100644 --- a/Source/SpeechToTextV1/SpeechToText.swift +++ b/Source/SpeechToTextV1/SpeechToText.swift @@ -364,9 +364,6 @@ public class SpeechToText { supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). - - parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the - customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not - specify both parameters with a request. - parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified @@ -404,7 +401,6 @@ public class SpeechToText { profanityFilter: Bool? = nil, smartFormatting: Bool? = nil, speakerLabels: Bool? = nil, - customizationID: String? = nil, grammarName: String? = nil, redaction: Bool? = nil, contentType: String? = nil, @@ -488,10 +484,6 @@ public class SpeechToText { let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)") queryParameters.append(queryParameter) } - if let customizationID = customizationID { - let queryParameter = URLQueryItem(name: "customization_id", value: customizationID) - queryParameters.append(queryParameter) - } if let grammarName = grammarName { let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName) queryParameters.append(queryParameter) @@ -805,9 +797,6 @@ public class SpeechToText { supports speaker labels, you can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. See [Speaker labels](https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels). - - parameter customizationID: **Deprecated.** Use the `language_customization_id` parameter to specify the - customization ID (GUID) of a custom language model that is to be used with the recognition request. Do not - specify both parameters with a request. - parameter grammarName: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language model for which the grammar is defined. The service recognizes only strings that are recognized by the specified @@ -849,7 +838,6 @@ public class SpeechToText { profanityFilter: Bool? = nil, smartFormatting: Bool? = nil, speakerLabels: Bool? = nil, - customizationID: String? = nil, grammarName: String? = nil, redaction: Bool? = nil, contentType: String? = nil, @@ -949,10 +937,6 @@ public class SpeechToText { let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)") queryParameters.append(queryParameter) } - if let customizationID = customizationID { - let queryParameter = URLQueryItem(name: "customization_id", value: customizationID) - queryParameters.append(queryParameter) - } if let grammarName = grammarName { let queryParameter = URLQueryItem(name: "grammar_name", value: grammarName) queryParameters.append(queryParameter) diff --git a/Source/TextToSpeechV1/TextToSpeech.swift b/Source/TextToSpeechV1/TextToSpeech.swift index 282030ab1..fee2eceff 100644 --- a/Source/TextToSpeechV1/TextToSpeech.swift +++ b/Source/TextToSpeechV1/TextToSpeech.swift @@ -360,7 +360,38 @@ public class TextToSpeech { ) // execute REST request - request.response(completionHandler: completionHandler) + request.response { (response: WatsonResponse?, error: WatsonError?) in + var response = response + guard let data = response?.result else { + completionHandler(response, error) + return + } + if accept?.lowercased().contains("audio/wav") == true { + // repair the WAV header + var wav = data + guard WAVRepair.isWAVFile(data: wav) else { + let error = WatsonError.other(message: "Expected returned audio to be in WAV format") + completionHandler(nil, error) + return + } + WAVRepair.repairWAVHeader(data: &wav) + response?.result = wav + completionHandler(response, nil) + } else if accept?.lowercased().contains("ogg") == true && accept?.lowercased().contains("opus") == true { + do { + let decodedAudio = try TextToSpeechDecoder(audioData: data) + response?.result = decodedAudio.pcmDataWithHeaders + completionHandler(response, nil) + } catch { + let error = WatsonError.serialization(values: "returned audio") + completionHandler(nil, error) + return + } + } else { + completionHandler(response, nil) + } + } + } /** diff --git a/Source/ToneAnalyzerV3/ToneAnalyzer.swift b/Source/ToneAnalyzerV3/ToneAnalyzer.swift index 5adf1c869..5698278cb 100644 --- a/Source/ToneAnalyzerV3/ToneAnalyzer.swift +++ b/Source/ToneAnalyzerV3/ToneAnalyzer.swift @@ -175,11 +175,6 @@ public class ToneAnalyzer { - parameter sentences: Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If `true` (the default), the service returns results for each sentence. - - parameter tones: **`2017-09-21`:** Deprecated. The service continues to accept the parameter for - backward-compatibility, but the parameter no longer affects the response. - **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the input; - the indicated tones apply both to the full document and to individual sentences of the document. You can specify - one or more of the valid values. Omit the parameter to request results for all three tones. - parameter contentLanguage: The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for @@ -195,7 +190,6 @@ public class ToneAnalyzer { public func tone( toneContent: ToneContent, sentences: Bool? = nil, - tones: [String]? = nil, contentLanguage: String? = nil, acceptLanguage: String? = nil, headers: [String: String]? = nil, @@ -230,10 +224,6 @@ public class ToneAnalyzer { let queryParameter = URLQueryItem(name: "sentences", value: "\(sentences)") queryParameters.append(queryParameter) } - if let tones = tones { - let queryParameter = URLQueryItem(name: "tones", value: tones.joined(separator: ",")) - queryParameters.append(queryParameter) - } // construct REST request let request = RestRequest( diff --git a/Source/VisualRecognitionV3/VisualRecognition.swift b/Source/VisualRecognitionV3/VisualRecognition.swift index aaf7f2bde..c43b20e76 100644 --- a/Source/VisualRecognitionV3/VisualRecognition.swift +++ b/Source/VisualRecognitionV3/VisualRecognition.swift @@ -124,6 +124,16 @@ public class VisualRecognition { errorMessage = message } else if case let .some(.string(message)) = json["message"] { errorMessage = message + // ErrorAuthentication + } else if case let .some(.string(message)) = json["statusInfo"] { + errorMessage = message + // ErrorInfo + } else if case let .some(.object(errorObj)) = json["error"], // 404 + case let .some(.string(message)) = errorObj["description"] { + errorMessage = message + // ErrorHTML + } else if case let .some(.string(message)) = json["Error"] { // 413 + errorMessage = message } else { errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } diff --git a/WatsonDeveloperCloud.xcodeproj/project.pbxproj b/WatsonDeveloperCloud.xcodeproj/project.pbxproj index 624084348..6e510ff0a 100644 --- a/WatsonDeveloperCloud.xcodeproj/project.pbxproj +++ b/WatsonDeveloperCloud.xcodeproj/project.pbxproj @@ -598,7 +598,6 @@ CA29B870222E0AE700626030 /* SentenceResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86B222E0AE700626030 /* SentenceResult.swift */; }; CA29B871222E0AE700626030 /* SyntaxOptionsTokens.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86C222E0AE700626030 /* SyntaxOptionsTokens.swift */; }; CA29B872222E0AE700626030 /* SyntaxResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B86D222E0AE700626030 /* SyntaxResult.swift */; }; - CA29B874222E100A00626030 /* MemoryUsage.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA29B873222E100A00626030 /* MemoryUsage.swift */; }; CA35CD4720E3234900FACB2B /* ToneContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35CD4620E3234800FACB2B /* ToneContent.swift */; }; CA35CD4920E3237400FACB2B /* ProfileContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA35CD4820E3237400FACB2B /* ProfileContent.swift */; }; CA59FDA1224AA0E000E152AE /* RowHeaderIDs.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA59FD9A224AA0DE00E152AE /* RowHeaderIDs.swift */; }; @@ -1329,7 +1328,6 @@ CA29B86B222E0AE700626030 /* SentenceResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SentenceResult.swift; sourceTree = ""; }; CA29B86C222E0AE700626030 /* SyntaxOptionsTokens.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyntaxOptionsTokens.swift; sourceTree = ""; }; CA29B86D222E0AE700626030 /* SyntaxResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SyntaxResult.swift; sourceTree = ""; }; - CA29B873222E100A00626030 /* MemoryUsage.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MemoryUsage.swift; sourceTree = ""; }; CA35CD4620E3234800FACB2B /* ToneContent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ToneContent.swift; sourceTree = ""; }; CA35CD4820E3237400FACB2B /* ProfileContent.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileContent.swift; sourceTree = ""; }; CA45954820A62FBE0060BF9B /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -1971,7 +1969,6 @@ 928204C62124BC200013315B /* LogQueryResponseResult.swift */, 928204C02124BC1E0013315B /* LogQueryResponseResultDocuments.swift */, 928204C12124BC1E0013315B /* LogQueryResponseResultDocumentsResult.swift */, - CA29B873222E100A00626030 /* MemoryUsage.swift */, 928204C42124BC1F0013315B /* MetricAggregation.swift */, 928204BB2124BC1C0013315B /* MetricAggregationResult.swift */, 928204C22124BC1F0013315B /* MetricResponse.swift */, @@ -4125,7 +4122,6 @@ CADA959B20FCD66600B5BD84 /* CredentialsList.swift in Sources */, 9254773B216D4710003C2829 /* SearchStatus.swift in Sources */, 68AF8F852069690300D552E3 /* XPathPatterns.swift in Sources */, - CA29B874222E100A00626030 /* MemoryUsage.swift in Sources */, 683955072077E613009E1C8A /* Filter.swift in Sources */, 68AF8F872069690300D552E3 /* DeleteConfigurationResponse.swift in Sources */, 68AF8F7A2069690300D552E3 /* Field.swift in Sources */, From 96c008f02d94491e77506f2c2c3fee876bca03d6 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Thu, 7 Mar 2019 07:27:21 -0600 Subject: [PATCH 05/13] feat: Rework hand-coded methods that take UIImage for major release --- .../VisualRecognition+UIImage.swift | 65 +++++-------------- 1 file changed, 15 insertions(+), 50 deletions(-) diff --git a/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift b/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift index 17e5e6ae5..73880092a 100644 --- a/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift +++ b/Source/VisualRecognitionV3/VisualRecognition+UIImage.swift @@ -69,31 +69,21 @@ extension VisualRecognition { acceptLanguage: String? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { - // save image to disk - let file: URL - do { - file = try saveToDisk(image: image) - } catch { - let error = WatsonError.saveData + // convert UIImage to Data + guard let imageData = getImageData(image: image) else { + let error = WatsonError.serialization(values: "image to data") completionHandler(nil, error) return } - // delete image after service call - let deleteFile = { try? FileManager.default.removeItem(at: file) } - let completion = { - (response: WatsonResponse?, error: WatsonError?) in - deleteFile() - completionHandler(response, error) - } - self.classify( - imagesFile: file, - acceptLanguage: acceptLanguage, + imagesFile: imageData, + imagesFilename: "image.png", threshold: threshold, owners: owners, classifierIDs: classifierIDs, - completionHandler: completion + acceptLanguage: acceptLanguage, + completionHandler: completionHandler ) } @@ -116,25 +106,14 @@ extension VisualRecognition { image: UIImage, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { - // save image to disk - let file: URL - do { - file = try saveToDisk(image: image) - } catch { - let error = WatsonError.saveData + // convert UIImage to Data + guard let imageData = getImageData(image: image) else { + let error = WatsonError.serialization(values: "image to data") completionHandler(nil, error) return } - // delete image after service call - let deleteFile = { try? FileManager.default.removeItem(at: file) } - let completion = { - (response: WatsonResponse?, error: WatsonError?) in - deleteFile() - completionHandler(response, error) - } - - self.detectFaces(imagesFile: file, completionHandler: completion) + self.detectFaces(imagesFile: imageData, imagesFilename: "image.png", completionHandler: completionHandler) } /** @@ -155,34 +134,20 @@ extension VisualRecognition { completionHandler: @escaping (ClassifiedImages?, WatsonError?) -> Void) { // convert UIImage to Data - #if swift(>=4.2) - guard let imageData = image.pngData() else { - let error = WatsonError.serialization(values: "image to data") - completionHandler(nil, error) - return - } - #else - guard let imageData = UIImagePNGRepresentation(image) else { + guard let imageData = getImageData(image: image) else { let error = WatsonError.serialization(values: "image to data") completionHandler(nil, error) return } - #endif self.classifyWithLocalModel(imageData: imageData, classifierIDs: classifierIDs, threshold: threshold, completionHandler: completionHandler) } /** - Save an image to a temporary location on disk. - The image will be compressed in an attempt to stay under the service's 10MB image size restriction. + Convert UIImage to Data */ - private func saveToDisk(image: UIImage) throws -> URL { - let filename = UUID().uuidString + ".jpg" - let directory = NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) - guard let file = directory.appendingPathComponent(filename) else { throw WatsonError.urlEncoding(path: filename) } - guard let data = image.jpegData(compressionQuality: 0.75) else { throw WatsonError.serialization(values: "classify image") } - try data.write(to: file) - return file + private func getImageData(image: UIImage) -> Data? { + return image.pngData() } } From 3c5d6ab1c212791adbdb7872c791b708bf22aa8e Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Sun, 10 Mar 2019 08:38:52 -0700 Subject: [PATCH 06/13] test: Test updates for major release --- Tests/AssistantV1Tests/AssistantTests.swift | 172 +++++++++--------- .../AssistantV1UnitTests.swift | 63 ++++--- .../CompareComplyTests.swift | 24 ++- Tests/DiscoveryV1Tests/DiscoveryTests.swift | 37 ++-- .../LanguageTranslatorTests.swift | 7 +- .../NaturalLanguageClassifierTests.swift | 13 +- .../SpeechToTextTests.swift | 16 +- Tests/TestUtilities.swift | 2 +- .../TextToSpeechPlaybackTests.swift | 6 +- .../VisualRecognition+UIImageTests.swift | 6 +- .../VisualRecognitionTestUtilities.swift | 28 +-- .../VisualRecognitionTests.swift | 32 ++-- .../VisualRecognitionUnitTests.swift | 34 ++-- .../VisualRecognitionWithIAMTests.swift | 6 +- .../xcschemes/AssistantV2.xcscheme | 6 +- .../xcschemes/CompareComplyV1.xcscheme | 11 ++ .../xcschemes/VisualRecognitionV3.xcscheme | 6 - 17 files changed, 245 insertions(+), 224 deletions(-) diff --git a/Tests/AssistantV1Tests/AssistantTests.swift b/Tests/AssistantV1Tests/AssistantTests.swift index 8a71293f5..efdcd68c5 100644 --- a/Tests/AssistantV1Tests/AssistantTests.swift +++ b/Tests/AssistantV1Tests/AssistantTests.swift @@ -139,7 +139,7 @@ class AssistantTests: XCTestCase { } // verify input - XCTAssertNil(message.input?.text) + XCTAssertNil(message.input.text) // verify context XCTAssertNotNil(message.context.conversationID) @@ -171,7 +171,7 @@ class AssistantTests: XCTestCase { let description2 = "Continue a conversation." let expectation2 = self.expectation(description: description2) - let input = InputData(text: "Turn on the radio.") + let input = MessageInput(text: "Turn on the radio.") let result2 = ["Sure thing! Which genre would you prefer? Jazz is my personal favorite."] assistant.message(workspaceID: workspaceID, input: input, context: context!) { @@ -187,7 +187,7 @@ class AssistantTests: XCTestCase { } // verify input - XCTAssertEqual(message.input?.text, input.text) + XCTAssertEqual(message.input.text, input.text) // verify context XCTAssertEqual(message.context.conversationID, context!.conversationID) @@ -251,13 +251,13 @@ class AssistantTests: XCTestCase { let description2 = "Continue a conversation." let expectation2 = expectation(description: description2) - let input2 = InputData(text: "Turn on the radio.") + let input2 = MessageInput(text: "Turn on the radio.") assistant.message( workspaceID: workspaceID, input: input2, - context: context, - entities: entities, intents: intents, + entities: entities, + context: context, output: output) { response, error in @@ -328,13 +328,13 @@ class AssistantTests: XCTestCase { let description2 = "Continue a conversation." let expectation2 = expectation(description: description2) - let input2 = InputData(text: "Turn on the radio.") + let input2 = MessageInput(text: "Turn on the radio.") assistant.message( workspaceID: workspaceID, input: input2, - context: context, - entities: entities, intents: intents, + entities: entities, + context: context, output: output) { response, error in @@ -359,13 +359,13 @@ class AssistantTests: XCTestCase { let description3 = "Continue a conversation with non-empty intents and entities." let expectation3 = expectation(description: description3) - let input3 = InputData(text: "Rock music.") + let input3 = MessageInput(text: "Rock music.") assistant.message( workspaceID: workspaceID, input: input3, - context: context, - entities: entities, intents: intents, + entities: entities, + context: context, output: output) { response, error in @@ -433,7 +433,7 @@ class AssistantTests: XCTestCase { let description2 = "Continue a conversation." let expectation2 = expectation(description: description2) - let input2 = InputData(text: "Turn on the radio.") + let input2 = MessageInput(text: "Turn on the radio.") assistant.message(workspaceID: workspaceID, input: input2, context: context) { response, error in @@ -565,22 +565,22 @@ class AssistantTests: XCTestCase { let workspaceDescription = "temporary workspace for the swift sdk unit tests" let workspaceLanguage = "en" let workspaceMetadata: [String: JSON] = ["testKey": .string("testValue")] - let intentExample = CreateExample(text: "This is an example of Intent1") + let intentExample = Example(text: "This is an example of Intent1") let workspaceIntent = CreateIntent(intent: "Intent1", description: "description of Intent1", examples: [intentExample]) let entityValue = CreateValue(value: "Entity1Value", metadata: workspaceMetadata, synonyms: ["Synonym1", "Synonym2"]) let workspaceEntity = CreateEntity(entity: "Entity1", description: "description of Entity1", values: [entityValue]) - let workspaceDialogNode = CreateDialogNode(dialogNode: "DialogNode1", description: "description of DialogNode1") - let workspaceCounterexample = CreateCounterexample(text: "This is a counterexample") + let workspaceDialogNode = DialogNode(dialogNode: "DialogNode1", description: "description of DialogNode1") + let workspaceCounterexample = Counterexample(text: "This is a counterexample") assistant.createWorkspace( name: workspaceName, description: workspaceDescription, language: workspaceLanguage, + metadata: workspaceMetadata, intents: [workspaceIntent], entities: [workspaceEntity], dialogNodes: [workspaceDialogNode], - counterexamples: [workspaceCounterexample], - metadata: workspaceMetadata) + counterexamples: [workspaceCounterexample]) { response, error in @@ -634,7 +634,7 @@ class AssistantTests: XCTestCase { XCTAssertNotNil(workspace.intents) for intent in workspace.intents! { - XCTAssertEqual(intent.intentName, workspaceIntent.intent) + XCTAssertEqual(intent.intent, workspaceIntent.intent) XCTAssertEqual(intent.description, workspaceIntent.description) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) @@ -642,7 +642,7 @@ class AssistantTests: XCTestCase { for example in intent.examples! { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertEqual(example.exampleText, intentExample.text) + XCTAssertEqual(example.text, intentExample.text) } } @@ -798,7 +798,7 @@ class AssistantTests: XCTestCase { } for intent in intents.intents { - XCTAssertNotNil(intent.intentName) + XCTAssertNotNil(intent.intent) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) XCTAssertNil(intent.examples) @@ -829,7 +829,7 @@ class AssistantTests: XCTestCase { } for intent in intents.intents { - XCTAssertNotNil(intent.intentName) + XCTAssertNotNil(intent.intent) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) XCTAssertNil(intent.examples) @@ -862,7 +862,7 @@ class AssistantTests: XCTestCase { XCTAssertEqual(intents.intents.count, 1) for intent in intents.intents { - XCTAssertNotNil(intent.intentName) + XCTAssertNotNil(intent.intent) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) XCTAssertNil(intent.examples) @@ -893,14 +893,14 @@ class AssistantTests: XCTestCase { } for intent in intents.intents { - XCTAssertNotNil(intent.intentName) + XCTAssertNotNil(intent.intent) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) XCTAssertNotNil(intent.examples) for example in intent.examples! { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertNotNil(example.exampleText) + XCTAssertNotNil(example.text) } } XCTAssertNotNil(intents.pagination.refreshURL) @@ -918,8 +918,8 @@ class AssistantTests: XCTestCase { let newIntentName = "swift-sdk-test-intent" + UUID().uuidString let newIntentDescription = "description for \(newIntentName)" - let example1 = CreateExample(text: "example 1 for \(newIntentName)") - let example2 = CreateExample(text: "example 2 for \(newIntentName)") + let example1 = Example(text: "example 1 for \(newIntentName)") + let example2 = Example(text: "example 2 for \(newIntentName)") assistant.createIntent(workspaceID: workspaceID, intent: newIntentName, description: newIntentDescription, examples: [example1, example2]) { response, error in @@ -932,7 +932,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(intent.intentName, newIntentName) + XCTAssertEqual(intent.intent, newIntentName) XCTAssertEqual(intent.description, newIntentDescription) expectation.fulfill() } @@ -969,14 +969,14 @@ class AssistantTests: XCTestCase { return } - XCTAssertNotNil(intent.intentName) + XCTAssertNotNil(intent.intent) XCTAssertNotNil(intent.created) XCTAssertNotNil(intent.updated) XCTAssertNotNil(intent.examples) for example in intent.examples! { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertNotNil(example.exampleText) + XCTAssertNotNil(example.text) } expectation.fulfill() } @@ -989,8 +989,8 @@ class AssistantTests: XCTestCase { let newIntentName = "swift-sdk-test-intent" + UUID().uuidString let newIntentDescription = "description for \(newIntentName)" - let example1 = CreateExample(text: "example 1 for \(newIntentName)") - let example2 = CreateExample(text: "example 2 for \(newIntentName)") + let example1 = Example(text: "example 1 for \(newIntentName)") + let example2 = Example(text: "example 2 for \(newIntentName)") assistant.createIntent(workspaceID: workspaceID, intent: newIntentName, description: newIntentDescription, examples: [example1, example2]) { response, error in @@ -1003,7 +1003,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(intent.intentName, newIntentName) + XCTAssertEqual(intent.intent, newIntentName) XCTAssertEqual(intent.description, newIntentDescription) expectation.fulfill() } @@ -1014,7 +1014,7 @@ class AssistantTests: XCTestCase { let updatedIntentName = "updated-name-for-\(newIntentName)" let updatedIntentDescription = "updated-description-for-\(newIntentName)" - let updatedExample1 = CreateExample(text: "updated example for \(newIntentName)") + let updatedExample1 = Example(text: "updated example for \(newIntentName)") assistant.updateIntent(workspaceID: workspaceID, intent: newIntentName, newIntent: updatedIntentName, newDescription: updatedIntentDescription, newExamples: [updatedExample1]) { response, error in @@ -1027,7 +1027,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(intent.intentName, updatedIntentName) + XCTAssertEqual(intent.intent, updatedIntentName) XCTAssertEqual(intent.description, updatedIntentDescription) expectation2.fulfill() } @@ -1069,7 +1069,7 @@ class AssistantTests: XCTestCase { for example in examples.examples { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertNotNil(example.exampleText) + XCTAssertNotNil(example.text) } XCTAssertNotNil(examples.pagination.refreshURL) XCTAssertNil(examples.pagination.total) @@ -1098,7 +1098,7 @@ class AssistantTests: XCTestCase { for example in examples.examples { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertNotNil(example.exampleText) + XCTAssertNotNil(example.text) } XCTAssertNotNil(examples.pagination.refreshURL) XCTAssertNotNil(examples.pagination.total) @@ -1129,7 +1129,7 @@ class AssistantTests: XCTestCase { for example in examples.examples { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertNotNil(example.exampleText) + XCTAssertNotNil(example.text) } XCTAssertNotNil(examples.pagination.refreshURL) XCTAssertNotNil(examples.pagination.nextURL) @@ -1157,7 +1157,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(example.exampleText, newExample) + XCTAssertEqual(example.text, newExample) expectation.fulfill() } waitForExpectations() @@ -1196,7 +1196,7 @@ class AssistantTests: XCTestCase { XCTAssertNotNil(example.created) XCTAssertNotNil(example.updated) - XCTAssertEqual(example.exampleText, exampleText) + XCTAssertEqual(example.text, exampleText) expectation.fulfill() } waitForExpectations() @@ -1219,7 +1219,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(example.exampleText, newExample) + XCTAssertEqual(example.text, newExample) expectation.fulfill() } waitForExpectations() @@ -1240,7 +1240,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(example.exampleText, updatedText) + XCTAssertEqual(example.text, updatedText) expectation2.fulfill() } waitForExpectations() @@ -1394,8 +1394,8 @@ class AssistantTests: XCTestCase { let description = "Get details of a specific counterexample." let expectation = self.expectation(description: description) - let exampleText = "when will it be funny" - assistant.getCounterexample(workspaceID: workspaceID, text: exampleText, includeAudit: true) { + let example = "when will it be funny" + assistant.getCounterexample(workspaceID: workspaceID, text: example, includeAudit: true) { response, error in if let error = error { @@ -1409,7 +1409,7 @@ class AssistantTests: XCTestCase { XCTAssertNotNil(counterexample.created) XCTAssertNotNil(counterexample.updated) - XCTAssertEqual(counterexample.text, exampleText) + XCTAssertEqual(counterexample.text, example) expectation.fulfill() } waitForExpectations() @@ -1492,7 +1492,7 @@ class AssistantTests: XCTestCase { } for entity in entities.entities { - XCTAssertNotNil(entity.entityName) + XCTAssertNotNil(entity.entity) XCTAssertNotNil(entity.created) XCTAssertNotNil(entity.updated) } @@ -1523,7 +1523,7 @@ class AssistantTests: XCTestCase { } for entity in entities.entities { - XCTAssertNotNil(entity.entityName) + XCTAssertNotNil(entity.entity) XCTAssertNotNil(entity.created) XCTAssertNotNil(entity.updated) } @@ -1554,7 +1554,7 @@ class AssistantTests: XCTestCase { } for entity in entities.entities { - XCTAssertNotNil(entity.entityName) + XCTAssertNotNil(entity.entity) XCTAssertNotNil(entity.created) XCTAssertNotNil(entity.updated) } @@ -1586,7 +1586,7 @@ class AssistantTests: XCTestCase { } for entity in entities.entities { - XCTAssertNotNil(entity.entityName) + XCTAssertNotNil(entity.entity) XCTAssertNotNil(entity.created) XCTAssertNotNil(entity.updated) } @@ -1618,7 +1618,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(entity.entityName, entityName) + XCTAssertEqual(entity.entity, entityName) XCTAssertEqual(entity.description, entityDescription) expectation.fulfill() } @@ -1658,7 +1658,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(entity.entityName, entityName) + XCTAssertEqual(entity.entity, entityName) XCTAssertEqual(entity.description, entityDescription) expectation.fulfill() } @@ -1686,7 +1686,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(entity.entityName, updatedEntityName) + XCTAssertEqual(entity.entity, updatedEntityName) XCTAssertEqual(entity.description, updatedEntityDescription) expectationTwo.fulfill() } @@ -1724,23 +1724,23 @@ class AssistantTests: XCTestCase { } XCTAssert(entityCollection.entities.count > 0) - let entity = entityCollection.entities[0] - self.assistant.getEntity(workspaceID: self.workspaceID, entity: entity.entityName, export: true, includeAudit: true) { + let entity0 = entityCollection.entities[0] + self.assistant.getEntity(workspaceID: self.workspaceID, entity: entity0.entity, export: true, includeAudit: true) { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) return } - guard let entityExport = response?.result else { + guard let entity = response?.result else { XCTFail(missingResultMessage) return } - XCTAssertEqual(entityExport.entityName, entity.entityName) - XCTAssertEqual(entityExport.description, entity.description) - XCTAssertNotNil(entityExport.created) - XCTAssertNotNil(entityExport.updated) + XCTAssertEqual(entity.entity, entity0.entity) + XCTAssertEqual(entity.description, entity0.description) + XCTAssertNotNil(entity.created) + XCTAssertNotNil(entity.updated) expectation.fulfill() } } @@ -1770,8 +1770,8 @@ class AssistantTests: XCTestCase { } for mention in mentionCollection.examples { - XCTAssertNotNil(mention.exampleText) - XCTAssertNotNil(mention.intentName) + XCTAssertNotNil(mention.text) + XCTAssertNotNil(mention.intent) XCTAssertNotNil(mention.location) XCTAssert(mention.location.count == 2) } @@ -1805,7 +1805,7 @@ class AssistantTests: XCTestCase { } for value in valueCollection.values { - XCTAssertNotNil(value.valueText) + XCTAssertNotNil(value.value) XCTAssertNotNil(value.created) XCTAssertNotNil(value.updated) } @@ -1835,7 +1835,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(value.valueText, valueName) + XCTAssertEqual(value.value, valueName) expectation.fulfill() } waitForExpectations() @@ -1862,7 +1862,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(value.valueText, updatedValueName) + XCTAssertEqual(value.value, updatedValueName) XCTAssertNotNil(value.metadata) expectationTwo.fulfill() } @@ -1902,22 +1902,22 @@ class AssistantTests: XCTestCase { } XCTAssert(valueCollection.values.count > 0) - let value = valueCollection.values[0] - self.assistant.getValue(workspaceID: self.workspaceID, entity: entityName, value: value.valueText, export: true, includeAudit: true) { + let value0 = valueCollection.values[0] + self.assistant.getValue(workspaceID: self.workspaceID, entity: entityName, value: value0.value, export: true, includeAudit: true) { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) return } - guard let valueExport = response?.result else { + guard let value = response?.result else { XCTFail(missingResultMessage) return } - XCTAssertEqual(valueExport.valueText, value.valueText) - XCTAssertNotNil(valueExport.created) - XCTAssertNotNil(valueExport.updated) + XCTAssertEqual(value0.value, value.value) + XCTAssertNotNil(value.created) + XCTAssertNotNil(value.updated) expectation.fulfill() } } @@ -1945,7 +1945,7 @@ class AssistantTests: XCTestCase { for synonym in synonyms.synonyms { XCTAssertNotNil(synonym.created) XCTAssertNotNil(synonym.updated) - XCTAssertNotNil(synonym.synonymText) + XCTAssertNotNil(synonym.synonym) } XCTAssertNotNil(synonyms.pagination.refreshURL) XCTAssertNil(synonyms.pagination.total) @@ -1974,7 +1974,7 @@ class AssistantTests: XCTestCase { for synonym in synonyms.synonyms { XCTAssertNotNil(synonym.created) XCTAssertNotNil(synonym.updated) - XCTAssertNotNil(synonym.synonymText) + XCTAssertNotNil(synonym.synonym) } XCTAssertNotNil(synonyms.pagination.refreshURL) XCTAssertNotNil(synonyms.pagination.total) @@ -2005,7 +2005,7 @@ class AssistantTests: XCTestCase { for synonym in synonyms.synonyms { XCTAssertNotNil(synonym.created) XCTAssertNotNil(synonym.updated) - XCTAssertNotNil(synonym.synonymText) + XCTAssertNotNil(synonym.synonym) } XCTAssertNotNil(synonyms.pagination.refreshURL) XCTAssertNotNil(synonyms.pagination.nextURL) @@ -2033,7 +2033,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(synonym.synonymText, newSynonym) + XCTAssertEqual(synonym.synonym, newSynonym) expectation.fulfill() } waitForExpectations() @@ -2070,7 +2070,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(synonym.synonymText, synonymName) + XCTAssertEqual(synonym.synonym, synonymName) XCTAssertNotNil(synonym.created) XCTAssertNotNil(synonym.updated) expectation.fulfill() @@ -2095,7 +2095,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(synonym.synonymText, newSynonym) + XCTAssertEqual(synonym.synonym, newSynonym) expectation.fulfill() } waitForExpectations() @@ -2116,7 +2116,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(synonym.synonymText, updatedSynonym) + XCTAssertEqual(synonym.synonym, updatedSynonym) expectation2.fulfill() } waitForExpectations() @@ -2155,7 +2155,7 @@ class AssistantTests: XCTestCase { } for node in nodes.dialogNodes { - XCTAssertNotNil(node.dialogNodeID) + XCTAssertNotNil(node.dialogNode) } XCTAssertGreaterThan(nodes.dialogNodes.count, 0) XCTAssertNotNil(nodes.pagination.refreshURL) @@ -2168,13 +2168,13 @@ class AssistantTests: XCTestCase { func testCreateAndDeleteDialogNode() { let description1 = "Create a dialog node." - let dialogNodeID = "OrderMyPizza" + let dialogNode = "OrderMyPizza" let dialogMetadata: [String: JSON] = ["swift-sdk-test": .boolean(true)] let expectation1 = self.expectation(description: description1) assistant.createDialogNode( workspaceID: workspaceID, - dialogNode: dialogNodeID, + dialogNode: dialogNode, description: "Reply affirmatively", conditions: "#order_pizza", metadata: dialogMetadata, @@ -2192,7 +2192,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(node.dialogNodeID, dialogNodeID) + XCTAssertEqual(node.dialogNode, dialogNode) XCTAssertEqual(node.description, "Reply affirmatively") XCTAssertEqual(node.conditions, "#order_pizza") XCTAssertNil(node.parent) @@ -2212,7 +2212,7 @@ class AssistantTests: XCTestCase { let description2 = "Delete a dialog node" let expectation2 = self.expectation(description: description2) - assistant.deleteDialogNode(workspaceID: workspaceID, dialogNode: dialogNodeID) { + assistant.deleteDialogNode(workspaceID: workspaceID, dialogNode: dialogNode) { _, error in if let error = error { @@ -2239,7 +2239,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(node.dialogNodeID, "test-node") + XCTAssertEqual(node.dialogNode, "test-node") expectation1.fulfill() } waitForExpectations() @@ -2262,7 +2262,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(node.dialogNodeID, "test-node-updated") + XCTAssertEqual(node.dialogNode, "test-node-updated") expectation2.fulfill() } waitForExpectations() @@ -2300,7 +2300,7 @@ class AssistantTests: XCTestCase { let dialogNode = nodes.dialogNodes.first! self.assistant.getDialogNode( workspaceID: self.workspaceID, - dialogNode: dialogNode.dialogNodeID) { + dialogNode: dialogNode.dialogNode) { response, error in if let error = error { @@ -2312,7 +2312,7 @@ class AssistantTests: XCTestCase { return } - XCTAssertEqual(dialogNode.dialogNodeID, node.dialogNodeID) + XCTAssertEqual(dialogNode.dialogNode, node.dialogNode) expectation.fulfill() } } diff --git a/Tests/AssistantV1Tests/AssistantV1UnitTests.swift b/Tests/AssistantV1Tests/AssistantV1UnitTests.swift index 3474127ac..0c55048d0 100644 --- a/Tests/AssistantV1Tests/AssistantV1UnitTests.swift +++ b/Tests/AssistantV1Tests/AssistantV1UnitTests.swift @@ -53,17 +53,16 @@ class AssistantV1UnitTests: XCTestCase { let testResponse = HTTPURLResponse(url: exampleURL, statusCode: 500, httpVersion: nil, headerFields: nil)! let error = assistant.errorResponseDecoder(data: testData, response: testResponse) - if case let .http(statusCode, message, metadata) = error { + if case let .http(statusCode, message, _) = error { XCTAssertEqual(statusCode, 500) - XCTAssertNil(message) - XCTAssertNil(metadata) + XCTAssertNotNil(message) } } // MARK: - Message func testMessage() { - let input = InputData(text: "asdf") + let input = MessageInput(text: "asdf") let alternateIntents = true let context = Context(conversationID: "Hi, how are you?") let entities = [RuntimeEntity(entity: "entity", location: [0], value: "whatever")] @@ -101,10 +100,10 @@ class AssistantV1UnitTests: XCTestCase { assistant.message( workspaceID: self.workspaceID, input: input, + intents: intents, + entities: entities, alternateIntents: alternateIntents, context: context, - entities: entities, - intents: intents, output: output, nodesVisitedDetails: true) { _, _ in @@ -151,8 +150,8 @@ class AssistantV1UnitTests: XCTestCase { let language = "en" let intents = [CreateIntent(intent: "intent")] let entities = [CreateEntity(entity: "entity")] - let dialogNodes = [CreateDialogNode(dialogNode: "Best node")] - let counterExamples = [CreateCounterexample(text: "no u")] + let dialogNodes = [DialogNode(dialogNode: "Best node")] + let counterExamples = [Counterexample(text: "no u")] let metadata: [String: JSON] = ["key": JSON.string("value")] let learningOptOut = true let systemSettings = WorkspaceSystemSettings(tooling: nil, disambiguation: nil, humanAgentAssist: nil) @@ -190,13 +189,13 @@ class AssistantV1UnitTests: XCTestCase { name: name, description: description, language: language, + metadata: metadata, + learningOptOut: learningOptOut, + systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, - counterexamples: counterExamples, - metadata: metadata, - learningOptOut: learningOptOut, - systemSettings: systemSettings) { + counterexamples: counterExamples) { _, _ in expectation.fulfill() } @@ -238,8 +237,8 @@ class AssistantV1UnitTests: XCTestCase { let language = "en" let intents = [CreateIntent(intent: "intent")] let entities = [CreateEntity(entity: "entity")] - let dialogNodes = [CreateDialogNode(dialogNode: "Best node")] - let counterExamples = [CreateCounterexample(text: "no u")] + let dialogNodes = [DialogNode(dialogNode: "Best node")] + let counterExamples = [Counterexample(text: "no u")] let metadata: [String: JSON] = ["key": JSON.string("value")] let learningOptOut = true let systemSettings = WorkspaceSystemSettings(tooling: nil, disambiguation: nil, humanAgentAssist: nil) @@ -281,13 +280,13 @@ class AssistantV1UnitTests: XCTestCase { name: name, description: description, language: language, + metadata: metadata, + learningOptOut: learningOptOut, + systemSettings: systemSettings, intents: intents, entities: entities, dialogNodes: dialogNodes, counterexamples: counterExamples, - metadata: metadata, - learningOptOut: learningOptOut, - systemSettings: systemSettings, append: true) { _, _ in expectation.fulfill() @@ -357,7 +356,7 @@ class AssistantV1UnitTests: XCTestCase { func testCreateIntent() { let description = "The best intent there ever was" - let examples = [CreateExample(text: "example")] + let examples = [Example(text: "example")] MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -430,7 +429,7 @@ class AssistantV1UnitTests: XCTestCase { let intent = "intent" let newIntent = "my new intent" let newDescription = "the best intent there ever was" - let newExamples = [CreateExample(text: "example")] + let newExamples = [Example(text: "example")] MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -540,7 +539,7 @@ class AssistantV1UnitTests: XCTestCase { func testCreateExample() { let intent = "intent" let text = "text" - let mentions = [Mentions(entity: "entity", location: [0, 1])] + let mentions = [Mention(entity: "entity", location: [0, 1])] MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -556,7 +555,7 @@ class AssistantV1UnitTests: XCTestCase { do { let body = Data(reading: request.httpBodyStream!) - let decodedBody = try JSONDecoder().decode(CreateExample.self, from: body) + let decodedBody = try JSONDecoder().decode(Example.self, from: body) XCTAssertEqual(decodedBody.text, text) XCTAssertEqual(decodedBody.mentions, mentions) @@ -617,7 +616,7 @@ class AssistantV1UnitTests: XCTestCase { let intent = "intent" let text = "text" let newText = "new text" - let newMentions = [Mentions(entity: "entity", location: [0, 1])] + let newMentions = [Mention(entity: "entity", location: [0, 1])] MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -741,7 +740,7 @@ class AssistantV1UnitTests: XCTestCase { do { let body = Data(reading: request.httpBodyStream!) - let decodedBody = try JSONDecoder().decode(CreateCounterexample.self, from: body) + let decodedBody = try JSONDecoder().decode(Counterexample.self, from: body) XCTAssertEqual(decodedBody.text, text) } catch { @@ -934,8 +933,8 @@ class AssistantV1UnitTests: XCTestCase { entity: entity, description: description, metadata: metadata, - values: values, - fuzzyMatch: fuzzyMatch) { + fuzzyMatch: fuzzyMatch, + values: values) { _, _ in expectation.fulfill() } @@ -1171,9 +1170,9 @@ class AssistantV1UnitTests: XCTestCase { entity: entity, value: value, metadata: metadata, + valueType: valueType, synonyms: synonyms, - patterns: patterns, - valueType: valueType) { + patterns: patterns) { _, _ in expectation.fulfill() } @@ -1261,7 +1260,7 @@ class AssistantV1UnitTests: XCTestCase { value: value, newValue: newValue, newMetadata: newMetadata, - newType: newType, + newValueType: newType, newSynonyms: newSynonyms, newPatterns: newPatterns) { _, _ in @@ -1368,7 +1367,7 @@ class AssistantV1UnitTests: XCTestCase { do { let body = Data(reading: request.httpBodyStream!) - let decodedBody = try JSONDecoder().decode(CreateSynonym.self, from: body) + let decodedBody = try JSONDecoder().decode(Synonym.self, from: body) XCTAssertEqual(decodedBody.synonym, synonym) } catch { @@ -1580,7 +1579,7 @@ class AssistantV1UnitTests: XCTestCase { do { let body = Data(reading: request.httpBodyStream!) - let decodedBody = try JSONDecoder().decode(CreateDialogNode.self, from: body) + let decodedBody = try JSONDecoder().decode(DialogNode.self, from: body) XCTAssertEqual(decodedBody.dialogNode, dialogNode) XCTAssertEqual(decodedBody.description, description) @@ -1619,11 +1618,11 @@ class AssistantV1UnitTests: XCTestCase { context: context, metadata: metadata, nextStep: nextStep, - actions: actions, title: title, nodeType: nodeType, eventName: eventName, variable: variable, + actions: actions, digressIn: digressIn, digressOut: digressOut, digressOutSlots: digressOutSlots, @@ -1741,7 +1740,7 @@ class AssistantV1UnitTests: XCTestCase { newMetadata: newMetadata, newNextStep: newNextStep, newTitle: newTitle, - newType: newType, + newNodeType: newType, newEventName: newEventName, newVariable: newVariable, newActions: newActions, diff --git a/Tests/CompareComplyV1Tests/CompareComplyTests.swift b/Tests/CompareComplyV1Tests/CompareComplyTests.swift index cd67b657b..007720a87 100644 --- a/Tests/CompareComplyV1Tests/CompareComplyTests.swift +++ b/Tests/CompareComplyV1Tests/CompareComplyTests.swift @@ -23,9 +23,9 @@ class CompareComplyTests: XCTestCase { private var compareComply: CompareComply! - var contractAFile: URL! - var contractBFile: URL! - var testTableFile: URL! + var contractAFile: Data! + var contractBFile: Data! + var testTableFile: Data! // MARK: - Test Configuration @@ -63,14 +63,15 @@ class CompareComplyTests: XCTestCase { compareComply.defaultHeaders["x-watson-metadata"] = "customer_id=sdk-test-customer-id" } - func loadDocument(name: String, ext: String) -> URL? { + func loadDocument(name: String, ext: String) -> Data? { #if os(Linux) let url = URL(fileURLWithPath: "Tests/CompareComplyV1Tests/Resources/" + name + "." + ext) #else let bundle = Bundle(for: type(of: self)) guard let url = bundle.url(forResource: name, withExtension: ext) else { return nil } #endif - return url + let data = try? Data(contentsOf: url) + return data } func waitForExpectations(timeout: TimeInterval = 20.0) { @@ -89,8 +90,7 @@ class CompareComplyTests: XCTestCase { compareComply.convertToHTML( file: file, - modelID: nil, - fileContentType: nil) { + filename: "contract_A.pdf") { response, error in if let error = error { @@ -121,7 +121,7 @@ class CompareComplyTests: XCTestCase { compareComply.classifyElements( file: contractAFile, - modelID: nil) { + fileContentType: "application/pdf") { response, error in if let error = error { @@ -159,7 +159,6 @@ class CompareComplyTests: XCTestCase { compareComply.extractTables( file: testTableFile, - modelID: nil, fileContentType: "application/pdf") { response, error in @@ -191,11 +190,10 @@ class CompareComplyTests: XCTestCase { compareComply.compareDocuments( file1: contractAFile, file2: contractBFile, - file1Label: "contract_a", - file2Label: "contract_b", - modelID: nil, file1ContentType: "application/pdf", - file2ContentType: "application/pdf") { + file2ContentType: "application/pdf", + file1Label: "contract_a", + file2Label: "contract_b") { response, error in if let error = error { diff --git a/Tests/DiscoveryV1Tests/DiscoveryTests.swift b/Tests/DiscoveryV1Tests/DiscoveryTests.swift index a3ad19b4c..3f45f2f11 100644 --- a/Tests/DiscoveryV1Tests/DiscoveryTests.swift +++ b/Tests/DiscoveryV1Tests/DiscoveryTests.swift @@ -27,7 +27,7 @@ class DiscoveryTests: XCTestCase { private var environment: Environment! private let newsEnvironmentID = "system" private let newsCollectionID = "news-en" - private var documentURL: URL! + private var document: Data! private let timeout: TimeInterval = 30.0 private let unexpectedAggregationTypeMessage = "Unexpected aggregation type" @@ -38,7 +38,7 @@ class DiscoveryTests: XCTestCase { continueAfterFailure = false instantiateDiscovery() environment = getTestEnvironment() - documentURL = loadDocument(name: "KennedySpeech", ext: "html") + document = loadDocument(name: "KennedySpeech", ext: "html") } func instantiateDiscovery() { @@ -56,14 +56,15 @@ class DiscoveryTests: XCTestCase { discovery.defaultHeaders["X-Watson-Test"] = "true" } - func loadDocument(name: String, ext: String) -> URL? { + func loadDocument(name: String, ext: String) -> Data? { #if os(Linux) let url = URL(fileURLWithPath: "Tests/DiscoveryV1Tests/Resources/" + name + "." + ext) #else let bundle = Bundle(for: type(of: self)) guard let url = bundle.url(forResource: name, withExtension: ext) else { return nil } #endif - return url + let data = try? Data(contentsOf: url) + return data } // MARK: - Test Definition for Linux @@ -287,8 +288,8 @@ class DiscoveryTests: XCTestCase { discovery.addDocument( environmentID: environmentID, collectionID: collectionID, - file: documentURL, - fileContentType: "text/html") + file: document, + filename: "KennedySpeech.html") { response, error in @@ -490,8 +491,8 @@ class DiscoveryTests: XCTestCase { XCTAssertNotNil(result.fields) XCTAssertGreaterThan(result.fields!.count, 0) - XCTAssertNotNil(result.fields!.first!.fieldName) - XCTAssertNotNil(result.fields!.first!.fieldType) + XCTAssertNotNil(result.fields?.first?.fieldName) + XCTAssertNotNil(result.fields?.first?.fieldType) expectation.fulfill() } waitForExpectations(timeout: timeout) @@ -731,10 +732,10 @@ class DiscoveryTests: XCTestCase { let expectation = self.expectation(description: "testConfigurationInEnvironment") discovery.testConfigurationInEnvironment( environmentID: environmentID, - configurationID: configuration.configurationID, - file: documentURL, + file: document, + filename: "KennedySpeech.html", metadata: "{ \"Creator\": \"John F. Kennedy\" }", - fileContentType: "text/html") + configurationID: configuration.configurationID) { response, error in @@ -941,8 +942,8 @@ class DiscoveryTests: XCTestCase { XCTAssertNotNil(result.fields) XCTAssertGreaterThan(result.fields!.count, 0) - XCTAssertNotNil(result.fields!.first!.fieldName) - XCTAssertNotNil(result.fields!.first!.fieldType) + XCTAssertNotNil(result.fields?.first?.fieldName) + XCTAssertNotNil(result.fields?.first?.fieldType) expectation.fulfill() } waitForExpectations(timeout: timeout) @@ -1045,7 +1046,7 @@ class DiscoveryTests: XCTestCase { } let expectation = self.expectation(description: "createTokenizationDictionary") - let tokenizationRule = TokenDictRule(text: "すしネコ", tokens: ["すし", "ネコ"], readings: ["寿司", "ネコ"], partOfSpeech: "カスタム名詞") + let tokenizationRule = TokenDictRule(text: "すしネコ", tokens: ["すし", "ネコ"], partOfSpeech: "カスタム名詞", readings: ["寿司", "ネコ"]) discovery.createTokenizationDictionary(environmentID: environmentID, collectionID: collectionID, tokenizationRules: [tokenizationRule]) { response, error in @@ -1111,7 +1112,7 @@ class DiscoveryTests: XCTestCase { let expectation1 = self.expectation(description: "createStopwordList") let stopwordFile = loadDocument(name: "stopwords", ext: "txt")! - discovery.createStopwordList(environmentID: environmentID, collectionID: collectionID, stopwordFile: stopwordFile) { + discovery.createStopwordList(environmentID: environmentID, collectionID: collectionID, stopwordFile: stopwordFile, stopwordFilename: "stopwords.txt") { response, error in if let error = error { @@ -1172,9 +1173,9 @@ class DiscoveryTests: XCTestCase { discovery.addDocument( environmentID: environmentID, collectionID: collectionID, - file: documentURL, - metadata: metadata, - fileContentType: "text/html") + file: document, + filename: "KennedySpeech.html", + metadata: metadata) { response, error in diff --git a/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift b/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift index 5d62b8c3a..c5a0b8706 100644 --- a/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift +++ b/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift @@ -190,16 +190,17 @@ class LanguageTranslatorTests: XCTestCase { let expectation = self.expectation(description: "Create and delete a custom language model.") #if os(Linux) - let glossary = URL(fileURLWithPath: "Tests/LanguageTranslatorV3Tests/glossary.tmx") + let url = URL(fileURLWithPath: "Tests/LanguageTranslatorV3Tests/glossary.tmx") #else let bundle = Bundle(for: type(of: self)) - guard let glossary = bundle.url(forResource: "glossary", withExtension: "tmx") else { + guard let url = bundle.url(forResource: "glossary", withExtension: "tmx") else { XCTFail("Unable to read forced glossary.") return } #endif + let glossary = try? Data(contentsOf: url) - languageTranslator.createModel(baseModelID: "en-es", name: "custom-english-to-spanish-model", forcedGlossary: glossary) { + languageTranslator.createModel(baseModelID: "en-es", forcedGlossary: glossary, name: "custom-english-to-spanish-model") { response, error in if let error = error { diff --git a/Tests/NaturalLanguageClassifierV1Tests/NaturalLanguageClassifierTests.swift b/Tests/NaturalLanguageClassifierV1Tests/NaturalLanguageClassifierTests.swift index 49858ddd8..8aa0c0da5 100644 --- a/Tests/NaturalLanguageClassifierV1Tests/NaturalLanguageClassifierTests.swift +++ b/Tests/NaturalLanguageClassifierV1Tests/NaturalLanguageClassifierTests.swift @@ -31,10 +31,10 @@ class NaturalLanguageClassifierTests: XCTestCase { private let trainedClassifierName = "swift-sdk-test-classifier - DO NOT DELETE" private let temporaryClassifierName = "swift-sdk-temporary-classifier" - private var metadataFile: URL! - private var metadataFileEmpty: URL! - private var metadataFileMissingName: URL! - private var trainingFile: URL! + private var metadataFile: Data! + private var metadataFileEmpty: Data! + private var metadataFileMissingName: Data! + private var trainingFile: Data! // MARK: - Test Configuration @@ -97,14 +97,15 @@ class NaturalLanguageClassifierTests: XCTestCase { } /** Load a file used when creating a classifier. */ - func loadClassifierFile(name: String, withExtension: String) -> URL? { + func loadClassifierFile(name: String, withExtension: String) -> Data? { #if os(Linux) let url = URL(fileURLWithPath: "Tests/NaturalLanguageClassifierV1Tests/" + name + "." + withExtension) #else let bundle = Bundle(for: type(of: self)) guard let url = bundle.url(forResource: name, withExtension: withExtension) else { return nil } #endif - return url + let data = try? Data(contentsOf: url) + return data } // MARK: - Positive Tests diff --git a/Tests/SpeechToTextV1Tests/SpeechToTextTests.swift b/Tests/SpeechToTextV1Tests/SpeechToTextTests.swift index 2723e335a..27ccf72d3 100644 --- a/Tests/SpeechToTextV1Tests/SpeechToTextTests.swift +++ b/Tests/SpeechToTextV1Tests/SpeechToTextTests.swift @@ -163,10 +163,11 @@ class SpeechToTextTests: XCTestCase { func addTrainingData(to languageModel: LanguageModel) { let expectation = self.expectation(description: "addCorpus") let file = Bundle(for: type(of: self)).url(forResource: "healthcare-short", withExtension: "txt")! + let fileData = try! Data(contentsOf: file) speechToText.addCorpus( customizationID: languageModel.customizationID, corpusName: "swift-test-corpus", - corpusFile: file, + corpusFile: fileData, allowOverwrite: true) { _, error in @@ -186,8 +187,8 @@ class SpeechToTextTests: XCTestCase { customizationID: acousticModel.customizationID, audioName: "audio", audioResource: audio, - contentType: "audio/wav", - allowOverwrite: true) + allowOverwrite: true, + contentType: "audio/wav") { _, error in if let error = error { @@ -331,7 +332,7 @@ class SpeechToTextTests: XCTestCase { func testRecognizeSessionless() { let expectation = self.expectation(description: "recognizeSessionless") let audio = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "SpeechSample", withExtension: "wav")!) - speechToText.recognize(audio: audio, contentType: "audio/wav", model: "en-US_BroadbandModel") { + speechToText.recognize(audio: audio, model: "en-US_BroadbandModel", contentType: "audio/wav") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -359,7 +360,7 @@ class SpeechToTextTests: XCTestCase { let expectation1 = self.expectation(description: "createJob") let audio = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "SpeechSample", withExtension: "wav")!) var job: RecognitionJob! - speechToText.createJob(audio: audio, contentType: "audio/wav", model: "en-US_BroadbandModel") { + speechToText.createJob(audio: audio, model: "en-US_BroadbandModel", contentType: "audio/wav") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -585,7 +586,8 @@ class SpeechToTextTests: XCTestCase { let id = languageModel.customizationID let corpusName = "test-corpus" let file = Bundle(for: type(of: self)).url(forResource: "healthcare-short", withExtension: "txt")! - speechToText.addCorpus(customizationID: id, corpusName: corpusName, corpusFile: file, allowOverwrite: true) { + let fileData = try! Data(contentsOf: file) + speechToText.addCorpus(customizationID: id, corpusName: corpusName, corpusFile: fileData, allowOverwrite: true) { _, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -955,7 +957,7 @@ class SpeechToTextTests: XCTestCase { // add audio resource to acoustic model let expectation1 = self.expectation(description: "addAudio") let audio = try! Data(contentsOf: Bundle(for: type(of: self)).url(forResource: "SpeechSample", withExtension: "wav")!) - speechToText.addAudio(customizationID: acousticModel.customizationID, audioName: "audio", audioResource: audio, contentType: "audio/wav", allowOverwrite: true) { + speechToText.addAudio(customizationID: acousticModel.customizationID, audioName: "audio", audioResource: audio, allowOverwrite: true, contentType: "audio/wav") { _, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) diff --git a/Tests/TestUtilities.swift b/Tests/TestUtilities.swift index 52b1a5037..c3da3f00f 100644 --- a/Tests/TestUtilities.swift +++ b/Tests/TestUtilities.swift @@ -33,7 +33,7 @@ func missingBodyMessage(_ error: Error) -> String { // MARK: - Service instantiation let accessToken = "my_access_token" -let versionDate = "2019-01-11" +let versionDate = "2019-03-29" // MARK: - Mocking requests diff --git a/Tests/TextToSpeechV1Tests/TextToSpeechPlaybackTests.swift b/Tests/TextToSpeechV1Tests/TextToSpeechPlaybackTests.swift index 14ec8ff5a..622f2b6a8 100644 --- a/Tests/TextToSpeechV1Tests/TextToSpeechPlaybackTests.swift +++ b/Tests/TextToSpeechV1Tests/TextToSpeechPlaybackTests.swift @@ -101,7 +101,7 @@ class TextToSpeechPlaybackTests: XCTestCase { let description = "Synthesize text to spoken audio." let expectation = self.expectation(description: description) - textToSpeech.synthesize(text: text, accept: "audio/wav", voice: "en-US_LisaVoice") { + textToSpeech.synthesize(text: text, voice: "en-US_LisaVoice", accept: "audio/wav") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -132,7 +132,7 @@ class TextToSpeechPlaybackTests: XCTestCase { let description = "Synthesize text to spoken audio." let expectation = self.expectation(description: description) - textToSpeech.synthesize(text: germanText, accept: "audio/wav", voice: "de-DE_DieterVoice") { + textToSpeech.synthesize(text: germanText, voice: "de-DE_DieterVoice", accept: "audio/wav") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -163,7 +163,7 @@ class TextToSpeechPlaybackTests: XCTestCase { let description = "Synthesize text to spoken audio." let expectation = self.expectation(description: description) - textToSpeech.synthesize(text: japaneseText, accept: "audio/wav", voice: "ja-JP_EmiVoice") { + textToSpeech.synthesize(text: japaneseText, voice: "ja-JP_EmiVoice", accept: "audio/wav") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift index 8e823fce2..f25a5ffb5 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognition+UIImageTests.swift @@ -148,10 +148,10 @@ class VisualRecognitionUIImageTests: XCTestCase { // verify the face location let location = face?.faces.first?.faceLocation - XCTAssertEqual(location?.height, 174) + XCTAssertEqual(location?.height, 172) XCTAssertEqual(location?.left, 219) - XCTAssertEqual(location?.top, 78) - XCTAssertEqual(location?.width, 143) + XCTAssertEqual(location?.top, 79) + XCTAssertEqual(location?.width, 141) // verify the gender let gender = face?.faces.first?.gender diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionTestUtilities.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionTestUtilities.swift index f137a5712..c232485e7 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionTestUtilities.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionTestUtilities.swift @@ -18,15 +18,15 @@ import Foundation import XCTest import VisualRecognitionV3 -let car: URL = loadResource(name: "car", ext: "png") -let cars: URL = loadResource(name: "cars", ext: "zip") -let carz: URL = loadResource(name: "carz", ext: "zip") -let trucks: URL = loadResource(name: "trucks", ext: "zip") -let baseball: URL = loadResource(name: "baseball", ext: "zip") -let faces: URL = loadResource(name: "faces", ext: "zip") -let face1: URL = loadResource(name: "face1", ext: "jpg") -let obama: URL = loadResource(name: "obama", ext: "jpg") -let sign: URL = loadResource(name: "sign", ext: "jpg") +let car: Data = loadResource(name: "car", ext: "png") +let cars: Data = loadResource(name: "cars", ext: "zip") +let carz: Data = loadResource(name: "carz", ext: "zip") +let trucks: Data = loadResource(name: "trucks", ext: "zip") +let baseball: Data = loadResource(name: "baseball", ext: "zip") +let faces: Data = loadResource(name: "faces", ext: "zip") +let face1: Data = loadResource(name: "face1", ext: "jpg") +let obama: Data = loadResource(name: "obama", ext: "jpg") +let sign: Data = loadResource(name: "sign", ext: "jpg") let obamaURL = "https://www.whitehouse.gov/sites/whitehouse.gov/files/images/" + "Administration/People/president_official_portrait_lores.jpg" @@ -35,15 +35,19 @@ let carURL = "https://raw.githubusercontent.com/watson-developer-cloud/java-sdk" let signURL = "https://raw.githubusercontent.com/watson-developer-cloud/java-sdk/" + "master/visual-recognition/src/test/resources/visual_recognition/open.png" -func loadResource(name: String, ext: String) -> URL { +func loadResource(name: String, ext: String) -> Data { #if os(Linux) - return URL(fileURLWithPath: "Tests/VisualRecognitionV3Tests/Resources/" + name + "." + ext) + let url = URL(fileURLWithPath: "Tests/VisualRecognitionV3Tests/Resources/" + name + "." + ext) #else let bundle = Bundle(for: VisualRecognitionTests.self) guard let url = bundle.url(forResource: name, withExtension: ext) else { XCTFail("Unable to locate sample image files.") assert(false) } - return url #endif + guard let data = try? Data(contentsOf: url) else { + XCTFail("Unable to locate sample image files.") + assert(false) + } + return data } diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift index fe1e9aa3e..b2fdea826 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift @@ -544,7 +544,7 @@ class VisualRecognitionTests: XCTestCase { func testClassifyByURL1() { let expectation = self.expectation(description: "Classify an image by URL") - visualRecognition.classify(acceptLanguage: "en", url: obamaURL) { + visualRecognition.classify(url: obamaURL, acceptLanguage: "en") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -599,11 +599,11 @@ class VisualRecognitionTests: XCTestCase { func testClassifyByURL2() { let expectation = self.expectation(description: "Classify an image by URL using the default classifier.") visualRecognition.classify( - acceptLanguage: "en", url: obamaURL, threshold: 0.5, owners: ["IBM"], - classifierIDs: ["default"]) + classifierIDs: ["default"], + acceptLanguage: "en") { response, error in if let error = error { @@ -658,9 +658,9 @@ class VisualRecognitionTests: XCTestCase { func testClassifyByURL3() { let expectation = self.expectation(description: "Classify an image by URL using a custom classifier.") visualRecognition.classify( - acceptLanguage: "en", url: carURL, - classifierIDs: [classifierID]) + classifierIDs: [classifierID], + acceptLanguage: "en") { response, error in if let error = error { @@ -702,11 +702,11 @@ class VisualRecognitionTests: XCTestCase { func testClassifyByURL4() { let expectation = self.expectation(description: "Classify an image by URL using a custom classifier.") visualRecognition.classify( - acceptLanguage: "en", url: carURL, threshold: 0.5, owners: ["me"], - classifierIDs: [classifierID]) + classifierIDs: [classifierID], + acceptLanguage: "en") { response, error in if let error = error { @@ -747,7 +747,7 @@ class VisualRecognitionTests: XCTestCase { /** Classify an image by URL with both the default classifier and a custom classifier. */ func testClassifyByURL5() { let expectation = self.expectation(description: "Classify an image by URL using a custom classifier.") - visualRecognition.classify(acceptLanguage: "en", url: carURL, classifierIDs: ["default", classifierID]) { + visualRecognition.classify(url: carURL, classifierIDs: ["default", classifierID]) { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -810,7 +810,7 @@ class VisualRecognitionTests: XCTestCase { /** Classify an uploaded image using the default classifier and all default parameters. */ func testClassifyImage1() { let expectation = self.expectation(description: "Classify an uploaded image using the default classifier.") - visualRecognition.classify(imagesFile: car, acceptLanguage: "en") { + visualRecognition.classify(imagesFile: car, imagesFilename: "car.png", acceptLanguage: "en") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -863,7 +863,7 @@ class VisualRecognitionTests: XCTestCase { let expectation = self.expectation(description: "Classify an uploaded image using the default classifier.") visualRecognition.classify( imagesFile: car, - acceptLanguage: "en", + imagesFilename: "car.png", threshold: 0.5, owners: ["IBM"], classifierIDs: ["default"]) @@ -921,7 +921,7 @@ class VisualRecognitionTests: XCTestCase { let expectation = self.expectation(description: "Classify an uploaded image using a custom classifier.") visualRecognition.classify( imagesFile: car, - acceptLanguage: "en", + imagesFilename: "car.png", classifierIDs: [classifierID]) { response, error in if let error = error { @@ -964,7 +964,7 @@ class VisualRecognitionTests: XCTestCase { let expectation = self.expectation(description: "Classify an uploaded image using a custom classifier.") visualRecognition.classify( imagesFile: car, - acceptLanguage: "en", + imagesFilename: "car.png", threshold: 0.5, owners: ["me"], classifierIDs: [classifierID]) @@ -1010,7 +1010,7 @@ class VisualRecognitionTests: XCTestCase { let expectation = self.expectation(description: "Classify an uploaded image with the default and custom classifiers.") visualRecognition.classify( imagesFile: car, - acceptLanguage: "en", + imagesFilename: "car.png", classifierIDs: ["default", classifierID]) { response, error in @@ -1078,7 +1078,7 @@ class VisualRecognitionTests: XCTestCase { let expectation = self.expectation(description: "Classify multiple images using a custom classifier.") visualRecognition.classify( imagesFile: carz, - acceptLanguage: "en", + imagesFilename: "cars.zip", classifierIDs: ["default", classifierID]) { response, error in @@ -1192,7 +1192,7 @@ class VisualRecognitionTests: XCTestCase { /** Detect faces in an uploaded image */ func testDetectFacesByImage1() { let expectation = self.expectation(description: "Detect faces in an uploaded image.") - visualRecognition.detectFaces(imagesFile: obama) { + visualRecognition.detectFaces(imagesFile: obama, imagesFilename: "obama.jpg") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -1242,7 +1242,7 @@ class VisualRecognitionTests: XCTestCase { /** Detect faces in uploaded images. */ func testDetectFacesByImage2() { let expectation = self.expectation(description: "Detect faces in uploaded images.") - visualRecognition.detectFaces(imagesFile: faces) { + visualRecognition.detectFaces(imagesFile: faces, imagesFilename: "faces.zip") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift index 79a87dc73..cbc4aefa8 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift @@ -59,8 +59,10 @@ class VisualRecognitionUnitTests: XCTestCase { XCTAssertEqual(statusCode, 403) XCTAssertNotNil(message) XCTAssertNotNil(metadata) - XCTAssertNotNil(metadata!["status"]) - XCTAssertNotNil(metadata!["statusInfo"]) + XCTAssertNotNil(metadata?["response"] as? [String: Any]) + let response = metadata?["response"] as? [String: Any] + XCTAssertNotNil(response?["status"]) + XCTAssertNotNil(response?["statusInfo"]) } } @@ -78,8 +80,15 @@ class VisualRecognitionUnitTests: XCTestCase { if case let .http(statusCode, message, metadata) = error { XCTAssertEqual(statusCode, 404) XCTAssertNotNil(message) - XCTAssertNotNil(metadata?["description"]) - XCTAssertNotNil(metadata?["errorID"]) + XCTAssertNotNil(metadata?["response"] as? [String: JSON]) + let response = metadata?["response"] as? [String: JSON] + XCTAssertNotNil(response?["error"]) + if case let .some(.object(responseError)) = response?["error"] { + XCTAssertNotNil(responseError["description"]) + XCTAssertNotNil(responseError["error_id"]) + } else { + XCTFail("error not present in response") + } } } @@ -114,8 +123,10 @@ class VisualRecognitionUnitTests: XCTestCase { let error = visualRecognition.errorResponseDecoder(data: testData, response: testResponse) if case let .http(statusCode, message, metadata) = error { XCTAssertEqual(statusCode, 500) - XCTAssertNil(message) - XCTAssertNil(metadata) + XCTAssertNotNil(message) + XCTAssertEqual("internal server error", message) + XCTAssertNotNil(metadata) + XCTAssertNotNil(metadata?["response"]) } } @@ -139,7 +150,7 @@ class VisualRecognitionUnitTests: XCTestCase { } let expectation = self.expectation(description: "classify") - visualRecognition.classify(imagesFile: obama, acceptLanguage: "en", url: "http://example.com", threshold: 1.0, owners: owners, classifierIDs: classifierIDs, imagesFileContentType: "png") { + visualRecognition.classify(imagesFile: obama, imagesFileContentType: "png", url: "http://example.com", threshold: 1.0, owners: owners, classifierIDs: classifierIDs) { _, _ in expectation.fulfill() } @@ -543,7 +554,6 @@ class VisualRecognitionUnitTests: XCTestCase { func testClassifyWithLocalModel() { if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { let classifierIDs = ["watson_tools"] - let data = try! Data(contentsOf: car) // Save a CoreML file to the Application Support directory on the simulator for the duration of this test saveCoreMLModelToSimulator(name: classifierIDs.first!, modelURL: watson_tools.urlOfModelInThisBundle) @@ -565,7 +575,7 @@ class VisualRecognitionUnitTests: XCTestCase { } let expectation = self.expectation(description: "classifyWithLocalModel") - visualRecognition.classifyWithLocalModel(imageData: data, classifierIDs: classifierIDs, threshold: 1.0) { + visualRecognition.classifyWithLocalModel(imageData: car, classifierIDs: classifierIDs, threshold: 1.0) { _, _ in expectation.fulfill() } @@ -651,7 +661,7 @@ class VisualRecognitionUnitTests: XCTestCase { func testClassifyWithImage() { let owners = ["Anthony", "Mike"] let classifierIDs = ["1", "2"] - let image = UIImage(contentsOfFile: car.path)! + let image = UIImage(data: car)! MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -675,7 +685,7 @@ class VisualRecognitionUnitTests: XCTestCase { } func testDetectFacesWithImage() { - let image = UIImage(contentsOfFile: obama.path)! + let image = UIImage(data: obama)! MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") @@ -701,7 +711,7 @@ class VisualRecognitionUnitTests: XCTestCase { func testClassifyWithLocalModelUIImage() { if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, *) { let classifierIDs = ["1"] - let image = UIImage(contentsOfFile: car.path)! + let image = UIImage(data: car)! MockURLProtocol.requestHandler = { request in XCTAssertEqual(request.httpMethod, "POST") diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionWithIAMTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionWithIAMTests.swift index efcafc764..7b68db6bb 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionWithIAMTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionWithIAMTests.swift @@ -90,7 +90,7 @@ class VisualRecognitionWithIAMTests: XCTestCase { let expectation = self.expectation(description: "Access service using IAM API Key WatsonCredentials.") - visualRecognition.classify(acceptLanguage: "en", url: ginniURL) { + visualRecognition.classify(url: ginniURL, acceptLanguage: "en") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -145,7 +145,7 @@ class VisualRecognitionWithIAMTests: XCTestCase { // Verify access to the service using the access token let expectation = self.expectation(description: "Access VR service with access token") - visualRecognition.classify(acceptLanguage: "en", url: obamaURL) { + visualRecognition.classify(url: obamaURL, acceptLanguage: "en") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) @@ -192,7 +192,7 @@ class VisualRecognitionWithIAMTests: XCTestCase { // Verify access to the service using the refreshed access token let expectation2 = self.expectation(description: "Access VR service with refreshed access token") - visualRecognition.classify(acceptLanguage: "en", url: trumpURL) { + visualRecognition.classify(url: trumpURL, acceptLanguage: "en") { response, error in if let error = error { XCTFail(unexpectedErrorMessage(error)) diff --git a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV2.xcscheme b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV2.xcscheme index 4aa4de680..ed2708f9c 100644 --- a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV2.xcscheme +++ b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/AssistantV2.xcscheme @@ -32,9 +32,9 @@ diff --git a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/CompareComplyV1.xcscheme b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/CompareComplyV1.xcscheme index 25c0e3669..568a19dc0 100644 --- a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/CompareComplyV1.xcscheme +++ b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/CompareComplyV1.xcscheme @@ -26,7 +26,18 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + codeCoverageEnabled = "YES" + onlyGenerateCoverageForSpecifiedTargets = "YES" shouldUseLaunchSchemeArgsEnv = "YES"> + + + + diff --git a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/VisualRecognitionV3.xcscheme b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/VisualRecognitionV3.xcscheme index f732cf5cd..937eacb56 100644 --- a/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/VisualRecognitionV3.xcscheme +++ b/WatsonDeveloperCloud.xcodeproj/xcshareddata/xcschemes/VisualRecognitionV3.xcscheme @@ -49,12 +49,6 @@ ReferencedContainer = "container:WatsonDeveloperCloud.xcodeproj"> - - - - From 1a3b0c5a61784ba0786b56923f5fedda2e7a75ac Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Sun, 10 Mar 2019 09:26:25 -0700 Subject: [PATCH 07/13] feat: Update Carthage and Cocoapods dependency to RestKit 3.0 --- Cartfile | 2 +- Cartfile.resolved | 2 +- IBMWatsonAssistantV1.podspec | 8 +++--- IBMWatsonAssistantV2.podspec | 8 +++--- IBMWatsonCompareComplyV1.podspec | 6 ++--- IBMWatsonDiscoveryV1.podspec | 10 +++---- IBMWatsonLanguageTranslatorV3.podspec | 2 +- IBMWatsonNaturalLanguageClassifierV1.podspec | 10 +++---- ...tsonNaturalLanguageUnderstandingV1.podspec | 8 +++--- IBMWatsonPersonalityInsightsV3.podspec | 6 ++--- IBMWatsonSpeechToTextV1.podspec | 10 +++---- IBMWatsonTextToSpeechV1.podspec | 6 ++--- IBMWatsonToneAnalyzerV3.podspec | 8 +++--- IBMWatsonVisualRecognitionV3.podspec | 8 +++--- .../SpeechToText+Recognize.swift | 2 +- .../WebSockets/SpeechToTextSession.swift | 6 ++--- .../WebSockets/SpeechToTextSocket.swift | 4 +-- .../VisualRecognition+CoreML.swift | 26 +++++++++---------- .../VisualRecognitionUnitTests.swift | 2 +- 19 files changed, 67 insertions(+), 67 deletions(-) diff --git a/Cartfile b/Cartfile index 8757d702a..b110f11fb 100644 --- a/Cartfile +++ b/Cartfile @@ -1,2 +1,2 @@ github "daltoniam/Starscream" == 3.0.5 -github "watson-developer-cloud/restkit" ~> 2.0.0 +github "watson-developer-cloud/restkit" ~> 3.0 diff --git a/Cartfile.resolved b/Cartfile.resolved index c67667b17..342cb7214 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ github "daltoniam/Starscream" "3.0.5" -github "watson-developer-cloud/restkit" "2.0.0" +github "watson-developer-cloud/restkit" "3.0.0" diff --git a/IBMWatsonAssistantV1.podspec b/IBMWatsonAssistantV1.podspec index 99e5bb604..4e8c2d09b 100644 --- a/IBMWatsonAssistantV1.podspec +++ b/IBMWatsonAssistantV1.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Assistant service' s.description = <<-DESC -With the IBM Watson™ Assistant service, you can build a solution that understands +With the IBM Watson™ Assistant service, you can build a solution that understands natural-language input and uses machine learning to respond to customers in a way that simulates a conversation between humans. DESC s.homepage = 'https://www.ibm.com/watson/ai-assistant/' @@ -15,11 +15,11 @@ natural-language input and uses machine learning to respond to customers in a wa s.module_name = 'Assistant' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/AssistantV1/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/AssistantV1/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonAssistantV2.podspec b/IBMWatsonAssistantV2.podspec index eaa160e92..2b8c9f248 100644 --- a/IBMWatsonAssistantV2.podspec +++ b/IBMWatsonAssistantV2.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Assistant service' s.description = <<-DESC -With the IBM Watson™ Assistant service, you can build a solution that understands +With the IBM Watson™ Assistant service, you can build a solution that understands natural-language input and uses machine learning to respond to customers in a way that simulates a conversation between humans. DESC s.homepage = 'https://www.ibm.com/watson/ai-assistant/' @@ -15,11 +15,11 @@ natural-language input and uses machine learning to respond to customers in a wa s.module_name = 'Assistant' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/AssistantV2/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/AssistantV2/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonCompareComplyV1.podspec b/IBMWatsonCompareComplyV1.podspec index 7c1f22c12..88315b29b 100644 --- a/IBMWatsonCompareComplyV1.podspec +++ b/IBMWatsonCompareComplyV1.podspec @@ -13,11 +13,11 @@ IBM Watson™ Compare and Comply analyzes governing documents to provide details s.module_name = 'CompareComply' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/CompareComplyV1/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/CompareComplyV1/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonDiscoveryV1.podspec b/IBMWatsonDiscoveryV1.podspec index 93bb8acfa..9f5092059 100644 --- a/IBMWatsonDiscoveryV1.podspec +++ b/IBMWatsonDiscoveryV1.podspec @@ -4,8 +4,8 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Discovery service' s.description = <<-DESC -IBM Watson™ Discovery makes it possible to rapidly build cognitive, cloud-based exploration applications -that unlock actionable insights hidden in unstructured data — including your own proprietary data, +IBM Watson™ Discovery makes it possible to rapidly build cognitive, cloud-based exploration applications +that unlock actionable insights hidden in unstructured data — including your own proprietary data, as well as public and third-party data. DESC s.homepage = 'https://www.ibm.com/watson/services/discovery/' @@ -16,11 +16,11 @@ as well as public and third-party data. s.module_name = 'Discovery' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/DiscoveryV1/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/DiscoveryV1/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonLanguageTranslatorV3.podspec b/IBMWatsonLanguageTranslatorV3.podspec index b2144d6ce..4e7f8dae6 100644 --- a/IBMWatsonLanguageTranslatorV3.podspec +++ b/IBMWatsonLanguageTranslatorV3.podspec @@ -19,6 +19,6 @@ IBM Watson™ Language Translator can identify the language of text and translat 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/LanguageTranslatorV3/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonNaturalLanguageClassifierV1.podspec b/IBMWatsonNaturalLanguageClassifierV1.podspec index 5e24a04ac..f58f2278d 100644 --- a/IBMWatsonNaturalLanguageClassifierV1.podspec +++ b/IBMWatsonNaturalLanguageClassifierV1.podspec @@ -4,8 +4,8 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Natural Language Classifier service' s.description = <<-DESC -Natural Language Classifier can help your application understand the language of short texts and -make predictions about how to handle them. A classifier learns from your example data and then can +Natural Language Classifier can help your application understand the language of short texts and +make predictions about how to handle them. A classifier learns from your example data and then can return information for texts that it is not trained on. DESC s.homepage = 'https://www.ibm.com/watson/services/natural-language-classifier/' @@ -16,11 +16,11 @@ return information for texts that it is not trained on. s.module_name = 'NaturalLanguageClassifier' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/NaturalLanguageClassifierV1/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/NaturalLanguageClassifierV1/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonNaturalLanguageUnderstandingV1.podspec b/IBMWatsonNaturalLanguageUnderstandingV1.podspec index a2176270e..d6c1b409f 100644 --- a/IBMWatsonNaturalLanguageUnderstandingV1.podspec +++ b/IBMWatsonNaturalLanguageUnderstandingV1.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Natural Language Understanding service' s.description = <<-DESC -IBM Watson™ Natural Language Understanding can analyze semantic features of text input, +IBM Watson™ Natural Language Understanding can analyze semantic features of text input, including categories, concepts, emotion, entities, keywords, metadata, relations, semantic roles, and sentiment. DESC s.homepage = 'https://www.ibm.com/watson/services/natural-language-understanding/' @@ -15,11 +15,11 @@ including categories, concepts, emotion, entities, keywords, metadata, relations s.module_name = 'NaturalLanguageUnderstanding' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/NaturalLanguageUnderstandingV1/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/NaturalLanguageUnderstandingV1/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonPersonalityInsightsV3.podspec b/IBMWatsonPersonalityInsightsV3.podspec index ea4712eea..333333dfb 100644 --- a/IBMWatsonPersonalityInsightsV3.podspec +++ b/IBMWatsonPersonalityInsightsV3.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Personality Insights service' s.description = <<-DESC -IBM Watson™ Personality Insights uses linguistic analytics to infer individuals' intrinsic personality characteristics +IBM Watson™ Personality Insights uses linguistic analytics to infer individuals' intrinsic personality characteristics from digital communications such as email, text messages, tweets, and forum posts. DESC s.homepage = 'https://www.ibm.com/watson/services/personality-insights/' @@ -20,6 +20,6 @@ from digital communications such as email, text messages, tweets, and forum post 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/PersonalityInsightsV3/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/IBMWatsonSpeechToTextV1.podspec b/IBMWatsonSpeechToTextV1.podspec index 54de47c3d..688a885df 100644 --- a/IBMWatsonSpeechToTextV1.podspec +++ b/IBMWatsonSpeechToTextV1.podspec @@ -4,8 +4,8 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Speech to Text service' s.description = <<-DESC -The IBM® Speech to Text leverages machine intelligence to transcribe the human voice accurately. -The service combines information about grammar and language structure with knowledge of the composition +The IBM® Speech to Text leverages machine intelligence to transcribe the human voice accurately. +The service combines information about grammar and language structure with knowledge of the composition of the audio signal. It continuously returns and retroactively updates a transcription as more speech is heard. DESC s.homepage = 'https://www.ibm.com/watson/services/speech-to-text/' @@ -16,7 +16,7 @@ of the audio signal. It continuously returns and retroactively updates a transcr s.module_name = 'SpeechToText' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/SpeechToTextV1/**/*.swift', 'Source/SupportingFiles/Shared.swift', 'Source/SupportingFiles/Dependencies/Source/**/*' @@ -25,12 +25,12 @@ of the audio signal. It continuously returns and retroactively updates a transcr '**/opus_header.h', '**/opus_header.c' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' s.dependency 'Starscream', '3.0.5' s.vendored_libraries = 'Source/SupportingFiles/Dependencies/Libraries/*.a' # The renaming of libogg.a and libopus.a is done to avoid duplicate library name errors - # in case TextToSpeech is being installed in the same app (which also includes libogg and libopus) + # in case TextToSpeech is being installed in the same app (which also includes libogg and libopus) # The ogg/ and opus/ files are flattened to the same directory so that all #include statements work s.prepare_command = <<-CMD cd Source/SupportingFiles/Dependencies/Libraries diff --git a/IBMWatsonTextToSpeechV1.podspec b/IBMWatsonTextToSpeechV1.podspec index 73ec96d2d..fe29ffa23 100644 --- a/IBMWatsonTextToSpeechV1.podspec +++ b/IBMWatsonTextToSpeechV1.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Text to Speech service' s.description = <<-DESC -IBM® Text to Speech uses IBM's speech-synthesis capabilities to convert written text to natural-sounding speech. +IBM® Text to Speech uses IBM's speech-synthesis capabilities to convert written text to natural-sounding speech. The service streams the results back to the client with minimal delay. DESC s.homepage = 'https://www.ibm.com/watson/services/text-to-speech/' @@ -22,11 +22,11 @@ The service streams the results back to the client with minimal delay. s.exclude_files = 'Source/TextToSpeechV1/Shared.swift', '**/config_types.h' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' s.vendored_libraries = 'Source/SupportingFiles/Dependencies/Libraries/*.a' # The renaming of libogg.a and libopus.a is done to avoid duplicate library name errors - # in case SpeechToText is being installed in the same app (which also includes libogg and libopus) + # in case SpeechToText is being installed in the same app (which also includes libogg and libopus) # The ogg/ and opus/ files are flattened to the same directory so that all #include statements work s.prepare_command = <<-CMD cd Source/SupportingFiles/Dependencies/Libraries diff --git a/IBMWatsonToneAnalyzerV3.podspec b/IBMWatsonToneAnalyzerV3.podspec index d50d482a9..f7a0e402e 100644 --- a/IBMWatsonToneAnalyzerV3.podspec +++ b/IBMWatsonToneAnalyzerV3.podspec @@ -1,10 +1,10 @@ Pod::Spec.new do |s| - + s.name = 'IBMWatsonToneAnalyzerV3' s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Tone Analyzer service' s.description = <<-DESC -IBM Watson™ Tone Analyzer uses linguistic analysis to detect emotional and language tones in written text. +IBM Watson™ Tone Analyzer uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and sentence levels. DESC s.homepage = 'https://www.ibm.com/watson/services/tone-analyzer/' @@ -15,11 +15,11 @@ The service can analyze tone at both the document and sentence levels. s.module_name = 'ToneAnalyzer' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/ToneAnalyzerV3/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/ToneAnalyzerV3/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonVisualRecognitionV3.podspec b/IBMWatsonVisualRecognitionV3.podspec index a7a585ab5..30ae3207e 100644 --- a/IBMWatsonVisualRecognitionV3.podspec +++ b/IBMWatsonVisualRecognitionV3.podspec @@ -4,7 +4,7 @@ Pod::Spec.new do |s| s.version = '1.4.0' s.summary = 'Client framework for the IBM Watson Visual Recognition service' s.description = <<-DESC -IBM Watson™ Visual Recognition uses deep learning algorithms to analyze images for +IBM Watson™ Visual Recognition uses deep learning algorithms to analyze images for scenes, objects, faces, and other content. The response includes keywords that provide information about the content. DESC s.homepage = 'https://www.ibm.com/watson/services/visual-recognition/' @@ -15,11 +15,11 @@ scenes, objects, faces, and other content. The response includes keywords that p s.module_name = 'VisualRecognition' s.ios.deployment_target = '10.0' s.source = { :git => 'https://github.com/watson-developer-cloud/swift-sdk.git', :tag => s.version.to_s } - + s.source_files = 'Source/VisualRecognitionV3/**/*.swift', 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/VisualRecognitionV3/Shared.swift' - s.dependency 'IBMWatsonRestKit', '~> 2.0.0' - + s.dependency 'IBMWatsonRestKit', '~> 3.0.0' + end diff --git a/Source/SpeechToTextV1/SpeechToText+Recognize.swift b/Source/SpeechToTextV1/SpeechToText+Recognize.swift index 33df54101..0c1154328 100644 --- a/Source/SpeechToTextV1/SpeechToText+Recognize.swift +++ b/Source/SpeechToTextV1/SpeechToText+Recognize.swift @@ -219,7 +219,7 @@ extension SpeechToText { try audioSession.setActive(true) } catch { let failureReason = "Failed to setup the AVAudioSession sharedInstance properly." - let error = WatsonError.other(message: failureReason) + let error = WatsonError.other(message: failureReason, metadata: nil) completionHandler(nil, error) return } diff --git a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift index 67efdcf7c..28bbaf173 100644 --- a/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift +++ b/Source/SpeechToTextV1/WebSockets/SpeechToTextSession.swift @@ -329,7 +329,7 @@ public class SpeechToTextSession { recorder.session.requestRecordPermission { granted in guard granted else { let failureReason = "Permission was not granted to access the microphone." - let error = WatsonError.other(message: failureReason) + let error = WatsonError.other(message: failureReason, metadata: nil) self.onError?(error) return } @@ -366,7 +366,7 @@ public class SpeechToTextSession { try self.recorder.startRecording() } catch { let failureReason = "Failed to start recording." - let error = WatsonError.other(message: failureReason) + let error = WatsonError.other(message: failureReason, metadata: nil) self.onError?(error) return } @@ -381,7 +381,7 @@ public class SpeechToTextSession { try recorder.stopRecording() } catch { let failureReason = "Failed to stop recording." - let error = WatsonError.other(message: failureReason) + let error = WatsonError.other(message: failureReason, metadata: nil) self.onError?(error) return } diff --git a/Source/SpeechToTextV1/WebSockets/SpeechToTextSocket.swift b/Source/SpeechToTextV1/WebSockets/SpeechToTextSocket.swift index 75453c7af..00bbe66b0 100644 --- a/Source/SpeechToTextV1/WebSockets/SpeechToTextSocket.swift +++ b/Source/SpeechToTextV1/WebSockets/SpeechToTextSocket.swift @@ -208,7 +208,7 @@ internal class SpeechToTextSocket: WebSocketDelegate { } private func onErrorMessage(error: String) { - let error = WatsonError.other(message: error) + let error = WatsonError.other(message: error, metadata: nil) onError?(error) } @@ -272,7 +272,7 @@ internal class SpeechToTextSocket: WebSocketDelegate { self.connect() return } - onError?(WatsonError.other(message: String(describing: error))) + onError?(WatsonError.other(message: String(describing: error), metadata: nil)) onDisconnect?() } } diff --git a/Source/VisualRecognitionV3/VisualRecognition+CoreML.swift b/Source/VisualRecognitionV3/VisualRecognition+CoreML.swift index eef6e5d20..bce9cd973 100644 --- a/Source/VisualRecognitionV3/VisualRecognition+CoreML.swift +++ b/Source/VisualRecognitionV3/VisualRecognition+CoreML.swift @@ -146,7 +146,7 @@ extension VisualRecognition { { // ensure a classifier id was provided guard !classifierIDs.isEmpty else { - let error = WatsonError.other(message: "Please provide at least one classifierID.") + let error = WatsonError.other(message: "Please provide at least one classifierID.", metadata: nil) completionHandler(nil, error) return } @@ -166,7 +166,7 @@ extension VisualRecognition { model = try self.loadModelFromDisk(classifierID: classifierID) } catch { dispatchGroup.leave() - let error = WatsonError.other(message: "Failed to load model for classifier \(classifierID): \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to load model for classifier \(classifierID): \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -177,7 +177,7 @@ extension VisualRecognition { classifier = try VNCoreMLModel(for: model) } catch { dispatchGroup.leave() - let error = WatsonError.other(message: "Failed to convert model for classifier \(classifierID): \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to convert model for classifier \(classifierID): \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -186,13 +186,13 @@ extension VisualRecognition { let request = VNCoreMLRequest(model: classifier) { request, error in if let error = error { dispatchGroup.leave() - let error = WatsonError.other(message: "Classifier \(classifierID) failed with error: \(error)") + let error = WatsonError.other(message: "Classifier \(classifierID) failed with error: \(error)", metadata: nil) completionHandler(nil, error) return } guard let observations = request.results as? [VNClassificationObservation] else { dispatchGroup.leave() - let error = WatsonError.other(message: "Failed to parse results for classifier \(classifierID)") + let error = WatsonError.other(message: "Failed to parse results for classifier \(classifierID)", metadata: nil) completionHandler(nil, error) return } @@ -209,7 +209,7 @@ extension VisualRecognition { try requestHandler.perform([request]) } catch { dispatchGroup.leave() - let error = WatsonError.other(message: "Failed to process classification request: \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to process classification request: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -223,7 +223,7 @@ extension VisualRecognition { do { classifiedImages = try self.convert(results: results, threshold: threshold) } catch { - let error = WatsonError.other(message: "Failed to represent results as JSON: \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to represent results as JSON: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -255,7 +255,7 @@ extension VisualRecognition { } // model not found -> throw an error - let error = WatsonError.other(message: "Failed to locate a Core ML model on disk for classifier \(classifierID).") + let error = WatsonError.other(message: "Failed to locate a Core ML model on disk for classifier \(classifierID).", metadata: nil) throw error } @@ -359,7 +359,7 @@ extension VisualRecognition { create: true ) } catch { - let error = WatsonError.other(message: "Failed to create temporary downloads directory: \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to create temporary downloads directory: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -374,7 +374,7 @@ extension VisualRecognition { create: true ) } catch { - let error = WatsonError.other(message: "Failed to locate application support directory: \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to locate application support directory: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -409,7 +409,7 @@ extension VisualRecognition { do { compiledModelTemporaryURL = try MLModel.compileModel(at: sourceModelURL) } catch { - let error = WatsonError.other(message: "Could not compile Core ML model from source: \(error.localizedDescription)") + let error = WatsonError.other(message: "Could not compile Core ML model from source: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -423,7 +423,7 @@ extension VisualRecognition { try fileManager.copyItem(at: compiledModelTemporaryURL, to: compiledModelURL) } } catch { - let error = WatsonError.other(message: "Failed to move compiled model: \(error.localizedDescription)") + let error = WatsonError.other(message: "Failed to move compiled model: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) return } @@ -434,7 +434,7 @@ extension VisualRecognition { do { try compiledModelURL.setResourceValues(urlResourceValues) } catch { - let error = WatsonError.other(message: "Could not exclude compiled model from backup: \(error.localizedDescription)") + let error = WatsonError.other(message: "Could not exclude compiled model from backup: \(error.localizedDescription)", metadata: nil) completionHandler(nil, error) } diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift index cbc4aefa8..9b39bb765 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionUnitTests.swift @@ -614,7 +614,7 @@ class VisualRecognitionUnitTests: XCTestCase { visualRecognition.downloadClassifier(classifierID: classifierID) { _, error in - if case .some(WatsonError.other(let message)) = error, + if case .some(WatsonError.other(let message, _)) = error, let errorMessage = message { XCTAssertTrue(errorMessage.contains("Could not compile Core ML model from source")) } else { From 3c630f301687fc44bdd4e2b3b0596f1bd54d0a53 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Wed, 13 Mar 2019 17:25:39 -0400 Subject: [PATCH 08/13] refactor: Separate UserAgent from SDK headers --- .../SpeechToText+Recognize.swift | 8 +-- Source/SupportingFiles/Shared.swift | 56 +++++++++---------- Source/SupportingFiles/SharedTests.swift | 6 +- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/Source/SpeechToTextV1/SpeechToText+Recognize.swift b/Source/SpeechToTextV1/SpeechToText+Recognize.swift index 0c1154328..5992a5d6a 100644 --- a/Source/SpeechToTextV1/SpeechToText+Recognize.swift +++ b/Source/SpeechToTextV1/SpeechToText+Recognize.swift @@ -141,8 +141,8 @@ extension SpeechToText { if let headers = headers { session.defaultHeaders.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognizeUsingWebSocket") - session.defaultHeaders.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognizeUsingWebSocket") + session.defaultHeaders.merge(sdkHeaders) { (_, new) in new } // set callbacks session.onResults = { result in @@ -247,8 +247,8 @@ extension SpeechToText { if let headers = headers { session.defaultHeaders.merge(headers) { (_, new) in new } } - let metadataHeaders = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognizeMicrophone") - session.defaultHeaders.merge(metadataHeaders) { (_, new) in new } + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "recognizeMicrophone") + session.defaultHeaders.merge(sdkHeaders) { (_, new) in new } // set callbacks session.onResults = { result in diff --git a/Source/SupportingFiles/Shared.swift b/Source/SupportingFiles/Shared.swift index 79b6a3311..13dbce9d1 100644 --- a/Source/SupportingFiles/Shared.swift +++ b/Source/SupportingFiles/Shared.swift @@ -35,6 +35,33 @@ internal struct Shared { static let sdkVersion = "1.4.0" + /// The "User-Agent" header to be sent with every RestRequest + static let userAgent: String? = { + let sdk = "watson-apis-swift-sdk" + + let operatingSystem: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "macOS" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + let operatingSystemVersion: String = { + // swiftlint:disable:next identifier_name + let os = ProcessInfo.processInfo.operatingSystemVersion + return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" + }() + return "\(sdk)/\(sdkVersion) \(operatingSystem)/\(operatingSystemVersion)" + }() + /// For Basic Authentication, switch to using IAM tokens for "apikey" usernames, /// but only for api keys that are not for ICP (which currently does not support IAM token authentication) static func getAuthMethod(username: String, password: String) -> AuthenticationMethod { @@ -102,37 +129,10 @@ internal struct Shared { } /// These headers must be sent with every request in order to collect SDK metrics - static func getMetadataHeaders(serviceName: String, serviceVersion: String, methodName: String) -> [String: String] { - let userAgent: String = { - let sdk = "watson-apis-swift-sdk" - - let operatingSystem: String = { - #if os(iOS) - return "iOS" - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "macOS" - #elseif os(Linux) - return "Linux" - #else - return "Unknown" - #endif - }() - let operatingSystemVersion: String = { - // swiftlint:disable:next identifier_name - let os = ProcessInfo.processInfo.operatingSystemVersion - return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" - }() - return "\(sdk)-\(sdkVersion) \(operatingSystem) \(operatingSystemVersion)" - }() - + static func getSDKHeaders(serviceName: String, serviceVersion: String, methodName: String) -> [String: String] { let serviceInfo = "service_name=\(serviceName);service_version=\(serviceVersion);operation_id=\(methodName);async=true" return [ - "User-Agent": userAgent, "X-IBMCloud-SDK-Analytics": serviceInfo, ] } diff --git a/Source/SupportingFiles/SharedTests.swift b/Source/SupportingFiles/SharedTests.swift index be93a29c0..7bba7bebc 100644 --- a/Source/SupportingFiles/SharedTests.swift +++ b/Source/SupportingFiles/SharedTests.swift @@ -98,13 +98,13 @@ class SharedTests: XCTestCase { XCTAssertEqual(visualRecognitionCredentials["url"], "https://test.us-south.containers.mybluemix.net/visual-recognition/api") } - func testGetMetadataHeaders() { + func testHeaders() { let serviceName = "test-service" let serviceVersion = "v9" let methodName = "testMethod" - let headers = Shared.getMetadataHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: methodName) - let userAgentHeader = headers["User-Agent"] + let userAgentHeader = Shared.userAgent + let headers = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: methodName) let analyticsHeader = headers["X-IBMCloud-SDK-Analytics"] XCTAssertNotNil(userAgentHeader) From a8ec80439a5ca84892a47c55bcb02e508ccd02c2 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Mon, 11 Mar 2019 10:01:42 -0700 Subject: [PATCH 09/13] feat: Rework init methods --- README.md | 46 +++++++++++-------- Source/SupportingFiles/Shared.swift | 34 +++++++++----- Source/SupportingFiles/SharedTests.swift | 25 ---------- Source/SupportingFiles/ibm-credentials.env | 7 ++- Tests/AssistantV1Tests/AssistantTests.swift | 39 ++++++++++++++-- Tests/AssistantV2Tests/AssistantV2Tests.swift | 2 +- Tests/DiscoveryV1Tests/DiscoveryTests.swift | 41 +++++++++++++++-- .../LanguageTranslatorTests.swift | 2 +- .../NaturalLanguageUnderstandingV1Tests.swift | 2 +- .../PersonalityInsightsTests.swift | 2 +- .../ToneAnalyzerTests.swift | 2 +- .../VisualRecognitionTests.swift | 35 ++++++++++++-- 12 files changed, 164 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 9604b6e56..9d11bb160 100755 --- a/README.md +++ b/README.md @@ -140,11 +140,8 @@ dependencies: [ ## Authentication -Watson services are migrating to token-based Identity and Access Management (IAM) authentication. - -- With some service instances, you authenticate to the API by using **[IAM](#iam)**. -- In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance. -- Visual Recognition uses a form of [API key](#api-key) only with instances created before May 23, 2018. Newer instances of Visual Recognition use [IAM](#iam). +The Identity and Access Management (IAM) service of the IBM Cloud is the primary method of authentication to IBM Cloud services. +Some service instances may use an alternate form of authentication, such as basic authentication (username and password). ### Getting credentials To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: @@ -156,16 +153,25 @@ To find out which authentication to use, view the service credentials. You find On this page, you will see your credentials to use in the SDK to access your service instance. ### Supplying credentials -There are two ways to supply the credentials from the steps above to the SDK: either downloading and using the credentials file, or copy-pasting the credentials into the SDK. -#### Credentials File +The SDK provides separate init methods for each form of authentication that may be used by instances of the service. + +- For service instances that use **[IAM](#iam)** authentication, the SDK provides two init methods -- one that accepts an apikey and another +that accepts an access token created from an apikey. If you use the init method that supplies the apikey, the SDK will obtain an +access token and refresh it when needed. If you initialize the SDK with the method that supplies an access token, you will need +to periodically refresh the token as they expire after a short time. Learn more about [IAM](link). + +- For service instances that use basic authentication (username and password), use the init method that specifies the username +and password. -On the **Manage** tab of your service instance on IBM Cloud, there is an button to download the credentials. The file will be called `ibm-credentials.env`, but you can rename it after downloading. Add this file to a location that is accessible from your project. For iOS apps, make sure to add it to the application target. +#### Credentials in the environment or a local credentials file -Get the `URL` for the credential file's location (you can use [Bundle](https://developer.apple.com/documentation/foundation/bundle) for iOS), and pass it to the service initializer. +The SDK can extract service credentails from the environment, e.g. the VCAP_SERVICES environment variable, or a local credentials file. + +To use credentials stored in a local file, go to the **Manage** tab of your service instance on IBM Cloud, and click on the button to download the credentials. The file will be called `ibm-credentials.env`. Add this file to a location that is accessible from your project. For iOS apps, make sure to add it to the application target. ```swift -let discovery = Discovery(credentialsFile: credentialsURL, version: "your-version") +let discovery = Discovery(version: "your-version") ``` If your project is using multiple Watson services, you can merge the contents of the `ibm-credentials.env` files into a single file. Lines in the file can be added, deleted, or reordered, but the content of each line **must not** be changed. @@ -174,14 +180,6 @@ If your project is using multiple Watson services, you can merge the contents of Copy the credentials from IBM Cloud and store them within your project. Then pass those values to the service initializer that accepts the type of credentials you have. - -##### Username and Password - -```swift -let discovery = Discovery(username: "your-username", password: "your-password", version: "your-version") -``` - - ##### IAM Some services use token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated. @@ -208,6 +206,14 @@ discovery.accessToken("new-accessToken") ``` +##### Username and Password + +```swift +let discovery = Discovery(version: "your-version", username: "your-username", password: "your-password") +``` + + + ## Custom Service URLs You can set a custom service URL by modifying the `serviceURL` property. A custom service URL may be required when running an instance in a particular region or connecting through a proxy. @@ -216,9 +222,9 @@ For example, here is how to connect to a Tone Analyzer instance that is hosted i ```swift let toneAnalyzer = ToneAnalyzer( + version: "yyyy-mm-dd", username: "your-username", - password: "your-password", - version: "yyyy-mm-dd" + password: "your-password" ) toneAnalyzer.serviceURL = "https://gateway-fra.watsonplatform.net/tone-analyzer/api" ``` diff --git a/Source/SupportingFiles/Shared.swift b/Source/SupportingFiles/Shared.swift index 13dbce9d1..fd5ba3f69 100644 --- a/Source/SupportingFiles/Shared.swift +++ b/Source/SupportingFiles/Shared.swift @@ -24,7 +24,7 @@ public typealias WatsonError = RestError internal struct Shared { struct Constant { - static let credentialsFileName = "ibm-credentials" + static let credentialsFileName = "ibm-credentials.env" static let serviceURL = "url" static let username = "username" static let password = "password" @@ -100,6 +100,19 @@ internal struct Shared { return credentials[Constant.serviceURL] } + /// These headers must be sent with every request in order to collect SDK metrics + static func getSDKHeaders(serviceName: String, serviceVersion: String, methodName: String) -> [String: String] { + let serviceInfo = "service_name=\(serviceName);service_version=\(serviceVersion);operation_id=\(methodName);async=true" + + return [ + "X-IBMCloud-SDK-Analytics": serviceInfo, + ] + } +} + +#if os(Linux) +extension Shared { + /// Get all credentials for the given service from a credentials file (ibm-credentials.env) /// See the discussion below for an example of what the credentials file could look like. /// @@ -108,8 +121,14 @@ internal struct Shared { /// VISUAL_RECOGNITION_IAM_URL=https://cloud.ibm.com/iam /// DISCOVERY_USERNAME=me /// DISCOVERY_PASSWORD=hunter2 - static func extractCredentials(from credentialsFile: URL, serviceName: String) -> [String: String]? { - // Extract credentials from file line-by-line + static func extractCredentials(serviceName: String) -> [String: String]? { + + // first look for an env variable called IBM_CREDENTIALS_FILE + // it should be the path to the file + let credentialsFileName = ProcessInfo.processInfo.environment["IBM_CREDENTIALS_FILE"] ?? + Constant.credentialsFileName + + let credentialsFile = URL(fileURLWithPath: credentialsFileName) guard let fileLines = try? String(contentsOf: credentialsFile).components(separatedBy: .newlines) else { return nil } @@ -128,12 +147,5 @@ internal struct Shared { return serviceCredentials } - /// These headers must be sent with every request in order to collect SDK metrics - static func getSDKHeaders(serviceName: String, serviceVersion: String, methodName: String) -> [String: String] { - let serviceInfo = "service_name=\(serviceName);service_version=\(serviceVersion);operation_id=\(methodName);async=true" - - return [ - "X-IBMCloud-SDK-Analytics": serviceInfo, - ] - } } +#endif diff --git a/Source/SupportingFiles/SharedTests.swift b/Source/SupportingFiles/SharedTests.swift index 7bba7bebc..ebc2dc83f 100644 --- a/Source/SupportingFiles/SharedTests.swift +++ b/Source/SupportingFiles/SharedTests.swift @@ -73,31 +73,6 @@ class SharedTests: XCTestCase { XCTAssertEqual(Shared.getServiceURL(from: credentials), serviceURL) } - func testExtractCredentials() { - let testCredentialsFile = Bundle(for: type(of: self)).url(forResource: "ibm-credentials", withExtension: "env") - guard testCredentialsFile != nil else { - XCTFail("Failed to load ibm-credentials.env file") - return - } - - // Discovery credentials (API key) - guard let discoveryCredentials = Shared.extractCredentials(from: testCredentialsFile!, serviceName: "discovery") else { - XCTFail("Failed to extract Discovery credentials") - return - } - XCTAssertEqual(discoveryCredentials["username"], "me") - XCTAssertEqual(discoveryCredentials["password"], "hunter2") - - // Visual Recognition credentials (username/password) - guard let visualRecognitionCredentials = Shared.extractCredentials(from: testCredentialsFile!, serviceName: "visual_recognition") else { - XCTFail("Failed to extract Visual Recognition credentials") - return - } - XCTAssertEqual(visualRecognitionCredentials["apikey"], "1234abcd") - XCTAssertEqual(visualRecognitionCredentials["iam_url"], "https://cloud.ibm.com/iam") - XCTAssertEqual(visualRecognitionCredentials["url"], "https://test.us-south.containers.mybluemix.net/visual-recognition/api") - } - func testHeaders() { let serviceName = "test-service" let serviceVersion = "v9" diff --git a/Source/SupportingFiles/ibm-credentials.env b/Source/SupportingFiles/ibm-credentials.env index 15a4f27bc..5be4da23e 100644 --- a/Source/SupportingFiles/ibm-credentials.env +++ b/Source/SupportingFiles/ibm-credentials.env @@ -1,5 +1,8 @@ +assistant_apikey=1234abcd + +DISCOVERY_USERNAME=me +DISCOVERY_PASSWORD=hunter2 + VISUAL_RECOGNITION_APIKEY=1234abcd VISUAL_RECOGNITION_URL=https://test.us-south.containers.mybluemix.net/visual-recognition/api VISUAL_RECOGNITION_IAM_URL=https://cloud.ibm.com/iam -DISCOVERY_USERNAME=me -DISCOVERY_PASSWORD=hunter2 \ No newline at end of file diff --git a/Tests/AssistantV1Tests/AssistantTests.swift b/Tests/AssistantV1Tests/AssistantTests.swift index efdcd68c5..3c7ba4a8d 100644 --- a/Tests/AssistantV1Tests/AssistantTests.swift +++ b/Tests/AssistantV1Tests/AssistantTests.swift @@ -18,7 +18,7 @@ import XCTest import Foundation -import AssistantV1 +@testable import AssistantV1 import RestKit class AssistantTests: XCTestCase { @@ -36,17 +36,20 @@ class AssistantTests: XCTestCase { } static var allTests: [(String, (AssistantTests) -> () throws -> Void)] { - return [ + let tests: [(String, (AssistantTests) -> () throws -> Void)] = [ + // Positive Tests ("testMessage", testMessage), ("testMessageAllFields1", testMessageAllFields1), ("testMessageAllFields2", testMessageAllFields2), ("testMessageContextVariable", testMessageContextVariable), + // Workspaces ("testListAllWorkspaces", testListAllWorkspaces), ("testListAllWorkspacesWithPageLimit1", testListAllWorkspacesWithPageLimit1), ("testListAllWorkspacesWithIncludeCount", testListAllWorkspacesWithIncludeCount), ("testCreateAndDeleteWorkspace", testCreateAndDeleteWorkspace), ("testListSingleWorkspace", testListSingleWorkspace), ("testCreateUpdateAndDeleteWorkspace", testCreateUpdateAndDeleteWorkspace), + // Intents ("testListAllIntents", testListAllIntents), ("testListAllIntentsWithIncludeCount", testListAllIntentsWithIncludeCount), ("testListAllIntentsWithPageLimit1", testListAllIntentsWithPageLimit1), @@ -54,18 +57,21 @@ class AssistantTests: XCTestCase { ("testCreateAndDeleteIntent", testCreateAndDeleteIntent), ("testGetIntentWithExport", testGetIntentWithExport), ("testCreateUpdateAndDeleteIntent", testCreateUpdateAndDeleteIntent), + // Examples ("testListAllExamples", testListAllExamples), ("testListAllExamplesWithIncludeCount", testListAllExamplesWithIncludeCount), ("testListAllExamplesWithPageLimit1", testListAllExamplesWithPageLimit1), ("testCreateAndDeleteExample", testCreateAndDeleteExample), ("testGetExample", testGetExample), ("testCreateUpdateAndDeleteExample", testCreateUpdateAndDeleteExample), + // Counterexamples ("testListAllCounterexamples", testListAllCounterexamples), ("testListAllCounterexamplesWithIncludeCount", testListAllCounterexamplesWithIncludeCount), ("testListAllCounterexamplesWithPageLimit1", testListAllCounterexamplesWithPageLimit1), ("testCreateAndDeleteCounterexample", testCreateAndDeleteCounterexample), ("testGetCounterexample", testGetCounterexample), ("testCreateUpdateAndDeleteCounterexample", testCreateUpdateAndDeleteCounterexample), + // Entities ("testListAllEntities", testListAllEntities), ("testListAllEntitiesWithIncludeCount", testListAllEntitiesWithIncludeCount), ("testListAllEntitiesWithPageLimit1", testListAllEntitiesWithPageLimit1), @@ -73,26 +79,41 @@ class AssistantTests: XCTestCase { ("testCreateAndDeleteEntity", testCreateAndDeleteEntity), ("testCreateUpdateAndDeleteEntity", testCreateUpdateAndDeleteEntity), ("testGetEntity", testGetEntity), + // Mentions ("testListMentions", testListMentions), + // Values ("testListAllValues", testListAllValues), ("testCreateUpdateAndDeleteValue", testCreateUpdateAndDeleteValue), ("testGetValue", testGetValue), + // Synonyms ("testListAllSynonym", testListAllSynonym), ("testListAllSynonymWithIncludeCount", testListAllSynonymWithIncludeCount), ("testListAllSynonymWithPageLimit1", testListAllSynonymWithPageLimit1), ("testCreateAndDeleteSynonym", testCreateAndDeleteSynonym), ("testGetSynonym", testGetSynonym), ("testCreateUpdateAndDeleteSynonym", testCreateUpdateAndDeleteSynonym), + // Dialog Nodes ("testListAllDialogNodes", testListAllDialogNodes), ("testCreateAndDeleteDialogNode", testCreateAndDeleteDialogNode), ("testCreateUpdateAndDeleteDialogNode", testCreateUpdateAndDeleteDialogNode), ("testGetDialogNode", testGetDialogNode), + // Logs // ("testListAllLogs", testListAllLogs), // temporarily disabled due to server-side bug // ("testListLogs", testListLogs), // temporarily disabled due to server-side bug + // Negative Tests ("testMessageUnknownWorkspace", testMessageUnknownWorkspace), ("testMessageInvalidWorkspaceID", testMessageInvalidWorkspaceID), ("testInvalidServiceURL", testInvalidServiceURL), ] + #if os(Linux) + let linuxTests: [(String, (AssistantTests) -> () throws -> Void)] = [ + // Inject Credentials + ("testInjectCredentialsFromFile", testInjectCredentialsFromFile), + ] + return tests + linuxTests + #else + return tests + #endif } /** Instantiate Assistant. */ @@ -102,7 +123,7 @@ class AssistantTests: XCTestCase { } else { let username = WatsonCredentials.AssistantUsername let password = WatsonCredentials.AssistantPassword - assistant = Assistant(username: username, password: password, version: versionDate) + assistant = Assistant(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.AssistantURL { assistant.serviceURL = url @@ -2415,4 +2436,16 @@ class AssistantTests: XCTestCase { } waitForExpectations() } + + // MARK: - Inject Credentials + + #if os(Linux) + func testInjectCredentialsFromFile() { + setenv("IBM_CREDENTIALS_FILE", "Source/SupportingFiles/ibm-credentials.env", 1) + let assistant = Assistant(version: versionDate) + XCTAssertNotNil(assistant) + XCTAssert(assistant?.authMethod is IAMAuthentication) + } + #endif + } diff --git a/Tests/AssistantV2Tests/AssistantV2Tests.swift b/Tests/AssistantV2Tests/AssistantV2Tests.swift index a9ce7f41d..d10d6287b 100644 --- a/Tests/AssistantV2Tests/AssistantV2Tests.swift +++ b/Tests/AssistantV2Tests/AssistantV2Tests.swift @@ -53,7 +53,7 @@ class AssistantV2Tests: XCTestCase { } else { let username = WatsonCredentials.AssistantV2Username let password = WatsonCredentials.AssistantV2Password - assistant = Assistant(username: username, password: password, version: versionDate) + assistant = Assistant(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.AssistantV2URL { assistant.serviceURL = url diff --git a/Tests/DiscoveryV1Tests/DiscoveryTests.swift b/Tests/DiscoveryV1Tests/DiscoveryTests.swift index 3f45f2f11..67b9b8b7c 100644 --- a/Tests/DiscoveryV1Tests/DiscoveryTests.swift +++ b/Tests/DiscoveryV1Tests/DiscoveryTests.swift @@ -18,7 +18,7 @@ import XCTest import Foundation -import DiscoveryV1 +@testable import DiscoveryV1 import RestKit class DiscoveryTests: XCTestCase { @@ -47,7 +47,7 @@ class DiscoveryTests: XCTestCase { } else { let username = WatsonCredentials.DiscoveryUsername let password = WatsonCredentials.DiscoveryPassword - discovery = Discovery(username: username, password: password, version: versionDate) + discovery = Discovery(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.DiscoveryURL { discovery.serviceURL = url @@ -70,25 +70,32 @@ class DiscoveryTests: XCTestCase { // MARK: - Test Definition for Linux static var allTests: [(String, (DiscoveryTests) -> () throws -> Void)] { - return [ + let tests: [(String, (DiscoveryTests) -> () throws -> Void)] = [ + // Environments ("testListEnvironments", testListEnvironments), ("testListEnvironmentsByName", testListEnvironmentsByName), ("testGetEnvironment", testGetEnvironment), ("testEnvironmentCRUD", testEnvironmentCRUD), ("testListFields", testListFields), + // Configurations ("testListConfigurations", testListConfigurations), ("testListConfigurationsByName", testListConfigurationsByName), ("testConfigurationCRUD", testConfigurationCRUD), ("testConfigurationWithSource", testConfigurationWithSource), + // Test Configuration in Environment ("testConfigurationInEnvironment", testConfigurationInEnvironment), + // Collections ("testListCollections", testListCollections), ("testListCollectionsByName", testListCollectionsByName), ("testCollectionsCRUD", testCollectionsCRUD), ("testListCollectionFields", testListCollectionFields), ("testExpansionsCRUD", testExpansionsCRUD), ("testTokenizationDictionaryOperations", testTokenizationDictionaryOperations), + // Stopwords List ("testStopwordListOperations", testStopwordListOperations), + // Documents ("testDocumentsCRUD", testDocumentsCRUD), + // Queries ("testQuery", testQuery), ("testQueryWithNaturalLanguage", testQueryWithNaturalLanguage), ("testQueryWithPassages", testQueryWithPassages), @@ -114,19 +121,35 @@ class DiscoveryTests: XCTestCase { ("testGetMetricsQueryNoResults", testGetMetricsQueryNoResults), ("testGetMetricsEventRate", testGetMetricsEventRate), ("testGetMetricsQueryTokenEvent", testGetMetricsQueryTokenEvent), + // Training Data ("testListTrainingData", testListTrainingData), ("testTrainingDataCRUD", testTrainingDataCRUD), ("testDeleteAllTrainingData", testDeleteAllTrainingData), + // Training Examples ("testListTrainingExamples", testListTrainingExamples), ("testTrainingExamplesCRUD", testTrainingExamplesCRUD), + // Credentials ("testListCredentials", testListCredentials), ("testCredentialsCRUD", testCredentialsCRUD), + // Gateways ("testGatewayOperations", testGatewayOperations), + // User Data + ("testDeleteLabeledData", testDeleteLabeledData), + // Negative Tests ("testGetEnvironmentWithInvalidID", testGetEnvironmentWithInvalidID), ("testGetConfigurationWithInvalidID", testGetConfigurationWithInvalidID), ("testGetCollectionWithInvalidID", testGetCollectionWithInvalidID), ("testQueryWithInvalidID", testQueryWithInvalidID), ] + #if os(Linux) + let linuxTests: [(String, (DiscoveryTests) -> () throws -> Void)] = [ + // Inject Credentials + ("testInjectCredentialsFromFile", testInjectCredentialsFromFile), + ] + return tests + linuxTests + #else + return tests + #endif } // MARK: - State Management @@ -2633,4 +2656,16 @@ class DiscoveryTests: XCTestCase { } waitForExpectations(timeout: timeout) } + + // MARK: - Inject Credentials + + #if os(Linux) + func testInjectCredentialsFromFile() { + setenv("IBM_CREDENTIALS_FILE", "Source/SupportingFiles/ibm-credentials.env", 1) + let discovery = Discovery(version: versionDate) + XCTAssertNotNil(discovery) + XCTAssert(discovery?.authMethod is BasicAuthentication) + } + #endif + } diff --git a/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift b/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift index c5a0b8706..f06e9737a 100644 --- a/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift +++ b/Tests/LanguageTranslatorV3Tests/LanguageTranslatorTests.swift @@ -57,7 +57,7 @@ class LanguageTranslatorTests: XCTestCase { } else { let username = WatsonCredentials.LanguageTranslatorV3Username let password = WatsonCredentials.LanguageTranslatorV3Password - languageTranslator = LanguageTranslator(username: username, password: password, version: versionDate) + languageTranslator = LanguageTranslator(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.LanguageTranslatorV3URL { languageTranslator.serviceURL = url diff --git a/Tests/NaturalLanguageUnderstandingV1Tests/NaturalLanguageUnderstandingV1Tests.swift b/Tests/NaturalLanguageUnderstandingV1Tests/NaturalLanguageUnderstandingV1Tests.swift index c14b2fdea..0008d15d5 100644 --- a/Tests/NaturalLanguageUnderstandingV1Tests/NaturalLanguageUnderstandingV1Tests.swift +++ b/Tests/NaturalLanguageUnderstandingV1Tests/NaturalLanguageUnderstandingV1Tests.swift @@ -64,7 +64,7 @@ class NaturalLanguageUnderstandingTests: XCTestCase { } else { let username = WatsonCredentials.NaturalLanguageUnderstandingUsername let password = WatsonCredentials.NaturalLanguageUnderstandingPassword - naturalLanguageUnderstanding = NaturalLanguageUnderstanding(username: username, password: password, version: versionDate) + naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.NaturalLanguageUnderstandingURL { naturalLanguageUnderstanding.serviceURL = url diff --git a/Tests/PersonalityInsightsV3Tests/PersonalityInsightsTests.swift b/Tests/PersonalityInsightsV3Tests/PersonalityInsightsTests.swift index 4a40ca459..ff37cef05 100644 --- a/Tests/PersonalityInsightsV3Tests/PersonalityInsightsTests.swift +++ b/Tests/PersonalityInsightsV3Tests/PersonalityInsightsTests.swift @@ -56,7 +56,7 @@ class PersonalityInsightsTests: XCTestCase { } else { let username = WatsonCredentials.PersonalityInsightsV3Username let password = WatsonCredentials.PersonalityInsightsV3Password - personalityInsights = PersonalityInsights(username: username, password: password, version: versionDate) + personalityInsights = PersonalityInsights(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.PersonalityInsightsV3URL { personalityInsights.serviceURL = url diff --git a/Tests/ToneAnalyzerV3Tests/ToneAnalyzerTests.swift b/Tests/ToneAnalyzerV3Tests/ToneAnalyzerTests.swift index 29943a3ba..c2916bbb5 100644 --- a/Tests/ToneAnalyzerV3Tests/ToneAnalyzerTests.swift +++ b/Tests/ToneAnalyzerV3Tests/ToneAnalyzerTests.swift @@ -66,7 +66,7 @@ class ToneAnalyzerTests: XCTestCase { } else { let username = WatsonCredentials.ToneAnalyzerUsername let password = WatsonCredentials.ToneAnalyzerPassword - toneAnalyzer = ToneAnalyzer(username: username, password: password, version: versionDate) + toneAnalyzer = ToneAnalyzer(version: versionDate, username: username, password: password) } if let url = WatsonCredentials.ToneAnalyzerURL { toneAnalyzer.serviceURL = url diff --git a/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift b/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift index b2fdea826..a82613230 100644 --- a/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift +++ b/Tests/VisualRecognitionV3Tests/VisualRecognitionTests.swift @@ -18,7 +18,8 @@ import XCTest import Foundation -import VisualRecognitionV3 +@testable import VisualRecognitionV3 +import RestKit class VisualRecognitionTests: XCTestCase { @@ -28,14 +29,17 @@ class VisualRecognitionTests: XCTestCase { private let classifierID = WatsonCredentials.VisualRecognitionClassifierID static var allTests: [(String, (VisualRecognitionTests) -> () throws -> Void)] { - return [ + let tests: [(String, (VisualRecognitionTests) -> () throws -> Void)] = [ + // Classifiers CRUD ("testListClassifiers", testListClassifiers), ("testListClassifiersVerbose", testListClassifiersVerbose), - // disabled: ("testCreateDeleteClassifier1", testCreateDeleteClassifier1), - // disabled: ("testCreateDeleteClassifier2", testCreateDeleteClassifier2), + ("testCreateDeleteClassifier1", testCreateDeleteClassifier1), + ("testCreateDeleteClassifier2", testCreateDeleteClassifier2), ("testGetClassifier", testGetClassifier), // disabled: ("testUpdateClassifierWithPositiveExample", testUpdateClassifierWithPositiveExample), // disabled: ("testUpdateClassifierWithNegativeExample", testUpdateClassifierWithNegativeExample), + ("testGetCoreMlModel", testGetCoreMlModel), + // Classify ("testClassifyByURL1", testClassifyByURL1), ("testClassifyByURL2", testClassifyByURL2), ("testClassifyByURL3", testClassifyByURL3), @@ -47,15 +51,26 @@ class VisualRecognitionTests: XCTestCase { ("testClassifyImage4", testClassifyImage4), ("testClassifyImage5", testClassifyImage5), ("testClassifyImage6", testClassifyImage6), + // Detect faces ("testDetectFacesByURL", testDetectFacesByURL), ("testDetectFacesByImage1", testDetectFacesByImage1), ("testDetectFacesByImage2", testDetectFacesByImage2), + // Negative tests ("testAuthenticationError", testAuthenticationError), ("testCreateClassifierWithInvalidPositiveExamples", testCreateClassifierWithInvalidPositiveExamples), ("testClassifyByInvalidURL", testClassifyByInvalidURL), ("testDetectFacesByInvalidURL", testDetectFacesByInvalidURL), ("testGetUnknownClassifier", testGetUnknownClassifier), ] + #if os(Linux) + let linuxTests: [(String, (VisualRecognitionTests) -> () throws -> Void)] = [ + // Inject Credentials + ("testInjectCredentialsFromFile", testInjectCredentialsFromFile), + ] + return tests + linuxTests + #else + return tests + #endif } // MARK: - Test Configuration @@ -1368,4 +1383,16 @@ class VisualRecognitionTests: XCTestCase { } waitForExpectations() } + + // MARK: - Inject Credentials + + #if os(Linux) + func testInjectCredentialsFromFile() { + setenv("IBM_CREDENTIALS_FILE", "Source/SupportingFiles/ibm-credentials.env", 1) + let visualRecognition = VisualRecognition(version: versionDate) + XCTAssertNotNil(visualRecognition) + XCTAssertEqual("https://test.us-south.containers.mybluemix.net/visual-recognition/api", visualRecognition?.serviceURL) + XCTAssert(visualRecognition?.authMethod is IAMAuthentication) + } + #endif } From fee84f166013a86c53592ec74ee5425440cb537e Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Mon, 18 Mar 2019 23:28:05 -0500 Subject: [PATCH 10/13] feat(SpeechToTextV1): Rework STT websockets methods --- .../SpeechToText+Recognize.swift | 78 +------ .../WebSockets/RecognizeCallback.swift | 27 +++ .../SpeechToTextRecognizeTests.swift | 193 ++++++++++-------- .../project.pbxproj | 4 + 4 files changed, 150 insertions(+), 152 deletions(-) create mode 100644 Source/SpeechToTextV1/WebSockets/RecognizeCallback.swift diff --git a/Source/SpeechToTextV1/SpeechToText+Recognize.swift b/Source/SpeechToTextV1/SpeechToText+Recognize.swift index 5992a5d6a..f3acd4973 100644 --- a/Source/SpeechToTextV1/SpeechToText+Recognize.swift +++ b/Source/SpeechToTextV1/SpeechToText+Recognize.swift @@ -32,57 +32,6 @@ extension SpeechToText { + "/v1/recognize" } - /** - Perform speech recognition for an audio file. - - - parameter audio: The audio file to transcribe. - - parameter settings: The configuration to use for this recognition request. - - parameter model: The language and sample rate of the audio. For supported models, visit - https://cloud.ibm.com/docs/services/speech-to-text/input.html#models. - - parameter baseModelVersion: The version of the specified base model that is to be used for all requests sent - over the connection. Multiple versions of a base model can exist when a model is updated for internal improvements. - The parameter is intended primarily for use with custom models that have been upgraded for a new base model. - The default value depends on whether the parameter is used with or without a custom model. See - [Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version). - - parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used - with the recognition request. The base model of the specified custom language model must match the model - specified with the `model` parameter. You must make the request with service credentials created for the instance - of the service that owns the custom model. By default, no custom language model is used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom). - - parameter learningOptOut: If `true`, then this request will not be logged for training. - - parameter customerID: Associates a customer ID with all data that is passed over the connection. - By default, no customer ID is associated with the data. - - parameter completionHandler: A function executed when the request completes with a successful result or error - */ - public func recognize( - audio: URL, - settings: RecognitionSettings, - model: String? = nil, - baseModelVersion: String? = nil, - languageCustomizationID: String? = nil, - learningOptOut: Bool? = nil, - customerID: String? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) - { - do { - let data = try Data(contentsOf: audio) - recognizeUsingWebSocket( - audio: data, - settings: settings, - model: model, - baseModelVersion: baseModelVersion, - languageCustomizationID: languageCustomizationID, - learningOptOut: learningOptOut, - customerID: customerID, - completionHandler: completionHandler - ) - } catch { - let error = WatsonError.serialization(values: "audio data from \(audio)") - completionHandler(nil, error) - return - } - } - /** Perform speech recognition for audio data using WebSockets. @@ -120,7 +69,7 @@ extension SpeechToText { learningOptOut: Bool? = nil, customerID: String? = nil, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + callback: RecognizeCallback) { // create SpeechToTextSession let session = SpeechToTextSession( @@ -145,14 +94,8 @@ extension SpeechToText { session.defaultHeaders.merge(sdkHeaders) { (_, new) in new } // set callbacks - session.onResults = { result in - var response = WatsonResponse(statusCode: 0) - response.result = result - completionHandler(response, nil) - } - session.onError = { error in - completionHandler(nil, error) - } + session.onResults = callback.onResults + session.onError = callback.onError // execute recognition request session.connect() @@ -210,7 +153,7 @@ extension SpeechToText { customerID: String? = nil, compress: Bool = true, headers: [String: String]? = nil, - completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) + callback: RecognizeCallback) { // make sure the AVAudioSession shared instance is properly configured do { @@ -219,8 +162,7 @@ extension SpeechToText { try audioSession.setActive(true) } catch { let failureReason = "Failed to setup the AVAudioSession sharedInstance properly." - let error = WatsonError.other(message: failureReason, metadata: nil) - completionHandler(nil, error) + callback.onError?(WatsonError.other(message: failureReason, metadata: nil)) return } @@ -251,14 +193,8 @@ extension SpeechToText { session.defaultHeaders.merge(sdkHeaders) { (_, new) in new } // set callbacks - session.onResults = { result in - var response = WatsonResponse(statusCode: 200) - response.result = result - completionHandler(response, nil) - } - session.onError = { error in - completionHandler(nil, error) - } + session.onResults = callback.onResults + session.onError = callback.onError // start recognition request session.connect() diff --git a/Source/SpeechToTextV1/WebSockets/RecognizeCallback.swift b/Source/SpeechToTextV1/WebSockets/RecognizeCallback.swift new file mode 100644 index 000000000..93c649eab --- /dev/null +++ b/Source/SpeechToTextV1/WebSockets/RecognizeCallback.swift @@ -0,0 +1,27 @@ +/** + * Copyright IBM Corporation 2019 + * + * 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. + **/ + +import Foundation + +public struct RecognizeCallback { + + /// Invoked when transcription results are received for a recognition request. + public var onResults: ((SpeechRecognitionResults) -> Void)? + + /// Invoked when an error or warning occurs. + public var onError: ((WatsonError) -> Void)? + +} diff --git a/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift b/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift index 1c5fbca24..bbe5b2175 100644 --- a/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift +++ b/Tests/SpeechToTextV1Tests/SpeechToTextRecognizeTests.swift @@ -112,18 +112,15 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTFail(cannotLocateFileMessage(filename, withExtension)) return } + let fileData = try! Data(contentsOf: file) let settings = RecognitionSettings(contentType: format) - speechToText.recognize(audio: file, settings: settings) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) XCTAssertEqual(results.results!.count, 1) @@ -133,6 +130,7 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTAssertGreaterThan(transcript!.count, 0) expectation.fulfill() } + speechToText.recognizeUsingWebSocket(audio: fileData, settings: settings, callback: callback) wait(for: [expectation], timeout: timeout) } @@ -163,6 +161,7 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTFail(cannotLocateFileMessage(filename, withExtension)) return } + let fileData = try! Data(contentsOf: file) var settings = RecognitionSettings(contentType: format) settings.inactivityTimeout = -1 @@ -176,16 +175,11 @@ class SpeechToTextRecognizeTests: XCTestCase { settings.filterProfanity = false settings.smartFormatting = true - speechToText.recognize(audio: file, settings: settings, model: "en-US_BroadbandModel", learningOptOut: true) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) if results.results!.last?.finalResults == true { @@ -195,6 +189,7 @@ class SpeechToTextRecognizeTests: XCTestCase { expectation.fulfill() } } + speechToText.recognizeUsingWebSocket(audio: fileData, settings: settings, model: "en-US_BroadbandModel", learningOptOut: true, callback: callback) wait(for: [expectation], timeout: timeout) } @@ -230,16 +225,12 @@ class SpeechToTextRecognizeTests: XCTestCase { let audio = try Data(contentsOf: file) let settings = RecognitionSettings(contentType: format) - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) XCTAssertEqual(results.results!.count, 1) @@ -249,6 +240,7 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTAssertGreaterThan(transcript!.count, 0) expectation.fulfill() } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, callback: callback) wait(for: [expectation], timeout: timeout) } catch { XCTFail(cannotReadFileMessage(filename, withExtension)) @@ -299,16 +291,12 @@ class SpeechToTextRecognizeTests: XCTestCase { settings.filterProfanity = false settings.smartFormatting = true - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_BroadbandModel", learningOptOut: true) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + return + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) if results.results?.last?.finalResults == true { let transcript = results.results!.last?.alternatives.last?.transcript @@ -317,6 +305,7 @@ class SpeechToTextRecognizeTests: XCTestCase { expectation.fulfill() } } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_BroadbandModel", learningOptOut: true, callback: callback) wait(for: [expectation], timeout: timeout) } catch { XCTFail(cannotReadFileMessage(filename, withExtension)) @@ -369,16 +358,12 @@ class SpeechToTextRecognizeTests: XCTestCase { do { let audio = try Data(contentsOf: file) let settings = RecognitionSettings(contentType: format) - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: baseModelName, languageCustomizationID: customizationID) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) XCTAssertEqual(results.results!.count, 1) @@ -388,6 +373,7 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTAssertGreaterThan(transcript!.count, 0) expectation2.fulfill() } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: baseModelName, languageCustomizationID: customizationID, callback: callback) wait(for: [expectation2], timeout: timeout) } catch { XCTFail("Unable to read \(filename).\(withExtension).") @@ -439,16 +425,11 @@ class SpeechToTextRecognizeTests: XCTestCase { let audio = try Data(contentsOf: file) let settings = RecognitionSettings(contentType: format) - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: baseModelName, acousticCustomizationID: customizationID) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) XCTAssertEqual(results.results!.count, 1) @@ -458,6 +439,7 @@ class SpeechToTextRecognizeTests: XCTestCase { XCTAssertGreaterThan(transcript!.count, 0) expectation.fulfill() } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: baseModelName, acousticCustomizationID: customizationID, callback: callback) wait(for: [expectation], timeout: timeout) } catch { XCTFail("Unable to read \(filename).\(withExtension).") @@ -494,16 +476,11 @@ class SpeechToTextRecognizeTests: XCTestCase { var settings = RecognitionSettings(contentType: format) settings.smartFormatting = true - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_BroadbandModel", learningOptOut: true) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in self.validateSTTResults(results: results, settings: settings) XCTAssertNotNil(results.results) if results.results!.last?.finalResults == true { @@ -514,6 +491,14 @@ class SpeechToTextRecognizeTests: XCTestCase { expectation.fulfill() } } + + speechToText.recognizeUsingWebSocket( + audio: audio, + settings: settings, + model: "en-US_BroadbandModel", + learningOptOut: true, + callback: callback) + wait(for: [expectation], timeout: timeout) } @@ -555,16 +540,11 @@ class SpeechToTextRecognizeTests: XCTestCase { settings.filterProfanity = false settings.speakerLabels = true - speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_NarrowbandModel", learningOptOut: true) { - response, error in - if let error = error { - XCTFail(unexpectedErrorMessage(error)) - return - } - guard let results = response?.result else { - XCTFail(missingResultMessage) - return - } + var callback = RecognizeCallback() + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + callback.onResults = { results in XCTAssertNotNil(results.speakerLabels) if !expectationFulfilled && results.speakerLabels!.count > 0 { self.validateSTTSpeakerLabels(speakerLabels: results.speakerLabels!) @@ -572,6 +552,7 @@ class SpeechToTextRecognizeTests: XCTestCase { expectation.fulfill() } } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_NarrowbandModel", learningOptOut: true, callback: callback) wait(for: [expectation], timeout: timeout) } catch { XCTFail(cannotReadFileMessage(filename, withExtension)) @@ -579,7 +560,57 @@ class SpeechToTextRecognizeTests: XCTestCase { } } - // MARK: - Results Accumulator + // MARK: - callbacks + + func testCallbacks() { + let filename = "SpeechSample" + let ext = "wav" + + let bundle = Bundle(for: type(of: self)) + guard let file = bundle.url(forResource: filename, withExtension: ext) else { + XCTFail(cannotLocateFileMessage(filename, ext)) + return + } + let audio = try! Data(contentsOf: file) + + var settings = RecognitionSettings(contentType: "audio/wav") + settings.inactivityTimeout = 5 + settings.interimResults = false + + let gotResults = self.expectation(description: "onResults received") + + var callback = RecognizeCallback() + callback.onResults = { results in + gotResults.fulfill() + } + callback.onError = { error in + XCTFail(unexpectedErrorMessage(error)) + } + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_NarrowbandModel", learningOptOut: true, callback: callback) + wait(for: [gotResults], timeout: timeout) + } + + func testErrorCallbacks() { + let audio = "This is bogus input".data(using: .utf8)! + + var settings = RecognitionSettings(contentType: "audio/wav") + settings.inactivityTimeout = 5 + settings.interimResults = false + + let gotError = self.expectation(description: "onError received") + gotError.assertForOverFulfill = false + + var callback = RecognizeCallback() + callback.onError = { results in + gotError.fulfill() + } + + speechToText.recognizeUsingWebSocket(audio: audio, settings: settings, model: "en-US_NarrowbandModel", learningOptOut: true, callback: callback) + wait(for: [gotError], timeout: timeout) + // onDisconnected not called because session was freed + } + + // MARK: - Results Accumulator func testResultsAccumulator() { let results1 = """ diff --git a/WatsonDeveloperCloud.xcodeproj/project.pbxproj b/WatsonDeveloperCloud.xcodeproj/project.pbxproj index 6e510ff0a..60cb8164c 100644 --- a/WatsonDeveloperCloud.xcodeproj/project.pbxproj +++ b/WatsonDeveloperCloud.xcodeproj/project.pbxproj @@ -660,6 +660,7 @@ CADC4B8F214216FC00C76DE6 /* VisualRecognitionUnitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADC4B8D2141BC9A00C76DE6 /* VisualRecognitionUnitTests.swift */; }; CAF9A5C420ACED3E006C86B7 /* CHANGELOG.md in Resources */ = {isa = PBXBuildFile; fileRef = CAF9A5C320ACED3E006C86B7 /* CHANGELOG.md */; }; CAF9A5CB20B75B3A006C86B7 /* VisualRecognitionWithIAMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAF9A5C920B753B7006C86B7 /* VisualRecognitionWithIAMTests.swift */; }; + CAFD2A9322400D7900325779 /* RecognizeCallback.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAFD2A9222400D7900325779 /* RecognizeCallback.swift */; }; CE6B98D41DF09D4B004CD6B5 /* face1.jpg in Resources */ = {isa = PBXBuildFile; fileRef = CE6B98D31DF09D4B004CD6B5 /* face1.jpg */; }; CE6B98DC1DF22638004CD6B5 /* metadata.txt in Resources */ = {isa = PBXBuildFile; fileRef = CE6B98DB1DF22638004CD6B5 /* metadata.txt */; }; CE75BAA91DDE5F2F006EBB51 /* KennedySpeech.html in Resources */ = {isa = PBXBuildFile; fileRef = CE75BAA81DDE5F2F006EBB51 /* KennedySpeech.html */; }; @@ -1393,6 +1394,7 @@ CADC4B8D2141BC9A00C76DE6 /* VisualRecognitionUnitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VisualRecognitionUnitTests.swift; sourceTree = ""; }; CAF9A5C320ACED3E006C86B7 /* CHANGELOG.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = CHANGELOG.md; sourceTree = ""; }; CAF9A5C920B753B7006C86B7 /* VisualRecognitionWithIAMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VisualRecognitionWithIAMTests.swift; sourceTree = ""; }; + CAFD2A9222400D7900325779 /* RecognizeCallback.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecognizeCallback.swift; sourceTree = ""; }; CE6B98D31DF09D4B004CD6B5 /* face1.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = face1.jpg; sourceTree = ""; }; CE6B98DB1DF22638004CD6B5 /* metadata.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = metadata.txt; sourceTree = ""; }; CE6D55C31DC7CC1300E7BDF9 /* trained_meta.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = trained_meta.txt; sourceTree = ""; }; @@ -1903,6 +1905,7 @@ 685E5D812087E343009BB020 /* WebSockets */ = { isa = PBXGroup; children = ( + CAFD2A9222400D7900325779 /* RecognizeCallback.swift */, 68F7FF1B207D47BC00E84DBF /* RecognitionSettings.swift */, 68F7FF1F207D47BD00E84DBF /* RecognitionState.swift */, 68F7FF1C207D47BC00E84DBF /* RecognitionStop.swift */, @@ -4422,6 +4425,7 @@ 68F7FF0A207D458900E84DBF /* SpeechModels.swift in Sources */, 68F7FF06207D458900E84DBF /* AudioDetails.swift in Sources */, 68F7FF0E207D458900E84DBF /* AudioResource.swift in Sources */, + CAFD2A9322400D7900325779 /* RecognizeCallback.swift in Sources */, 68F7FF22207D47BD00E84DBF /* WordTimestamp.swift in Sources */, 68F7FF19207D458900E84DBF /* CreateAcousticModel.swift in Sources */, 68F7FF00207D458900E84DBF /* AcousticModels.swift in Sources */, From f3b0020538fac5a7f7b7f33234492d00ca1963a9 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Thu, 28 Mar 2019 11:08:25 -0500 Subject: [PATCH 11/13] ci: Drop generated changelog and travis branch restrictions --- .releaserc | 4 ---- .travis.yml | 4 ---- 2 files changed, 8 deletions(-) diff --git a/.releaserc b/.releaserc index 18a091b50..cb3f34651 100644 --- a/.releaserc +++ b/.releaserc @@ -3,10 +3,6 @@ "verifyConditions": [], "tagFormat": "${version}", "prepare": [ - { - "path": "@semantic-release/changelog", - "changelogFile": "CHANGELOG.md", - }, "@semantic-release/git", { "path": "@semantic-release/exec", diff --git a/.travis.yml b/.travis.yml index 7cbb75158..0152a5135 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,4 @@ osx_image: xcode10.1 -branches: - only: - - master - - develop jobs: include: - stage: test Linux From edff064ed324e28d197efdcc2bb1a2a5992853e9 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Thu, 28 Mar 2019 12:26:43 -0500 Subject: [PATCH 12/13] docs: Update Changelog for Release 2.0 --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 234919fcf..cea52ff36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,22 @@ + +# [2.0.0](https://github.com/watson-developer-cloud/swift-sdk/compare/1.4.0...2.0.0) (2019-03-28) + + +### Features + +* **All:** + * Version moved to first parameter of init methods for basic authentication + * Credentials file support in the intializer dropped for iOS. Only supported in Linux + * Error response handling reworked for consistency across services and languages + * Ordering of parameters in some methods has changed due to migration of the API docs and generator to OpenAPI 3.0 + * File-type parameters are now defined as `Data` rather than `URL` +* **AssistantV1:** + * Some model classes have been merged / simplified + * The `InputData` class has been renamed to `MessageInput` +* **SpeechToTextV1:** + * The `recognizeWithWebsockets` method has been revised to accept a `RecognizeCallback` object with `onResults` and `onError` callback properties + + # [1.4.0](https://github.com/watson-developer-cloud/swift-sdk/compare/1.3.1...1.4.0) (2019-02-12) From 9194604077c88d43d7072882aad8fdbd8607e708 Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Thu, 28 Mar 2019 16:39:46 -0500 Subject: [PATCH 13/13] ci: Add swift_version to podspecs --- IBMWatsonAssistantV1.podspec | 1 + IBMWatsonAssistantV2.podspec | 1 + IBMWatsonCompareComplyV1.podspec | 1 + IBMWatsonDiscoveryV1.podspec | 1 + IBMWatsonLanguageTranslatorV3.podspec | 1 + IBMWatsonNaturalLanguageClassifierV1.podspec | 1 + IBMWatsonNaturalLanguageUnderstandingV1.podspec | 1 + IBMWatsonPersonalityInsightsV3.podspec | 1 + IBMWatsonSpeechToTextV1.podspec | 1 + IBMWatsonTextToSpeechV1.podspec | 1 + IBMWatsonToneAnalyzerV3.podspec | 1 + IBMWatsonVisualRecognitionV3.podspec | 1 + 12 files changed, 12 insertions(+) diff --git a/IBMWatsonAssistantV1.podspec b/IBMWatsonAssistantV1.podspec index 4e8c2d09b..db494f5fc 100644 --- a/IBMWatsonAssistantV1.podspec +++ b/IBMWatsonAssistantV1.podspec @@ -20,6 +20,7 @@ natural-language input and uses machine learning to respond to customers in a wa 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/AssistantV1/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonAssistantV2.podspec b/IBMWatsonAssistantV2.podspec index 2b8c9f248..f9d17cccb 100644 --- a/IBMWatsonAssistantV2.podspec +++ b/IBMWatsonAssistantV2.podspec @@ -20,6 +20,7 @@ natural-language input and uses machine learning to respond to customers in a wa 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/AssistantV2/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonCompareComplyV1.podspec b/IBMWatsonCompareComplyV1.podspec index 88315b29b..6270dfcee 100644 --- a/IBMWatsonCompareComplyV1.podspec +++ b/IBMWatsonCompareComplyV1.podspec @@ -18,6 +18,7 @@ IBM Watson™ Compare and Comply analyzes governing documents to provide details 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/CompareComplyV1/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonDiscoveryV1.podspec b/IBMWatsonDiscoveryV1.podspec index 9f5092059..3d17371f6 100644 --- a/IBMWatsonDiscoveryV1.podspec +++ b/IBMWatsonDiscoveryV1.podspec @@ -21,6 +21,7 @@ as well as public and third-party data. 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/DiscoveryV1/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonLanguageTranslatorV3.podspec b/IBMWatsonLanguageTranslatorV3.podspec index 4e7f8dae6..957e18206 100644 --- a/IBMWatsonLanguageTranslatorV3.podspec +++ b/IBMWatsonLanguageTranslatorV3.podspec @@ -19,6 +19,7 @@ IBM Watson™ Language Translator can identify the language of text and translat 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/LanguageTranslatorV3/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonNaturalLanguageClassifierV1.podspec b/IBMWatsonNaturalLanguageClassifierV1.podspec index f58f2278d..ddd0eb9a6 100644 --- a/IBMWatsonNaturalLanguageClassifierV1.podspec +++ b/IBMWatsonNaturalLanguageClassifierV1.podspec @@ -21,6 +21,7 @@ return information for texts that it is not trained on. 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/NaturalLanguageClassifierV1/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonNaturalLanguageUnderstandingV1.podspec b/IBMWatsonNaturalLanguageUnderstandingV1.podspec index d6c1b409f..9852b5fdc 100644 --- a/IBMWatsonNaturalLanguageUnderstandingV1.podspec +++ b/IBMWatsonNaturalLanguageUnderstandingV1.podspec @@ -20,6 +20,7 @@ including categories, concepts, emotion, entities, keywords, metadata, relations 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/NaturalLanguageUnderstandingV1/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonPersonalityInsightsV3.podspec b/IBMWatsonPersonalityInsightsV3.podspec index 333333dfb..81911ef20 100644 --- a/IBMWatsonPersonalityInsightsV3.podspec +++ b/IBMWatsonPersonalityInsightsV3.podspec @@ -20,6 +20,7 @@ from digital communications such as email, text messages, tweets, and forum post 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/PersonalityInsightsV3/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonSpeechToTextV1.podspec b/IBMWatsonSpeechToTextV1.podspec index 688a885df..3fe394341 100644 --- a/IBMWatsonSpeechToTextV1.podspec +++ b/IBMWatsonSpeechToTextV1.podspec @@ -25,6 +25,7 @@ of the audio signal. It continuously returns and retroactively updates a transcr '**/opus_header.h', '**/opus_header.c' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' s.dependency 'Starscream', '3.0.5' s.vendored_libraries = 'Source/SupportingFiles/Dependencies/Libraries/*.a' diff --git a/IBMWatsonTextToSpeechV1.podspec b/IBMWatsonTextToSpeechV1.podspec index fe29ffa23..465ff5cc2 100644 --- a/IBMWatsonTextToSpeechV1.podspec +++ b/IBMWatsonTextToSpeechV1.podspec @@ -22,6 +22,7 @@ The service streams the results back to the client with minimal delay. s.exclude_files = 'Source/TextToSpeechV1/Shared.swift', '**/config_types.h' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' s.vendored_libraries = 'Source/SupportingFiles/Dependencies/Libraries/*.a' diff --git a/IBMWatsonToneAnalyzerV3.podspec b/IBMWatsonToneAnalyzerV3.podspec index f7a0e402e..7b1dc6e73 100644 --- a/IBMWatsonToneAnalyzerV3.podspec +++ b/IBMWatsonToneAnalyzerV3.podspec @@ -20,6 +20,7 @@ The service can analyze tone at both the document and sentence levels. 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/ToneAnalyzerV3/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end diff --git a/IBMWatsonVisualRecognitionV3.podspec b/IBMWatsonVisualRecognitionV3.podspec index 30ae3207e..1ec9fbd37 100644 --- a/IBMWatsonVisualRecognitionV3.podspec +++ b/IBMWatsonVisualRecognitionV3.podspec @@ -20,6 +20,7 @@ scenes, objects, faces, and other content. The response includes keywords that p 'Source/SupportingFiles/Shared.swift' s.exclude_files = 'Source/VisualRecognitionV3/Shared.swift' + s.swift_version = '4.2' s.dependency 'IBMWatsonRestKit', '~> 3.0.0' end