def test_basic_authenticator():
    authenticator = BasicAuthenticator('my_username', 'my_password')
    assert authenticator is not None
    assert authenticator.username == 'my_username'
    assert authenticator.password == 'my_password'

    request = {'headers': {}}
    authenticator.authenticate(request)
    assert request['headers'][
        'Authorization'] == 'Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ='
def test_json_to_csv():

    authenticator = BasicAuthenticator('username', 'password')
    personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator)

    with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt'), 'r') as expect_file:
        profile_response = expect_file.read()

    responses.add(responses.POST, profile_url,
                  body=profile_response, status=200,
                  content_type='text/csv')

    with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text:
        personality_insights.profile(
            personality_text,
            'text/csv',
            content_type='application/json',
            csv_headers=True,
            raw_scores=True,
            consumption_preferences=True)

    assert 'version=2016-10-20' in responses.calls[0].request.url
    assert 'raw_scores=true' in responses.calls[0].request.url
    assert 'consumption_preferences=true' in responses.calls[0].request.url
    assert 'csv_headers=true' in responses.calls[0].request.url
    assert responses.calls[0].response.text == profile_response
    assert len(responses.calls) == 1
def test_plain_to_json_es():

    authenticator = BasicAuthenticator('username', 'password')
    personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator)

    with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), 'r') as expect_file:
        profile_response = expect_file.read()

    responses.add(responses.POST, profile_url,
                  body=profile_response, status=200,
                  content_type='application/json')

    with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-es.txt'), 'rb') as personality_text:
        response = personality_insights.profile(
            personality_text,
            'application/json',
            content_type='text/plain;charset=utf-8',
            content_language='es',
            accept_language='es').get_result()

    assert 'version=2016-10-20' in responses.calls[0].request.url
    assert responses.calls[0].response.text == profile_response
    assert len(responses.calls) == 1
    # Verify that response can be converted to a Profile
    Profile._from_dict(response)
def test_json_to_json():

    authenticator = BasicAuthenticator('username', 'password')
    personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator)

    with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt'), 'r') as expect_file:
        profile_response = expect_file.read()

    responses.add(responses.POST, profile_url,
                  body=profile_response, status=200,
                  content_type='application/json')

    with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text:
        response = personality_insights.profile(
            personality_text, accept='application/json',
            content_type='application/json',
            raw_scores=True,
            consumption_preferences=True).get_result()

    assert 'version=2016-10-20' in responses.calls[0].request.url
    assert 'raw_scores=true' in responses.calls[0].request.url
    assert 'consumption_preferences=true' in responses.calls[0].request.url
    assert responses.calls[0].response.text == profile_response
    assert len(responses.calls) == 1
    # Verify that response can be converted to a Profile
    Profile._from_dict(response)
def retrieve_workspace(iam_apikey=None,
                       workspace_id=None,
                       url=DEFAULT_PROD_URL,
                       api_version=DEFAULT_API_VERSION,
                       username=DEFAULT_USERNAME,
                       password=None,
                       export_flag=True):
    """
    Retrieve workspace from Assistant instance
    :param iam_apikey:
    :param workspace_id:
    :param url:
    :param api_version:
    :param username:
    :param password:
    :param export_flag:
    :return workspace: workspace json
    """

    if iam_apikey:
        authenticator = IAMAuthenticator(apikey=iam_apikey)
    elif username and password:
        authenticator = BasicAuthenticator(username=username,
                                           password=password)
    else:
        authenticator = NoAuthAuthenticator()

    conversation = ibm_watson.AssistantV1(authenticator=authenticator,
                                          version=api_version)

    if export_flag:
        ws_json = conversation.get_workspace(workspace_id, export=export_flag)
        return conversation, ws_json.get_result()
    return conversation
Ejemplo n.º 6
0
 def test_version_date(self):
     with pytest.raises(TypeError):
         NaturalLanguageUnderstandingV1() # pylint: disable=E1120
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     assert nlu
Ejemplo n.º 7
0
def test_message():
    endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(
        'bogus_id', 'session_id')
    url = '{0}{1}'.format(base_url, endpoint)
    response = {
        'output': {
            'generic': [{
                'text':
                'I did not understand that. I can help you get pizza, tell a joke or find a movie.',
                'response_type': 'text'
            }],
            'entities': [],
            'intents': [{
                'confidence': 0.8521236419677736,
                'intent': 'Weather'
            }]
        }
    }
    responses.add(responses.POST,
                  url,
                  body=json.dumps(response),
                  status=200,
                  content_type='application/json')
    authenticator = BasicAuthenticator('username', 'password')
    service = ibm_watson.AssistantV2(version='2017-02-03',
                                     authenticator=authenticator)
    message = service.message('bogus_id',
                              'session_id',
                              input={
                                  'text': 'What\'s the weather like?'
                              }).get_result()
    assert len(responses.calls) == 1
    assert responses.calls[0].request.url.startswith(url)
    assert message == response
