Ejemplo n.º 1
0
def test_success():
    models_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models'
    models_response = '{"models": [{"url": "https://stream.watsonplatform.net/speech-to-text/api/v1/models/' \
                      'WatsonModel", "rate": 16000, "name": "WatsonModel", "language": "en-US", "description": ' \
                      '"Watson model \'v7w_134k.3\' for Attila 2-5 reco engine."}]}'

    responses.add(responses.GET,
                  models_url,
                  body=models_response,
                  status=200,
                  content_type='application/json')

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

    assert responses.calls[0].request.url == models_url
    assert responses.calls[0].response.text == models_response

    recognize_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize'
    recognize_response = '{"results":[{"alternatives":[{"transcript":"thunderstorms could produce large hail ' \
                         'isolated tornadoes and heavy rain "}],"final":true}],"result_index":0}'

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

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/speech.wav'), 'rb') as audio_file:
        speech_to_text.recognize(audio=audio_file,
                                 content_type='audio/l16; rate=44100')

    request_url = responses.calls[1].request.url
    assert request_url == recognize_url
    assert responses.calls[1].response.text == recognize_response

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/speech.wav'), 'rb') as audio_file:
        speech_to_text.recognize(audio=audio_file,
                                 customization_id='x',
                                 content_type='audio/l16; rate=44100')
    expected_url = "{0}?customization_id=x".format(recognize_url)
    assert expected_url == responses.calls[2].request.url
    assert len(responses.calls) == 3
Ejemplo n.º 2
0
def test_custom_corpora():

    corpora_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/corpora'
    get_corpora_url = '{0}/{1}'.format(corpora_url.format('customid'),
                                       'corpus')

    with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps:
        rsps.add(responses.GET,
                 corpora_url.format('customid'),
                 body='{"get response": "yep"}',
                 status=200,
                 content_type='application/json')

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

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

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

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

        speech_to_text.list_corpora(customization_id='customid')

        file_path = '../../resources/speech_to_text/corpus-short-1.txt'
        full_path = os.path.join(os.path.dirname(__file__), file_path)
        with open(full_path) as corpus_file:
            speech_to_text.add_corpus(customization_id='customid',
                                      corpus_name="corpus",
                                      corpus_file=corpus_file)

        speech_to_text.get_corpus(customization_id='customid',
                                  corpus_name='corpus')

        speech_to_text.delete_corpus(customization_id='customid',
                                     corpus_name='corpus')
Ejemplo n.º 3
0
def test_custom_audio_resources():
    url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/{0}/audio/{1}'

    responses.add(responses.POST,
                  url.format('custid', 'hiee'),
                  body='{"post response": "done"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  url.format('custid', 'hiee'),
                  body='{"delete response": "done"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.GET,
                  url.format('custid', 'hiee'),
                  body='{"get response": "done"}',
                  status=200,
                  content_type='application/json')

    responses.add(
        responses.GET,
        'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/custid/audio',
        body='{"get response all": "done"}',
        status=200,
        content_type='application/json')

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

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/speech.wav'), 'rb') as audio_file:
        speech_to_text.add_audio(customization_id='custid',
                                 audio_name="hiee",
                                 audio_resource=audio_file,
                                 content_type="application/json")
    assert responses.calls[0].response.json() == {"post response": "done"}

    speech_to_text.delete_audio('custid', 'hiee')
    assert responses.calls[1].response.json() == {"delete response": "done"}

    speech_to_text.get_audio('custid', 'hiee')
    assert responses.calls[2].response.json() == {"get response": "done"}

    speech_to_text.list_audio('custid')
    assert responses.calls[3].response.json() == {"get response all": "done"}
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
Ejemplo n.º 5
0
def test_create_session():
    endpoint = '/v2/assistants/{0}/sessions'.format('bogus_id')
    url = '{0}{1}'.format(base_url, endpoint)
    response = {'session_id': 'session_id'}
    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)
    session = service.create_session('bogus_id').get_result()
    assert len(responses.calls) == 1
    assert responses.calls[0].request.url.startswith(url)
    assert session == response
