From 8a1543fb784c034f3d323217e75afea764dc38a8 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 30 Oct 2020 18:46:28 -0400 Subject: [PATCH] LT V3, NLC V1, NLU V1, PI V3 changes --- .../LanguageTranslator.swift | 220 ++++++++++-------- .../Models/TranslateRequest.swift | 82 ------- .../Models/ClassifyCollectionInput.swift | 48 ---- .../NaturalLanguageClassifier.swift | 121 ++++++---- .../Models/AnalysisResults.swift | 4 +- .../Models/Features.swift | 7 +- ...ta.swift => FeaturesResultsMetadata.swift} | 4 +- .../Models/MetadataOptions.swift | 25 -- .../Models/Parameters.swift | 143 ------------ .../NaturalLanguageUnderstanding.swift | 110 +++++---- .../PersonalityInsights.swift | 86 ++++--- 11 files changed, 333 insertions(+), 517 deletions(-) delete mode 100644 Sources/LanguageTranslatorV3/Models/TranslateRequest.swift delete mode 100644 Sources/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift rename Sources/NaturalLanguageUnderstandingV1/Models/{AnalysisResultsMetadata.swift => FeaturesResultsMetadata.swift} (93%) delete mode 100644 Sources/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift delete mode 100644 Sources/NaturalLanguageUnderstandingV1/Models/Parameters.swift diff --git a/Sources/LanguageTranslatorV3/LanguageTranslator.swift b/Sources/LanguageTranslatorV3/LanguageTranslator.swift index b6cb0b19e..9366899d2 100644 --- a/Sources/LanguageTranslatorV3/LanguageTranslator.swift +++ b/Sources/LanguageTranslatorV3/LanguageTranslator.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2018, 2020. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ + +/** + * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-36b26b63-20201028-122900 + **/ + // swiftlint:disable file_length import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif import IBMSwiftSDKCore +public typealias WatsonError = RestError +public typealias WatsonResponse = RestResponse /** IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language @@ -29,8 +39,14 @@ public class LanguageTranslator { /// The base URL to use when contacting the service. public var serviceURL: String? = "https://api.us-south.language-translator.watson.cloud.ibm.com" + /// Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version + /// is `2018-05-01`. + public var version: String + /// Service identifiers - internal let serviceName = "LanguageTranslator" + public static let defaultServiceName = "language_translator" + // Service info for SDK headers + internal let serviceName = defaultServiceName internal let serviceVersion = "v3" internal let serviceSdkName = "language_translator" @@ -39,41 +55,39 @@ public class LanguageTranslator { var session = URLSession(configuration: URLSessionConfiguration.default) public let authenticator: Authenticator - let version: String #if os(Linux) /** Create a `LanguageTranslator` object. - This initializer will retrieve credentials from the environment or a local credentials file. + If an authenticator is not supplied, the initializer will retrieve credentials from the environment or + a local credentials file and construct an appropriate authenticator using these credentials. 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 credentials are not available in the environment or a local credentials file, initialization will fail. + If an authenticator is not supplied and credentials are not available in the environment or a local + credentials file, initialization will fail by throwing an exception. In that case, try another initializer that directly passes in the credentials. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. + The current version is `2018-05-01`. + - parameter authenticator: The Authenticator object used to authenticate requests to the service + - serviceName: String = defaultServiceName */ - public init(version: String) throws { + public init(version: String, authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws { self.version = version - - let authenticator = try ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceSdkName) - self.authenticator = authenticator - - if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceSdkName) { + self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName) + if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) { self.serviceURL = serviceURL } - RestRequest.userAgent = Shared.userAgent } - #endif - + #else /** Create a `LanguageTranslator` object. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. + The current version is `2018-05-01`. - parameter authenticator: The Authenticator object used to authenticate requests to the service */ public init(version: String, authenticator: Authenticator) { @@ -81,6 +95,7 @@ public class LanguageTranslator { self.authenticator = authenticator RestRequest.userAgent = Shared.userAgent } + #endif #if !os(Linux) /** @@ -99,7 +114,7 @@ public class LanguageTranslator { - parameter data: Raw data returned by the service that may represent an error. - parameter response: the URL response returned by the service. */ - func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> WatsonError { + func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError { let statusCode = response.statusCode var errorMessage: String? @@ -124,14 +139,17 @@ public class LanguageTranslator { errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) + return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** List supported languages. - Lists all supported languages. The method returns an array of supported languages with information about each - language. Languages are listed in alphabetical order by language code (for example, `af`, `ar`). + Lists all supported languages for translation. The method returns an array of supported languages with information + about each language. Languages are listed in alphabetical order by language code (for example, `af`, `ar`). In + addition to basic information about each language, the response indicates whether the language is + `supported_as_source` for translation and `supported_as_target` for translation. It also lists whether the language + is `identifiable`. - 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 @@ -142,12 +160,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listLanguages") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -157,7 +175,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -182,8 +200,11 @@ public class LanguageTranslator { source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language. + You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded + in UTF-8 format. - - parameter text: Input text in UTF-8 encoding. Multiple entries result in multiple translations in the response. + - parameter text: Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single + request. Multiple elements result in multiple translations in the response. - parameter modelID: The model to use for translation. For example, `en-de` selects the IBM-provided base model for English-to-German translation. A model ID overrides the `source` and `target` parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language. @@ -206,23 +227,23 @@ public class LanguageTranslator { // construct body let translateRequest = TranslateRequest( text: text, - modelID: modelID, + model_id: modelID, source: source, target: target) guard let body = try? JSON.encoder.encode(translateRequest) else { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -232,7 +253,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -251,6 +272,16 @@ public class LanguageTranslator { request.responseObject(completionHandler: completionHandler) } + // Private struct for the translate request body + private struct TranslateRequest: Encodable { + // swiftlint:disable identifier_name + let text: [String] + let model_id: String? + let source: String? + let target: String? + // swiftlint:enable identifier_name + } + /** List identifiable languages. @@ -266,12 +297,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listIdentifiableLanguages") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -281,7 +312,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -313,23 +344,22 @@ public class LanguageTranslator { headers: [String: String]? = nil, completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { - // construct body // convert body parameter to Data with UTF-8 encoding guard let body = text.data(using: .utf8) else { - let error = WatsonError.serialization(values: "text could not be encoded with UTF8.") + let error = RestError.serialization(values: "text could not be encoded with UTF8.") completionHandler(nil, error) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -339,7 +369,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -381,12 +411,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -408,7 +438,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -453,9 +483,11 @@ public class LanguageTranslator { * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories. * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The - first row contains the language code. + first row must have two language codes. The first column is for the source language code, and the second column is + for the target language code. * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. - The first row contains the language code. + The first row must have two language codes. The first column is for the source language code, and the second column + is for the target language code. * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and phrases. * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code. @@ -517,19 +549,19 @@ public class LanguageTranslator { multipartFormData.append(parallelCorpus, withName: "parallel_corpus", fileName: "filename") } guard let body = try? multipartFormData.toData() else { - completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) + completionHandler(nil, RestError.serialization(values: "request multipart form data")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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 + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -544,7 +576,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -579,12 +611,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -593,13 +625,13 @@ public class LanguageTranslator { // construct REST request let path = "/v3/models/\(modelID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -634,12 +666,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getModel") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -648,13 +680,13 @@ public class LanguageTranslator { // construct REST request let path = "/v3/models/\(modelID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -686,12 +718,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listDocuments") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -701,7 +733,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -723,12 +755,14 @@ public class LanguageTranslator { Translate document. Submit a document for translation. You can submit the document contents in the `file` parameter, or you can - reference a previously submitted document by document ID. - - - parameter file: The contents of the source file to translate. - [Supported file - types](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) - Maximum file size: **20 MB**. + reference a previously submitted document by document ID. The maximum file size for document translation is + * 20 MB for service instances on the Standard, Advanced, and Premium plans + * 2 MB for service instances on the Lite plan. + + - parameter file: The contents of the source file to translate. The maximum file size for document translation is + 20 MB for service instances on the Standard, Advanced, and Premium plans, and 2 MB for service instances on the + Lite plan. For more information, see [Supported file formats + (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - parameter filename: The filename for file. - parameter fileContentType: The content type of file. - parameter modelID: The model to use for translation. For example, `en-de` selects the IBM-provided base model @@ -779,19 +813,19 @@ public class LanguageTranslator { } } guard let body = try? multipartFormData.toData() else { - completionHandler(nil, WatsonError.serialization(values: "request multipart form data")) + completionHandler(nil, RestError.serialization(values: "request multipart form data")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "translateDocument") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" headerParameters["Content-Type"] = multipartFormData.contentType + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -801,7 +835,7 @@ public class LanguageTranslator { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -836,12 +870,12 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getDocumentStatus") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -850,13 +884,13 @@ public class LanguageTranslator { // construct REST request let path = "/v3/documents/\(documentID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -890,11 +924,11 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders + let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDocument") + headerParameters.merge(sdkHeaders) { (_, new) in new } if let headers = headers { headerParameters.merge(headers) { (_, new) in new } } - let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteDocument") - headerParameters.merge(sdkHeaders) { (_, new) in new } // construct query parameters var queryParameters = [URLQueryItem]() @@ -903,13 +937,13 @@ public class LanguageTranslator { // construct REST request let path = "/v3/documents/\(documentID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -953,14 +987,14 @@ public class LanguageTranslator { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getTranslatedDocument") headerParameters.merge(sdkHeaders) { (_, new) in new } if let accept = accept { headerParameters["Accept"] = accept } + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -969,13 +1003,13 @@ public class LanguageTranslator { // construct REST request let path = "/v3/documents/\(documentID)/translated_document" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } diff --git a/Sources/LanguageTranslatorV3/Models/TranslateRequest.swift b/Sources/LanguageTranslatorV3/Models/TranslateRequest.swift deleted file mode 100644 index 952c78340..000000000 --- a/Sources/LanguageTranslatorV3/Models/TranslateRequest.swift +++ /dev/null @@ -1,82 +0,0 @@ -/** - * (C) Copyright IBM Corp. 2018, 2020. - * - * 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 - -/** TranslateRequest. */ -internal struct TranslateRequest: Codable, Equatable { - - /** - Input text in UTF-8 encoding. Multiple entries result in multiple translations in the response. - */ - public var text: [String] - - /** - The model to use for translation. For example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and is required if you use a custom model. - If no model ID is specified, you must specify at least a target language. - */ - public var modelID: String? - - /** - Language code that specifies the language of the input text. If omitted, the service derives the source language - from the input text. The input must contain sufficient text for the service to identify the language reliably. - */ - public var source: String? - - /** - Language code that specifies the target language for translation. Required if model ID is not specified. - */ - public var target: String? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case text = "text" - case modelID = "model_id" - case source = "source" - case target = "target" - } - - /** - Initialize a `TranslateRequest` with member variables. - - - parameter text: Input text in UTF-8 encoding. Multiple entries result in multiple translations in the - response. - - parameter modelID: The model to use for translation. For example, `en-de` selects the IBM-provided base model - for English-to-German translation. A model ID overrides the `source` and `target` parameters and is required if - you use a custom model. If no model ID is specified, you must specify at least a target language. - - parameter source: Language code that specifies the language of the input text. If omitted, the service derives - the source language from the input text. The input must contain sufficient text for the service to identify the - language reliably. - - parameter target: Language code that specifies the target language for translation. Required if model ID is - not specified. - - - returns: An initialized `TranslateRequest`. - */ - public init( - text: [String], - modelID: String? = nil, - source: String? = nil, - target: String? = nil - ) - { - self.text = text - self.modelID = modelID - self.source = source - self.target = target - } - -} diff --git a/Sources/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift b/Sources/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift deleted file mode 100644 index b117b261d..000000000 --- a/Sources/NaturalLanguageClassifierV1/Models/ClassifyCollectionInput.swift +++ /dev/null @@ -1,48 +0,0 @@ -/** - * (C) Copyright IBM Corp. 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 - -/** - Request payload to classify. - */ -internal struct ClassifyCollectionInput: Codable, Equatable { - - /** - The submitted phrases. - */ - public var collection: [ClassifyInput] - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case collection = "collection" - } - - /** - Initialize a `ClassifyCollectionInput` with member variables. - - - parameter collection: The submitted phrases. - - - returns: An initialized `ClassifyCollectionInput`. - */ - public init( - collection: [ClassifyInput] - ) - { - self.collection = collection - } - -} diff --git a/Sources/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift b/Sources/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift index 22a828317..ac22ba113 100644 --- a/Sources/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift +++ b/Sources/NaturalLanguageClassifierV1/NaturalLanguageClassifier.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2016, 2020. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ + +/** + * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-36b26b63-20201028-122900 + **/ + // swiftlint:disable file_length import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif import IBMSwiftSDKCore +public typealias WatsonError = RestError +public typealias WatsonResponse = RestResponse /** IBM Watson™ Natural Language Classifier uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a classifier to connect predefined classes to example texts so that @@ -29,7 +39,9 @@ public class NaturalLanguageClassifier { public var serviceURL: String? = "https://api.us-south.natural-language-classifier.watson.cloud.ibm.com" /// Service identifiers - internal let serviceName = "NaturalLanguageClassifier" + public static let defaultServiceName = "natural_language_classifier" + // Service info for SDK headers + internal let serviceName = defaultServiceName internal let serviceVersion = "v1" internal let serviceSdkName = "natural_language_classifier" @@ -43,26 +55,26 @@ public class NaturalLanguageClassifier { /** Create a `NaturalLanguageClassifier` object. - This initializer will retrieve credentials from the environment or a local credentials file. + If an authenticator is not supplied, the initializer will retrieve credentials from the environment or + a local credentials file and construct an appropriate authenticator using these credentials. 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 credentials are not available in the environment or a local credentials file, initialization will fail. + If an authenticator is not supplied and credentials are not available in the environment or a local + credentials file, initialization will fail by throwing an exception. In that case, try another initializer that directly passes in the credentials. + - parameter authenticator: The Authenticator object used to authenticate requests to the service + - serviceName: String = defaultServiceName */ - public init() throws { - let authenticator = try ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceSdkName) - self.authenticator = authenticator - - if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceSdkName) { + public init(authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws { + self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName) + if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) { self.serviceURL = serviceURL } - RestRequest.userAgent = Shared.userAgent } - #endif - + #else /** Create a `NaturalLanguageClassifier` object. @@ -72,6 +84,7 @@ public class NaturalLanguageClassifier { self.authenticator = authenticator RestRequest.userAgent = Shared.userAgent } + #endif #if !os(Linux) /** @@ -90,7 +103,7 @@ public class NaturalLanguageClassifier { - parameter data: Raw data returned by the service that may represent an error. - parameter response: the URL response returned by the service. */ - func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> WatsonError { + func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError { let statusCode = response.statusCode var errorMessage: String? @@ -115,7 +128,7 @@ public class NaturalLanguageClassifier { errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) + return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -136,33 +149,33 @@ public class NaturalLanguageClassifier { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let classifyRequest = ClassifyInput( + let classifyRequest = ClassifyRequest( text: text) guard let body = try? JSON.encoder.encode(classifyRequest) else { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request let path = "/v1/classifiers/\(classifierID)/classify" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -180,6 +193,13 @@ public class NaturalLanguageClassifier { request.responseObject(completionHandler: completionHandler) } + // Private struct for the classify request body + private struct ClassifyRequest: Encodable { + // swiftlint:disable identifier_name + let text: String + // swiftlint:enable identifier_name + } + /** Classify multiple phrases. @@ -199,33 +219,33 @@ public class NaturalLanguageClassifier { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let classifyCollectionRequest = ClassifyCollectionInput( + let classifyCollectionRequest = ClassifyCollectionRequest( collection: collection) guard let body = try? JSON.encoder.encode(classifyCollectionRequest) else { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request let path = "/v1/classifiers/\(classifierID)/classify_collection" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -243,6 +263,13 @@ public class NaturalLanguageClassifier { request.responseObject(completionHandler: completionHandler) } + // Private struct for the classifyCollection request body + private struct ClassifyCollectionRequest: Encodable { + // swiftlint:disable identifier_name + let collection: [ClassifyInput] + // swiftlint:enable identifier_name + } + /** Create classifier. @@ -270,25 +297,25 @@ public class NaturalLanguageClassifier { multipartFormData.append(trainingMetadata, 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")) + completionHandler(nil, RestError.serialization(values: "request multipart form data")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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 + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -320,18 +347,18 @@ public class NaturalLanguageClassifier { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listClassifiers") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -364,23 +391,23 @@ public class NaturalLanguageClassifier { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "getClassifier") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request let path = "/v1/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -411,23 +438,23 @@ public class NaturalLanguageClassifier { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteClassifier") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct REST request let path = "/v1/classifiers/\(classifierID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } diff --git a/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift b/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift index 177f6c5b6..d3c9c8614 100644 --- a/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift +++ b/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResults.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2017, 2019. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ public struct AnalysisResults: Codable, Equatable { /** Webpage metadata, such as the author and the title of the page. */ - public var metadata: AnalysisResultsMetadata? + public var metadata: FeaturesResultsMetadata? /** The relationships between entities in the content. diff --git a/Sources/NaturalLanguageUnderstandingV1/Models/Features.swift b/Sources/NaturalLanguageUnderstandingV1/Models/Features.swift index 914239698..755e03943 100644 --- a/Sources/NaturalLanguageUnderstandingV1/Models/Features.swift +++ b/Sources/NaturalLanguageUnderstandingV1/Models/Features.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2017, 2020. + * (C) Copyright IBM Corp. 2020. * * 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 IBMSwiftSDKCore /** Analysis features and options. @@ -55,7 +56,7 @@ public struct Features: Codable, Equatable { 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? + public var metadata: [String: JSON]? /** Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation @@ -146,7 +147,7 @@ public struct Features: Codable, Equatable { emotion: EmotionOptions? = nil, entities: EntitiesOptions? = nil, keywords: KeywordsOptions? = nil, - metadata: MetadataOptions? = nil, + metadata: [String: JSON]? = nil, relations: RelationsOptions? = nil, semanticRoles: SemanticRolesOptions? = nil, sentiment: SentimentOptions? = nil, diff --git a/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift b/Sources/NaturalLanguageUnderstandingV1/Models/FeaturesResultsMetadata.swift similarity index 93% rename from Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift rename to Sources/NaturalLanguageUnderstandingV1/Models/FeaturesResultsMetadata.swift index f397aed2b..8b83c2f66 100644 --- a/Sources/NaturalLanguageUnderstandingV1/Models/AnalysisResultsMetadata.swift +++ b/Sources/NaturalLanguageUnderstandingV1/Models/FeaturesResultsMetadata.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2019. + * (C) Copyright IBM Corp. 2020. * * 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 /** Webpage metadata, such as the author and the title of the page. */ -public struct AnalysisResultsMetadata: Codable, Equatable { +public struct FeaturesResultsMetadata: Codable, Equatable { /** The authors of the document. diff --git a/Sources/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift b/Sources/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift deleted file mode 100644 index 95c7e89a5..000000000 --- a/Sources/NaturalLanguageUnderstandingV1/Models/MetadataOptions.swift +++ /dev/null @@ -1,25 +0,0 @@ -/** - * (C) Copyright IBM Corp. 2017, 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 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() { } -} diff --git a/Sources/NaturalLanguageUnderstandingV1/Models/Parameters.swift b/Sources/NaturalLanguageUnderstandingV1/Models/Parameters.swift deleted file mode 100644 index a1295f7af..000000000 --- a/Sources/NaturalLanguageUnderstandingV1/Models/Parameters.swift +++ /dev/null @@ -1,143 +0,0 @@ -/** - * (C) Copyright IBM Corp. 2017, 2020. - * - * 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 object containing request parameters. - */ -internal struct Parameters: Codable, Equatable { - - /** - The plain text to analyze. One of the `text`, `html`, or `url` parameters is required. - */ - public var text: String? - - /** - The HTML file to analyze. One of the `text`, `html`, or `url` parameters is required. - */ - public var html: String? - - /** - The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. - */ - public var url: String? - - /** - Specific features to analyze the document for. - */ - public var features: Features - - /** - Set this to `false` to disable webpage cleaning. For more information about webpage cleaning, see [Analyzing - webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages). - */ - public var clean: Bool? - - /** - An [XPath - query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) - to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text before it is - analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`. - */ - public var xpath: String? - - /** - Whether to use raw HTML content if text cleaning fails. - */ - public var fallbackToRaw: Bool? - - /** - Whether or not to return the analyzed text. - */ - public var returnAnalyzedText: Bool? - - /** - 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. For more information, see [Language - support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support). - */ - public var language: String? - - /** - Sets the maximum number of characters that are processed by the service. - */ - public var limitTextCharacters: Int? - - // Map each property name to the key that shall be used for encoding/decoding. - private enum CodingKeys: String, CodingKey { - case text = "text" - case html = "html" - case url = "url" - case features = "features" - case clean = "clean" - case xpath = "xpath" - case fallbackToRaw = "fallback_to_raw" - case returnAnalyzedText = "return_analyzed_text" - case language = "language" - case limitTextCharacters = "limit_text_characters" - } - - /** - Initialize a `Parameters` with member variables. - - - 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. - - parameter clean: Set this to `false` to disable webpage cleaning. For more information about webpage cleaning, - see [Analyzing - webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages). - - parameter xpath: An [XPath - query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) - to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text before it - is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`. - - parameter fallbackToRaw: Whether to use raw HTML content if text cleaning fails. - - 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. For more information, - see [Language - support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support). - - parameter limitTextCharacters: Sets the maximum number of characters that are processed by the service. - - - returns: An initialized `Parameters`. - */ - public init( - features: Features, - text: String? = nil, - html: String? = nil, - url: String? = nil, - clean: Bool? = nil, - xpath: String? = nil, - fallbackToRaw: Bool? = nil, - returnAnalyzedText: Bool? = nil, - language: String? = nil, - limitTextCharacters: Int? = nil - ) - { - self.features = features - self.text = text - self.html = html - self.url = url - self.clean = clean - self.xpath = xpath - self.fallbackToRaw = fallbackToRaw - self.returnAnalyzedText = returnAnalyzedText - self.language = language - self.limitTextCharacters = limitTextCharacters - } - -} diff --git a/Sources/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift b/Sources/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift index 5a42adcd0..f42788c9c 100644 --- a/Sources/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift +++ b/Sources/NaturalLanguageUnderstandingV1/NaturalLanguageUnderstanding.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2017, 2020. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ + +/** + * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-36b26b63-20201028-122900 + **/ + // swiftlint:disable file_length import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif import IBMSwiftSDKCore +public typealias WatsonError = RestError +public typealias WatsonResponse = RestResponse /** Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you request. The service cleans HTML content before @@ -31,8 +41,14 @@ public class NaturalLanguageUnderstanding { /// The base URL to use when contacting the service. public var serviceURL: String? = "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" + /// Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is + /// `2020-08-01`. + public var version: String + /// Service identifiers - internal let serviceName = "NaturalLanguageUnderstanding" + public static let defaultServiceName = "natural-language-understanding" + // Service info for SDK headers + internal let serviceName = defaultServiceName internal let serviceVersion = "v1" internal let serviceSdkName = "natural_language_understanding" @@ -41,41 +57,39 @@ public class NaturalLanguageUnderstanding { var session = URLSession(configuration: URLSessionConfiguration.default) public let authenticator: Authenticator - let version: String #if os(Linux) /** Create a `NaturalLanguageUnderstanding` object. - This initializer will retrieve credentials from the environment or a local credentials file. + If an authenticator is not supplied, the initializer will retrieve credentials from the environment or + a local credentials file and construct an appropriate authenticator using these credentials. 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 credentials are not available in the environment or a local credentials file, initialization will fail. + If an authenticator is not supplied and credentials are not available in the environment or a local + credentials file, initialization will fail by throwing an exception. In that case, try another initializer that directly passes in the credentials. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The + current version is `2020-08-01`. + - parameter authenticator: The Authenticator object used to authenticate requests to the service + - serviceName: String = defaultServiceName */ - public init(version: String) throws { + public init(version: String, authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws { self.version = version - - let authenticator = try ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceSdkName) - self.authenticator = authenticator - - if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceSdkName) { + self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName) + if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) { self.serviceURL = serviceURL } - RestRequest.userAgent = Shared.userAgent } - #endif - + #else /** Create a `NaturalLanguageUnderstanding` object. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The + current version is `2020-08-01`. - parameter authenticator: The Authenticator object used to authenticate requests to the service */ public init(version: String, authenticator: Authenticator) { @@ -83,6 +97,7 @@ public class NaturalLanguageUnderstanding { self.authenticator = authenticator RestRequest.userAgent = Shared.userAgent } + #endif #if !os(Linux) /** @@ -101,7 +116,7 @@ public class NaturalLanguageUnderstanding { - parameter data: Raw data returned by the service that may represent an error. - parameter response: the URL response returned by the service. */ - func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> WatsonError { + func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError { let statusCode = response.statusCode var errorMessage: String? @@ -126,7 +141,7 @@ public class NaturalLanguageUnderstanding { errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) + return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -142,7 +157,8 @@ public class NaturalLanguageUnderstanding { - Relations - Semantic roles - Sentiment - - Syntax. + - Syntax + - Summarization (Experimental) If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -183,31 +199,31 @@ public class NaturalLanguageUnderstanding { completionHandler: @escaping (WatsonResponse?, WatsonError?) -> Void) { // construct body - let analyzeRequest = Parameters( + let analyzeRequest = AnalyzeRequest( features: features, text: text, html: html, url: url, clean: clean, xpath: xpath, - fallbackToRaw: fallbackToRaw, - returnAnalyzedText: returnAnalyzedText, + fallback_to_raw: fallbackToRaw, + return_analyzed_text: returnAnalyzedText, language: language, - limitTextCharacters: limitTextCharacters) + limit_text_characters: limitTextCharacters) guard let body = try? JSON.encoder.encode(analyzeRequest) else { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, 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" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -217,7 +233,7 @@ public class NaturalLanguageUnderstanding { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -236,6 +252,22 @@ public class NaturalLanguageUnderstanding { request.responseObject(completionHandler: completionHandler) } + // Private struct for the analyze request body + private struct AnalyzeRequest: Encodable { + // swiftlint:disable identifier_name + let features: Features + let text: String? + let html: String? + let url: String? + let clean: Bool? + let xpath: String? + let fallback_to_raw: Bool? + let return_analyzed_text: Bool? + let language: String? + let limit_text_characters: Int? + // swiftlint:enable identifier_name + } + /** List models. @@ -252,12 +284,12 @@ public class NaturalLanguageUnderstanding { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "listModels") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -267,7 +299,7 @@ public class NaturalLanguageUnderstanding { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -301,12 +333,12 @@ public class NaturalLanguageUnderstanding { { // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "deleteModel") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -315,13 +347,13 @@ public class NaturalLanguageUnderstanding { // construct REST request let path = "/v1/models/\(modelID)" guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { - completionHandler(nil, WatsonError.urlEncoding(path: path)) + completionHandler(nil, RestError.urlEncoding(path: path)) return } // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } diff --git a/Sources/PersonalityInsightsV3/PersonalityInsights.swift b/Sources/PersonalityInsightsV3/PersonalityInsights.swift index 0285d642f..b0c1d2cdd 100644 --- a/Sources/PersonalityInsightsV3/PersonalityInsights.swift +++ b/Sources/PersonalityInsightsV3/PersonalityInsights.swift @@ -1,5 +1,5 @@ /** - * (C) Copyright IBM Corp. 2016, 2020. + * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. **/ + +/** + * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-36b26b63-20201028-122900 + **/ + // swiftlint:disable file_length import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif import IBMSwiftSDKCore +public typealias WatsonError = RestError +public typealias WatsonResponse = RestResponse /** The IBM Watson™ Personality Insights service enables applications to derive insights from social media, enterprise data, or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic @@ -38,8 +48,14 @@ public class PersonalityInsights { /// The base URL to use when contacting the service. public var serviceURL: String? = "https://api.us-south.personality-insights.watson.cloud.ibm.com" + /// Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version + /// is `2017-10-13`. + public var version: String + /// Service identifiers - internal let serviceName = "PersonalityInsights" + public static let defaultServiceName = "personality_insights" + // Service info for SDK headers + internal let serviceName = defaultServiceName internal let serviceVersion = "v3" internal let serviceSdkName = "personality_insights" @@ -48,41 +64,39 @@ public class PersonalityInsights { var session = URLSession(configuration: URLSessionConfiguration.default) public let authenticator: Authenticator - let version: String #if os(Linux) /** Create a `PersonalityInsights` object. - This initializer will retrieve credentials from the environment or a local credentials file. + If an authenticator is not supplied, the initializer will retrieve credentials from the environment or + a local credentials file and construct an appropriate authenticator using these credentials. 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 credentials are not available in the environment or a local credentials file, initialization will fail. + If an authenticator is not supplied and credentials are not available in the environment or a local + credentials file, initialization will fail by throwing an exception. In that case, try another initializer that directly passes in the credentials. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. + The current version is `2017-10-13`. + - parameter authenticator: The Authenticator object used to authenticate requests to the service + - serviceName: String = defaultServiceName */ - public init(version: String) throws { + public init(version: String, authenticator: Authenticator? = nil, serviceName: String = defaultServiceName) throws { self.version = version - - let authenticator = try ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceSdkName) - self.authenticator = authenticator - - if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceSdkName) { + self.authenticator = try authenticator ?? ConfigBasedAuthenticatorFactory.getAuthenticator(credentialPrefix: serviceName) + if let serviceURL = CredentialUtils.getServiceURL(credentialPrefix: serviceName) { self.serviceURL = serviceURL } - RestRequest.userAgent = Shared.userAgent } - #endif - + #else /** Create a `PersonalityInsights` object. - - parameter version: The release date of the version of the API to use. Specify the date - in "YYYY-MM-DD" format. + - parameter version: Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. + The current version is `2017-10-13`. - parameter authenticator: The Authenticator object used to authenticate requests to the service */ public init(version: String, authenticator: Authenticator) { @@ -90,6 +104,7 @@ public class PersonalityInsights { self.authenticator = authenticator RestRequest.userAgent = Shared.userAgent } + #endif #if !os(Linux) /** @@ -108,7 +123,7 @@ public class PersonalityInsights { - parameter data: Raw data returned by the service that may represent an error. - parameter response: the URL response returned by the service. */ - func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> WatsonError { + func errorResponseDecoder(data: Data, response: HTTPURLResponse) -> RestError { let statusCode = response.statusCode var errorMessage: String? @@ -133,7 +148,7 @@ public class PersonalityInsights { errorMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode) } - return WatsonError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) + return RestError.http(statusCode: statusCode, message: errorMessage, metadata: metadata) } /** @@ -184,6 +199,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. @@ -194,21 +211,18 @@ 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) { - // construct body guard let body = profileContent.content else { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profile") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "application/json" @@ -219,6 +233,9 @@ public class PersonalityInsights { if let acceptLanguage = acceptLanguage { headerParameters["Accept-Language"] = acceptLanguage } + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -227,6 +244,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) @@ -236,7 +257,7 @@ public class PersonalityInsights { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return } @@ -318,19 +339,15 @@ 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 { - completionHandler(nil, WatsonError.serialization(values: "request body")) + completionHandler(nil, RestError.serialization(values: "request body")) return } // construct header parameters var headerParameters = defaultHeaders - if let headers = headers { - headerParameters.merge(headers) { (_, new) in new } - } let sdkHeaders = Shared.getSDKHeaders(serviceName: serviceName, serviceVersion: serviceVersion, methodName: "profileAsCSV") headerParameters.merge(sdkHeaders) { (_, new) in new } headerParameters["Accept"] = "text/csv" @@ -341,6 +358,9 @@ public class PersonalityInsights { if let acceptLanguage = acceptLanguage { headerParameters["Accept-Language"] = acceptLanguage } + if let headers = headers { + headerParameters.merge(headers) { (_, new) in new } + } // construct query parameters var queryParameters = [URLQueryItem]() @@ -362,7 +382,7 @@ public class PersonalityInsights { // ensure that serviceURL is set guard let serviceEndpoint = serviceURL else { - completionHandler(nil, WatsonError.noEndpoint) + completionHandler(nil, RestError.noEndpoint) return }