Ejemplo n.º 8
0
def test_tone_chat():
    tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone_chat'
    tone_args = '?version=2016-05-19'
    tone_response = None
    with open(
            os.path.join(
                os.path.dirname(__file__),
                '../../resources/tone-v3-expect2.json')) as response_json:
        tone_response = response_json.read()

    responses.add(responses.POST,
                  tone_url,
                  body=tone_response,
                  status=200,
                  content_type='application/json')

    authenticator = BasicAuthenticator('username', 'password')
    tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19',
                                              authenticator=authenticator)
    utterances = [{'text': 'I am very happy', 'user': '******'}]
    tone_analyzer.tone_chat(utterances)

    assert responses.calls[0].request.url == tone_url + tone_args
    assert responses.calls[0].response.text == tone_response
    assert len(responses.calls) == 1
Ejemplo n.º 9
0
 def test_create_model(cls):
     authenticator = BasicAuthenticator('xxx', 'yyy')
     service = ibm_watson.LanguageTranslatorV3('2018-05-01',
                                               authenticator=authenticator)
     endpoint = '/v3/models'
     url = '{0}{1}'.format(base_url, endpoint)
     expected = {
         "status": "available",
         "model_id": "en-es-conversational",
         "domain": "conversational",
         "target": "es",
         "customizable": False,
         "source": "en",
         "base_model_id": "en-es-conversational",
         "owner": "",
         "default_model": False,
         "name": "test_glossary"
     }
     responses.add(responses.POST,
                   url,
                   body=json.dumps(expected),
                   status=200,
                   content_type='application/json')
     with open(
             join(dirname(__file__),
                  '../../resources/language_translator_model.tmx'),
             'rb') as custom_model:
         response = service.create_model(
             'en-fr', name='test_glossary',
             forced_glossary=custom_model).get_result()
     assert len(responses.calls) == 1
     assert responses.calls[0].request.url.startswith(url)
     assert response == expected
     TranslationModel._from_dict(response)
Ejemplo n.º 10
0
def test_error():
    tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone'
    error_code = 400
    error_message = "Invalid JSON input at line 2, column 12"
    tone_response = {
        "code": error_code,
        "sub_code": "C00012",
        "error": error_message
    }
    responses.add(responses.POST,
                  tone_url,
                  body=json.dumps(tone_response),
                  status=error_code,
                  content_type='application/json')

    authenticator = BasicAuthenticator('username', 'password')
    tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19',
                                              authenticator=authenticator)

    text = 'Team, I know that times are tough!'
    try:
        tone_analyzer.tone(text, content_type='application/json')
    except ApiException as ex:
        assert len(responses.calls) == 1
        assert isinstance(ex, ApiException)
        assert ex.code == error_code
        assert ex.message == error_message
Ejemplo n.º 11
0
    def test_document_translation(cls):
        document_status = {
            'status': 'processing',
            'model_id': 'en-es',
            'target': 'es',
            'created': '2019-06-05T20:59:37',
            'filename': 'hello_world.txt',
            'source': 'en',
            'document_id': '2a683723'
        }
        endpoint = '/v3/documents'
        url = '{0}{1}'.format(base_url, endpoint)
        responses.add(responses.POST,
                      url,
                      body=json.dumps(document_status),
                      status=200,
                      content_type='application_json')
        responses.add(responses.DELETE, url + '/2a683723', status=200)
        responses.add(responses.GET,
                      url,
                      body=json.dumps({'documents': [document_status]}),
                      status=200,
                      content_type='application_json')
        responses.add(responses.GET,
                      url + '/2a683723/translated_document?version=2018-05-01',
                      body='binary response',
                      status=200)
        responses.add(responses.GET,
                      url + '/2a683723?version=2018-05-01',
                      body=json.dumps(document_status),
                      status=200,
                      content_type='application_json')
        authenticator = BasicAuthenticator('xxx', 'yyy')
        language_translator = ibm_watson.LanguageTranslatorV3(
            '2018-05-01', authenticator=authenticator)

        with open(join(dirname(__file__), '../../resources/hello_world.txt'),
                  'r') as fileinfo:
            translation = language_translator.translate_document(
                file=fileinfo,
                file_content_type='text/plain',
                model_id='en-es').get_result()
            assert translation == document_status

        status = language_translator.list_documents().get_result()
        assert status['documents'][0]['document_id'] == '2a683723'

        delete_result = language_translator.delete_document(
            '2a683723').get_result()
        assert delete_result is None

        response = language_translator.get_translated_document(
            '2a683723', accept='text/plain').get_result()
        assert response.content is not None

        doc_status = language_translator.get_document_status(
            '2a683723').get_result()
        assert doc_status['document_id'] == '2a683723'

        assert len(responses.calls) == 5
