     /// The default HTTP headers for all requests to the service.
     public var defaultHeaders = [String: String]()
 
-    internal let username: String
-    internal let password: String
     internal let credentials: Credentials
     internal let domain = "com.ibm.watson.developer-cloud.SpeechToTextV1"
 

/**
 * Copyright IBM Corporation 2016, 2018
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.

        do {
            let json = try JSONWrapper(data: data)
            let code = response?.statusCode ?? 400
            return NSError(domain: domain, code: code, userInfo: nil)
        } catch {
            return nil
        }
    }

    /**
     Get models.

     Retrieves a list of all language models that are available for use with the service. The information includes the
     name of the model and its minimum sampling rate in Hertz, among other things.

     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func listModels(
        failure: ((Error) -> Void)? = nil,
        success: @escaping (SpeechModels) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct REST request
        let request = RestRequest(
            method: "GET",
            url: serviceURL + "/v1/models",
            credentials: credentials,
            headerParameters: headers
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<SpeechModels>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Get a model.

     Retrieves information about a single specified language model that is available for use with the service. The
     information includes the name of the model and its minimum sampling rate in Hertz, among other things.

     - parameter modelID: The identifier of the desired model in the form of its `name` from the output of the **Get models** method.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func getModel(
        modelID: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (SpeechModel) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct REST request
        let path = "/v1/models/\(modelID)"
        guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
            failure?(RestError.encodingError)
            return
        }
        let request = RestRequest(
            method: "GET",
            url: serviceURL + encodedPath,
            credentials: credentials,
            headerParameters: headers
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<SpeechModel>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Sends audio for speech recognition in sessionless mode.

     Sends audio and returns transcription results for a sessionless recognition request. Returns only the final
     results; to enable interim results, use session-based requests or the WebSocket API. The service imposes a data
     size limit of 100 MB. It automatically detects the endianness of the incoming audio and, for audio that includes
     multiple channels, downmixes the audio to one-channel mono during transcoding. (For the `audio/l16` format, you can
     specify the endianness.)   ###Streaming mode   For requests to transcribe live audio as it becomes available or to
     transcribe multiple audio files with multipart requests, 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 the service 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.   ###Non-multipart
     requests   For non-multipart requests, you specify all parameters of the request as a collection of request headers
     and query parameters, and you provide the audio as the body of the request. This is the recommended means of
     submitting a recognition request. Use the following parameters: * **Required:** `Content-Type` and `audio` *
     **Optional:** `Transfer-Encoding`, `model`, `customization_id`, `acoustic_customization_id`, `base_model_version`,
     `customization_weight`, `inactivity_timeout`, `keywords`, `keywords_threshold`, `max_alternatives`,
     `word_alternatives_threshold`, `word_confidence`, `timestamps`, `profanity_filter`, `smart_formatting`, and
     `speaker_labels`     ###Multipart requests   For multipart requests, you specify a few parameters of the request as
     request headers and query parameters, but you specify most parameters as multipart form data in the form of JSON
     metadata, in which only `part_content_type` is required. You then specify the audio files for the request as
     subsequent parts of the form data. Use this approach with browsers that do not support JavaScript or when the
     parameters of the request are greater than the 8 KB limit imposed by most HTTP servers and proxies. Use the
     following parameters: * **Required:** `Content-Type`, `metadata`, and `upload` * **Optional:** `Transfer-Encoding`,
     `model`, `customization_id`, `acoustic_customization_id`, and `base_model_version`   An example of the multipart
     metadata for a pair of FLAC files follows. This first part of the request is sent as JSON; the remaining parts are
     the audio files for the request.
     `metadata=\"{\\\"part_content_type\\\":\\\"audio/flac\\\",\\\"data_parts_count\\\":2,\\\"inactivity_timeout\\\"=-1}\"`
       **Note about the Try It Out feature:** The `Try it out!` button is **not** supported for use with the the `POST
     /v1/recognize` method. For examples of calls to the method, see the [Speech to Text API
     reference](http://www.ibm.com/watson/developercloud/speech-to-text/api/v1/).

     - parameter model: The identifier of the model that is to be used for the recognition request or, for the **Create a session** method,
     with the new session.
     - parameter customizationID: The GUID of a custom language model that is to be used with the recognition request or, for the **Create a
     session** method, with the new session. 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.
     - parameter acousticCustomizationID: The GUID of a custom acoustic model that is to be used with the recognition request or, for the **Create a
     session** method, with the new session. The base model of the specified custom acoustic 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 acoustic model is used.
     - parameter baseModelVersion: The version of the specified base model that is to be used with recognition request or, for the **Create a
     session** method, with the new session. 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. For more
     information, see [Base model version](https://console.bluemix.net/docs/services/speech-to-text/input.html#version).
     - parameter customizationWeight: If you specify the GUID of a custom language model with the recognition request or, for sessions, with the **Create
     a session** method, the customization weight tells the service how much weight to give to words from the custom
     language model compared to those from the base model for the current request.   Specify a value between 0.0 and
     1.0. Unless a different customization weight was specified for the custom model when it was trained, the default
     value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model
     was trained.   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.   **Do not use with MULTIPART recognition requests.**.
     - parameter audio: The audio to transcribe in the format specified by the `Content-Type` header.   **Required for NON-MULTIPART
     recognition requests. Do not use with MULTIPART recognition requests.**.
     - parameter contentType: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg,
     audio/ogg;codecs=opus, audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus,
     audio/webm;codecs=vorbis, or multipart/form-data.
     - 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. Useful for stopping audio submission from a live microphone when a user simply walks away.
     Use `-1` for infinity.   **Do not use with MULTIPART recognition requests.**.
     - parameter keywords: NON-MULTIPART ONLY: An array of keyword strings to spot in the audio. Each keyword string can include one or more
     tokens. Keywords are spotted only in the final hypothesis, not in interim results. If you specify any keywords, you
     must also specify a keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an
     empty array if you do not need to spot keywords.
     - parameter keywordsThreshold: NON-MULTIPART ONLY: A confidence value that is the lower bound for spotting a keyword. A word is considered to
     match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0 and 1
     inclusive. No keyword spotting is performed if you omit the parameter. If you specify a threshold, you must also
     specify one or more keywords.
     - parameter maxAlternatives: NON-MULTIPART ONLY: The maximum number of alternative transcripts to be returned. By default, a single
     transcription is returned.
     - parameter wordAlternativesThreshold: NON-MULTIPART ONLY: 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 confidence is greater
     than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No alternative words are computed
     if you omit the parameter.
     - parameter wordConfidence: If `true`, a confidence measure in the range of 0 to 1 is returned for each word. By default, no word confidence
     measures are returned.   **Do not use with MULTIPART recognition requests.**.
     - parameter timestamps: If `true`, time alignment is returned for each word. By default, no timestamps are returned.   **Do not use with
     MULTIPART recognition requests.**.
     - parameter profanityFilter: If `true` (the default), filters profanity from all output except for keyword results by replacing inappropriate
     words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US
     English transcription only.   **Do not use with MULTIPART recognition requests.**.
     - parameter smartFormatting: If `true`, converts dates, times, series of digits and numbers, phone numbers, currency values, and Internet
     addresses into more readable, conventional representations in the final transcript of a recognition request. By
     default, no smart formatting is performed. Applies to US English transcription only.   **Do not use with MULTIPART
     recognition requests.**.
     - parameter speakerLabels: If `true`, the response includes labels that identify which words were spoken by which participants in a
     multi-person exchange. By default, no speaker labels are returned. Setting `speaker_labels` to `true` forces the
     `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter.   To determine
     whether a language model supports speaker labels, use the **Get models** method and check that the attribute
     `speaker_labels` is set to `true`. You can also refer to [Speaker
     labels](https://console.bluemix.net/docs/services/speech-to-text/output.html#speaker_labels).   **Do not use with
     MULTIPART recognition requests.**.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func recognizeSessionless(
        model: String? = nil,
        customizationID: String? = nil,
        acousticCustomizationID: String? = nil,
        baseModelVersion: String? = nil,
        customizationWeight: Double? = nil,
        audio: Data? = nil,
        contentType: String? = nil,
        inactivityTimeout: Int? = nil,
        keywords: [String]? = nil,
        keywordsThreshold: Double? = nil,
        maxAlternatives: Int? = nil,
        wordAlternativesThreshold: Double? = nil,
        wordConfidence: Bool? = nil,
        timestamps: Bool? = nil,
        profanityFilter: Bool? = nil,
        smartFormatting: Bool? = nil,
        speakerLabels: Bool? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (SpeechRecognitionResults) -> Void)
    {
        // construct body
        let body = audio

        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"
        if let contentType = contentType {
            headers["Content-Type"] = contentType
        }

        // construct query parameters
        var queryParameters = [URLQueryItem]()
        if let model = model {
            let queryParameter = URLQueryItem(name: "model", value: model)
            queryParameters.append(queryParameter)
        }
        if let customizationID = customizationID {
            let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
            queryParameters.append(queryParameter)
        }
        if let acousticCustomizationID = acousticCustomizationID {
            let queryParameter = URLQueryItem(name: "acoustic_customization_id", value: acousticCustomizationID)
            queryParameters.append(queryParameter)
        }
        if let baseModelVersion = baseModelVersion {
            let queryParameter = URLQueryItem(name: "base_model_version", value: baseModelVersion)
            queryParameters.append(queryParameter)
        }
        if let customizationWeight = customizationWeight {
            let queryParameter = URLQueryItem(name: "customization_weight", value: "\(customizationWeight)")
            queryParameters.append(queryParameter)
        }
        if let inactivityTimeout = inactivityTimeout {
            let queryParameter = URLQueryItem(name: "inactivity_timeout", value: "\(inactivityTimeout)")
            queryParameters.append(queryParameter)
        }
        if let keywords = keywords {
            let queryParameter = URLQueryItem(name: "keywords", value: keywords.joined(separator: ","))
            queryParameters.append(queryParameter)
        }
        if let keywordsThreshold = keywordsThreshold {
            let queryParameter = URLQueryItem(name: "keywords_threshold", value: "\(keywordsThreshold)")
            queryParameters.append(queryParameter)
        }
        if let maxAlternatives = maxAlternatives {
            let queryParameter = URLQueryItem(name: "max_alternatives", value: "\(maxAlternatives)")
            queryParameters.append(queryParameter)
        }
        if let wordAlternativesThreshold = wordAlternativesThreshold {
            let queryParameter = URLQueryItem(name: "word_alternatives_threshold", value: "\(wordAlternativesThreshold)")
            queryParameters.append(queryParameter)
        }
        if let wordConfidence = wordConfidence {
            let queryParameter = URLQueryItem(name: "word_confidence", value: "\(wordConfidence)")
            queryParameters.append(queryParameter)
        }
        if let timestamps = timestamps {
            let queryParameter = URLQueryItem(name: "timestamps", value: "\(timestamps)")
            queryParameters.append(queryParameter)
        }
        if let profanityFilter = profanityFilter {
            let queryParameter = URLQueryItem(name: "profanity_filter", value: "\(profanityFilter)")
            queryParameters.append(queryParameter)
        }
        if let smartFormatting = smartFormatting {
            let queryParameter = URLQueryItem(name: "smart_formatting", value: "\(smartFormatting)")
            queryParameters.append(queryParameter)
        }
        if let speakerLabels = speakerLabels {
            let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)")
            queryParameters.append(queryParameter)
        }

        // construct REST request
        let request = RestRequest(
            method: "POST",
            url: serviceURL + "/v1/recognize",
            credentials: credentials,
            headerParameters: headers,
            queryItems: queryParameters,
            messageBody: body
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<SpeechRecognitionResults>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Register a callback.

     Registers a callback URL with the service for use with subsequent asynchronous recognition requests. The service
     attempts to register, or white-list, the callback URL if it is not already registered by sending a `GET` request to
     the callback URL. The service passes a random alphanumeric challenge string via the `challenge_string` parameter of
     the request. The request includes an `Accept` header that specifies `text/plain` as the required response type.
     To be registered successfully, the callback URL must respond to the `GET` request from the service. The response
     must send status code 200 and must include the challenge string in its body. Set the `Content-Type` response header
     to `text/plain`. Upon receiving this response, the service responds to the original registration request with
     response code 201.   The service sends only a single `GET` request to the callback URL. If the service does not
     receive a reply with a response code of 200 and a body that echoes the challenge string sent by the service within
     five seconds, it does not white-list the URL; it instead sends status code 400 in response to the **Register a
     callback** request. If the requested callback URL is already white-listed, the service responds to the initial
     registration request with response code 200.   If you specify a user secret with the request, the service uses it
     as a key to calculate an HMAC-SHA1 signature of the challenge string in its response to the `POST` request. It
     sends this signature in the `X-Callback-Signature` header of its `GET` request to the URL during registration. It
     also uses the secret to calculate a signature over the payload of every callback notification that uses the URL.
     The signature provides authentication and data integrity for HTTP communications.   After you successfully register
     a callback URL, you can use it with an indefinite number of recognition requests. You can register a maximum of 20
     callback URLS in a one-hour span of time. For more information, see [Registering a callback
     URL](https://console.bluemix.net/docs/services/speech-to-text/async.html#register).

     - parameter callbackUrl: An HTTP or HTTPS URL to which callback notifications are to be sent. To be white-listed, the URL must successfully
     echo the challenge string during URL verification. During verification, the client can also check the signature
     that the service sends in the `X-Callback-Signature` header to verify the origin of the request.
     - parameter userSecret: A user-specified string that the service uses to generate the HMAC-SHA1 signature that it sends via the
     `X-Callback-Signature` header. The service includes the header during URL verification and with every notification
     sent to the callback URL. It calculates the signature over the payload of the notification. If you omit the
     parameter, the service does not send the header.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func registerCallback(
        callbackUrl: String,
        userSecret: String? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (RegisterStatus) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct query parameters
        var queryParameters = [URLQueryItem]()
        queryParameters.append(URLQueryItem(name: "callback_url", value: callbackUrl))
        if let userSecret = userSecret {
            let queryParameter = URLQueryItem(name: "user_secret", value: userSecret)
            queryParameters.append(queryParameter)
        }

        // construct REST request
        let request = RestRequest(
            method: "POST",
            url: serviceURL + "/v1/register_callback",
            credentials: credentials,
            headerParameters: headers,
            queryItems: queryParameters
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<RegisterStatus>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Unregister a callback.

     Unregisters a callback URL that was previously white-listed with a **Register a callback** request for use with the
     asynchronous interface. Once unregistered, the URL can no longer be used with asynchronous recognition requests.

     - parameter callbackUrl: The callback URL that is to be unregistered.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func unregisterCallback(
        callbackUrl: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping () -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct query parameters
        var queryParameters = [URLQueryItem]()
        queryParameters.append(URLQueryItem(name: "callback_url", value: callbackUrl))

        // construct REST request
        let request = RestRequest(
            method: "POST",
            url: serviceURL + "/v1/unregister_callback",
            credentials: credentials,
            headerParameters: headers,
            queryItems: queryParameters
        )

        // execute REST request
        request.responseVoid(responseToError: responseToError) {
            (response: RestResponse) in
            switch response.result {
            case .success: success()
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Create a job.

     Creates a job for a new asynchronous recognition request. The job is owned by the user whose service credentials
     are used to create it. How you learn the status and results of a job depends on the parameters you include with the
     job creation request: * By callback notification: Include the `callback_url` parameter to specify a URL to which
     the service is to send callback notifications when the status of the job changes. Optionally, you can also include
     the `events` and `user_token` parameters to subscribe to specific events and to specify a string that is to be
     included with each notification for the job. * By polling the service: Omit the `callback_url`, `events`, and
     `user_token` parameters. You must then use the **Check jobs** or **Check a job** methods to check the status of the
     job, using the latter to retrieve the results when the job is complete.  The two approaches are not mutually
     exclusive. You can poll the service for job status or obtain results from the service manually even if you include
     a callback URL. In both cases, you can include the `results_ttl` parameter to specify how long the results are to
     remain available after the job is complete. For detailed usage information about the two approaches, including
     callback notifications, see [Creating a
     job](https://console.bluemix.net/docs/services/speech-to-text/async.html#create). Note that using the HTTPS **Check
     a job** method to retrieve results is more secure than receiving them via callback notification over HTTP because
     it provides confidentiality in addition to authentication and data integrity.   The method supports the same basic
     parameters as other HTTP and WebSocket recognition requests. The service imposes a data size limit of 100 MB. It
     automatically detects the endianness of the incoming audio and, for audio that includes multiple channels,
     downmixes the audio to one-channel mono during transcoding. (For the `audio/l16` format, you can specify the
     endianness.).

     - parameter audio: The audio to transcribe in the format specified by the `Content-Type` header.
     - parameter contentType: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg,
     audio/ogg;codecs=opus, audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus, or
     audio/webm;codecs=vorbis.
     - parameter model: The identifier of the model that is to be used for the recognition request or, for the **Create a session** method,
     with the new session.
     - parameter callbackUrl: A URL to which callback notifications are to be sent. The URL must already be successfully white-listed by using
     the **Register a callback** method. Omit the parameter to poll the service for job completion and results. You can
     include the same callback URL with any number of job creation requests. Use the `user_token` parameter to specify a
     unique user-specified string with each job to differentiate the callback notifications for the jobs.
     - parameter events: If the job includes a callback URL, a comma-separated list of notification events to which to subscribe. Valid
     events are: `recognitions.started` generates a callback notification when the service begins to process the job.
     `recognitions.completed` generates a callback notification when the job is complete; you must use the **Check a
     job** method to retrieve the results before they time out or are deleted. `recognitions.completed_with_results`
     generates a callback notification when the job is complete; the notification includes the results of the request.
     `recognitions.failed` generates a callback notification if the service experiences an error while processing the
     job. Omit the parameter to subscribe to the default events: `recognitions.started`, `recognitions.completed`, and
     `recognitions.failed`. The `recognitions.completed` and `recognitions.completed_with_results` events are
     incompatible; you can specify only of the two events. If the job does not include a callback URL, omit the
     parameter.
     - parameter userToken: If the job includes a callback URL, a user-specified string that the service is to include with each callback
     notification for the job; the token allows the user to maintain an internal mapping between jobs and notification
     events. If the job does not include a callback URL, omit the parameter.
     - parameter resultsTtl: The number of minutes for which the results are to be available after the job has finished. If not delivered via a
     callback, the results must be retrieved within this time. Omit the parameter to use a time to live of one week. The
     parameter is valid with or without a callback URL.
     - parameter customizationID: The GUID of a custom language model that is to be used with the recognition request or, for the **Create a
     session** method, with the new session. 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.
     - parameter acousticCustomizationID: The GUID of a custom acoustic model that is to be used with the recognition request or, for the **Create a
     session** method, with the new session. The base model of the specified custom acoustic 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 acoustic model is used.
     - parameter baseModelVersion: The version of the specified base model that is to be used with recognition request or, for the **Create a
     session** method, with the new session. 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. For more
     information, see [Base model version](https://console.bluemix.net/docs/services/speech-to-text/input.html#version).
     - parameter customizationWeight: If you specify the GUID of a custom language model with the recognition request or, for sessions, with the **Create
     a session** method, the customization weight tells the service how much weight to give to words from the custom
     language model compared to those from the base model for the current request.   Specify a value between 0.0 and
     1.0. Unless a different customization weight was specified for the custom model when it was trained, the default
     value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model
     was trained.   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.   **Do not use with MULTIPART recognition requests.**.
     - 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. Useful for stopping audio submission from a live microphone when a user simply walks away.
     Use `-1` for infinity.   **Do not use with MULTIPART recognition requests.**.
     - parameter keywords: Array of keyword strings to spot in the audio. Each keyword string can include one or more tokens. Keywords are
     spotted only in the final hypothesis, not in interim results. If you specify any keywords, you must also specify a
     keywords threshold. You can spot a maximum of 1000 keywords. Omit the parameter or specify an empty array if you do
     not need to spot keywords.
     - parameter keywordsThreshold: Confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its
     confidence is greater than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No keyword
     spotting is performed if you omit the parameter. If you specify a threshold, you must also specify one or more
     keywords.
     - parameter maxAlternatives: Maximum number of alternative transcripts to be returned. By default, a single transcription is returned.
     - parameter wordAlternativesThreshold: 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 confidence is greater than or equal to the
     threshold. Specify a probability between 0 and 1 inclusive. No alternative words are computed if you omit the
     parameter.
     - parameter wordConfidence: If `true`, a confidence measure in the range of 0 to 1 is returned for each word. By default, no word confidence
     measures are returned.   **Do not use with MULTIPART recognition requests.**.
     - parameter timestamps: If `true`, time alignment is returned for each word. By default, no timestamps are returned.   **Do not use with
     MULTIPART recognition requests.**.
     - parameter profanityFilter: If `true` (the default), filters profanity from all output except for keyword results by replacing inappropriate
     words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US
     English transcription only.   **Do not use with MULTIPART recognition requests.**.
     - parameter smartFormatting: If `true`, converts dates, times, series of digits and numbers, phone numbers, currency values, and Internet
     addresses into more readable, conventional representations in the final transcript of a recognition request. By
     default, no smart formatting is performed. Applies to US English transcription only.   **Do not use with MULTIPART
     recognition requests.**.
     - parameter speakerLabels: If `true`, the response includes labels that identify which words were spoken by which participants in a
     multi-person exchange. By default, no speaker labels are returned. Setting `speaker_labels` to `true` forces the
     `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter.   To determine
     whether a language model supports speaker labels, use the **Get models** method and check that the attribute
     `speaker_labels` is set to `true`. You can also refer to [Speaker
     labels](https://console.bluemix.net/docs/services/speech-to-text/output.html#speaker_labels).   **Do not use with
     MULTIPART recognition requests.**.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func createJob(
        audio: Data,
        contentType: String,
        model: String? = nil,
        callbackUrl: String? = nil,
        events: String? = nil,
        userToken: String? = nil,
        resultsTtl: Int? = nil,
        customizationID: String? = nil,
        acousticCustomizationID: String? = nil,
        baseModelVersion: String? = nil,
        customizationWeight: Double? = nil,
        inactivityTimeout: Int? = nil,
        keywords: [String]? = nil,
        keywordsThreshold: Double? = nil,
        maxAlternatives: Int? = nil,
        wordAlternativesThreshold: Double? = nil,
        wordConfidence: Bool? = nil,
        timestamps: Bool? = nil,
        profanityFilter: Bool? = nil,
        smartFormatting: Bool? = nil,
        speakerLabels: Bool? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (RecognitionJob) -> Void)
    {
        // construct body
        let body = audio

        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"
        headers["Content-Type"] = contentType

        // construct query parameters
        var queryParameters = [URLQueryItem]()
        if let model = model {
            let queryParameter = URLQueryItem(name: "model", value: model)
            queryParameters.append(queryParameter)
        }
        if let callbackUrl = callbackUrl {
            let queryParameter = URLQueryItem(name: "callback_url", value: callbackUrl)
            queryParameters.append(queryParameter)
        }
        if let events = events {
            let queryParameter = URLQueryItem(name: "events", value: events)
            queryParameters.append(queryParameter)
        }
        if let userToken = userToken {
            let queryParameter = URLQueryItem(name: "user_token", value: userToken)
            queryParameters.append(queryParameter)
        }
        if let resultsTtl = resultsTtl {
            let queryParameter = URLQueryItem(name: "results_ttl", value: "\(resultsTtl)")
            queryParameters.append(queryParameter)
        }
        if let customizationID = customizationID {
            let queryParameter = URLQueryItem(name: "customization_id", value: customizationID)
            queryParameters.append(queryParameter)
        }
        if let acousticCustomizationID = acousticCustomizationID {
            let queryParameter = URLQueryItem(name: "acoustic_customization_id", value: acousticCustomizationID)
            queryParameters.append(queryParameter)
        }
        if let baseModelVersion = baseModelVersion {
            let queryParameter = URLQueryItem(name: "base_model_version", value: baseModelVersion)
            queryParameters.append(queryParameter)
        }
        if let customizationWeight = customizationWeight {
            let queryParameter = URLQueryItem(name: "customization_weight", value: "\(customizationWeight)")
            queryParameters.append(queryParameter)
        }
        if let inactivityTimeout = inactivityTimeout {
            let queryParameter = URLQueryItem(name: "inactivity_timeout", value: "\(inactivityTimeout)")
            queryParameters.append(queryParameter)
        }
        if let keywords = keywords {
            let queryParameter = URLQueryItem(name: "keywords", value: keywords.joined(separator: ","))
            queryParameters.append(queryParameter)
        }
        if let keywordsThreshold = keywordsThreshold {
            let queryParameter = URLQueryItem(name: "keywords_threshold", value: "\(keywordsThreshold)")
            queryParameters.append(queryParameter)
        }
        if let maxAlternatives = maxAlternatives {
            let queryParameter = URLQueryItem(name: "max_alternatives", value: "\(maxAlternatives)")
            queryParameters.append(queryParameter)
        }
        if let wordAlternativesThreshold = wordAlternativesThreshold {
            let queryParameter = URLQueryItem(name: "word_alternatives_threshold", value: "\(wordAlternativesThreshold)")
            queryParameters.append(queryParameter)
        }
        if let wordConfidence = wordConfidence {
            let queryParameter = URLQueryItem(name: "word_confidence", value: "\(wordConfidence)")
            queryParameters.append(queryParameter)
        }
        if let timestamps = timestamps {
            let queryParameter = URLQueryItem(name: "timestamps", value: "\(timestamps)")
            queryParameters.append(queryParameter)
        }
        if let profanityFilter = profanityFilter {
            let queryParameter = URLQueryItem(name: "profanity_filter", value: "\(profanityFilter)")
            queryParameters.append(queryParameter)
        }
        if let smartFormatting = smartFormatting {
            let queryParameter = URLQueryItem(name: "smart_formatting", value: "\(smartFormatting)")
            queryParameters.append(queryParameter)
        }
        if let speakerLabels = speakerLabels {
            let queryParameter = URLQueryItem(name: "speaker_labels", value: "\(speakerLabels)")
            queryParameters.append(queryParameter)
        }

        // construct REST request
        let request = RestRequest(
            method: "POST",
            url: serviceURL + "/v1/recognitions",
            credentials: credentials,
            headerParameters: headers,
            queryItems: queryParameters,
            messageBody: body
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<RecognitionJob>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Check jobs.

     Returns the ID and status of the latest 100 outstanding jobs associated with the service credentials with which it
     is called. The method also returns the creation and update times of each job, and, if a job was created with a
     callback URL and a user token, the user token for the job. To obtain the results for a job whose status is
     `completed` or not one of the latest 100 outstanding jobs, use the **Check a job** method. A job and its results
     remain available until you delete them with the **Delete a job** method or until the job's time to live expires,
     whichever comes first.

     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func checkJobs(
        failure: ((Error) -> Void)? = nil,
        success: @escaping (RecognitionJobs) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct REST request
        let request = RestRequest(
            method: "GET",
            url: serviceURL + "/v1/recognitions",
            credentials: credentials,
            headerParameters: headers
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<RecognitionJobs>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Check a job.

     Returns information about the specified job. The response always includes the status of the job and its creation
     and update times. If the status is `completed`, the response includes the results of the recognition request. You
     must submit the request with the service credentials of the user who created the job.   You can use the method to
     retrieve the results of any job, regardless of whether it was submitted with a callback URL and the
     `recognitions.completed_with_results` event, and you can retrieve the results multiple times for as long as they
     remain available. Use the **Check jobs** method to request information about the most recent jobs associated with
     the calling user.

     - parameter id: The ID of the job whose status is to be checked.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func checkJob(
        id: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (RecognitionJob) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct REST request
        let path = "/v1/recognitions/\(id)"
        guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
            failure?(RestError.encodingError)
            return
        }
        let request = RestRequest(
            method: "GET",
            url: serviceURL + encodedPath,
            credentials: credentials,
            headerParameters: headers
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<RecognitionJob>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Delete a job.

     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 submit the request with the service credentials of the user who created the job.

     - parameter id: The ID of the job that is to be deleted.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func deleteJob(
        id: String,
        failure: ((Error) -> Void)? = nil,
        success: @escaping () -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct REST request
        let path = "/v1/recognitions/\(id)"
        guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
            failure?(RestError.encodingError)
            return
        }
        let request = RestRequest(
            method: "DELETE",
            url: serviceURL + encodedPath,
            credentials: credentials,
            headerParameters: headers
        )

        // execute REST request
        request.responseVoid(responseToError: responseToError) {
            (response: RestResponse) in
            switch response.result {
            case .success: success()
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     Create a custom language model.

     Creates a new custom language model for a specified base model. The custom language model can be used only with the
     base model for which it is created. The model is owned by the instance of the service whose credentials are used to
     create it.

     - parameter createLanguageModel: A `CreateLanguageModel` object that provides basic information about the new custom language model.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func createLanguageModel(
        createLanguageModel: CreateLanguageModel,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (LanguageModel) -> Void)
    {
        // construct body
        guard let body = try? JSONEncoder().encode(createLanguageModel) else {
            failure?(RestError.serializationError)
            return
        }

        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"
        headers["Content-Type"] = "application/json"

        // construct REST request
        let request = RestRequest(
            method: "POST",
            url: serviceURL + "/v1/customizations",
            credentials: credentials,
            headerParameters: headers,
            messageBody: body
        )

        // execute REST request
        request.responseObject(responseToError: responseToError) {
            (response: RestResponse<LanguageModel>) in
            switch response.result {
            case .success(let retval): success(retval)
            case .failure(let error): failure?(error)
            }
        }
    }

    /**
     List custom language models.

     Lists information about all custom language models that are owned by an instance of the service. Use the `language`
     parameter to see all custom language models for the specified language; omit the parameter to see all custom
     language models for all languages. You must use credentials for the instance of the service that owns a model to
     list information about it.

     - parameter language: The identifier of the language for which custom language models are to be returned (for example, `en-US`). Omit the
     parameter to see all custom language models owned by the requesting service credentials.
     - parameter failure: A function executed if an error occurs.
     - parameter success: A function executed with the successful result.
     */
    public func listLanguageModels(
        language: String? = nil,
        failure: ((Error) -> Void)? = nil,
        success: @escaping (LanguageModels) -> Void)
    {
        // construct header parameters
        var headers = defaultHeaders
        headers["Accept"] = "application/json"

        // construct query parameters
        var queryParameters = [URLQueryItem]()
        if let language = language {
            let queryParameter = URLQueryItem(name: "language", value: language)
            queryParameters.append(queryParameter)
        }

        // construct REST request