Ejemplo n.º 6
0
def test_custom_voice_models():
    responses.add(
        responses.GET,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations',
        body='{"customizations": "yep" }',
        status=200,
        content_type='application_json')
    responses.add(
        responses.POST,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations',
        body='{"customizations": "yep" }',
        status=200,
        content_type='application_json')
    responses.add(
        responses.GET,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid',
        body='{"customization": "yep, just one" }',
        status=200,
        content_type='application_json')
    responses.add(
        responses.POST,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid',
        body='{"customizations": "yep" }',
        status=200,
        content_type='application_json')
    responses.add(
        responses.DELETE,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid',
        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_voice_models()
    text_to_speech.list_voice_models(language="en-US")
    assert len(responses.calls) == 2

    text_to_speech.create_voice_model(name="name", description="description")
    text_to_speech.get_voice_model(customization_id='custid')
    text_to_speech.update_voice_model(customization_id="custid",
                                      name="name",
                                      description="description")
    text_to_speech.delete_voice_model(customization_id="custid")

    assert len(responses.calls) == 6
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', '<watson_stt_apikey>')

    # 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('<watson_stt_endpoint_url>')

    # 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.º 8
0
def test_get_pronunciation():

    responses.add(
        responses.GET,
        'https://stream.watsonplatform.net/text-to-speech/api/v1/pronunciation',
        body='{"pronunciation": "pronunciation info" }',
        status=200,
        content_type='application_json')

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

    text_to_speech.get_pronunciation(text="this is some text")
    text_to_speech.get_pronunciation(text="yo", voice="VoiceEnUsLisa")
    text_to_speech.get_pronunciation(text="yo",
                                     voice="VoiceEnUsLisa",
                                     format='ipa')

    assert len(responses.calls) == 3
Ejemplo n.º 9
0
def test_request_success_json():
    responses.add(responses.GET,
                  'https://gateway.watsonplatform.net/test/api',
                  status=200,
                  body=json.dumps({'foo': 'bar'}),
                  content_type='application/json')
    service = AnyServiceV1('2018-11-20', authenticator=NoAuthAuthenticator())
    prepped = service.prepare_request('GET', url='')
    detailed_response = service.send(prepped)
    assert detailed_response.get_result() == {'foo': 'bar'}

    service = AnyServiceV1('2018-11-20',
                           authenticator=BasicAuthenticator(
                               'my_username', 'my_password'))
    service.set_default_headers({'test': 'header'})
    service.set_disable_ssl_verification(True)
    prepped = service.prepare_request('GET', url='')
    detailed_response = service.send(prepped)
    assert detailed_response.get_result() == {'foo': 'bar'}
Ejemplo n.º 10
0
def test_upgrade_acoustic_model():
    acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations'
    upgrade_url = "{0}/{1}/upgrade_model".format(acoustic_customization_url,
                                                 'customid')

    responses.add(responses.POST,
                  upgrade_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.upgrade_acoustic_model('customid',
                                          custom_language_model_id='model_x',
                                          force=True)
    assert responses.calls[0].response.json() == {"bogus_response": "yep"}

    assert len(responses.calls) == 1
def test_plain_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-expect1.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.txt'), 'rb') as personality_text:
        response = personality_insights.profile(
            personality_text, 'application/json', content_type='text/plain;charset=utf-8').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 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
    )
    conversation.set_service_url(url)

    if export_flag:
        ws_json = conversation.get_workspace(workspace_id, export=export_flag)
        return conversation, ws_json.get_result()
    return conversation
Ejemplo n.º 13
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
    )
   

    try:
        # Build flac file from stream of bytes
        fo = open("audio_sample.flac", 'wb')
        fo.write(multipart_data.get('audio')[0])
        fo.close()
        teste=False
    except: 
        teste=True
    #teste = multipart_data.items
    #Pegando o Carro
    carro=multipart_data.get('car')[0]
    
    if teste == False: 
         
         # Basic Authentication with Watson STT API
        stt_authenticator = BasicAuthenticator(
        'apikey',
        'apikey'
        )

         #Autenticacao STT
        # 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()

        authenticator_nlu = BasicAuthenticator(
        'apikey',
        'apikey'
        )
        natural_language_understanding = NaturalLanguageUnderstandingV1(version='2020-09-16',authenticator=authenticator_nlu)
        natural_language_understanding.set_service_url('https://api.us-south.natural-language-understanding.watson.cloud.ibm.com')

        texto_stt=stt_result['results'][0]['alternatives'][0]['transcript']
        try:
            nlu_resp = natural_language_understanding.analyze(text=texto_stt,features=Features(entities=EntitiesOptions(sentiment=True, model ='54f2d12a-54fb-4683-b89f-c76c8b93de3f'))).get_result()
        except ApiException as ex:
            print ("Method failed with status code " + str(ex.code) + ": " + ex.message)

    elif teste == True : 
        
        #Pegando o Text 
        texto=multipart_data.get('text')[0]
        carro=multipart_data.get('car')[0]

        authenticator_nlu = BasicAuthenticator(
        'apikey',
        'apikey'
        )
        natural_language_understanding = NaturalLanguageUnderstandingV1(version='2020-09-16',authenticator=authenticator_nlu)
        natural_language_understanding.set_service_url('https://api.us-south.natural-language-understanding.watson.cloud.ibm.com')

        #Definindo features  
        try:
            nlu_resp = natural_language_understanding.analyze(text=texto,features=Features(entities=EntitiesOptions(sentiment=True, model ='54f2d12a-54fb-4683-b89f-c76c8b93de3f'))).get_result()
        except ApiException as ex:
            print ("Method failed with status code " + str(ex.code) + ": " + ex.message)

 
    sent_rec=[]
    sent_json=[]
    score_rec=[]
    score_json=[]
    ent_rec=[]
    ent_json=[]
    ment_json=[]
    #Pegando a lista de sentimentos negativos
    try:
        for x in range(50):
            aux=nlu_resp['entities'][x]['sentiment']['label']
            sent_json.append(nlu_resp['entities'][x]['sentiment']['label'])
            score_json.append(nlu_resp['entities'][x]['sentiment']['score'])
            ent_json.append(nlu_resp['entities'][x]['type'])
            ment_json.append(nlu_resp['entities'][x]['text'])
        
            #print(aux)
            if  aux != 'neutral':
                if aux !='positive':
                    sent_rec.append(nlu_resp['entities'][x]['sentiment']['label'])
                    score_rec.append(nlu_resp['entities'][x]['sentiment']['score'])
                    ent_rec.append(nlu_resp['entities'][x]['type'])
                    #print("entrou")
        
    except:
        saiu=1

    #lista de carros que podemos usar 
    lista= ["FIAT 500","DUCATO","ARGO","FIORINO","MAREA","RENEGADE","CRONOS"]
    lista_seg_op=["TORO","ARGO","DUCATO","FIAT 500","CRONOS","CRONOS","ARGO"]
    lista_prioridade=["SEGURANCA","CONSUMO","DESEMPENHO","MANUTENCAO","CONFORTO","DESIGN","ACESSORIOS"]

    for x in range(len(lista)):
        if carro == lista[x]:
            lista[x]=lista_seg_op[x]

    #Decidindo qual carro escolher 
    if sent_rec !=[]:

        #entidade.append("MANUTENCAO")
        #Sentimento.append(-1)
        #cont=0
        entidade_aux=0
        sent_aux=0

        for x in range(len(score_rec)):
            dif=abs(sent_aux-score_rec[x])

            if dif > 0.1:
                if score_rec[x] < sent_aux:
                    sent_aux= score_rec[x]
                    entidade_aux=ent_rec[x]
                    print(sent_aux,entidade_aux)
            elif dif < 0.1:
            #Desempate
                #print("aqui")
                for y in range(len(lista)):
                    if entidade_aux == lista_prioridade[y]:
                        sent_aux=sent_aux
                        entidade_aux=entidade_aux
                    elif ent_rec[x] == lista_prioridade[y]:
                        sent_aux= score_rec[x]
                        entidade_aux=ent_rec[x]
        
        for x in range(len(lista)):
            if lista_prioridade[x] == entidade_aux:
                sugest=lista[x]
    else:
        sugest=""

    list_json=[]
    for x in range(len(sent_json)):
        list_json.append({"entity":ent_json[x], "sentiment": score_json[x],"mention": ment_json[x]})

    return {
        "recommendation":sugest,
        "entities":list_json
        
        
    }