Ejemplo n.º 12
0
def test_tone_with_positional_args():
    tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone'
    tone_args = {'version': '2016-05-19', 'sentences': 'false'}
    tone_response = None
    with open(
            os.path.join(
                os.path.dirname(__file__),
                '../../resources/tone-v3-expect1.json')) as response_json:
        tone_response = response_json.read()

    responses.add(responses.POST,
                  tone_url,
                  body=tone_response,
                  status=200,
                  content_type='application/json')

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/personality.txt')) as tone_text:
        authenticator = BasicAuthenticator('username', 'password')
        tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19',
                                                  authenticator=authenticator)
        tone_analyzer.tone(tone_text.read(),
                           content_type='application/json',
                           sentences=False)

    assert responses.calls[0].request.url.split('?')[0] == tone_url
    # Compare args. Order is not deterministic!
    actualArgs = {}
    for arg in responses.calls[0].request.url.split('?')[1].split('&'):
        actualArgs[arg.split('=')[0]] = arg.split('=')[1]
    assert actualArgs == tone_args
    assert responses.calls[0].response.text == tone_response
    assert len(responses.calls) == 1
def retrieve_conversation(
    iam_apikey=None,
    url=DEFAULT_PROD_URL,
    api_version=DEFAULT_API_VERSION,
    username=DEFAULT_USERNAME,
    password=None,
    authenticator_url=DEFAULT_AUTHENTICATOR_URL,
):
    """
    Retrieve workspace from Assistant instance
    :param iam_apikey:
    :param url:
    :param api_version:
    :param username:
    :param password:
    :return workspace: workspace json
    """

    if iam_apikey:
        authenticator = IAMAuthenticator(apikey=iam_apikey,
                                         url=authenticator_url)
    elif username and password:
        authenticator = BasicAuthenticator(username=username,
                                           password=password)
    else:
        authenticator = NoAuthAuthenticator()

    conversation = ibm_watson.AssistantV1(authenticator=authenticator,
                                          version=api_version)
    conversation.set_service_url(url)

    return conversation
Ejemplo n.º 14
0
def test_callbacks():
    base_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1'
    responses.add(responses.POST,
                  "{0}/register_callback".format(base_url),
                  body='{"status": "created", "url": "monitorcalls.com"}',
                  status=200,
                  content_type='application/json')

    responses.add(
        responses.POST,
        "{0}/unregister_callback".format(base_url),
        body='{"response": "The callback URL was successfully unregistered"}',
        status=200,
        content_type='application/json')

    authenticator = BasicAuthenticator('username', 'password')
    speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator)
    speech_to_text.register_callback("monitorcalls.com")
    assert responses.calls[0].response.json() == {
        "status": "created",
        "url": "monitorcalls.com"
    }

    speech_to_text.unregister_callback("monitorcalls.com")
    assert responses.calls[1].response.json() == {
        "response": "The callback URL was successfully unregistered"
    }

    assert len(responses.calls) == 2
Ejemplo n.º 15
0
def test_acoustic_model():
    acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations'
    train_url = "{0}/{1}/train".format(acoustic_customization_url, 'customid')

    responses.add(responses.GET,
                  acoustic_customization_url,
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.POST,
                  acoustic_customization_url,
                  body='{"bogus_response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.GET,
                  "{0}/modelid".format(acoustic_customization_url),
                  body='{"bogus_response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  "{0}/modelid".format(acoustic_customization_url),
                  body='{"bogus_response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.POST,
                  train_url,
                  body='{"bogus_response": "yep"}',
                  status=200,
                  content_type='application/json')

    authenticator = BasicAuthenticator('username', 'password')
    speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator)

    speech_to_text.list_acoustic_models()

    speech_to_text.create_acoustic_model(
        name="Example model",
        base_model_name="en-US_BroadbandModel",
        description="Example custom language model")

    parsed_body = json.loads(_decode_body(responses.calls[1].request.body))
    assert parsed_body['name'] == 'Example model'

    speech_to_text.create_acoustic_model(
        name="Example model Two", base_model_name="en-US_BroadbandModel")

    parsed_body = json.loads(_decode_body(responses.calls[2].request.body))
    assert parsed_body['name'] == 'Example model Two'
    assert parsed_body['base_model_name'] == 'en-US_BroadbandModel'

    speech_to_text.train_acoustic_model('customid')
    speech_to_text.get_acoustic_model(customization_id='modelid')
    speech_to_text.delete_acoustic_model(customization_id='modelid')

    assert len(responses.calls) == 6
Ejemplo n.º 16
0
def test_has_bad_first_or_last_char():
    with pytest.raises(ValueError) as err:
        basic_authenticator = BasicAuthenticator('{my_username}',
                                                 'my_password')
        AnyServiceV1('2018-11-20', authenticator=basic_authenticator)
    assert str(
        err.value
    ) == 'The username and password shouldn\'t start or end with curly brackets or quotes. Please remove any surrounding {, }, or \" characters.'
Ejemplo n.º 17
0
def test_basic_authenticator_validate_failed():
    with pytest.raises(ValueError) as err:
        BasicAuthenticator('my_username', None)
    assert str(err.value) == 'The username and password shouldn\'t be None.'

    with pytest.raises(ValueError) as err:
        BasicAuthenticator(None, 'my_password')
    assert str(err.value) == 'The username and password shouldn\'t be None.'

    with pytest.raises(ValueError) as err:
        BasicAuthenticator('{my_username}', 'my_password')
    assert str(err.value) == 'The username and password shouldn\'t start or end with curly brackets or quotes. '\
                             'Please remove any surrounding {, }, or \" characters.'

    with pytest.raises(ValueError) as err:
        BasicAuthenticator('my_username', '{my_password}')
    assert str(err.value) == 'The username and password shouldn\'t start or end with curly brackets or quotes. '\
                             'Please remove any surrounding {, }, or \" characters.'
Ejemplo n.º 18
0
 def test_text_analyze(self):
     nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"
     responses.add(responses.POST, nlu_url,
                   body="{\"resulting_key\": true}", status=200,
                   content_type='application/json')
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     nlu.analyze(Features(sentiment=SentimentOptions()), text="hello this is a test")
     assert len(responses.calls) == 1
Ejemplo n.º 19
0
 def test_delete_model(self):
     model_id = "invalid_model_id"
     nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models/" + model_id
     responses.add(responses.DELETE, nlu_url, status=200,
                   body="{}", content_type='application/json')
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     nlu.delete_model(model_id)
     assert len(responses.calls) == 1
Ejemplo n.º 20
0
 def test_list_models(self):
     nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models"
     responses.add(responses.GET, nlu_url, status=200,
                   body="{\"resulting_key\": true}",
                   content_type='application/json')
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     nlu.list_models()
     assert len(responses.calls) == 1
Ejemplo n.º 21
0
def test_classify_collection():
    authenticator = BasicAuthenticator('username', 'password')
    natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(
        authenticator=authenticator)
    classify_collection_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/497EF2-nlc-00/classify_collection'
    classify_collection_response = '{ \
            "classifier_id": "497EF2-nlc-00", \
            "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1", \
            "collection": [ \
                { \
                    "text": "How hot will it be today?", \
                    "top_class": "temperature", \
                    "classes": [ \
                        { \
                            "class_name": "temperature", \
                            "confidence": 0.9930558798985937 \
                        }, \
                        { \
                            "class_name": "conditions", \
                            "confidence": 0.006944120101406304 \
                        } \
                    ] \
                }, \
                { \
                    "text": "Is it hot outside?", \
                    "top_class": "temperature", \
                    "classes": [ \
                        { \
                            "class_name": "temperature", \
                            "confidence": 1 \
                        }, \
                        { \
                            "class_name": "conditions", \
                            "confidence": 0 \
                        } \
                    ] \
                } \
            ] \
            }'

    responses.add(responses.POST,
                  classify_collection_url,
                  body=classify_collection_response,
                  status=200,
                  content_type='application/json')

    classifier_id = '497EF2-nlc-00'
    collection = [
        '{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}'
    ]
    natural_language_classifier.classify_collection(classifier_id, collection)

    assert responses.calls[0].request.url == classify_collection_url
    assert responses.calls[0].response.text == classify_collection_response