Ejemplo n.º 14
0
        sys.stdout.write(bcolors.WARNING + "\rFailed to find environmental variables.\n")
        sys.stdout.flush()
        sys.stdout.write(bcolors.ENDC + "Generating config file 'config.conf'...")
        sys.stdout.flush()
        file = open("config.conf", "w")
        file.write("watson_user=''\nwatson_pass=''")
        sys.stdout.write(bcolors.ENDC + "\rSuccessfully generated configuration file 'config.conf'.\n")
        sys.stdout.write(bcolors.FAIL + "Please access the config or evironment variables:\nWATSON_USER\nWATSON_PASS\n\nSet them using values of your Watson API username and password.\nExiting program...\n" + bcolors.ENDC)
        sys.stdout.flush()
        exit()
#
#
#
#for key in keys:
	#print(type(key))
authenticator = BasicAuthenticator('apikey',keys[1])
tone_analyzer = ToneAnalyzerV3(
   version='2017-09-21',
   authenticator=authenticator
)
tone_analyzer.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/c556e4af-30a2-4acb-a342-0da1419f9b59')


try:
    url = args.url
    #url = input('Enter the URL of a news article:')
    url = url.replace(' ','')
    sys.stdout.write("Retrieving satus code...")
    page = urllib.request.urlopen(url, data=None)