Ejemplo n.º 22
0
def test_has_bad_first_or_last_char():
    with pytest.raises(ValueError) as err:
        basic_authenticator = BasicAuthenticator('{my_username}', 'my_password')
        AnyServiceV1('2018-11-20', authenticator=basic_authenticator).prepare_request(
            responses.GET,
            'https://gateway.watsonplatform.net/test/api'
        )
    assert str(
        err.value
    ) == 'The username and password shouldn\'t start or end with curly brackets or quotes. '\
         'Please remove any surrounding {, }, or \" characters.'
Ejemplo n.º 23
0
def test_get_model():
    model_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models/modelid'
    responses.add(responses.GET,
                  model_url,
                  body='{"bogus_response": "yep"}',
                  status=200,
                  content_type='application/json')
    authenticator = BasicAuthenticator('username', 'password')
    speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator)
    speech_to_text.get_model(model_id='modelid')
    assert len(responses.calls) == 1
Ejemplo n.º 24
0
def test_custom_words():
    base_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations'
    responses.add(responses.GET,
                  "{0}/{1}/words".format(base_url, "custid"),
                  body='{"customizations": "yep" }',
                  status=200,
                  content_type='application_json')
    responses.add(responses.POST,
                  "{0}/{1}/words".format(base_url, "custid"),
                  body='{"customizations": "yep" }',
                  status=200,
                  content_type='application_json')
    responses.add(responses.GET,
                  "{0}/{1}/words/{2}".format(base_url, "custid", "word"),
                  body='{"customization": "yep, just one" }',
                  status=200,
                  content_type='application_json')
    responses.add(responses.POST,
                  "{0}/{1}/words/{2}".format(base_url, "custid", "word"),
                  body='{"customizations": "yep" }',
                  status=200,
                  content_type='application_json')
    responses.add(responses.PUT,
                  "{0}/{1}/words/{2}".format(base_url, "custid", "word"),
                  body='{"customizations": "yep" }',
                  status=200,
                  content_type='application_json')
    responses.add(responses.DELETE,
                  "{0}/{1}/words/{2}".format(base_url, "custid", "word"),
                  body='{"customizations": "yep" }',
                  status=200,
                  content_type='application_json')

    authenticator = BasicAuthenticator('username', 'password')
    text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator)

    text_to_speech.list_words(customization_id="custid")
    text_to_speech.add_words(customization_id="custid",
                             words=[{
                                 "word": "one",
                                 "translation": "one"
                             }, {
                                 "word": "two",
                                 "translation": "two"
                             }])
    text_to_speech.get_word(customization_id="custid", word="word")
    text_to_speech.add_word(customization_id='custid',
                            word="word",
                            translation="I'm translated")
    text_to_speech.delete_word(customization_id="custid", word="word")

    assert len(responses.calls) == 5
Ejemplo n.º 25
0
 def test_url_analyze(self):
     nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"
     responses.add(responses.POST, nlu_url,
                   body="{\"resulting_key\": true}", status=200,
                   content_type='application/json')
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     nlu.analyze(Features(sentiment=SentimentOptions(),
                          emotion=EmotionOptions(document=False)),
                 url="http://cnn.com",
                 xpath="/bogus/xpath", language="en")
     assert len(responses.calls) == 1
Ejemplo n.º 26
0
def test_delete_user_data():
    url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/user_data'
    responses.add(responses.DELETE,
                  url,
                  body='{"description": "success" }',
                  status=204,
                  content_type='application_json')

    authenticator = BasicAuthenticator('username', 'password')
    speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator)
    response = speech_to_text.delete_user_data('id').get_result()
    assert response is None
    assert len(responses.calls) == 1