# error thrown if the status code is bad
Ejemplo n.º 15
0
def test_get_authenticator():
    auth = BasicAuthenticator('my_username', 'my_password')
    service = AnyServiceV1('2018-11-20', authenticator=auth)
    assert service.get_authenticator() is not None
Ejemplo n.º 16
0
from flask import Flask, render_template
import json
from ibm_watson import AssistantV2
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator, BasicAuthenticator

app = Flask(__name__)

authenticator = BasicAuthenticator('*****@*****.**', 'Kurogane970426')

assistant = AssistantV2(
    version='2019-02-28',
    authenticator=authenticator
)

# replace url

assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api')

assistant_id = 'ad14b037-49bc-4fdb-9025-3a40584574b7'

# create session.
session_id = assistant.create_session(
    assistant_id=assistant_id
).get_result()['session_id']

'''
# Set up Assistant service.
authenticator = IAMAuthenticator('{apikey}') # replace with API key
service = AssistantV2(
    version = '2019-02-28',
    authenticator = authenticator
    for creds in wa_credentials:
        wa_version = creds['wa_version']
        wa_username = creds['wa_username']
        wa_password = creds['wa_password']
        wa_url = creds['wa_url']

        if (wa_version == '' or wa_username == '' or wa_password == ''
                or wa_url == ''):
            print(
                "No or invalid Watson Assistant credentials detected. Skipping."
            )
        else:
            print("Starting Watson Assistant backup...")
            start_time = time.time()

            authenticator = BasicAuthenticator(wa_username, wa_password)

            assistant_service = AssistantV1(version=wa_version,
                                            authenticator=authenticator)

            assistant_service.set_service_url(wa_url)

            # Get all workspace IDs
            try:
                list_wrkspc_response = assistant_service.list_workspaces(
                ).get_result()['workspaces']
                all_wrkspc_ids = []
            except ApiException as ex:
                print("Method failed with status code " + str(ex.code) + ": " +
                      ex.message)
Ejemplo n.º 18
0
def test_success():
    voices_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices'
    voices_response = {
        "voices": [{
            "url":
            "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsLisa",
            "gender": "female",
            "name": "VoiceEnUsLisa",
            "language": "en-US"
        }, {
            "url":
            "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEsEsEnrique",
            "gender": "male",
            "name": "VoiceEsEsEnrique",
            "language": "es-ES"
        }, {
            "url":
            "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsMichael",
            "gender": "male",
            "name": "VoiceEnUsMichael",
            "language": "en-US"
        }, {
            "url":
            "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsAllison",
            "gender": "female",
            "name": "VoiceEnUsAllison",
            "language": "en-US"
        }]
    }
    voice_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-us_AllisonVoice'
    voice_response = {
        "url":
        "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-US_AllisonVoice",
        "name": "en-US_AllisonVoice",
        "language": "en-US",
        "customizable": True,
        "gender": "female",
        "description": "Allison: American English female voice.",
        "supported_features": {
            "custom_pronunciation": True,
            "voice_transformation": True
        }
    }
    synthesize_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize'
    synthesize_response_body = '<binary response>'

    responses.add(responses.GET,
                  voices_url,
                  body=json.dumps(voices_response),
                  status=200,
                  content_type='application/json')
    responses.add(responses.GET,
                  voice_url,
                  body=json.dumps(voice_response),
                  status=200,
                  content_type='application/json')
    responses.add(responses.POST,
                  synthesize_url,
                  body=synthesize_response_body,
                  status=200,
                  content_type='application/json',
                  match_querystring=True)

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

    text_to_speech.list_voices()
    assert responses.calls[0].request.url == voices_url
    assert responses.calls[0].response.text == json.dumps(voices_response)

    text_to_speech.get_voice('en-us_AllisonVoice')
    assert responses.calls[1].request.url == voice_url
    assert responses.calls[1].response.text == json.dumps(voice_response)

    text_to_speech.synthesize('hello')
    assert responses.calls[2].request.url == synthesize_url
    assert responses.calls[2].response.text == synthesize_response_body

    assert len(responses.calls) == 3
Ejemplo n.º 19
0
# step 4: save transcript to cloudant db

from ibmcloudant.cloudant_v1 import Document, CloudantV1
from ibmcloudant import CouchDbSessionAuthenticator
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator
import random
import config
import stt
#print(stt.output)


# Save results to Cloudant DB
authenticator = BasicAuthenticator(config.CLOUDANT_USERNAME, config.CLOUDANT_PASSWORD)

service = CloudantV1(authenticator=authenticator)

service.set_service_url(config.CLOUDANT_URL)
transcript_doc = Document(
    id="transcript-"+str(random.randint(0,500)),
    transcript_txt=stt.output
    )
response = service.post_document(db='test', document=transcript_doc).get_result()
##print(transcript)
Ejemplo n.º 20
0
import json, os
from io import BytesIO
from base64 import b64decode
from cgi import parse_multipart, parse_header
from os.path import join, dirname
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

# Basic Authentication with Watson STT API

stt_authenticator = BasicAuthenticator(
    'apikey', 'yH2qmAtMsfapTdFSh12-MgcGoZ9z17SC-rFfY5VCaenz')

# 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')


def recive_audio(audio_file_):

    # Build flac file from stream of bytes
    fo = open("audio_sample.flac", 'wb')
    fo.write(audio_file_.read())
    fo.close()

    with open(
            os.path.join(os.path.dirname(__file__), './.',
Ejemplo n.º 21
0
from ibmcloudant.cloudant_v1 import CloudantV1
from ibmcloudant import CouchDbSessionAuthenticator
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

authenticator = BasicAuthenticator(
    'apikey-v2-26g9t1z3q0xklw9t9abzzlugdatwuhb184e6alna2xmt',
    '569e622c6ed6c4118b9877c19391f54e')

service = CloudantV1(authenticator=authenticator)

service.set_service_url(
    'https://*****:*****@b121a610-4bb6-47e9-9aed-3191c167e220-bluemix.cloudantnosqldb.appdomain.cloud'
)
#response = service.put_database(db='products', ).get_result()
#print(response)

products_doc = {"_id": "Rachana", "name": "GCET", "Domain": "IoT"}

response = service.post_document(db='assgn7',
                                 document=products_doc).get_result()

print(response)
Ejemplo n.º 22
0
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator
import wiotp.sdk.device
# Constants for IBM COS values
COS_ENDPOINT = "https://manohar.s3.jp-tok.cloud-object-storage.appdomain.cloud"  # Current list avaiable at https://control.cloud-object-storage.cloud.ibm.com/v2/endpoints
COS_API_KEY_ID = "67MBwu0H49L21goGQBII-SufzagQ-j-Lc-1xIRZOyqat"  # eg "W00YixxxxxxxxxxMB-odB-2ySfTrFBIQQWanc--P3byk"
COS_INSTANCE_CRN = "crn:v1:bluemix:public:cloud-object-storage:global:a/94a9058de7634a75b86a721e2524a404:9eaeda1b-4ff4-4fa1-94a8-9917e79c2fc3::"

# Create resource
cos = ibm_boto3.resource("s3",
                         ibm_api_key_id=COS_API_KEY_ID,
                         ibm_service_instance_id=COS_INSTANCE_CRN,
                         config=Config(signature_version="oauth"),
                         endpoint_url=COS_ENDPOINT)

authenticator = BasicAuthenticator(
    'apikey-v2-2y8twpk3cni02ngsc297oqatoulogdt961768upuw79q',
    '43c3fef46c4ca6560b7359d05c4c3d57')
service = CloudantV1(authenticator=authenticator)
service.set_service_url(
    'https://*****:*****@7b88ba8a-383b-49c5-ba00-9a03115de98a-bluemix.cloudantnosqldb.appdomain.cloud'
)


def myCommandCallback(cmd):
    print("Command received: %s" % cmd.data)


myConfig = {
    "identity": {
        "orgId": "sn7dm1",
        "typeId": "ESP32",
Ejemplo n.º 23
0
def test_custom_words():
    words_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words'
    word_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words/{1}'

    responses.add(responses.PUT,
                  word_url.format('custid', 'IEEE'),
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.PUT,
                  word_url.format('custid', 'wordname'),
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  word_url.format('custid', 'IEEE'),
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  word_url.format('custid', 'wordname'),
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

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

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

    responses.add(responses.POST,
                  words_url.format('custid'),
                  body='{"get response": "yep"}',
                  status=200,
                  content_type='application/json')

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

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

    custom_word = CustomWord(word="IEEE",
                             sounds_like=["i triple e"],
                             display_as="IEEE")

    speech_to_text.add_word(customization_id='custid',
                            word_name="IEEE",
                            sounds_like=["i triple e"],
                            display_as="IEEE")

    speech_to_text.delete_word(customization_id='custid', word_name="wordname")

    speech_to_text.delete_word(customization_id='custid', word_name='IEEE')

    custom_words = [custom_word, custom_word, custom_word]
    speech_to_text.add_words(customization_id='custid', words=custom_words)

    speech_to_text.get_word(customization_id='custid', word_name="IEEE")

    speech_to_text.get_word(customization_id='custid', word_name='wordname')

    speech_to_text.list_words(customization_id='custid')
    speech_to_text.list_words(customization_id='custid', sort='alphabetical')

    speech_to_text.list_words(customization_id='custid', word_type='all')

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

    model_id = '956978fa-b5e6-4108-96ad-3367bde3478b';

    #NLU
    authenticatorNLU = IAMAuthenticator('bbTi93KoBLq60M_Lj5fMpXInVoYI_CJFp66VBBTtsmhE')
    natural_language_understanding = NaturalLanguageUnderstandingV1(version='2020-08-01',authenticator=authenticatorNLU)
    natural_language_understanding.set_service_url('https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/340adba1-4277-46f0-aca3-412077e9b53d')

    _c_type, p_dict = parse_header(
        args['__ow_headers']['content-type']
    )
    
    decoded_string = b64decode(args['__ow_body'])

    p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
    p_dict['CONTENT-LENGTH'] = len(decoded_string)

    multipart_data = parse_multipart(BytesIO(decoded_string), p_dict)

    name_audio = uuid.uuid4().hex.upper()[0:50]+'.flac'

    try:
        fo = open(name_audio, 'wb')
        fo.write(multipart_data.get('audio')[0])
        fo.close()
    except:
        fo = False

    if fo: # file audio
        stt_authenticator = BasicAuthenticator(
            'apikey',
            'MaKHsSDKPKgfvQRPDfbFhXSMfvY-JtogeRyQIZn6WPem'
        )
        stt = SpeechToTextV1(authenticator=stt_authenticator)
        stt.set_service_url('https://api.us-south.speech-to-text.watson.cloud.ibm.com')
        with open(
            os.path.join(
                os.path.dirname(__file__), './.',
                name_audio
            ), 'rb'
        ) as audio_file:
            stt_result = stt.recognize(
                audio=audio_file,
                content_type='audio/flac',
                model='pt-BR_BroadbandModel'
            ).get_result()
        # print(json.dumps(stt_result, indent=2))
        transcript_audio = stt_result['results'][0]['alternatives'][0]['transcript']
        entities = getEntities(model_id, natural_language_understanding, transcript_audio)
    else:
        text = multipart_data.get('text')[0]
        entities = getEntities(model_id, natural_language_understanding, text)

    #entities[1]['sentiment'] = -0.92
    #entities[2]['sentiment'] = -0.98
    #entities[3]['sentiment'] = -0.92
    #entities[4]['sentiment'] = -0.96

    if general_sentiment > 0:
        return { "recommendation": "", "entities": entities }
    elif general_sentiment < 0:
        nums = []
        repetidos = []
        definidos = []
        for i, item in enumerate(entities):
            nums.append(item['sentiment'])
        min_sentiment = min(nums)
        if len(nums) == len(set(nums)):
            definidos.append(min_sentiment)
        else:
            for idx,sentiment in enumerate(nums):
                if sentiment == min_sentiment:
                    repetidos.append(idx)

            if len(repetidos) > 1:
                definidos.append(entities[min(repetidos)])
            elif len(repetidos) == 1:
                definidos.append(entities[repetidos[0]]) #min_sentiment
                #vector_new = removeElement(nums, min_sentiment)
                #second_min_sentiment = min(vector_new)
                #difference = vector_new - second_min_sentiment
                #if difference < 0.1:
                #    definidos.append(min_sentiment)
                #else:
                #    definidos.append(min_sentiment)
                #definidos.append(min_sentiment)
                #definidos.append(min(vector_new))

        recommendation = ""
        for item in recommendations:
            if item['entity'] == definidos[0]['entity']:
                recommendation = item['car']
        return {
            'recommendation': recommendation, #entities[3]['sentiment']
            'entities': entities
        }

    #return entities
    return {
        "recommendation": "",
        #"general_sentiment": general_sentiment,
        "entities": entities
    }
Ejemplo n.º 25
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)

    text = multipart_data.get('text')

    if text is not None:
        text = text[0]
    else:

        # 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', '9kesqvRxa7lKR3WUkcR81zFXfhrJXXYl3dzobsEWEfCM')

        # 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
        transcript = stt_result['results'][0]['alternatives'][0]['transcript']
        text = transcript

    # Serviço NLU
    nlu_apikey = "rv_tVs7qTDhdlEtEwcY-D11AGDdI6VVkVh8RaZj1jwQ-"
    nlu_service_url = "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com"
    nlu_entity_model = "187ea1d8-ea11-4285-b96e-32db2996a9aa"

    # Cria-se um autenticador
    nlu_authenticator = IAMAuthenticator(apikey=nlu_apikey)

    # Criamos o serviço passando esse autenticador
    nlu_service = NaturalLanguageUnderstandingV1(
        version='2018-03-16', authenticator=nlu_authenticator)

    # Setamos a URL de acesso do nosso serviço
    nlu_service.set_service_url(nlu_service_url)

    # O método analyze cuida de tudo
    nlu_response = nlu_service.analyze(
        text=text,
        features=Features(
            entities=EntitiesOptions(model=nlu_entity_model, sentiment=True)),
        language='pt').get_result()

    return {
        'result':
        json.dumps(nlu_response['entities'][0], indent=2, ensure_ascii=False)
    }
Ejemplo n.º 26
0
def test_success():
    authenticator = BasicAuthenticator('username', 'password')
    natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(
        authenticator=authenticator)

    list_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers'
    list_response = '{"classifiers": [{"url": "https://gateway.watsonplatform.net/natural-language-classifier-' \
                    'experimental/api/v1/classifiers/497EF2-nlc-00", "classifier_id": "497EF2-nlc-00"}]}'
    responses.add(responses.GET,
                  list_url,
                  body=list_response,
                  status=200,
                  content_type='application/json')

    natural_language_classifier.list_classifiers()

    assert responses.calls[0].request.url == list_url
    assert responses.calls[0].response.text == list_response

    status_url = (
        'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/'
        '497EF2-nlc-00')
    status_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \
                      'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \
                      'instance is now available and is ready to take classifier requests.", "classifier_id": ' \
                      '"497EF2-nlc-00"}'

    responses.add(responses.GET,
                  status_url,
                  body=status_response,
                  status=200,
                  content_type='application/json')

    natural_language_classifier.get_classifier('497EF2-nlc-00')

    assert responses.calls[1].request.url == status_url
    assert responses.calls[1].response.text == status_response

    classify_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' \
                   '497EF2-nlc-00/classify'
    classify_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/' \
                        'v1", "text": "test", "classes": [{"class_name": "conditions", "confidence": ' \
                        '0.6575315710901418}, {"class_name": "temperature", "confidence": 0.3424684289098582}], ' \
                        '"classifier_id": "497EF2-nlc-00", "top_class": "conditions"}'

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

    natural_language_classifier.classify('497EF2-nlc-00', 'test')

    assert responses.calls[2].request.url == classify_url
    assert responses.calls[2].response.text == classify_response

    create_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers'
    create_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \
                      'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \
                      'instance is now available and is ready to take classifier requests.", "classifier_id": ' \
                      '"497EF2-nlc-00"}'

    responses.add(responses.POST,
                  create_url,
                  body=create_response,
                  status=200,
                  content_type='application/json')
    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/weather_data_train.csv'),
            'rb') as training_data:
        natural_language_classifier.create_classifier(
            training_metadata='{"language": "en"}',
            training_data=training_data)

    assert responses.calls[3].request.url == create_url
    assert responses.calls[3].response.text == create_response

    remove_url = status_url
    remove_response = '{}'

    responses.add(responses.DELETE,
                  remove_url,
                  body=remove_response,
                  status=200,
                  content_type='application/json')

    natural_language_classifier.delete_classifier('497EF2-nlc-00')

    assert responses.calls[4].request.url == remove_url
    assert responses.calls[4].response.text == remove_response

    assert len(responses.calls) == 5
Ejemplo n.º 27
0
 def test_analyze_throws(self):
     authenticator = BasicAuthenticator('username', 'password')
     nlu = NaturalLanguageUnderstandingV1(version='2016-01-23',
                                          authenticator=authenticator)
     with pytest.raises(ValueError):
         nlu.analyze(None, text="this will not work")
Ejemplo n.º 28
0
def test_custom_grammars():
    url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/grammars/{1}'

    responses.add(responses.POST,
                  url.format('customization_id', 'grammar_name'),
                  body='{}',
                  status=200,
                  content_type='application/json')

    responses.add(responses.DELETE,
                  url.format('customization_id', 'grammar_name'),
                  status=200,
                  content_type='application/json')

    responses.add(
        responses.GET,
        url.format('customization_id', 'grammar_name'),
        body=
        '{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}',
        status=200,
        content_type='application/json')

    responses.add(
        responses.GET,
        url=
        'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/customization_id/grammars',
        body=
        '{"grammars":[{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}]}',
        status=200,
        content_type='application/json')

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

    with open(
            os.path.join(os.path.dirname(__file__),
                         '../../resources/confirm-grammar.xml'),
            'rb') as grammar_file:
        speech_to_text.add_grammar("customization_id",
                                   grammar_name='grammar_name',
                                   grammar_file=grammar_file,
                                   content_type='application/srgs+xml',
                                   allow_overwrite=True)
    assert responses.calls[0].response.json() == {}

    speech_to_text.delete_grammar('customization_id', 'grammar_name')
    assert responses.calls[1].response.status_code == 200

    speech_to_text.get_grammar('customization_id', 'grammar_name')
    assert responses.calls[2].response.json() == {
        "status": "analyzed",
        "name": "test-add-grammar-python",
        "out_of_vocabulary_words": 0
    }

    speech_to_text.list_grammars('customization_id')
    assert responses.calls[3].response.json() == {
        "grammars": [{
            "status": "analyzed",
            "name": "test-add-grammar-python",
            "out_of_vocabulary_words": 0
        }]
    }