Ejemplo n.º 27
0
def test_http_client():
    auth = BasicAuthenticator('my_username', 'my_password')
    service = AnyServiceV1('2018-11-20', authenticator=auth)
    assert isinstance(service.get_http_client(), requests.sessions.Session)
    assert service.get_http_client().headers.get(
        'Accept-Encoding') == 'gzip, deflate'

    new_http_client = requests.Session()
    new_http_client.headers.update({'Accept-Encoding': 'gzip'})
    service.set_http_client(http_client=new_http_client)
    assert service.get_http_client().headers.get('Accept-Encoding') == 'gzip'

    with pytest.raises(TypeError):
        service.set_http_client("bad_argument_type")
Ejemplo n.º 28
0
def test_recognitions():
    url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognitions'
    get_response = '{"recognitions": [{"created": "2018-02-01T17:43:15.432Z","id": "6193190c-0777-11e8-9b4b-43ad845196dd","updated": "2018-02-01T17:43:17.998Z","status": "failed"}]}'
    responses.add(responses.GET,
                  url,
                  body=get_response,
                  status=200,
                  content_type='application/json')

    responses.add(responses.POST,
                  url,
                  body='{"status": "waiting"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  "{0}/jobid".format(url),
                  body='{"description": "deleted successfully"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.GET,
                  "{0}/jobid".format(url),
                  body='{"status": "waiting"}',
                  status=200,
                  content_type='application/json')

    authenticator = BasicAuthenticator('username', 'password')
    speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator)

    speech_to_text.check_jobs()
    assert responses.calls[0].response.json(
    )['recognitions'][0]['id'] == '6193190c-0777-11e8-9b4b-43ad845196dd'

    speech_to_text.check_job('jobid')
    assert responses.calls[1].response.json() == {'status': 'waiting'}

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/speech.wav'), 'rb') as audio_file:
        speech_to_text.create_job(audio=audio_file, content_type='audio/basic')
    assert responses.calls[2].response.json() == {'status': 'waiting'}

    speech_to_text.delete_job('jobid')
    assert responses.calls[3].response.json() == {
        "description": "deleted successfully"
    }

    assert len(responses.calls) == 4
Ejemplo n.º 29
0
def main(args):

    # Parse incoming request headers
    _c_type, p_dict = parse_header(args['__ow_headers']['content-type'])

    # Decode body (base64)
    decoded_string = b64decode(args['__ow_body'])

    # Set Headers for multipart_data parsing
    p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
    p_dict['CONTENT-LENGTH'] = len(decoded_string)

    # Parse incoming request data
    multipart_data = parse_multipart(BytesIO(decoded_string), p_dict)

    # Build flac file from stream of bytes
    fo = open("audio_sample.flac", 'wb')
    fo.write(multipart_data.get('audio')[0])
    fo.close()

    # Basic Authentication with Watson STT API
    stt_authenticator = BasicAuthenticator(
        'apikey', 'zlgvP1jXnCCBMsNIK76OFagmlJcnlEC_BnmptKYXun3u')

    # Construct a Watson STT client with the authentication object
    stt = SpeechToTextV1(authenticator=stt_authenticator)

    # Set the URL endpoint for your Watson STT client
    stt.set_service_url(
        'https://api.us-south.speech-to-text.watson.cloud.ibm.com')

    # Read audio file and call Watson STT API:
    with open(
            os.path.join(os.path.dirname(__file__), './.',
                         'audio_sample.flac'), 'rb') as audio_file:
        # Transcribe the audio.flac with Watson STT
        # Recognize method API reference:
        # https://cloud.ibm.com/apidocs/speech-to-text?code=python#recognize
        stt_result = stt.recognize(audio=audio_file,
                                   content_type='audio/flac',
                                   model='pt-BR_BroadbandModel').get_result()

    # Print STT API call results
    print(json.dumps(stt_result, indent=2))

    # Return a dictionary with the transcribed text
    return {
        "transcript": stt_result['results'][0]['alternatives'][0]['transcript']
    }
Ejemplo n.º 30
0
def test_setting_proxy():
    service = BaseService(service_url='test',
                          authenticator=IAMAuthenticator('wonder woman'))
    assert service.authenticator is not None
    assert service.authenticator.token_manager.http_config == {}

    http_config = {"proxies": {"http": "user:password@host:port"}}
    service.set_http_config(http_config)
    assert service.authenticator.token_manager.http_config == http_config

    service2 = BaseService(service_url='test',
                           authenticator=BasicAuthenticator(
                               'marvellous', 'mrs maisel'))
    service2.set_http_config(http_config)
    assert service2.authenticator is not None